Skip to content

AsyncSocketBroker

Async Socket Broker.

AsyncSocketBroker

Bases: BaseBroker, AsyncPluginMixin

A broker that listens to sockets and adds tasks to the queue.

Example

from qtasks import QueueTasks
from qtasks.brokers import AsyncSocketBroker

broker = AsyncSocketBroker(name="QueueTasks", url="127.0.0.1")

app = QueueTasks(broker=broker)
Source code in src/qtasks/brokers/async_socket.py
 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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
class AsyncSocketBroker(BaseBroker, AsyncPluginMixin):
    """
    A broker that listens to sockets and adds tasks to the queue.

    ## Example

    ```python
    from qtasks import QueueTasks
    from qtasks.brokers import AsyncSocketBroker

    broker = AsyncSocketBroker(name="QueueTasks", url="127.0.0.1")

    app = QueueTasks(broker=broker)
    ```
    """

    def __init__(
        self,
        name: Annotated[
            str,
            Doc("""
                    Project name. This name is also used by the broker.

                    Default: `QueueTasks`.
                    """),
        ] = "QueueTasks",
        url: Annotated[
            str,
            Doc("""
                    URL to connect to the socket.

                    Default: `127.0.0.1`.
                    """),
        ] = "127.0.0.1",
        port: Annotated[
            int,
            Doc("""
                    Port for connecting to a socket.

                    Default: `6379`.
                    """),
        ] = 6379,
        storage: Annotated[
            Optional[BaseStorage],
            Doc("""
                    Storage.

                    Default: `AsyncRedisStorage`.
                    """),
        ] = None,
        log: Annotated[
            Logger | None,
            Doc("""
                    Logger.

                    Default: `qtasks.logs.Logger`.
                    """),
        ] = None,
        config: Annotated[
            QueueConfig | None,
            Doc("""
                    Config.

                    Default: `qtasks.configs.config.QueueConfig`.
                    """),
        ] = None,
        events: Annotated[
            Optional[BaseEvents],
            Doc("""
                    Events.

                    Default: `qtasks.events.AsyncEvents`.
                    """),
        ] = None,
    ):
        """
        Initializing AsyncSocketBroker.

        Args:
            name (str, optional): Project name. Default: `QueueTasks`.
            url (str, optional): URL to connect to the socket. Default: `127.0.0.1`.
            port (int, optional): Port to connect to the socket. Default: `6379`.
            storage (BaseStorage, optional): Storage. Default: `None`.
            log (Logger, optional): Logger. Default: `None`.
            config (QueueConfig, optional): Config. Default: `None`.
            events (BaseEvents, optional): Events. Default: `qtasks.events.AsyncEvents`.
        """
        self.url = url
        self.port = port
        storage = storage or AsyncRedisStorage(
            name=name, log=log, config=config, events=events
        )

        super().__init__(
            name=name, log=log, config=config, events=events, storage=storage
        )

        self.storage: BaseStorage[Literal[True]]

        self.events = self.events or AsyncEvents()

        self.client = None
        self.default_sleep = 0.01
        self.running = False

        self.queue = asyncio.Queue()
        self._serve_task: asyncio.Task | None = None
        self._listen_task: asyncio.Task | None = None

    async def handle_connection(
        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
    ):
        """
        Handles an incoming connection.

        Args:
            reader(asyncio.StreamReader): Reader for incoming data.
            writer(asyncio.StreamWriter): Writer for outgoing data.
        """
        try:
            data = await reader.read(4096)
            message = json.loads(data.decode())
            task_name = message["task_name"]
            uuid = message["uuid"]
            priority = message["priority"]
            args = message.get("args", ())
            kwargs = message.get("kwargs", {})
            created_at = message["created_at"]

            await self.storage.add(
                uuid=uuid,
                task_status=TaskStatusNewSchema(
                    task_name=task_name,
                    priority=priority,
                    args=args,
                    kwargs=kwargs,
                    created_at=created_at,
                    updated_at=created_at,
                ),
            )

            await self.queue.put((task_name, uuid, priority))
            writer.write(b"OK")
            await writer.drain()
        finally:
            writer.close()
            with contextlib.suppress(Exception):
                await writer.wait_closed()

    async def listen(
        self,
        worker: Annotated[
            BaseWorker[Literal[True]],
            Doc("""
                    Worker class.
                    """),
        ],
    ):
        """
        Listens to the socket queue and transfers tasks to the worker.

        Args:
            worker (BaseWorker): Worker class.

        Raises:
            KeyError: Task not found.
        """
        await self._plugin_trigger("broker_listen_start", broker=self, worker=worker)
        self.running = True

        while self.running:
            try:
                item = await self.queue.get()
            except asyncio.CancelledError:
                break
            if item is None:
                break

            task_name, uuid, priority = item
            model_get = await self.get(uuid=uuid)
            if not model_get:
                raise KeyError(f"Task not found: {uuid}")

            args, kwargs, created_at = (
                model_get.args or (),
                model_get.kwargs or {},
                model_get.created_at.timestamp(),
            )

            await self.storage.add_process(f"{task_name}:{uuid}:{priority}", priority)

            if self.log:
                self.log.info(f"Received new task: {uuid}")
            new_args = await self._plugin_trigger(
                "broker_add_worker",
                broker=self,
                worker=worker,
                task_name=task_name,
                uuid=uuid,
                priority=int(priority),
                args=args,
                kw=kwargs,
                created_at=created_at,
                return_last=True,
            )
            if new_args:
                task_name = new_args.get("task_name", task_name)
                uuid = new_args.get("uuid", uuid)
                priority = new_args.get("priority", priority)
                args = new_args.get("args", args)
                kwargs = new_args.get("kw", kwargs)
                created_at = new_args.get("created_at", created_at)

            await worker.add(
                name=task_name,
                uuid=uuid,
                priority=int(priority),
                args=args,
                kwargs=kwargs,
                created_at=created_at,
            )
            return

    async def add(
        self,
        task_name: Annotated[
            str,
            Doc("""
                    Task name.
                    """),
        ],
        priority: Annotated[
            int,
            Doc("""
                    Task priority.

                    Default: `0`.
                    """),
        ] = 0,
        extra: Annotated[
            dict | None,
            Doc("""
                    Additional task parameters.

                    Default: `None`.
                    """),
        ] = None,
        args: Annotated[
            tuple | None,
            Doc("""
                    Task arguments of type args.

                    Default: `()`.
                    """),
        ] = None,
        kwargs: Annotated[
            dict | None,
            Doc("""
                    Task arguments of type kwargs.

                    Default: `{}`.
                    """),
        ] = None,
    ) -> Task:
        """
        Adds a task to the broker.

        Args:
            task_name (str): The name of the task.
            priority (int, optional): Task priority. By default: 0.
            extra (dict, optional): Additional task parameters. Default: `None`.
            args (tuple, optional): Task arguments of type args. Default: `()`.
            kwargs (dict, optional): Task arguments of type kwargs. Default: `{}`.

        Returns:
            Task: `schemas.task.Task`

        Raises:
            ValueError: Invalid task status.
        """
        loop = asyncio.get_running_loop()
        asyncio_atexit.register(self.stop, loop=loop)
        asyncio_atexit.register(self.storage.stop, loop=loop)

        args, kwargs = args or (), kwargs or {}
        uuid = uuid4()
        uuid_str = str(uuid)
        created_at = time()
        model = TaskStatusNewSchema(
            task_name=task_name,
            priority=priority,
            created_at=created_at,
            updated_at=created_at,
            args=str(args),
            kwargs=str(kwargs),
        )

        if extra:
            model = self._dynamic_model(model=model, extra=extra)

        new_model = await self._plugin_trigger(
            "broker_add_before", broker=self, storage=self.storage, model=model
        )
        if new_model:
            model = new_model.get("model", model)

        if not isinstance(model, TaskStatusNewSchema):
            raise ValueError("Invalid task status.")

        await self.storage.add(uuid=uuid, task_status=model)
        reader, writer = await asyncio.open_connection(self.url, self.port)
        payload = asdict(model)
        payload.update({"uuid": uuid_str})
        writer.write(json.dumps(payload).encode())
        await writer.drain()
        with contextlib.suppress(Exception):
            writer.close()

        await self._plugin_trigger(
            "broker_add_after", broker=self, storage=self.storage, model=model
        )
        return Task(
            status=TaskStatusEnum.NEW.value,
            task_name=task_name,
            uuid=uuid,
            priority=priority,
            args=args,
            kwargs=kwargs,
            created_at=datetime.fromtimestamp(created_at),
            updated_at=datetime.fromtimestamp(created_at),
        )

    async def get(
        self,
        uuid: Annotated[
            UUID | str,
            Doc("""
                    UUID of the task.
                    """),
        ],
    ) -> Task | None:
        """
        Obtaining information about a task.

        Args:
            uuid (UUID|str): UUID of the task.

        Returns:
            Task|None: If there is task information, returns `schemas.task.Task`, otherwise `None`.
        """
        if isinstance(uuid, str):
            uuid = UUID(uuid)
        task = await self.storage.get(uuid=uuid)
        new_task = await self._plugin_trigger(
            "broker_get", broker=self, task=task, return_last=True
        )
        if new_task:
            task = new_task.get("task", task)
        return task

    async def update(
        self,
        **kwargs: Annotated[
            Any,
            Doc("""
                    Update arguments for storage type kwargs.
                    """),
        ],
    ) -> None:
        """
        Updates task information.

        Args:
            kwargs (dict, optional): task data of type kwargs.
        """
        new_kw = await self._plugin_trigger(
            "broker_update", broker=self, kw=kwargs, return_last=True
        )
        if new_kw:
            kwargs = new_kw.get("kw", kwargs)
        return await self.storage.update(**kwargs)

    async def start(
        self,
        worker: Annotated[
            BaseWorker,
            Doc("""
                    Worker class.
                    """),
        ],
    ) -> None:
        """
        Launches the broker.

        Args:
            worker (BaseWorker): Worker class.
        """
        await self._plugin_trigger("broker_start", broker=self, worker=worker)
        await self.storage.start()

        if self.config.delete_finished_tasks:
            await self.storage._delete_finished_tasks()

        if self.config.running_older_tasks:
            await self.storage._running_older_tasks(worker)

        self.client = await asyncio.start_server(
            self.handle_connection, self.url, self.port
        )

        self._listen_task = asyncio.create_task(
            self.listen(worker), name="broker-listen"
        )
        self._serve_task = asyncio.create_task(
            self.client.serve_forever(), name="broker-serve"
        )
        with contextlib.suppress(asyncio.CancelledError):
            await self._serve_task

    async def stop(self):
        """The broker stops."""
        await self._plugin_trigger("broker_stop", broker=self)
        self.running = False

        if self._listen_task and not self._listen_task.done():
            self.queue.put_nowait(None)

        if self.client:
            self.client.close()
            with contextlib.suppress(Exception):
                await self.client.wait_closed()

        if self._serve_task and not self._serve_task.done():
            self._serve_task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await self._serve_task

        if self._listen_task and not self._listen_task.done():
            with contextlib.suppress(asyncio.CancelledError):
                await self._listen_task

    async def remove_finished_task(
        self,
        task_broker: Annotated[
            TaskPrioritySchema,
            Doc("""
                    Priority task diagram.
                    """),
        ],
        model: Annotated[
            TaskStatusSuccessSchema | TaskStatusErrorSchema,
            Doc("""
                    Model of the task result.
                    """),
        ],
    ) -> None:
        """
        Updates storage data via the `self.storage.remove_finished_task` function.

        Args:
            task_broker (TaskPrioritySchema): The priority task schema.
            model (TaskStatusSuccessSchema | TaskStatusErrorSchema): Model of the task result.
        """
        new_model = await self._plugin_trigger(
            "broker_remove_finished_task",
            broker=self,
            storage=self.storage,
            model=model,
            return_last=True,
        )
        if new_model:
            model = new_model.get("model", model)

        await self.storage.remove_finished_task(task_broker, model)
        return

    async def _running_older_tasks(self, worker):
        await self._plugin_trigger(
            "broker_running_older_tasks", broker=self, worker=worker
        )
        return await self.storage._running_older_tasks(worker)

    async def flush_all(self) -> None:
        """Delete all data."""
        await self._plugin_trigger("broker_flush_all", broker=self)
        await self.storage.flush_all()

