grindsharp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
grindsharp/worker.py ADDED
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import socket
5
+ import threading
6
+ import time
7
+ import traceback
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from datetime import datetime, timezone
10
+ from typing import Any
11
+
12
+ from .app import Jobs
13
+ from .errors import TaskNotFound
14
+ from .models import Job
15
+
16
+ log = logging.getLogger("grindsharp")
17
+
18
+
19
+ class Worker:
20
+ def __init__(
21
+ self,
22
+ jobs: Jobs,
23
+ *,
24
+ poll_interval: float = 1.0,
25
+ concurrency: int = 1,
26
+ stale_timeout_seconds: int = 300,
27
+ worker_name: str | None = None,
28
+ ):
29
+ self.jobs = jobs
30
+ self.poll_interval = max(0.05, poll_interval)
31
+ self.concurrency = max(1, concurrency)
32
+ self.stale_timeout_seconds = stale_timeout_seconds
33
+ self.worker_name = worker_name or f"{socket.gethostname()}:{threading.get_ident()}"
34
+ self._stop = threading.Event()
35
+
36
+ def stop(self) -> None:
37
+ self._stop.set()
38
+
39
+ def run(self, *, max_jobs: int | None = None) -> None:
40
+ """Run forever (until stop() or KeyboardInterrupt)."""
41
+ log.info("worker starting name=%s concurrency=%s", self.worker_name, self.concurrency)
42
+ handled = 0
43
+ try:
44
+ with ThreadPoolExecutor(max_workers=self.concurrency, thread_name_prefix="grindsharp") as pool:
45
+ in_flight: set[Any] = set()
46
+ while not self._stop.is_set():
47
+ try:
48
+ self.jobs.tick()
49
+ except Exception:
50
+ log.exception("periodic tick failed")
51
+ self.jobs.store.recover_stale(timeout_seconds=self.stale_timeout_seconds)
52
+
53
+ done = {f for f in in_flight if f.done()}
54
+ for f in done:
55
+ try:
56
+ f.result()
57
+ except Exception:
58
+ log.exception("worker future crashed unexpectedly")
59
+ in_flight -= done
60
+
61
+ if max_jobs is not None and handled >= max_jobs and not in_flight:
62
+ break
63
+
64
+ capacity = self.concurrency - len(in_flight)
65
+ if max_jobs is not None:
66
+ capacity = min(capacity, max(0, max_jobs - handled))
67
+ claimed = 0
68
+ for _ in range(max(0, capacity)):
69
+ job = self.jobs.store.claim_next(self.worker_name)
70
+ if not job:
71
+ break
72
+ claimed += 1
73
+ handled += 1
74
+ in_flight.add(pool.submit(self._execute_job, job))
75
+
76
+ if claimed == 0 and not in_flight:
77
+ self._stop.wait(self.poll_interval)
78
+ finally:
79
+ log.info("worker stopped name=%s handled=%s", self.worker_name, handled)
80
+
81
+ def run_once(self) -> Job | None:
82
+ """Claim and execute at most one job. Returns the job if one was claimed."""
83
+ try:
84
+ self.jobs.tick()
85
+ except Exception:
86
+ log.exception("periodic tick failed")
87
+ self.jobs.store.recover_stale(timeout_seconds=self.stale_timeout_seconds)
88
+ job = self.jobs.store.claim_next(self.worker_name)
89
+ if not job:
90
+ return None
91
+ self._execute_job(job)
92
+ return self.jobs.store.get(job.id)
93
+
94
+ def _execute_job(self, job: Job) -> None:
95
+ log.info("job started id=%s name=%s attempt=%s", job.id, job.name, job.attempts)
96
+ try:
97
+ result = self.jobs.run_job(job)
98
+ # only store JSON-safe results; ignore non-serializable results
99
+ safe_result = _safe_result(result)
100
+ self.jobs.store.mark_succeeded(job.id, result=safe_result)
101
+ log.info("job succeeded id=%s name=%s", job.id, job.name)
102
+ except TaskNotFound as e:
103
+ # Force dead: retrying won't help if the task isn't registered.
104
+ dead_job = Job(
105
+ id=job.id,
106
+ name=job.name,
107
+ payload=job.payload,
108
+ status=job.status,
109
+ run_at=job.run_at,
110
+ attempts=job.max_retries + 1,
111
+ max_retries=job.max_retries,
112
+ timeout_seconds=job.timeout_seconds,
113
+ created_at=job.created_at,
114
+ updated_at=job.updated_at,
115
+ started_at=job.started_at,
116
+ finished_at=job.finished_at,
117
+ locked_by=job.locked_by,
118
+ locked_at=job.locked_at,
119
+ last_error=str(e),
120
+ )
121
+ self.jobs.store.mark_failed(dead_job, error=str(e), retry_backoff_seconds=0)
122
+ log.error("job dead (no task registered) id=%s name=%s error=%s", job.id, job.name, e)
123
+ except Exception:
124
+ err = traceback.format_exc()
125
+ status = self.jobs.store.mark_failed(
126
+ job,
127
+ error=err,
128
+ retry_backoff_seconds=getattr(self.jobs.tasks.get(job.name), "retry_backoff_seconds", 30),
129
+ )
130
+ log.warning("job %s id=%s name=%s", status, job.id, job.name)
131
+
132
+
133
+ def _safe_result(result: Any) -> Any:
134
+ if result is None:
135
+ return None
136
+ try:
137
+ import json
138
+
139
+ json.dumps(result)
140
+ return result
141
+ except Exception:
142
+ return repr(result)
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: grindsharp
3
+ Version: 0.1.0
4
+ Summary: SQLite-first background jobs for Python. No Redis required.
5
+ Author: REDX Contributors
6
+ License: MIT
7
+ Keywords: background-jobs,queue,sqlite,worker,tasks,scheduler
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.4; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # Grindsharp
23
+
24
+ Most Python apps eventually need to do stuff in the background: send an email, process an upload, call a webhook, generate a report, retry something that flopped.
25
+
26
+ The usual setup works, but it can be overkill for a small app — Redis, a broker, worker containers, extra config, the whole mission.
27
+
28
+ Grindsharp is for the common case: you just want background jobs that are reliable and easy to run.
29
+
30
+ It uses **SQLite** by default. No Redis needed.
31
+
32
+ ## What you get
33
+
34
+ - A simple `@task` decorator
35
+ - `enqueue()`, `enqueue_in()`, `enqueue_at()`
36
+ - Retries with backoff
37
+ - A worker process (with basic concurrency)
38
+ - SQLite-backed job storage (WAL mode)
39
+ - Job status, crash recovery, and idempotent job IDs
40
+ - A small CLI for listing/retrying/stats
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install -e .
46
+ ```
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ # jobs.py
52
+ from grindsharp import Jobs
53
+
54
+ jobs = Jobs("jobs.db")
55
+
56
+ @jobs.task(retries=3, retry_backoff_seconds=30, timeout_seconds=60)
57
+ def send_receipt_email(user_id: int, invoice_id: str) -> None:
58
+ print(f"send receipt to user={user_id} invoice={invoice_id}")
59
+ ```
60
+
61
+ Enqueue work from your app:
62
+
63
+ ```python
64
+ from jobs import send_receipt_email
65
+
66
+ # run in the background
67
+ send_receipt_email.enqueue(user_id=42, invoice_id="inv_123")
68
+
69
+ # run later
70
+ send_receipt_email.enqueue_in(600, user_id=42, invoice_id="inv_123")
71
+
72
+ # avoid duplicates (idempotent job id)
73
+ send_receipt_email.enqueue(
74
+ user_id=42,
75
+ invoice_id="inv_123",
76
+ job_id="receipt:inv_123",
77
+ )
78
+
79
+ # if you want the existing job back instead of an error:
80
+ send_receipt_email.enqueue(
81
+ user_id=42,
82
+ invoice_id="inv_123",
83
+ job_id="receipt:inv_123",
84
+ if_exists="ignore",
85
+ )
86
+ ```
87
+
88
+ Run a worker:
89
+
90
+ ```bash
91
+ grindsharp worker --app jobs:jobs --db jobs.db
92
+ ```
93
+
94
+ That’s it: your web request returns quickly, and the worker handles the job.
95
+
96
+ ## FastAPI example
97
+
98
+ ```python
99
+ from fastapi import FastAPI
100
+ from grindsharp import Jobs
101
+
102
+ app = FastAPI()
103
+ jobs = Jobs("jobs.db")
104
+
105
+ @jobs.task(retries=3, retry_backoff_seconds=10)
106
+ def send_welcome_email(email: str) -> None:
107
+ ...
108
+
109
+ @app.post("/signup")
110
+ def signup(email: str):
111
+ send_welcome_email.enqueue(email=email)
112
+ return {"ok": True}
113
+ ```
114
+
115
+ Run the API and worker as separate processes:
116
+
117
+ ```bash
118
+ uvicorn app:app
119
+ grindsharp worker --app app:jobs --db jobs.db
120
+ ```
121
+
122
+ ## How jobs behave
123
+
124
+ - **Durable:** jobs are saved in SQLite, so they survive app restarts.
125
+ - **At-least-once:** if a worker crashes mid-job, that job might run again. So write tasks like they may be retried (because they might).
126
+ - **Retries:** failed jobs retry with backoff (`retry_backoff_seconds * attempt`).
127
+ - **Dead jobs:** when retries run out, the job gets marked `dead` and keeps the last error so you can see what happened.
128
+ - **Crash recovery:** stale `running` jobs get moved back to `pending` after a timeout.
129
+
130
+ ## CLI
131
+
132
+ ```bash
133
+ # run a worker
134
+ grindsharp worker --app jobs:jobs --db jobs.db --concurrency 4
135
+
136
+ # process one job then exit (useful for debugging)
137
+ grindsharp worker --app jobs:jobs --db jobs.db --once
138
+
139
+ # inspect jobs
140
+ grindsharp --db jobs.db list --status pending --limit 20
141
+ grindsharp --db jobs.db stats
142
+
143
+ # retry a dead/failed job
144
+ grindsharp --db jobs.db retry <job_id>
145
+
146
+ # clean up old succeeded jobs
147
+ grindsharp --db jobs.db purge --status succeeded --older-than-seconds 86400
148
+ ```
149
+
150
+ ## When Grindsharp is a good fit
151
+
152
+ Use it when you want background jobs without extra infrastructure:
153
+
154
+ - small/medium web apps
155
+ - internal tools and SaaS MVPs
156
+ - single-server deployments
157
+ - low-to-moderate job volume
158
+
159
+ ## When to use something else
160
+
161
+ - you need lots of workers spread across many machines
162
+ - you already run Redis/RabbitMQ and need the fancy queue features
163
+ - you need complex workflow/DAG orchestration
164
+
165
+ For many apps, a Postgres/Redis-backed queue is the next step up. Grindsharp is here to make the simple case easy.
166
+
167
+ ## Postgres / Redis backends
168
+
169
+ SQLite is the default. When you outgrow a single-node setup, Grindsharp can use a different store:
170
+
171
+ ```python
172
+ from grindsharp import Jobs, PostgresJobStore, RedisJobStore
173
+
174
+ # Postgres (pass a DBAPI connect callable, e.g. psycopg.connect)
175
+ jobs = Jobs(store=PostgresJobStore(connect=lambda: psycopg.connect(DB_URL)))
176
+
177
+ # Redis (pass a redis-py compatible client)
178
+ jobs = Jobs(store=RedisJobStore(redis.Redis.from_url(REDIS_URL)))
179
+ ```
180
+
181
+ These adapters keep the same `Jobs`/`Worker` API. Use SQLite for simple/local apps, Postgres for durable multi-worker SQL setups, and Redis for fast queue-style workloads.
182
+
183
+ ## Design notes
184
+
185
+ - Jobs are **at-least-once** (tasks should be idempotent).
186
+ - Payloads must be **JSON-serializable**.
187
+ - SQLite makes this a great fit for **small/medium single-node apps**. When you need distributed throughput, grow to a Postgres/Redis-style queue.
188
+
189
+ ## Development
190
+
191
+ ```bash
192
+ pip install -e .[dev]
193
+ pytest
194
+ ```
195
+
196
+ Integration tests (real services):
197
+
198
+ ```bash
199
+ docker compose -f docker-compose.integration.yml up -d
200
+ python -m pip install psycopg[binary] redis
201
+ python scripts/integration_test_backends.py
202
+ ```
203
+
204
+ This runs the same enqueue/retry/dead-job flow against real Postgres and Redis services.
@@ -0,0 +1,17 @@
1
+ grindsharp/__init__.py,sha256=_5e_kkMKfrIaYSU6ttcOblfyPrnkwiLyBhvW4_fWPns,504
2
+ grindsharp/__main__.py,sha256=o_f4co2aGmCc41GH28AM5kbPh_JPiAyzsDGStZlxd80,107
3
+ grindsharp/app.py,sha256=_J5aHQxJkyMDW12slUoPs5OkyhHqEqS9opm1cA81H4k,7296
4
+ grindsharp/cli.py,sha256=Zin1ABuAMc5wUSlUMcW2g-F41jIloOWsgp5Y4P2TH6I,4511
5
+ grindsharp/errors.py,sha256=ctK_FMkRQWNqWuUNgcudAnF7duUr2EvV2BeKRHEZOVk,381
6
+ grindsharp/models.py,sha256=Du26KBASSgYA94HQ0lWb5NlQYKE1_1Jg7B782r-v050,1530
7
+ grindsharp/postgres.py,sha256=kBP8Lw1PSj8-0AWVYFP_YeJp8R5HWC1sE_XLCGkCjP0,9573
8
+ grindsharp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ grindsharp/redis_store.py,sha256=lEtZh36PyhOfC74_0b8jtvl_d9FtOGW4VvXaCSJQpWY,10692
10
+ grindsharp/store.py,sha256=KXL-dIRtznjykSa2BSFNNx9u4ViwHs0SAnh8JcuW1uc,13117
11
+ grindsharp/worker.py,sha256=oFzLc8YeV3YaRj85kAyDDTuGHmzGFLzKKaslNwBJZOo,5357
12
+ grindsharp-0.1.0.dist-info/licenses/LICENSE,sha256=xqlhK2dYD4XQ0q8RVsRpcpTyqR5AMUzga2Ta0PJpTrU,1078
13
+ grindsharp-0.1.0.dist-info/METADATA,sha256=LR3AaI8iVwhCrfIQru-0v-So5nglrkUqczHsspr6fro,5984
14
+ grindsharp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ grindsharp-0.1.0.dist-info/entry_points.txt,sha256=lr8ZvmOAvdkZCwmC-8LMiTLmptwlKzgSaxDW10NAjJw,51
16
+ grindsharp-0.1.0.dist-info/top_level.txt,sha256=6dyg3k243iDKyPAJy4waPNQmR5yLFDb1CeYuOzqEuQQ,11
17
+ grindsharp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ grindsharp = grindsharp.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 REDX Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ grindsharp