Skip to content

Commit 06d924b

Browse files
authored
feat: hiredis optional; add option to run in existing process
feat: `hiredis` optional; add option to run in existing process
2 parents d1551d2 + 95dd762 commit 06d924b

7 files changed

Lines changed: 276 additions & 291 deletions

File tree

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ repos:
2828
- id: codespell
2929
exclude: "pdm.lock"
3030
- repo: https://github.com/psf/black
31-
rev: 23.9.1
31+
rev: 23.10.0
3232
hooks:
3333
- id: black
3434
args: [--config=./pyproject.toml]

litestar_saq/base.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@
1313

1414
if TYPE_CHECKING:
1515
from collections.abc import Collection
16-
from signal import Signals
1716

1817
from redis.asyncio.client import Redis
19-
from saq.types import DumpType, Function, LoadType, PartialTimersDict, ReceivesContext
18+
from saq.types import DumpType as SaqDumpType
19+
from saq.types import Function, LoadType, PartialTimersDict, ReceivesContext
20+
21+
from litestar_saq.config import DumpType
2022

2123

2224
@dataclass
@@ -64,7 +66,7 @@ def __init__(
6466
queue_namespace: str | None = None,
6567
) -> None:
6668
self._namespace = queue_namespace if queue_namespace is not None else "saq"
67-
super().__init__(redis, name, dump, load, max_concurrent_ops)
69+
super().__init__(redis, name, cast("SaqDumpType", dump), load, max_concurrent_ops)
6870

6971
def namespace(self, key: str) -> str:
7072
"""Make the namespace unique per app."""
@@ -85,8 +87,10 @@ def job_id(self, job_key: str) -> str:
8587
class Worker(SaqWorker):
8688
"""Worker."""
8789

90+
"""
8891
# same issue: https://github.com/samuelcolvin/arq/issues/182
8992
SIGNALS: list[Signals] = []
93+
"""
9094

9195
def __init__(
9296
self,
@@ -101,7 +105,9 @@ def __init__(
101105
after_process: ReceivesContext | None = None,
102106
timers: PartialTimersDict | None = None,
103107
dequeue_timeout: float = 0,
108+
separate_process: bool = True,
104109
) -> None:
110+
self.separate_process = separate_process
105111
super().__init__(
106112
cast("SaqQueue", queue),
107113
functions,
@@ -117,5 +123,13 @@ def __init__(
117123

118124
async def on_app_startup(self) -> None:
119125
"""Attach the worker to the running event loop."""
120-
loop = asyncio.get_running_loop()
121-
_ = loop.create_task(self.start())
126+
if not self.separate_process:
127+
self.SIGNALS = []
128+
loop = asyncio.get_running_loop()
129+
_ = loop.create_task(self.start())
130+
131+
async def on_app_shutdown(self) -> None:
132+
"""Attach the worker to the running event loop."""
133+
if not self.separate_process:
134+
loop = asyncio.get_running_loop()
135+
_ = loop.create_task(self.stop())

litestar_saq/cli.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,10 +137,11 @@ def run_worker_process(workers: list[Worker], logging_config: BaseLoggingConfig
137137
logging_config.configure()
138138
try:
139139
for i, worker_instance in enumerate(workers):
140-
if i < len(workers) - 1:
141-
loop.create_task(worker_instance.start())
142-
else:
143-
loop.run_until_complete(worker_instance.start())
140+
if worker_instance.separate_process:
141+
if i < len(workers) - 1:
142+
loop.create_task(worker_instance.start())
143+
else:
144+
loop.run_until_complete(worker_instance.start())
144145
except KeyboardInterrupt:
145146
for worker in workers:
146147
loop.run_until_complete(worker.stop())

litestar_saq/config.py

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
from dataclasses import dataclass, field
44
from pathlib import Path
5-
from typing import TYPE_CHECKING, Collection, Mapping, TypeVar, cast
5+
from typing import TYPE_CHECKING, Callable, Collection, Dict, Mapping, TypeVar, cast
66

77
from litestar.exceptions import ImproperlyConfiguredException
88
from litestar.serialization import decode_json, encode_json
99
from redis.asyncio import ConnectionPool, Redis
1010
from saq.queue import Queue as SaqQueue
11-
from saq.types import DumpType, LoadType, PartialTimersDict, QueueInfo, QueueStats, ReceivesContext
11+
from saq.types import DumpType as SaqDumpType
12+
from saq.types import LoadType, PartialTimersDict, QueueInfo, QueueStats, ReceivesContext
1213

1314
from litestar_saq._util import import_string, module_to_os_path
1415
from litestar_saq.base import CronJob, Job, Queue, Worker
@@ -22,6 +23,7 @@
2223

2324
T = TypeVar("T")
2425
TaskQueue = Queue | SaqQueue
26+
DumpType = SaqDumpType | Callable[[Dict], bytes]
2527

2628

2729
def serializer(value: Any) -> str:
@@ -112,16 +114,6 @@ def signature_namespace(self) -> dict[str, Any]:
112114
"TaskQueues": TaskQueues,
113115
}
114116

115-
async def on_shutdown(self, app: Litestar) -> None:
116-
"""Disposes of the SAQ Workers.
117-
118-
Args:
119-
app: The ``Litestar`` instance.
120-
121-
Returns:
122-
None
123-
"""
124-
125117
def provide_queues(self, state: State) -> TaskQueues:
126118
"""Provide the configured job queues.
127119
@@ -161,7 +153,7 @@ def get_queues(self) -> TaskQueues:
161153
queue_namespace=self.namespace,
162154
redis=self.get_redis(),
163155
name=queue_config.name,
164-
dump=self.json_serializer,
156+
dump=cast("SaqDumpType", self.json_serializer),
165157
load=self.json_deserializer,
166158
max_concurrent_ops=queue_config.max_concurrent_ops,
167159
)

litestar_saq/plugin.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,12 @@ def on_app_init(self, app_config: AppConfig) -> AppConfig:
6666
)
6767
app_config.route_handlers.append(build_controller(self._config.web_path))
6868
app_config.on_startup.append(self._config.update_app_state)
69-
app_config.on_shutdown.append(self._config.on_shutdown)
7069
app_config.signature_namespace.update(self._config.signature_namespace)
71-
70+
workers = self.get_workers()
71+
for worker in workers:
72+
if not worker.separate_process:
73+
app_config.on_startup.append(worker.on_app_startup)
74+
app_config.on_shutdown.append(worker.on_app_shutdown)
7275
return app_config
7376

7477
def get_workers(self) -> list[Worker]:
@@ -88,6 +91,7 @@ def get_workers(self) -> list[Worker]:
8891
after_process=queue_config.after_process,
8992
timers=queue_config.timers,
9093
dequeue_timeout=queue_config.dequeue_timeout,
94+
separate_process=queue_config.separate_process,
9195
)
9296
for queue_config in self._config.queue_configs
9397
)

0 commit comments

Comments
 (0)