__init__(name='QueueTasks', url='127.0.0.1', port=6379, storage=None, log=None, config=None, events=None)

Initializing AsyncSocketBroker.

Parameters:

Name Type Description Default
name str

Project name. Default: QueueTasks.

'QueueTasks'
url str

URL to connect to the socket. Default: 127.0.0.1.

'127.0.0.1'
port int

Port to connect to the socket. Default: 6379.

6379
storage BaseStorage

Storage. Default: None.

None
log Logger

Logger. Default: None.

None
config QueueConfig

Config. Default: None.

None
events BaseEvents

Events. Default: qtasks.events.AsyncEvents.

None
Source code in src/qtasks/brokers/async_socket.py
 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
def __init__(
    self,
    name: Annotated[
        str,
        Doc("""
                Project name. This name is also used by the broker.

                Default: `QueueTasks`.
                """),
    ] = "QueueTasks",
    url: Annotated[
        str,
        Doc("""
                URL to connect to the socket.

                Default: `127.0.0.1`.
                """),
    ] = "127.0.0.1",
    port: Annotated[
        int,
        Doc("""
                Port for connecting to a socket.

                Default: `6379`.
                """),
    ] = 6379,
    storage: Annotated[
        Optional[BaseStorage],
        Doc("""
                Storage.

                Default: `AsyncRedisStorage`.
                """),
    ] = None,
    log: Annotated[
        Logger | None,
        Doc("""
                Logger.

                Default: `qtasks.logs.Logger`.
                """),
    ] = None,
    config: Annotated[
        QueueConfig | None,
        Doc("""
                Config.

                Default: `qtasks.configs.config.QueueConfig`.
                """),
    ] = None,
    events: Annotated[
        Optional[BaseEvents],
        Doc("""
                Events.

                Default: `qtasks.events.AsyncEvents`.
                """),
    ] = None,
):
    """
    Initializing AsyncSocketBroker.

    Args:
        name (str, optional): Project name. Default: `QueueTasks`.
        url (str, optional): URL to connect to the socket. Default: `127.0.0.1`.
        port (int, optional): Port to connect to the socket. Default: `6379`.
        storage (BaseStorage, optional): Storage. Default: `None`.
        log (Logger, optional): Logger. Default: `None`.
        config (QueueConfig, optional): Config. Default: `None`.
        events (BaseEvents, optional): Events. Default: `qtasks.events.AsyncEvents`.
    """
    self.url = url
    self.port = port
    storage = storage or AsyncRedisStorage(
        name=name, log=log, config=config, events=events
    )

    super().__init__(
        name=name, log=log, config=config, events=events, storage=storage
    )

    self.storage: BaseStorage[Literal[True]]

    self.events = self.events or AsyncEvents()

    self.client = None
    self.default_sleep = 0.01
    self.running = False

    self.queue = asyncio.Queue()
    self._serve_task: asyncio.Task | None = None
    self._listen_task: asyncio.Task | None = None

