Skip to content

AlchemicalQueues

The core entrypoint to Alchemical Queues.

Source code in src/alchemical_queues/main.py
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
class AlchemicalQueues:
    """The core entrypoint to Alchemical Queues."""

    def __init__(
        self,
        engine: Union[Engine, None] = None,
        queue_tablename: str = "AlchemicalQueue",
        response_tablename: str = "AlchemicalResult",
        base: Union[Type[DeclarativeBase], None] = None,
    ) -> None:
        """Create the main queue entrypoint object.

        Args:
            engine (sqlalchemy.engine.Engine | None): The SQLAlchemy engine you want to use. May be left None and initialized later.
            queue_tablename (str): The name of the table AlchemicalQueues uses for queues.
            response_tablename (str): The name of the table AlchemicalQueues uses for task results.
            base (Type[DeclarativeBase] | None, optional): An existing declarative base to attach
                the queue/response tables to, so they share a registry and metadata with tables
                defined elsewhere in your application (e.g. Flask-SQLAlchemy's `db.Model`). Leave
                `None` to let AlchemicalQueues create its own isolated base.
        """

        self._engine = engine
        self._base, self._qmodel, self._rmodel = _generate_models(
            queue_tablename, response_tablename, base
        )
        self._queues: Dict[str, "AlchemicalQueue"] = {}
        self._task_queues: Dict[str, "AlchemicalTaskQueue"] = {}

    def set_engine(self, engine: Engine) -> None:
        """Set the SQLAlchemy engine post-initialization

        Args:
            engine (sqlalchemy.engine.Engine): The SQLAlchemy engine you want to use.

        Raises:
            Exception: when the engine was already set.
        """

        if self._engine is not None:
            raise Exception(
                "Cannot set the engine on Alchemical Queues more than once!"
            )

        self._engine = engine

    def create_all(self) -> None:
        """Create the needed SQLAlchemy table. You would normally call this
        when you are also creating your own tables, e.g. db.create_all()."""
        if self._engine is None:
            raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

        self._base.metadata.create_all(self._engine)

    @_retry_on_deadlock
    def clear(self) -> None:
        """Clear all entries from all queues and task results. Might fail-silent an update call."""

        if self._engine is None:
            raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

        with Session(self._engine) as session:
            session.execute(delete(self._qmodel))
            session.execute(delete(self._rmodel))
            session.commit()

    def get(
        self, key: str, *, serializer: Serializer[Any] = DEFAULT_SERIALIZER
    ) -> "AlchemicalQueue[Any]":
        """Get a plain Queue instance: `put()`/`get()`/`qsize()`/`empty()`/`clear()`,
        where `get()` removes the entry immediately. If your process dies
        between `get()` and finishing whatever you needed the entry for, the
        entry is simply gone -- there's no redelivery. For that (and for
        result-tracking via `respond()`/`responses()`), see
        [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].

        Args:
            key (str): The name of the queue you wish to access.
            serializer (Serializer, optional): how entries put into this queue
                are turned into bytes for storage and back. Defaults to
                [PickleSerializer][alchemical_queues.serializers.PickleSerializer],
                matching previous behavior. Only takes effect the first time
                this queue name is requested; later calls return the same
                cached instance. See
                [get_serialized][alchemical_queues.AlchemicalQueues.get_serialized]
                for a typed equivalent.

        Returns:
            AlchemicalQueue
        """
        if self._engine is None:
            raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

        if key not in self._queues:
            _validate_queue_name(key)
            self._queues[key] = AlchemicalQueue(
                self._engine, self._qmodel, key, serializer=serializer
            )

        return self._queues[key]

    def get_typed(
        self,
        key: str,
        typeof: Type[T],
        *,
        serializer: Union[Serializer[T], None] = None,
    ) -> "AlchemicalQueue[T]":
        """Get a typed Queue instance

        Args:
            key (str): The name of the queue you wish to access.
            typeof (Type[T]): The type of the queue you wish to use
            serializer (Serializer[T] | None, optional): see
                [get][alchemical_queues.AlchemicalQueues.get]. Defaults to
                [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

        Returns:
            AlchemicalQueue[T]
        """
        # pylint: disable=unused-argument
        return cast(
            AlchemicalQueue[T],
            self.get(key, serializer=serializer or DEFAULT_SERIALIZER),
        )

    def get_serialized(
        self, key: str, serializer: Serializer[T]
    ) -> "AlchemicalQueue[T]":
        """Get a Queue instance typed by its `serializer` instead of an
        explicit `typeof`, e.g. `queues.get_serialized("q", PydanticSerializer(MyModel))`
        gives you an `AlchemicalQueue[MyModel]` without repeating the type.

        Args:
            key (str): The name of the queue you wish to access.
            serializer (Serializer[T]): see [get][alchemical_queues.AlchemicalQueues.get].

        Returns:
            AlchemicalQueue[T]
        """
        return cast(AlchemicalQueue[T], self.get(key, serializer=serializer))

    def get_task_queue(
        self,
        key: str,
        *,
        visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
        serializer: Serializer[Any] = DEFAULT_SERIALIZER,
        response_serializer: Serializer[Any] = DEFAULT_SERIALIZER,
    ) -> "AlchemicalTaskQueue[Any, Any]":
        """Get an [AlchemicalTaskQueue][alchemical_queues.AlchemicalTaskQueue]
        instance: `get()` claims an entry rather than removing it, with
        `release()`/`discard()`/`extend()` to manage that claim and
        `respond()`/`responses()` to record and retrieve results. This is
        what [tasks.Worker][alchemical_queues.tasks.Worker] requires.

        Args:
            key (str): The name of the queue you wish to access.
            visibility_timeout (timedelta, optional): how long a claimed entry
                stays claimed before it becomes claimable again if nobody has
                responded to or released it. Only takes effect the first time
                this queue name is requested; later calls return the same
                cached AlchemicalTaskQueue instance.
            serializer (Serializer, optional): how entries put into this queue
                are turned into bytes for storage and back. Defaults to
                [PickleSerializer][alchemical_queues.serializers.PickleSerializer],
                matching previous behavior. Only takes effect the first time
                this queue name is requested. See
                [get_task_queue_serialized][alchemical_queues.AlchemicalQueues.get_task_queue_serialized]
                for a typed equivalent.
            response_serializer (Serializer, optional): how responses recorded
                via `respond()` are turned into bytes for storage and back.
                Independent of `serializer` -- a task's input and its result
                are usually different shapes. Defaults to
                [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

        Returns:
            AlchemicalTaskQueue
        """
        if self._engine is None:
            raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

        if key not in self._task_queues:
            _validate_queue_name(key)
            self._task_queues[key] = AlchemicalTaskQueue(
                self._engine,
                self._qmodel,
                self._rmodel,
                key,
                visibility_timeout,
                serializer=serializer,
                response_serializer=response_serializer,
            )

        return self._task_queues[key]

    def get_task_queue_typed(
        self,
        key: str,
        typeof: Type[T],
        *,
        visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
        serializer: Union[Serializer[T], None] = None,
    ) -> "AlchemicalTaskQueue[T, Any]":
        """Get a typed AlchemicalTaskQueue instance. Only the entry type `T`
        is given explicitly here -- responses stay `Any`
        (`PickleSerializer` by default). See
        [get_task_queue_serialized][alchemical_queues.AlchemicalQueues.get_task_queue_serialized]
        to also type (and independently serialize) responses.

        Args:
            key (str): The name of the queue you wish to access.
            typeof (Type[T]): The type of the queue you wish to use
            visibility_timeout (timedelta, optional): see
                [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
            serializer (Serializer[T] | None, optional): see
                [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
                Defaults to [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

        Returns:
            AlchemicalTaskQueue[T, Any]
        """
        # pylint: disable=unused-argument
        return cast(
            AlchemicalTaskQueue[T, Any],
            self.get_task_queue(
                key,
                visibility_timeout=visibility_timeout,
                serializer=serializer or DEFAULT_SERIALIZER,
            ),
        )

    def get_task_queue_serialized(
        self,
        key: str,
        serializer: Serializer[T],
        *,
        response_serializer: Union[Serializer[R], None] = None,
        visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
    ) -> "AlchemicalTaskQueue[T, R]":
        """Get an AlchemicalTaskQueue instance typed by its `serializer`/
        `response_serializer` instead of explicit `typeof`s, e.g.
        `queues.get_task_queue_serialized("q", PydanticSerializer(Job), response_serializer=PydanticSerializer(JobResult))`
        gives you an `AlchemicalTaskQueue[Job, JobResult]` without repeating
        either type -- `entry.data` is a `Job`, `responses()[i].data` is a
        `JobResult`, independently serialized.

        Args:
            key (str): The name of the queue you wish to access.
            serializer (Serializer[T]): see
                [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
            response_serializer (Serializer[R] | None, optional): see
                [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
                Defaults to [PickleSerializer][alchemical_queues.serializers.PickleSerializer].
                For a queue `tasks.Worker` runs, consider
                [tasks.TaskResultSerializer][alchemical_queues.tasks.TaskResultSerializer],
                which keeps Worker's `{"result": ...}`/`{"error": ...}`
                envelope while serializing the success value with a
                serializer of your choice.
            visibility_timeout (timedelta, optional): see
                [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].

        Returns:
            AlchemicalTaskQueue[T, R]
        """
        return cast(
            AlchemicalTaskQueue[T, R],
            self.get_task_queue(
                key,
                visibility_timeout=visibility_timeout,
                serializer=serializer,
                response_serializer=response_serializer or DEFAULT_SERIALIZER,
            ),
        )

