Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 9 additions & 14 deletions src/mixpanel_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
import urllib.parse
import urllib.request
import zipfile
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from http.client import IncompleteRead
from inspect import isfunction
from json.decoder import JSONDecodeError
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from socket import timeout

from .paginator import ConcurrentPaginator
Expand Down Expand Up @@ -2299,9 +2299,13 @@ def _dispatch_batches(
:type prep_args: list

"""
pool = ThreadPool(processes=self.pool_size)
# ThreadPoolExecutor rather than multiprocessing.pool.ThreadPool, which needs /dev/shm (missing on AWS Lambda)
executor = ThreadPoolExecutor(max_workers=self.pool_size)
batch = []

def send_batch(items):
MixpanelUtils._async_response_handler_callback(self._send_batch(base_url, endpoint, items))

# Decide which _prep function to use based on the endpoint
if endpoint == "import" or endpoint == "import-events":
prep_function = MixpanelUtils._prep_event_for_import
Expand All @@ -2327,23 +2331,14 @@ def _dispatch_batches(

if len(batch) == batch_size:
# Add an asynchronous call to _send_batch to the thread pool
pool.apply_async(
self._send_batch,
args=(base_url, endpoint, batch),
callback=MixpanelUtils._async_response_handler_callback,
)
executor.submit(send_batch, batch)
batch = []

# If there are fewer than 50 updates left ensure one last call is made
if len(batch):
# Add an asynchronous call to _send_batch to the thread pool
pool.apply_async(
self._send_batch,
args=(base_url, endpoint, batch),
callback=MixpanelUtils._async_response_handler_callback,
)
pool.close()
pool.join()
executor.submit(send_batch, batch)
executor.shutdown(wait=True)

def _send_batch(
self, base_url, endpoint, batch, retries=0,
Expand Down
12 changes: 6 additions & 6 deletions src/mixpanel_utils/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import math
import itertools
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor


class ConcurrentPaginator(object):
Expand Down Expand Up @@ -76,11 +76,11 @@ def _fetcher_func(page):
return _fetcher_func

def _concurrent_flatmap(self, func, iterable):
pool = ThreadPool(processes=self.concurrency)
res = list(itertools.chain(*pool.map(func, iterable)))
pool.close()
pool.join()
return res
# ThreadPoolExecutor is used instead of multiprocessing.pool.ThreadPool
# because the latter needs POSIX semaphores (/dev/shm), which are not
# available in environments such as AWS Lambda.
with ThreadPoolExecutor(max_workers=self.concurrency) as executor:
return list(itertools.chain(*executor.map(func, iterable)))

def _remaining_page_range(self, response):
num_pages = math.ceil(response["total"] / float(response["page_size"]))
Expand Down
37 changes: 37 additions & 0 deletions tests/test_dispatch_batches.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Tests for MixpanelUtils._dispatch_batches."""

import multiprocessing.synchronize
from unittest.mock import patch

from mixpanel_utils import MixpanelUtils


def _client():
return MixpanelUtils(
service_account_username="test.a12345.mp-service-account",
service_account_password="test123TEST123abc1234testing",
project_id=1234567,
pool_size=2,
)


def test_dispatch_batches_sends_every_batch_without_multiprocessing_semaphores():
client = _client()
sent = []

def fake_send_batch(base_url, endpoint, batch):
sent.append(list(batch))
return "1"

# AWS Lambda has no /dev/shm, so creating a multiprocessing lock fails.
with patch.object(
multiprocessing.synchronize.SemLock,
"__init__",
side_effect=FileNotFoundError(2, "No such file or directory"),
), patch.object(client, "_send_batch", side_effect=fake_send_batch), patch.object(
MixpanelUtils, "_async_response_handler_callback"
) as callback:
client._dispatch_batches(client.import_api, "import", list(range(5)), None, batch_size=2)

assert sorted(sent) == [[0, 1], [2, 3], [4]]
assert callback.call_count == 3
39 changes: 39 additions & 0 deletions tests/test_paginator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Tests for ConcurrentPaginator."""

import multiprocessing.synchronize
from unittest.mock import patch

from mixpanel_utils.paginator import ConcurrentPaginator


def _fake_engage(total=7, page_size=2):
"""Return a get_func that serves `total` profiles split into pages."""

def get_page(params):
page = params.get("page", 0)
start = page * page_size
return {
"results": list(range(start, min(start + page_size, total))),
"session_id": "abc",
"page": page,
"page_size": page_size,
"total": total,
}

return get_page


def test_fetch_all_returns_every_page_in_order():
paginator = ConcurrentPaginator(_fake_engage(), concurrency=3)
assert paginator.fetch_all() == list(range(7))


def test_fetch_all_does_not_need_multiprocessing_semaphores():
# AWS Lambda has no /dev/shm, so creating a multiprocessing lock fails.
with patch.object(
multiprocessing.synchronize.SemLock,
"__init__",
side_effect=FileNotFoundError(2, "No such file or directory"),
):
paginator = ConcurrentPaginator(_fake_engage(), concurrency=2)
assert paginator.fetch_all() == list(range(7))
Loading