add(task_name, priority=0, extra=None, args=None, kwargs=None) async

Adds a task to the broker.

Parameters:

Name Type Description Default
task_name str

The name of the task.

required
priority int

Task priority. By default: 0.

0
extra dict

Additional task parameters. Default: None.

None
args tuple

Task arguments of type args. Default: ().

None
kwargs dict

Task arguments of type kwargs. Default: {}.

None

Returns:

Name Type Description
Task Task

schemas.task.Task

Raises:

Type Description
ValueError

Invalid task status.

Source code in src/qtasks/brokers/async_socket.py
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
async def add(
    self,
    task_name: Annotated[
        str,
        Doc("""
                Task name.
                """),
    ],
    priority: Annotated[
        int,
        Doc("""
                Task priority.

                Default: `0`.
                """),
    ] = 0,
    extra: Annotated[
        dict | None,
        Doc("""
                Additional task parameters.

                Default: `None`.
                """),
    ] = None,
    args: Annotated[
        tuple | None,
        Doc("""
                Task arguments of type args.

                Default: `()`.
                """),
    ] = None,
    kwargs: Annotated[
        dict | None,
        Doc("""
                Task arguments of type kwargs.

                Default: `{}`.
                """),
    ] = None,
) -> Task:
    """
    Adds a task to the broker.

    Args:
        task_name (str): The name of the task.
        priority (int, optional): Task priority. By default: 0.
        extra (dict, optional): Additional task parameters. Default: `None`.
        args (tuple, optional): Task arguments of type args. Default: `()`.
        kwargs (dict, optional): Task arguments of type kwargs. Default: `{}`.

    Returns:
        Task: `schemas.task.Task`

    Raises:
        ValueError: Invalid task status.
    """
    loop = asyncio.get_running_loop()
    asyncio_atexit.register(self.stop, loop=loop)
    asyncio_atexit.register(self.storage.stop, loop=loop)

    args, kwargs = args or (), kwargs or {}
    uuid = uuid4()
    uuid_str = str(uuid)
    created_at = time()
    model = TaskStatusNewSchema(
        task_name=task_name,
        priority=priority,
        created_at=created_at,
        updated_at=created_at,
        args=str(args),
        kwargs=str(kwargs),
    )

    if extra:
        model = self._dynamic_model(model=model, extra=extra)

    new_model = await self._plugin_trigger(
        "broker_add_before", broker=self, storage=self.storage, model=model
    )
    if new_model:
        model = new_model.get("model", model)

    if not isinstance(model, TaskStatusNewSchema):
        raise ValueError("Invalid task status.")

    await self.storage.add(uuid=uuid, task_status=model)
    reader, writer = await asyncio.open_connection(self.url, self.port)
    payload = asdict(model)
    payload.update({"uuid": uuid_str})
    writer.write(json.dumps(payload).encode())
    await writer.drain()
    with contextlib.suppress(Exception):
        writer.close()

    await self._plugin_trigger(
        "broker_add_after", broker=self, storage=self.storage, model=model
    )
    return Task(
        status=TaskStatusEnum.NEW.value,
        task_name=task_name,
        uuid=uuid,
        priority=priority,
        args=args,
        kwargs=kwargs,
        created_at=datetime.fromtimestamp(created_at),
        updated_at=datetime.fromtimestamp(created_at),
    )

