/
task_streaming.py
376 lines (317 loc) · 11.6 KB
/
task_streaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/006_TaskStreaming.ipynb.
# %% auto 0
__all__ = ['logger', 'TaskPool', 'ExceptionMonitor', 'StreamExecutor', 'DynamicTaskExecutor', 'SequentialExecutor',
'get_executor']
# %% ../../nbs/006_TaskStreaming.ipynb 1
import asyncio
import sys
from abc import ABC, abstractmethod
from asyncio import Task
from typing import *
import anyio
from aiokafka import ConsumerRecord
from logging import Logger
from .logger import get_logger
from .meta import export
# %% ../../nbs/006_TaskStreaming.ipynb 3
logger = get_logger(__name__)
# %% ../../nbs/006_TaskStreaming.ipynb 10
class TaskPool:
def __init__(
self,
size: int = 100_000,
on_error: Optional[Callable[[BaseException], None]] = None,
):
"""
Initializes a TaskPool instance.
Args:
size: The size of the task pool. Defaults to 100,000.
on_error: Optional callback function to handle task errors. Defaults to None.
Returns:
None
"""
self.size = size
self.pool: Set[Task] = set()
self.on_error = on_error
self.finished = False
async def add(self, item: Task) -> None:
"""
Adds a task to the task pool.
Args:
item: The task to be added.
Returns:
None
"""
while len(self.pool) >= self.size:
await asyncio.sleep(0)
self.pool.add(item)
item.add_done_callback(self.discard)
def discard(self, task: Task) -> None:
"""
Discards a completed task from the task pool.
Args:
task: The completed task to be discarded.
Returns:
None
"""
e = task.exception()
if e is not None and self.on_error is not None:
try:
self.on_error(e)
except Exception as ee:
logger.warning(
f"Exception {ee} raised when calling on_error() callback: {e}"
)
self.pool.discard(task)
def __len__(self) -> int:
"""
Returns the number of tasks in the task pool.
Returns:
The number of tasks in the task pool.
"""
return len(self.pool)
async def __aenter__(self) -> "TaskPool":
self.finished = False
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
while len(self) > 0:
await asyncio.sleep(0)
self.finished = True
@staticmethod
def log_error(logger: Logger) -> Callable[[Exception], None]:
"""
Creates a decorator that logs errors using the specified logger.
Args:
logger: The logger to use for error logging.
Returns:
The decorator function.
"""
def _log_error(e: Exception, logger: Logger = logger) -> None:
logger.warning(f"{e=}")
return _log_error
# %% ../../nbs/006_TaskStreaming.ipynb 14
class ExceptionMonitor:
def __init__(self) -> None:
"""
Initializes an ExceptionMonitor instance.
Returns:
None
"""
self.exceptions: List[Exception] = []
self.exception_found = False
def on_error(self, e: Exception) -> None:
"""
Handles an error by storing the exception.
Args:
e: The exception to be handled.
Returns:
None
"""
self.exceptions.append(e)
self.exception_found = True
def _monitor_step(self) -> None:
"""
Raises the next exception in the queue.
Returns:
None
"""
if len(self.exceptions) > 0:
e = self.exceptions.pop(0)
raise e
async def __aenter__(self) -> "ExceptionMonitor":
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
while len(self.exceptions) > 0:
self._monitor_step()
await asyncio.sleep(0)
# %% ../../nbs/006_TaskStreaming.ipynb 17
class StreamExecutor(ABC):
@abstractmethod
async def run( # type: ignore
self,
*,
is_shutting_down_f: Callable[[], bool],
generator: Callable[[], Awaitable[ConsumerRecord]],
processor: Callable[[ConsumerRecord], Awaitable[None]],
) -> None:
"""
Abstract method for running the stream executor.
Args:
is_shutting_down_f: Function to check if the executor is shutting down.
generator: Generator function for retrieving consumer records.
processor: Processor function for processing consumer records.
"""
pass
# %% ../../nbs/006_TaskStreaming.ipynb 20
def _process_items_task( # type: ignore
processor: Callable[[ConsumerRecord], Awaitable[None]], task_pool: TaskPool
) -> Callable[
[
anyio.streams.memory.MemoryObjectReceiveStream,
Callable[[ConsumerRecord], Awaitable[None]],
bool,
],
Coroutine[Any, Any, Awaitable[None]],
]:
async def _process_items_wrapper( # type: ignore
receive_stream: anyio.streams.memory.MemoryObjectReceiveStream,
processor: Callable[[ConsumerRecord], Awaitable[None]] = processor,
task_pool=task_pool,
):
async with receive_stream:
async for msg in receive_stream:
task: asyncio.Task = asyncio.create_task(processor(msg)) # type: ignore
await task_pool.add(task)
return _process_items_wrapper
# %% ../../nbs/006_TaskStreaming.ipynb 21
@export("fastkafka.executors")
class DynamicTaskExecutor(StreamExecutor):
"""A class that implements a dynamic task executor for processing consumer records.
The DynamicTaskExecutor class extends the StreamExecutor class and provides functionality
for running a tasks in parallel using asyncio.Task.
"""
def __init__(
self,
throw_exceptions: bool = False,
max_buffer_size: int = 100_000,
size: int = 100_000,
):
"""Create an instance of DynamicTaskExecutor
Args:
throw_exceptions: Flag indicating whether exceptions should be thrown ot logged.
Defaults to False.
max_buffer_size: Maximum buffer size for the memory object stream.
Defaults to 100_000.
size: Size of the task pool. Defaults to 100_000.
"""
self.throw_exceptions = throw_exceptions
self.max_buffer_size = max_buffer_size
self.exception_monitor = ExceptionMonitor()
self.task_pool = TaskPool(
on_error=self.exception_monitor.on_error # type: ignore
if throw_exceptions
else TaskPool.log_error(logger),
size=size,
)
async def run( # type: ignore
self,
*,
is_shutting_down_f: Callable[[], bool],
generator: Callable[[], Awaitable[ConsumerRecord]],
processor: Callable[[ConsumerRecord], Awaitable[None]],
) -> None:
"""
Runs the dynamic task executor.
Args:
is_shutting_down_f: Function to check if the executor is shutting down.
generator: Generator function for retrieving consumer records.
processor: Processor function for processing consumer records.
"""
send_stream, receive_stream = anyio.create_memory_object_stream(
max_buffer_size=self.max_buffer_size
)
async with self.exception_monitor, self.task_pool:
async with anyio.create_task_group() as tg:
tg.start_soon(
_process_items_task(processor, self.task_pool), receive_stream
)
async with send_stream:
while not is_shutting_down_f():
if (
self.exception_monitor.exception_found
and self.throw_exceptions
):
break
msgs = await generator()
for msg in msgs:
await send_stream.send(msg)
# %% ../../nbs/006_TaskStreaming.ipynb 30
def _process_items_coro( # type: ignore
processor: Callable[[ConsumerRecord], Awaitable[None]],
throw_exceptions: bool,
) -> Callable[
[
anyio.streams.memory.MemoryObjectReceiveStream,
Callable[[ConsumerRecord], Awaitable[None]],
bool,
],
Coroutine[Any, Any, Awaitable[None]],
]:
async def _process_items_wrapper( # type: ignore
receive_stream: anyio.streams.memory.MemoryObjectReceiveStream,
processor: Callable[[ConsumerRecord], Awaitable[None]] = processor,
throw_exceptions: bool = throw_exceptions,
) -> Awaitable[None]:
async with receive_stream:
async for msg in receive_stream:
try:
await processor(msg)
except Exception as e:
if throw_exceptions:
raise e
else:
logger.warning(f"{e=}")
return _process_items_wrapper
# %% ../../nbs/006_TaskStreaming.ipynb 31
@export("fastkafka.executors")
class SequentialExecutor(StreamExecutor):
"""A class that implements a sequential executor for processing consumer records.
The SequentialExecutor class extends the StreamExecutor class and provides functionality
for running processing tasks in sequence by awaiting their coroutines.
"""
def __init__(
self,
throw_exceptions: bool = False,
max_buffer_size: int = 100_000,
):
"""Create an instance of SequentialExecutor
Args:
throw_exceptions: Flag indicating whether exceptions should be thrown or logged.
Defaults to False.
max_buffer_size: Maximum buffer size for the memory object stream.
Defaults to 100_000.
"""
self.throw_exceptions = throw_exceptions
self.max_buffer_size = max_buffer_size
async def run( # type: ignore
self,
*,
is_shutting_down_f: Callable[[], bool],
generator: Callable[[], Awaitable[ConsumerRecord]],
processor: Callable[[ConsumerRecord], Awaitable[None]],
) -> None:
"""
Runs the sequential executor.
Args:
is_shutting_down_f: Function to check if the executor is shutting down.
generator: Generator function for retrieving consumer records.
processor: Processor function for processing consumer records.
"""
send_stream, receive_stream = anyio.create_memory_object_stream(
max_buffer_size=self.max_buffer_size
)
async with anyio.create_task_group() as tg:
tg.start_soon(
_process_items_coro(processor, self.throw_exceptions), receive_stream
)
async with send_stream:
while not is_shutting_down_f():
msgs = await generator()
for msg in msgs:
await send_stream.send(msg)
# %% ../../nbs/006_TaskStreaming.ipynb 34
def get_executor(executor: Union[str, StreamExecutor, None] = None) -> StreamExecutor:
"""
Returns an instance of the specified executor.
Args:
executor: Executor instance or name of the executor.
Returns:
Instance of the specified executor.
Raises:
AttributeError: If the executor is not found.
"""
if isinstance(executor, StreamExecutor):
return executor
elif executor is None:
executor = "SequentialExecutor"
return getattr(sys.modules["fastkafka._components.task_streaming"], executor)() # type: ignore