__init__(engine=None, queue_tablename='AlchemicalQueue', response_tablename='AlchemicalResult', base=None)

Create the main queue entrypoint object.

Parameters:

Name Type Description Default
engine Engine | None

The SQLAlchemy engine you want to use. May be left None and initialized later.

None
queue_tablename str

The name of the table AlchemicalQueues uses for queues.

'AlchemicalQueue'
response_tablename str

The name of the table AlchemicalQueues uses for task results.

'AlchemicalResult'
base Type[DeclarativeBase] | None

An existing declarative base to attach the queue/response tables to, so they share a registry and metadata with tables defined elsewhere in your application (e.g. Flask-SQLAlchemy's db.Model). Leave None to let AlchemicalQueues create its own isolated base.

None
Source code in src/alchemical_queues/main.py
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
def __init__(
    self,
    engine: Union[Engine, None] = None,
    queue_tablename: str = "AlchemicalQueue",
    response_tablename: str = "AlchemicalResult",
    base: Union[Type[DeclarativeBase], None] = None,
) -> None:
    """Create the main queue entrypoint object.

    Args:
        engine (sqlalchemy.engine.Engine | None): The SQLAlchemy engine you want to use. May be left None and initialized later.
        queue_tablename (str): The name of the table AlchemicalQueues uses for queues.
        response_tablename (str): The name of the table AlchemicalQueues uses for task results.
        base (Type[DeclarativeBase] | None, optional): An existing declarative base to attach
            the queue/response tables to, so they share a registry and metadata with tables
            defined elsewhere in your application (e.g. Flask-SQLAlchemy's `db.Model`). Leave
            `None` to let AlchemicalQueues create its own isolated base.
    """

    self._engine = engine
    self._base, self._qmodel, self._rmodel = _generate_models(
        queue_tablename, response_tablename, base
    )
    self._queues: Dict[str, "AlchemicalQueue"] = {}
    self._task_queues: Dict[str, "AlchemicalTaskQueue"] = {}

set_engine(engine)

Set the SQLAlchemy engine post-initialization

Parameters:

Name Type Description Default
engine Engine

The SQLAlchemy engine you want to use.

required

Raises:

Type Description
Exception

when the engine was already set.

Source code in src/alchemical_queues/main.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def set_engine(self, engine: Engine) -> None:
    """Set the SQLAlchemy engine post-initialization

    Args:
        engine (sqlalchemy.engine.Engine): The SQLAlchemy engine you want to use.

    Raises:
        Exception: when the engine was already set.
    """

    if self._engine is not None:
        raise Exception(
            "Cannot set the engine on Alchemical Queues more than once!"
        )

    self._engine = engine

create_all()

Create the needed SQLAlchemy table. You would normally call this when you are also creating your own tables, e.g. db.create_all().

Source code in src/alchemical_queues/main.py
277
278
279
280
281
282
283
def create_all(self) -> None:
    """Create the needed SQLAlchemy table. You would normally call this
    when you are also creating your own tables, e.g. db.create_all()."""
    if self._engine is None:
        raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

    self._base.metadata.create_all(self._engine)

clear()

Clear all entries from all queues and task results. Might fail-silent an update call.

Source code in src/alchemical_queues/main.py
285
286
287
288
289
290
291
292
293
294
295
@_retry_on_deadlock
def clear(self) -> None:
    """Clear all entries from all queues and task results. Might fail-silent an update call."""

    if self._engine is None:
        raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

    with Session(self._engine) as session:
        session.execute(delete(self._qmodel))
        session.execute(delete(self._rmodel))
        session.commit()

get(key, *, serializer=DEFAULT_SERIALIZER)

Get a plain Queue instance: put()/get()/qsize()/empty()/clear(), where get() removes the entry immediately. If your process dies between get() and finishing whatever you needed the entry for, the entry is simply gone -- there's no redelivery. For that (and for result-tracking via respond()/responses()), see get_task_queue.

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
serializer Serializer

how entries put into this queue are turned into bytes for storage and back. Defaults to PickleSerializer, matching previous behavior. Only takes effect the first time this queue name is requested; later calls return the same cached instance. See get_serialized for a typed equivalent.

DEFAULT_SERIALIZER

Returns:

Type Description
AlchemicalQueue[Any]

AlchemicalQueue

Source code in src/alchemical_queues/main.py
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
def get(
    self, key: str, *, serializer: Serializer[Any] = DEFAULT_SERIALIZER
) -> "AlchemicalQueue[Any]":
    """Get a plain Queue instance: `put()`/`get()`/`qsize()`/`empty()`/`clear()`,
    where `get()` removes the entry immediately. If your process dies
    between `get()` and finishing whatever you needed the entry for, the
    entry is simply gone -- there's no redelivery. For that (and for
    result-tracking via `respond()`/`responses()`), see
    [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].

    Args:
        key (str): The name of the queue you wish to access.
        serializer (Serializer, optional): how entries put into this queue
            are turned into bytes for storage and back. Defaults to
            [PickleSerializer][alchemical_queues.serializers.PickleSerializer],
            matching previous behavior. Only takes effect the first time
            this queue name is requested; later calls return the same
            cached instance. See
            [get_serialized][alchemical_queues.AlchemicalQueues.get_serialized]
            for a typed equivalent.

    Returns:
        AlchemicalQueue
    """
    if self._engine is None:
        raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

    if key not in self._queues:
        _validate_queue_name(key)
        self._queues[key] = AlchemicalQueue(
            self._engine, self._qmodel, key, serializer=serializer
        )

    return self._queues[key]

get_typed(key, typeof, *, serializer=None)

Get a typed Queue instance

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
typeof Type[T]

The type of the queue you wish to use

required
serializer Serializer[T] | None

see get. Defaults to PickleSerializer.

None

Returns:

Type Description
AlchemicalQueue[T]

AlchemicalQueue[T]

Source code in src/alchemical_queues/main.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def get_typed(
    self,
    key: str,
    typeof: Type[T],
    *,
    serializer: Union[Serializer[T], None] = None,
) -> "AlchemicalQueue[T]":
    """Get a typed Queue instance

    Args:
        key (str): The name of the queue you wish to access.
        typeof (Type[T]): The type of the queue you wish to use
        serializer (Serializer[T] | None, optional): see
            [get][alchemical_queues.AlchemicalQueues.get]. Defaults to
            [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

    Returns:
        AlchemicalQueue[T]
    """
    # pylint: disable=unused-argument
    return cast(
        AlchemicalQueue[T],
        self.get(key, serializer=serializer or DEFAULT_SERIALIZER),
    )

get_serialized(key, serializer)

Get a Queue instance typed by its serializer instead of an explicit typeof, e.g. queues.get_serialized("q", PydanticSerializer(MyModel)) gives you an AlchemicalQueue[MyModel] without repeating the type.

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
serializer Serializer[T]

see get.

required

Returns:

Type Description
AlchemicalQueue[T]

AlchemicalQueue[T]

Source code in src/alchemical_queues/main.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def get_serialized(
    self, key: str, serializer: Serializer[T]
) -> "AlchemicalQueue[T]":
    """Get a Queue instance typed by its `serializer` instead of an
    explicit `typeof`, e.g. `queues.get_serialized("q", PydanticSerializer(MyModel))`
    gives you an `AlchemicalQueue[MyModel]` without repeating the type.

    Args:
        key (str): The name of the queue you wish to access.
        serializer (Serializer[T]): see [get][alchemical_queues.AlchemicalQueues.get].

    Returns:
        AlchemicalQueue[T]
    """
    return cast(AlchemicalQueue[T], self.get(key, serializer=serializer))

get_task_queue(key, *, visibility_timeout=DEFAULT_VISIBILITY_TIMEOUT, serializer=DEFAULT_SERIALIZER, response_serializer=DEFAULT_SERIALIZER)

Get an AlchemicalTaskQueue instance: get() claims an entry rather than removing it, with release()/discard()/extend() to manage that claim and respond()/responses() to record and retrieve results. This is what tasks.Worker requires.

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
visibility_timeout timedelta

how long a claimed entry stays claimed before it becomes claimable again if nobody has responded to or released it. Only takes effect the first time this queue name is requested; later calls return the same cached AlchemicalTaskQueue instance.

DEFAULT_VISIBILITY_TIMEOUT
serializer Serializer

how entries put into this queue are turned into bytes for storage and back. Defaults to PickleSerializer, matching previous behavior. Only takes effect the first time this queue name is requested. See get_task_queue_serialized for a typed equivalent.

DEFAULT_SERIALIZER
response_serializer Serializer

how responses recorded via respond() are turned into bytes for storage and back. Independent of serializer -- a task's input and its result are usually different shapes. Defaults to PickleSerializer.

DEFAULT_SERIALIZER

Returns:

Type Description
AlchemicalTaskQueue[Any, Any]

AlchemicalTaskQueue

Source code in src/alchemical_queues/main.py
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def get_task_queue(
    self,
    key: str,
    *,
    visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
    serializer: Serializer[Any] = DEFAULT_SERIALIZER,
    response_serializer: Serializer[Any] = DEFAULT_SERIALIZER,
) -> "AlchemicalTaskQueue[Any, Any]":
    """Get an [AlchemicalTaskQueue][alchemical_queues.AlchemicalTaskQueue]
    instance: `get()` claims an entry rather than removing it, with
    `release()`/`discard()`/`extend()` to manage that claim and
    `respond()`/`responses()` to record and retrieve results. This is
    what [tasks.Worker][alchemical_queues.tasks.Worker] requires.

    Args:
        key (str): The name of the queue you wish to access.
        visibility_timeout (timedelta, optional): how long a claimed entry
            stays claimed before it becomes claimable again if nobody has
            responded to or released it. Only takes effect the first time
            this queue name is requested; later calls return the same
            cached AlchemicalTaskQueue instance.
        serializer (Serializer, optional): how entries put into this queue
            are turned into bytes for storage and back. Defaults to
            [PickleSerializer][alchemical_queues.serializers.PickleSerializer],
            matching previous behavior. Only takes effect the first time
            this queue name is requested. See
            [get_task_queue_serialized][alchemical_queues.AlchemicalQueues.get_task_queue_serialized]
            for a typed equivalent.
        response_serializer (Serializer, optional): how responses recorded
            via `respond()` are turned into bytes for storage and back.
            Independent of `serializer` -- a task's input and its result
            are usually different shapes. Defaults to
            [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

    Returns:
        AlchemicalTaskQueue
    """
    if self._engine is None:
        raise Exception("AlchemicalQueues SQLAlchemy engine was not initialized.")

    if key not in self._task_queues:
        _validate_queue_name(key)
        self._task_queues[key] = AlchemicalTaskQueue(
            self._engine,
            self._qmodel,
            self._rmodel,
            key,
            visibility_timeout,
            serializer=serializer,
            response_serializer=response_serializer,
        )

    return self._task_queues[key]

get_task_queue_typed(key, typeof, *, visibility_timeout=DEFAULT_VISIBILITY_TIMEOUT, serializer=None)

Get a typed AlchemicalTaskQueue instance. Only the entry type T is given explicitly here -- responses stay Any (PickleSerializer by default). See get_task_queue_serialized to also type (and independently serialize) responses.

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
typeof Type[T]

The type of the queue you wish to use

required
visibility_timeout timedelta DEFAULT_VISIBILITY_TIMEOUT
serializer Serializer[T] | None

see get_task_queue. Defaults to PickleSerializer.

None

Returns:

Type Description
AlchemicalTaskQueue[T, Any]

AlchemicalTaskQueue[T, Any]

Source code in src/alchemical_queues/main.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def get_task_queue_typed(
    self,
    key: str,
    typeof: Type[T],
    *,
    visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
    serializer: Union[Serializer[T], None] = None,
) -> "AlchemicalTaskQueue[T, Any]":
    """Get a typed AlchemicalTaskQueue instance. Only the entry type `T`
    is given explicitly here -- responses stay `Any`
    (`PickleSerializer` by default). See
    [get_task_queue_serialized][alchemical_queues.AlchemicalQueues.get_task_queue_serialized]
    to also type (and independently serialize) responses.

    Args:
        key (str): The name of the queue you wish to access.
        typeof (Type[T]): The type of the queue you wish to use
        visibility_timeout (timedelta, optional): see
            [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
        serializer (Serializer[T] | None, optional): see
            [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
            Defaults to [PickleSerializer][alchemical_queues.serializers.PickleSerializer].

    Returns:
        AlchemicalTaskQueue[T, Any]
    """
    # pylint: disable=unused-argument
    return cast(
        AlchemicalTaskQueue[T, Any],
        self.get_task_queue(
            key,
            visibility_timeout=visibility_timeout,
            serializer=serializer or DEFAULT_SERIALIZER,
        ),
    )

get_task_queue_serialized(key, serializer, *, response_serializer=None, visibility_timeout=DEFAULT_VISIBILITY_TIMEOUT)

Get an AlchemicalTaskQueue instance typed by its serializer/ response_serializer instead of explicit typeofs, e.g. queues.get_task_queue_serialized("q", PydanticSerializer(Job), response_serializer=PydanticSerializer(JobResult)) gives you an AlchemicalTaskQueue[Job, JobResult] without repeating either type -- entry.data is a Job, responses()[i].data is a JobResult, independently serialized.

Parameters:

Name Type Description Default
key str

The name of the queue you wish to access.

required
serializer Serializer[T] required
response_serializer Serializer[R] | None

see get_task_queue. Defaults to PickleSerializer. For a queue tasks.Worker runs, consider tasks.TaskResultSerializer, which keeps Worker's {"result": ...}/{"error": ...} envelope while serializing the success value with a serializer of your choice.

None
visibility_timeout timedelta DEFAULT_VISIBILITY_TIMEOUT

Returns:

Type Description
AlchemicalTaskQueue[T, R]

AlchemicalTaskQueue[T, R]

Source code in src/alchemical_queues/main.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def get_task_queue_serialized(
    self,
    key: str,
    serializer: Serializer[T],
    *,
    response_serializer: Union[Serializer[R], None] = None,
    visibility_timeout: timedelta = DEFAULT_VISIBILITY_TIMEOUT,
) -> "AlchemicalTaskQueue[T, R]":
    """Get an AlchemicalTaskQueue instance typed by its `serializer`/
    `response_serializer` instead of explicit `typeof`s, e.g.
    `queues.get_task_queue_serialized("q", PydanticSerializer(Job), response_serializer=PydanticSerializer(JobResult))`
    gives you an `AlchemicalTaskQueue[Job, JobResult]` without repeating
    either type -- `entry.data` is a `Job`, `responses()[i].data` is a
    `JobResult`, independently serialized.

    Args:
        key (str): The name of the queue you wish to access.
        serializer (Serializer[T]): see
            [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
        response_serializer (Serializer[R] | None, optional): see
            [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].
            Defaults to [PickleSerializer][alchemical_queues.serializers.PickleSerializer].
            For a queue `tasks.Worker` runs, consider
            [tasks.TaskResultSerializer][alchemical_queues.tasks.TaskResultSerializer],
            which keeps Worker's `{"result": ...}`/`{"error": ...}`
            envelope while serializing the success value with a
            serializer of your choice.
        visibility_timeout (timedelta, optional): see
            [get_task_queue][alchemical_queues.AlchemicalQueues.get_task_queue].

    Returns:
        AlchemicalTaskQueue[T, R]
    """
    return cast(
        AlchemicalTaskQueue[T, R],
        self.get_task_queue(
            key,
            visibility_timeout=visibility_timeout,
            serializer=serializer,
            response_serializer=response_serializer or DEFAULT_SERIALIZER,
        ),
    )