flush_all() async

Delete all data.

Source code in src/qtasks/brokers/async_socket.py
520
521
522
523
async def flush_all(self) -> None:
    """Delete all data."""
    await self._plugin_trigger("broker_flush_all", broker=self)
    await self.storage.flush_all()

get(uuid) async

Obtaining information about a task.

Parameters:

Name Type Description Default
uuid UUID | str

UUID of the task.

required

Returns:

Type Description
Task | None

Task|None: If there is task information, returns schemas.task.Task, otherwise None.

Source code in src/qtasks/brokers/async_socket.py
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
async def get(
    self,
    uuid: Annotated[
        UUID | str,
        Doc("""
                UUID of the task.
                """),
    ],
) -> Task | None:
    """
    Obtaining information about a task.

    Args:
        uuid (UUID|str): UUID of the task.

    Returns:
        Task|None: If there is task information, returns `schemas.task.Task`, otherwise `None`.
    """
    if isinstance(uuid, str):
        uuid = UUID(uuid)
    task = await self.storage.get(uuid=uuid)
    new_task = await self._plugin_trigger(
        "broker_get", broker=self, task=task, return_last=True
    )
    if new_task:
        task = new_task.get("task", task)
    return task

handle_connection(reader, writer) async

Handles an incoming connection.

Parameters:

