-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproducer.py
More file actions
405 lines (341 loc) · 14.4 KB
/
producer.py
File metadata and controls
405 lines (341 loc) · 14.4 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
from __future__ import annotations
from collections.abc import Iterable, Iterator, AsyncIterator
from typing import Any, cast
import itertools
from opentelemetry import trace
from opsqueue.common import (
SerializationFormat,
encode_chunk,
decode_chunk,
DEFAULT_SERIALIZATION_FORMAT,
)
from . import opsqueue_internal
from . import tracing
from opsqueue.exceptions import (
SubmissionFailedError,
SubmissionNotCancellableError,
SubmissionNotFoundError,
)
from .opsqueue_internal import ( # type: ignore[import-not-found]
SubmissionId,
SubmissionStatus,
SubmissionCompleted,
SubmissionFailed,
ChunkFailed,
SubmissionNotCancellable,
)
__all__ = [
"ProducerClient",
"SubmissionId",
"SubmissionStatus",
"SubmissionCompleted",
"SubmissionFailedError",
"SubmissionFailed",
"SubmissionNotCancellable",
"SubmissionNotCancellableError",
"SubmissionNotFoundError",
"ChunkFailed",
]
class ProducerClient:
"""
Opsqueue producer client. Allows sending of large collections of operations ('submissions')
and waiting for them to be completed.
Can also be used for basic introspection/debugging/maintenance of an opsqueue queue.
"""
__slots__ = "inner"
def __init__(
self,
opsqueue_url: str,
object_store_url: str,
*,
object_store_options: list[tuple[str, str]] = [],
):
"""
Creates a new producer client.
- opsqueue_url: URL at which the opsqueue binary can be reached.
- object_store_url: URL to reach the object store in which chunks are stored.
Use `file:///some/local/path` for local testing.
Use `gs://bucket/path` for a GCS bucket.
See https://docs.rs/object_store/0.11.1/object_store/enum.ObjectStoreScheme.html for details.
Raises `NewObjectStoreClientError` when the given `object_store_url` is incorrect.
"""
self.inner = opsqueue_internal.ProducerClient(
opsqueue_url, object_store_url, object_store_options
)
def __repr__(self) -> str:
return cast(str, self.inner.__repr__())
def server_version(self) -> str:
"""
Ask the Opsqueue server/service to return its version information as a string.
This is mainly useful for debugging
"""
return cast(str, self.inner.server_version())
def run_submission(
self,
ops: Iterable[Any],
*,
chunk_size: int,
serialization_format: SerializationFormat = DEFAULT_SERIALIZATION_FORMAT,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
) -> Iterator[Any]:
"""
Inserts a submission into the queue, and blocks until it is completed.
Chunking is done automatically, based on the provided chunk size.
If the submission fails, an exception will be raised.
(If opsqueue or the object storage cannot be reached, exceptions will also be raised).
Raises:
- `ChunkSizeIsZeroError` if passing an incorrect chunk size of zero;
- `InternalProducerClientError` if there is a low-level internal error.
"""
tracer = trace.get_tracer("opsqueue.producer")
with tracer.start_as_current_span("run_submission"):
results_iter = self.run_submission_chunks(
_chunk_iterator(ops, chunk_size, serialization_format),
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
)
return _unchunk_iterator(results_iter, serialization_format)
async def async_run_submission(
self,
ops: Iterable[Any],
*,
chunk_size: int,
serialization_format: SerializationFormat = DEFAULT_SERIALIZATION_FORMAT,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
) -> AsyncIterator[Any]:
tracer = trace.get_tracer("opsqueue.producer")
with tracer.start_as_current_span("run_submission"):
results_iter = await self.async_run_submission_chunks(
_chunk_iterator(ops, chunk_size, serialization_format),
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
)
return _async_unchunk_iterator(results_iter, serialization_format)
def insert_submission(
self,
ops: Iterable[Any],
*,
chunk_size: int,
serialization_format: SerializationFormat = DEFAULT_SERIALIZATION_FORMAT,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
) -> SubmissionId:
"""
Inserts a submission into the queue,
returning an ID you can use to track the submission's progress afterwards.
Chunking is done automatically, based on the provided chunk size.
Raises:
- `ChunkSizeIsZeroError` if passing an incorrect chunk size of zero;
- `InternalProducerClientError` if there is a low-level internal error.
"""
return self.insert_submission_chunks(
_chunk_iterator(ops, chunk_size, serialization_format),
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
)
def blocking_stream_completed_submission(
self,
submission_id: SubmissionId,
*,
serialization_format: SerializationFormat = DEFAULT_SERIALIZATION_FORMAT,
) -> Iterator[Any]:
"""
Blocks until the submission is completed.
Then, returns the operation-results, as an iterator that lazily
looks up each of the chunk-results one by one from the object storage.
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
- `SubmissionFailedError` if the submission failed permanently
(after retrying a consumer kept failing on one of the chunks)
"""
return _unchunk_iterator(
self.blocking_stream_completed_submission_chunks(submission_id),
serialization_format,
)
def try_stream_completed_submission(
self,
submission_id: SubmissionId,
*,
serialization_format: SerializationFormat = DEFAULT_SERIALIZATION_FORMAT,
) -> Iterator[Any]:
"""
Returns the operation-results of a completed submission, as an iterator that lazily
looks up each of the chunk-results one by one from the object storage.
Raises:
- `SubmissionNotCompletedYet` if the submission you want to stream is not in the completed state.
- `InternalProducerClientError` if there is a low-level internal error.
"""
return _unchunk_iterator(
self.try_stream_completed_submission_chunks(submission_id),
serialization_format,
)
def run_submission_chunks(
self,
chunk_contents: Iterable[bytes],
*,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
chunk_size: None | int = None,
) -> Iterator[bytes]:
"""
Inserts an already-chunked submission into the queue, and blocks until it is completed.
If the submission fails, an exception will be raised.
(If opsqueue or the object storage cannot be reached, exceptions will also be raised).
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
- `SubmissionFailedError` if the submission failed permanently
(after retrying a consumer kept failing on one of the chunks)
"""
submission_id = self.insert_submission_chunks(
chunk_contents,
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
)
return self.blocking_stream_completed_submission_chunks(submission_id)
async def async_run_submission_chunks(
self,
chunk_contents: Iterable[bytes],
*,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
chunk_size: None | int = None,
) -> AsyncIterator[bytes]:
# NOTE: the insertion is not currently async.
# Why? Simplicity. This is unlikely to be the bottleneck
# for most async apps.
# If it does cause a problem in the future this can be revisited
submission_id = self.insert_submission_chunks(
chunk_contents,
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
)
return await self.async_stream_completed_submission_chunks(submission_id)
def insert_submission_chunks(
self,
chunk_contents: Iterable[bytes],
*,
metadata: None | bytes = None,
strategic_metadata: None | dict[str, int] = None,
chunk_size: None | int = None,
) -> SubmissionId:
"""
Inserts an already-chunked submission into the queue,
returning an ID you can use to track the submission's progress afterwards.
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
"""
otel_trace_carrier = tracing.current_opentelemetry_tracecontext_to_carrier()
return self.inner.insert_submission_chunks(
iter(chunk_contents),
metadata=metadata,
strategic_metadata=strategic_metadata,
chunk_size=chunk_size,
otel_trace_carrier=otel_trace_carrier,
)
def blocking_stream_completed_submission_chunks(
self, submission_id: SubmissionId
) -> Iterator[bytes]:
"""
Blocks until the submission is completed, and returns an iterator that lazily
looks up the chunk-results one by one from the object storage.
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
- `SubmissionFailedError` if the submission failed permanently
(after retrying a consumer kept failing on one of the chunks)
"""
return self.inner.blocking_stream_completed_submission_chunks(submission_id) # type: ignore[no-any-return]
async def async_stream_completed_submission_chunks(
self, submission_id: SubmissionId
) -> AsyncIterator[bytes]:
return await self.inner.async_stream_completed_submission_chunks(submission_id) # type: ignore[no-any-return]
def try_stream_completed_submission_chunks(
self, submission_id: SubmissionId
) -> Iterator[bytes]:
"""
Non-blocking version of `blocking_stream_completed_submission_chunks`.
Will fail with a `SubmissionNotCompletedYet` exception
if called before the submission is completed.
Returns the chunk-results of a completed submission, as an iterator that lazily
looks up the chunk-results one by one from the object storage.
Raises:
- `SubmissionNotCompletedYet` if the submission you want to stream is not in the completed state.
- `InternalProducerClientError` if there is a low-level internal error.
"""
return self.inner.try_stream_completed_submission_chunks(submission_id) # type: ignore[no-any-return]
def count_submissions(self) -> int:
"""
Returns the number of active submissions in the queue.
(This does not include completed or failed submissions.)
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
"""
return self.inner.count_submissions() # type: ignore[no-any-return]
def cancel_submission(self, submission_id: SubmissionId) -> None:
"""
Cancel a specific submission that is in progress.
Returns None if the submission was successfully cancelled.
Raises:
- `SubmissionNotCancellableError` if the submission could not be
cancelled because it was already completed, failed or cancelled.
- `SubmissionNotFoundError` if the submission could not be found.
"""
self.inner.cancel_submission(submission_id)
def get_submission_status(
self, submission_id: SubmissionId
) -> SubmissionStatus | None:
"""
Retrieve the status (in progress, completed, or failed) of a specific submission.
Returns `None` if no submission for the given ID can be found.
The returned SubmissionStatus object also includes the number of chunks finished so far,
timestamps indicating when the submission was started/completed/failed,
and the metadata submitted earlier.
This call does not on its own fetch the results of a (completed) submission.
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
"""
return self.inner.get_submission_status(submission_id)
def lookup_submission_id_by_prefix(self, prefix: str) -> SubmissionId | None:
"""
Attempts to find the submission ID if only the prefix of the submission
(AKA the path at which the submision's chunks are stored in the object store)
is known.
Returns `None` if no submission could be found.
Raises:
- `InternalProducerClientError` if there is a low-level internal error.
"""
return self.inner.lookup_submission_id_by_prefix(prefix)
def is_completed(self, submission_id: SubmissionId) -> bool:
raise NotImplementedError
def _chunk_iterator(
iter: Iterable[Any], chunk_size: int, serialization_format: SerializationFormat
) -> Iterator[bytes]:
if chunk_size <= 0:
raise ChunkSizeIsZeroError
return map(
lambda c: encode_chunk(c, serialization_format),
itertools.batched(iter, chunk_size),
)
def _unchunk_iterator(
encoded_chunks_iter: Iterable[bytes], serialization_format: SerializationFormat
) -> Iterator[Any]:
for chunk in encoded_chunks_iter:
ops = decode_chunk(chunk, serialization_format)
for op in ops:
yield op
async def _async_unchunk_iterator(
encoded_chunks_iter: AsyncIterator[bytes], serialization_format: SerializationFormat
) -> AsyncIterator[Any]:
async for chunk in encoded_chunks_iter:
ops = decode_chunk(chunk, serialization_format)
for op in ops:
yield op
class ChunkSizeIsZeroError(Exception):
def __str__(self) -> str:
return "Chunk size must be a positive integer"