|
1 | 1 | from collections import namedtuple |
2 | 2 | from urllib.parse import urljoin |
| 3 | +import concurrent.futures |
3 | 4 | import threading |
4 | 5 | import requests |
5 | 6 | import datetime |
|
10 | 11 | import json |
11 | 12 | import math |
12 | 13 |
|
13 | | -# Allows you to retrieve the arguments passed to a function and |
14 | | -# an arbitrary value by passing a 'store' or '_store' argument |
15 | | -# as its return value. Good for use with concurrent.futures. |
| 14 | +# Calls a function and returns an object with the arguments used, its |
| 15 | +# return value and an arbitrary value provided by 'store' or '_store'. |
| 16 | +# In addition, a callable may be passed to either 'cancel' or '_cancel' |
| 17 | +# that may override the return value if it evaluates to a truthy value, |
| 18 | +# in which case, the original call will not be made. The callable must |
| 19 | +# take no arguments. This is intended for use with concurrent.futures. |
16 | 20 | def wrap_call(function, *args, **kwargs): |
17 | 21 | store = kwargs.pop('_store', kwargs.pop('store', None)) |
| 22 | + cancel = kwargs.pop('_cancel', kwargs.pop('cancel', lambda: None)) |
18 | 23 | Wrap = namedtuple('Wrap', ['result', 'store', 'args', 'kwargs']) |
19 | | - return Wrap(function(*args, **kwargs), store, args, kwargs) |
| 24 | + return Wrap(cancel() or function(*args, **kwargs), store, args, kwargs) |
| 25 | + |
| 26 | +class BufferedExecutor(object): |
| 27 | + def __init__(self, submit_size, *args, **kwargs): |
| 28 | + self._submit_size = submit_size |
| 29 | + self._executor = concurrent.futures.ThreadPoolExecutor(*args, **kwargs) |
| 30 | + self._buffer = list() |
| 31 | + self._shutdown = False |
| 32 | + |
| 33 | + def submit(self, fn, *args, **kwargs): |
| 34 | + self._buffer.append((fn, args, kwargs)) |
| 35 | + |
| 36 | + def __submit_from_buffer(self): |
| 37 | + fn, args, kwargs = self._buffer.pop(0) |
| 38 | + return self._executor.submit(fn, *args, **kwargs) |
| 39 | + |
| 40 | + def as_completed(self): |
| 41 | + submitted = [self.__submit_from_buffer() for _ in range(self._submit_size)] |
| 42 | + while self._buffer and not self._shutdown: |
| 43 | + done, _ = concurrent.futures.wait(submitted, return_when=concurrent.futures.FIRST_COMPLETED) |
| 44 | + for future in done: |
| 45 | + submitted.remove(future) |
| 46 | + submitted.append(self.__submit_from_buffer()) |
| 47 | + yield future |
| 48 | + |
| 49 | + def shutdown(self, wait=True): |
| 50 | + self._shutdown = True |
| 51 | + self._executor.shutdown(wait=wait) |
| 52 | + |
| 53 | + def __enter__(self): |
| 54 | + return self |
| 55 | + |
| 56 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 57 | + self.shutdown(wait=True) |
| 58 | + return False |
20 | 59 |
|
21 | 60 | class IndexServer(object): |
22 | 61 | # Index metadata schema: |
|
0 commit comments