Name Type Description Default
reader StreamReader

Reader for incoming data.

required
writer StreamWriter

Writer for outgoing data.

required
Source code in src/qtasks/brokers/async_socket.py
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
async def handle_connection(
    self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
    """
    Handles an incoming connection.

    Args:
        reader(asyncio.StreamReader): Reader for incoming data.
        writer(asyncio.StreamWriter): Writer for outgoing data.
    """
    try:
        data = await reader.read(4096)
        message = json.loads(data.decode())
        task_name = message["task_name"]
        uuid = message["uuid"]
        priority = message["priority"]
        args = message.get("args", ())
        kwargs = message.get("kwargs", {})
        created_at = message["created_at"]

        await self.storage.add(
            uuid=uuid,
            task_status=TaskStatusNewSchema(
                task_name=task_name,
                priority=priority,
                args=args,
                kwargs=kwargs,
                created_at=created_at,
                updated_at=created_at,
            ),
        )

        await self.queue.put((task_name, uuid, priority))
        writer.write(b"OK")
        await writer.drain()
    finally:
        writer.close()
        with contextlib.suppress(Exception):
            await writer.wait_closed()

listen(worker) async

Listens to the socket queue and transfers tasks to the worker.

Parameters:

Name Type Description Default
worker BaseWorker

Worker class.

required

Raises:

Type Description
KeyError

Task not found.

Source code in src/qtasks/brokers/async_socket.py
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
async def listen(
    self,
    worker: Annotated[
        BaseWorker[Literal[True]],
        Doc("""
                Worker class.
                """),
    ],
):
    """
    Listens to the socket queue and transfers tasks to the worker.

    Args:
        worker (BaseWorker): Worker class.

    Raises:
        KeyError: Task not found.
    """
    await self._plugin_trigger("broker_listen_start", broker=self, worker=worker)
    self.running = True

    while self.running:
        try:
            item = await self.queue.get()
        except asyncio.CancelledError:
            break
        if item is None:
            break

        task_name, uuid, priority = item
        model_get = await self.get(uuid=uuid)
        if not model_get:
            raise KeyError(f"Task not found: {uuid}")

        args, kwargs, created_at = (
            model_get.args or (),
            model_get.kwargs or {},
            model_get.created_at.timestamp(),
        )

        await self.storage.add_process(f"{task_name}:{uuid}:{priority}", priority)

        if self.log:
            self.log.info(f"Received new task: {uuid}")
        new_args = await self._plugin_trigger(
            "broker_add_worker",
            broker=self,
            worker=worker,
            task_name=task_name,
            uuid=uuid,
            priority=int(priority),
            args=args,
            kw=kwargs,
            created_at=created_at,
            return_last=True,
        )
        if new_args:
            task_name = new_args.get("task_name", task_name)
            uuid = new_args.get("uuid", uuid)
            priority = new_args.get("priority", priority)
            args = new_args.get("args", args)
            kwargs = new_args.get("kw", kwargs)
            created_at = new_args.get("created_at", created_at)

        await worker.add(
            name=task_name,
            uuid=uuid,
            priority=int(priority),
            args=args,
            kwargs=kwargs,
            created_at=created_at,
        )
        return

remove_finished_task(task_broker, model) async

Updates storage data via the self.storage.remove_finished_task function.

Parameters:

Name Type Description Default
task_broker TaskPrioritySchema

The priority task schema.

required
model TaskStatusSuccessSchema | TaskStatusErrorSchema

Model of the task result.

required
Source code in src/qtasks/brokers/async_socket.py
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
505
506
507
508
509
510
511
512
async def remove_finished_task(
    self,
    task_broker: Annotated[
        TaskPrioritySchema,
        Doc("""
                Priority task diagram.
                """),
    ],
    model: Annotated[
        TaskStatusSuccessSchema | TaskStatusErrorSchema,
        Doc("""
                Model of the task result.
                """),
    ],
) -> None:
    """
    Updates storage data via the `self.storage.remove_finished_task` function.

    Args:
        task_broker (TaskPrioritySchema): The priority task schema.
        model (TaskStatusSuccessSchema | TaskStatusErrorSchema): Model of the task result.
    """
    new_model = await self._plugin_trigger(
        "broker_remove_finished_task",
        broker=self,
        storage=self.storage,
        model=model,
        return_last=True,
    )
    if new_model:
        model = new_model.get("model", model)

    await self.storage.remove_finished_task(task_broker, model)
    return

start(worker) async

Launches the broker.

Parameters:

Name Type Description Default
worker BaseWorker

Worker class.

required
Source code in src/qtasks/brokers/async_socket.py
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
async def start(
    self,
    worker: Annotated[
        BaseWorker,
        Doc("""
                Worker class.
                """),
    ],
) -> None:
    """
    Launches the broker.

    Args:
        worker (BaseWorker): Worker class.
    """
    await self._plugin_trigger("broker_start", broker=self, worker=worker)
    await self.storage.start()

    if self.config.delete_finished_tasks:
        await self.storage._delete_finished_tasks()

    if self.config.running_older_tasks:
        await self.storage._running_older_tasks(worker)

    self.client = await asyncio.start_server(
        self.handle_connection, self.url, self.port
    )

    self._listen_task = asyncio.create_task(
        self.listen(worker), name="broker-listen"
    )
    self._serve_task = asyncio.create_task(
        self.client.serve_forever(), name="broker-serve"
    )
    with contextlib.suppress(asyncio.CancelledError):
        await self._serve_task

stop() async

The broker stops.

Source code in src/qtasks/brokers/async_socket.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
async def stop(self):
    """The broker stops."""
    await self._plugin_trigger("broker_stop", broker=self)
    self.running = False

    if self._listen_task and not self._listen_task.done():
        self.queue.put_nowait(None)

    if self.client:
        self.client.close()
        with contextlib.suppress(Exception):
            await self.client.wait_closed()

    if self._serve_task and not self._serve_task.done():
        self._serve_task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self._serve_task

    if self._listen_task and not self._listen_task.done():
        with contextlib.suppress(asyncio.CancelledError):
            await self._listen_task

update(**kwargs) async

Updates task information.

Parameters:

Name Type Description Default
kwargs dict

task data of type kwargs.

{}
Source code in src/qtasks/brokers/async_socket.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
async def update(
    self,
    **kwargs: Annotated[
        Any,
        Doc("""
                Update arguments for storage type kwargs.
                """),
    ],
) -> None:
    """
    Updates task information.

    Args:
        kwargs (dict, optional): task data of type kwargs.
    """
    new_kw = await self._plugin_trigger(
        "broker_update", broker=self, kw=kwargs, return_last=True
    )
    if new_kw:
        kwargs = new_kw.get("kw", kwargs)
    return await self.storage.update(**kwargs)