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.
@@ -0,0 +1,250 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Any
7
+
8
+ from .errors import DuplicateJob
9
+ from .models import Job
10
+
11
+
12
+ def _utcnow() -> datetime:
13
+ return datetime.now(timezone.utc)
14
+
15
+
16
+ def _dt(value: datetime | str | float | int | None) -> datetime | None:
17
+ if value is None:
18
+ return None
19
+ if isinstance(value, datetime):
20
+ return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
21
+ if isinstance(value, (int, float)):
22
+ return datetime.fromtimestamp(float(value), tz=timezone.utc)
23
+ dt = datetime.fromisoformat(str(value))
24
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
25
+
26
+
27
+ def _iso(value: datetime | None) -> str | None:
28
+ if value is None:
29
+ return None
30
+ if value.tzinfo is None:
31
+ value = value.replace(tzinfo=timezone.utc)
32
+ return value.isoformat()
33
+
34
+
35
+ class RedisJobStore:
36
+ """Redis-backed job store.
37
+
38
+ Requires a redis-py compatible client (e.g. redis.Redis).
39
+ Uses sorted sets for scheduling and hashes for job payloads.
40
+
41
+ This is a simple MVP store for single-queue background jobs.
42
+ """
43
+
44
+ def __init__(self, redis_client: Any, *, prefix: str = "grindsharp"):
45
+ self.r = redis_client
46
+ self.prefix = prefix
47
+
48
+ def _k(self, *parts: str) -> str:
49
+ return ":".join([self.prefix, *parts])
50
+
51
+ def close(self) -> None:
52
+ close = getattr(self.r, "close", None)
53
+ if close:
54
+ close()
55
+
56
+ def enqueue(self, *, job_id: str, name: str, payload: dict[str, Any], run_at: datetime | None = None, max_retries: int = 0, timeout_seconds: int | None = None, priority: int = 0, if_exists: str = "error") -> Job:
57
+ now = _utcnow()
58
+ run_at = _dt(run_at) or now
59
+ key = self._k("job", job_id)
60
+ if self.r.exists(key):
61
+ if if_exists == "ignore":
62
+ return self.get(job_id) # type: ignore[return-value]
63
+ raise DuplicateJob(f"Job with id '{job_id}' already exists")
64
+ data = {
65
+ "id": job_id,
66
+ "name": name,
67
+ "payload": json.dumps(payload),
68
+ "status": "pending",
69
+ "run_at": _iso(run_at),
70
+ "attempts": "0",
71
+ "max_retries": str(max_retries),
72
+ "timeout_seconds": "" if timeout_seconds is None else str(timeout_seconds),
73
+ "priority": str(int(priority)),
74
+ "created_at": _iso(now),
75
+ "updated_at": _iso(now),
76
+ "started_at": "",
77
+ "finished_at": "",
78
+ "locked_by": "",
79
+ "locked_at": "",
80
+ "last_error": "",
81
+ "result": "",
82
+ }
83
+ pipe = self.r.pipeline()
84
+ pipe.hset(key, mapping=data)
85
+ # score: run_at timestamp minus priority*small epsilon for ordering
86
+ score = run_at.timestamp() - (int(priority) * 0.001)
87
+ pipe.zadd(self._k("pending"), {job_id: score})
88
+ pipe.sadd(self._k("jobs"), job_id)
89
+ pipe.execute()
90
+ return self.get(job_id) # type: ignore[return-value]
91
+
92
+ def get(self, job_id: str) -> Job | None:
93
+ data = self.r.hgetall(self._k("job", job_id))
94
+ if not data:
95
+ return None
96
+ # redis-py may return bytes
97
+ d = { (k.decode() if isinstance(k, bytes) else k): (v.decode() if isinstance(v, bytes) else v) for k, v in data.items() }
98
+ return Job(
99
+ id=d["id"],
100
+ name=d["name"],
101
+ payload=json.loads(d.get("payload") or "{}"),
102
+ status=d.get("status", "pending"),
103
+ run_at=_dt(d.get("run_at")),
104
+ attempts=int(d.get("attempts") or 0),
105
+ max_retries=int(d.get("max_retries") or 0),
106
+ timeout_seconds=int(d["timeout_seconds"]) if d.get("timeout_seconds") else None,
107
+ priority=int(d.get("priority") or 0),
108
+ created_at=_dt(d.get("created_at")),
109
+ updated_at=_dt(d.get("updated_at")),
110
+ started_at=_dt(d.get("started_at") or None),
111
+ finished_at=_dt(d.get("finished_at") or None),
112
+ locked_by=d.get("locked_by") or None,
113
+ locked_at=_dt(d.get("locked_at") or None),
114
+ last_error=d.get("last_error") or None,
115
+ result=json.loads(d["result"]) if d.get("result") else None,
116
+ )
117
+
118
+ def list_jobs(self, *, status: str | None = None, limit: int = 100) -> list[Job]:
119
+ ids = list(self.r.smembers(self._k("jobs")))
120
+ jobs = []
121
+ for raw in ids:
122
+ jid = raw.decode() if isinstance(raw, bytes) else raw
123
+ job = self.get(jid)
124
+ if job and (status is None or job.status == status):
125
+ jobs.append(job)
126
+ jobs.sort(key=lambda j: j.created_at, reverse=True)
127
+ return jobs[:limit]
128
+
129
+ def claim_next(self, worker_id: str, *, now: datetime | None = None) -> Job | None:
130
+ now = _dt(now) or _utcnow()
131
+ # Prefer Lua for atomic claim; fall back to simple non-atomic claim.
132
+ try:
133
+ lua = """
134
+ local pending = KEYS[1]
135
+ local now = tonumber(ARGV[1])
136
+ local ids = redis.call('ZRANGEBYSCORE', pending, '-inf', now, 'LIMIT', 0, 1)
137
+ if #ids == 0 then return nil end
138
+ local id = ids[1]
139
+ redis.call('ZREM', pending, id)
140
+ return id
141
+ """
142
+ jid = self.r.eval(lua, 1, self._k("pending"), now.timestamp())
143
+ except Exception:
144
+ ids = self.r.zrangebyscore(self._k("pending"), "-inf", now.timestamp(), start=0, num=1)
145
+ if not ids:
146
+ return None
147
+ jid = ids[0]
148
+ self.r.zrem(self._k("pending"), jid)
149
+ if not jid:
150
+ return None
151
+ if isinstance(jid, bytes):
152
+ jid = jid.decode()
153
+ key = self._k("job", jid)
154
+ pipe = self.r.pipeline()
155
+ pipe.hgetall(key)
156
+ pipe.hincrby(key, "attempts", 1)
157
+ pipe.hset(key, mapping={"status": "running", "locked_by": worker_id, "locked_at": _iso(now), "started_at": _iso(now), "updated_at": _iso(now)})
158
+ pipe.sadd(self._k("running"), jid)
159
+ pipe.execute()
160
+ return self.get(jid)
161
+
162
+ def mark_succeeded(self, job_id: str, *, result: Any = None, now: datetime | None = None) -> None:
163
+ now = _dt(now) or _utcnow()
164
+ pipe = self.r.pipeline()
165
+ pipe.hset(self._k("job", job_id), mapping={"status": "succeeded", "finished_at": _iso(now), "updated_at": _iso(now), "locked_by": "", "locked_at": "", "last_error": "", "result": json.dumps(result) if result is not None else ""})
166
+ pipe.srem(self._k("running"), job_id)
167
+ pipe.execute()
168
+
169
+ def mark_failed(self, job: Job, *, error: str, now: datetime | None = None, retry_backoff_seconds: int = 0) -> str:
170
+ now = _dt(now) or _utcnow()
171
+ key = self._k("job", job.id)
172
+ if job.attempts <= job.max_retries:
173
+ run_at = now + timedelta(seconds=max(0, retry_backoff_seconds) * max(1, job.attempts))
174
+ pipe = self.r.pipeline()
175
+ pipe.hset(key, mapping={"status": "pending", "run_at": _iso(run_at), "updated_at": _iso(now), "locked_by": "", "locked_at": "", "last_error": error[:4000]})
176
+ pipe.zadd(self._k("pending"), {job.id: run_at.timestamp() - (int(job.priority) * 0.001)})
177
+ pipe.srem(self._k("running"), job.id)
178
+ pipe.execute()
179
+ return "pending"
180
+ pipe = self.r.pipeline()
181
+ pipe.hset(key, mapping={"status": "dead", "finished_at": _iso(now), "updated_at": _iso(now), "locked_by": "", "locked_at": "", "last_error": error[:4000]})
182
+ pipe.srem(self._k("running"), job.id)
183
+ pipe.execute()
184
+ return "dead"
185
+
186
+ def cancel(self, job_id: str, *, now: datetime | None = None) -> Job | None:
187
+ now = _dt(now) or _utcnow()
188
+ job = self.get(job_id)
189
+ if not job:
190
+ return None
191
+ if job.status in ("pending", "running"):
192
+ pipe = self.r.pipeline()
193
+ pipe.hset(self._k("job", job_id), mapping={"status": "cancelled", "updated_at": _iso(now), "finished_at": _iso(now), "locked_by": "", "locked_at": ""})
194
+ pipe.zrem(self._k("pending"), job_id)
195
+ pipe.srem(self._k("running"), job_id)
196
+ pipe.execute()
197
+ return self.get(job_id)
198
+ return job
199
+
200
+ def retry_job(self, job_id: str, *, now: datetime | None = None) -> Job | None:
201
+ now = _dt(now) or _utcnow()
202
+ if not self.r.exists(self._k("job", job_id)):
203
+ return None
204
+ pipe = self.r.pipeline()
205
+ pipe.hset(self._k("job", job_id), mapping={"status": "pending", "run_at": _iso(now), "updated_at": _iso(now), "finished_at": "", "locked_by": "", "locked_at": "", "last_error": ""})
206
+ pipe.zadd(self._k("pending"), {job_id: now.timestamp()})
207
+ pipe.execute()
208
+ return self.get(job_id)
209
+
210
+ def recover_stale(self, *, timeout_seconds: int = 300, now: datetime | None = None) -> int:
211
+ # Simple best-effort recovery: requeue running jobs with old locked_at.
212
+ now = _dt(now) or _utcnow()
213
+ count = 0
214
+ for raw in list(self.r.smembers(self._k("running"))):
215
+ jid = raw.decode() if isinstance(raw, bytes) else raw
216
+ job = self.get(jid)
217
+ if not job or not job.locked_at:
218
+ continue
219
+ if (now - job.locked_at).total_seconds() > timeout_seconds:
220
+ self.retry_job(jid, now=now)
221
+ count += 1
222
+ return count
223
+
224
+ def purge(self, *, status: str = "succeeded", older_than_seconds: int | None = None, now: datetime | None = None) -> int:
225
+ now = _dt(now) or _utcnow()
226
+ deleted = 0
227
+ for raw in list(self.r.smembers(self._k("jobs"))):
228
+ jid = raw.decode() if isinstance(raw, bytes) else raw
229
+ job = self.get(jid)
230
+ if not job or job.status != status:
231
+ continue
232
+ if older_than_seconds is not None and (now - job.updated_at).total_seconds() < older_than_seconds:
233
+ continue
234
+ pipe = self.r.pipeline()
235
+ pipe.delete(self._k("job", jid))
236
+ pipe.srem(self._k("jobs"), jid)
237
+ pipe.zrem(self._k("pending"), jid)
238
+ pipe.srem(self._k("running"), jid)
239
+ pipe.execute()
240
+ deleted += 1
241
+ return deleted
242
+
243
+ def counts(self) -> dict[str, int]:
244
+ out = {"pending": 0, "running": 0, "succeeded": 0, "failed": 0, "dead": 0, "cancelled": 0}
245
+ for raw in list(self.r.smembers(self._k("jobs"))):
246
+ jid = raw.decode() if isinstance(raw, bytes) else raw
247
+ job = self.get(jid)
248
+ if job:
249
+ out[job.status] = out.get(job.status, 0) + 1
250
+ return out
grindsharp/store.py ADDED
@@ -0,0 +1,325 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sqlite3
5
+ from datetime import datetime, timedelta, timezone
6
+ from pathlib import Path
7
+ from threading import Lock
8
+ from typing import Any
9
+
10
+ from .errors import DuplicateJob
11
+ from .models import Job
12
+
13
+
14
+ def _utcnow() -> datetime:
15
+ return datetime.now(timezone.utc)
16
+
17
+
18
+ def _dt(value: datetime | str | None) -> datetime | None:
19
+ if value is None:
20
+ return None
21
+ if isinstance(value, datetime):
22
+ return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
23
+ dt = datetime.fromisoformat(value)
24
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
25
+
26
+
27
+ def _iso(value: datetime | None) -> str | None:
28
+ if value is None:
29
+ return None
30
+ if value.tzinfo is None:
31
+ value = value.replace(tzinfo=timezone.utc)
32
+ return value.isoformat()
33
+
34
+
35
+ class SQLiteJobStore:
36
+ def __init__(self, path: str | Path = "grindsharp.db", *, busy_timeout_ms: int = 5000):
37
+ self.path = str(path)
38
+ self._lock = Lock()
39
+ self._conn = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
40
+ self._conn.row_factory = sqlite3.Row
41
+ with self._lock:
42
+ self._conn.execute("PRAGMA journal_mode=WAL")
43
+ self._conn.execute("PRAGMA synchronous=NORMAL")
44
+ self._conn.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}")
45
+ self._init()
46
+
47
+ def close(self) -> None:
48
+ with self._lock:
49
+ self._conn.close()
50
+
51
+ def _init(self) -> None:
52
+ self._conn.executescript(
53
+ """
54
+ CREATE TABLE IF NOT EXISTS jobs (
55
+ id TEXT PRIMARY KEY,
56
+ name TEXT NOT NULL,
57
+ payload TEXT NOT NULL,
58
+ status TEXT NOT NULL,
59
+ run_at TEXT NOT NULL,
60
+ attempts INTEGER NOT NULL DEFAULT 0,
61
+ max_retries INTEGER NOT NULL DEFAULT 0,
62
+ timeout_seconds INTEGER,
63
+ priority INTEGER NOT NULL DEFAULT 0,
64
+ created_at TEXT NOT NULL,
65
+ updated_at TEXT NOT NULL,
66
+ started_at TEXT,
67
+ finished_at TEXT,
68
+ locked_by TEXT,
69
+ locked_at TEXT,
70
+ last_error TEXT,
71
+ result TEXT
72
+ );
73
+ CREATE INDEX IF NOT EXISTS idx_jobs_status_run_at ON jobs(status, run_at);
74
+ CREATE INDEX IF NOT EXISTS idx_jobs_name ON jobs(name);
75
+ """
76
+ )
77
+ # migration for existing DBs
78
+ cols = {r["name"] for r in self._conn.execute("PRAGMA table_info(jobs)").fetchall()}
79
+ if "priority" not in cols:
80
+ self._conn.execute("ALTER TABLE jobs ADD COLUMN priority INTEGER NOT NULL DEFAULT 0")
81
+
82
+ def enqueue(
83
+ self,
84
+ *,
85
+ job_id: str,
86
+ name: str,
87
+ payload: dict[str, Any],
88
+ run_at: datetime | None = None,
89
+ max_retries: int = 0,
90
+ timeout_seconds: int | None = None,
91
+ priority: int = 0,
92
+ if_exists: str = "error", # error | ignore
93
+ ) -> Job:
94
+ now = _utcnow()
95
+ run_at = _dt(run_at) or now
96
+ row = {
97
+ "id": job_id,
98
+ "name": name,
99
+ "payload": json.dumps(payload),
100
+ "status": "pending",
101
+ "run_at": _iso(run_at),
102
+ "attempts": 0,
103
+ "max_retries": max_retries,
104
+ "timeout_seconds": timeout_seconds,
105
+ "priority": int(priority),
106
+ "created_at": _iso(now),
107
+ "updated_at": _iso(now),
108
+ "started_at": None,
109
+ "finished_at": None,
110
+ "locked_by": None,
111
+ "locked_at": None,
112
+ "last_error": None,
113
+ "result": None,
114
+ }
115
+ with self._lock:
116
+ try:
117
+ self._conn.execute(
118
+ """
119
+ INSERT INTO jobs (
120
+ id, name, payload, status, run_at, attempts, max_retries, timeout_seconds, priority,
121
+ created_at, updated_at, started_at, finished_at, locked_by, locked_at, last_error, result
122
+ ) VALUES (
123
+ :id, :name, :payload, :status, :run_at, :attempts, :max_retries, :timeout_seconds, :priority,
124
+ :created_at, :updated_at, :started_at, :finished_at, :locked_by, :locked_at, :last_error, :result
125
+ )
126
+ """,
127
+ row,
128
+ )
129
+ except sqlite3.IntegrityError as e:
130
+ if if_exists == "ignore":
131
+ existing = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
132
+ if existing:
133
+ return self._row_to_job(existing)
134
+ raise DuplicateJob(f"Job with id '{job_id}' already exists") from e
135
+ return self.get(job_id) # type: ignore[return-value]
136
+
137
+ def get(self, job_id: str) -> Job | None:
138
+ with self._lock:
139
+ row = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
140
+ return self._row_to_job(row) if row else None
141
+
142
+ def list_jobs(self, *, status: str | None = None, limit: int = 100) -> list[Job]:
143
+ q = "SELECT * FROM jobs"
144
+ params: list[Any] = []
145
+ if status:
146
+ q += " WHERE status = ?"
147
+ params.append(status)
148
+ q += " ORDER BY created_at DESC LIMIT ?"
149
+ params.append(limit)
150
+ with self._lock:
151
+ rows = self._conn.execute(q, params).fetchall()
152
+ return [self._row_to_job(r) for r in rows]
153
+
154
+ def claim_next(self, worker_id: str, *, now: datetime | None = None) -> Job | None:
155
+ now = _dt(now) or _utcnow()
156
+ now_iso = _iso(now)
157
+ with self._lock:
158
+ self._conn.execute("BEGIN IMMEDIATE")
159
+ try:
160
+ row = self._conn.execute(
161
+ """
162
+ SELECT * FROM jobs
163
+ WHERE status = 'pending' AND run_at <= ?
164
+ ORDER BY priority DESC, run_at ASC, created_at ASC
165
+ LIMIT 1
166
+ """,
167
+ (now_iso,),
168
+ ).fetchone()
169
+ if not row:
170
+ self._conn.execute("COMMIT")
171
+ return None
172
+ updated = self._conn.execute(
173
+ """
174
+ UPDATE jobs
175
+ SET status = 'running', locked_by = ?, locked_at = ?, started_at = ?,
176
+ attempts = attempts + 1, updated_at = ?
177
+ WHERE id = ? AND status = 'pending'
178
+ """,
179
+ (worker_id, now_iso, now_iso, now_iso, row["id"]),
180
+ )
181
+ if updated.rowcount != 1:
182
+ self._conn.execute("ROLLBACK")
183
+ return None
184
+ claimed = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (row["id"],)).fetchone()
185
+ self._conn.execute("COMMIT")
186
+ return self._row_to_job(claimed)
187
+ except Exception:
188
+ self._conn.execute("ROLLBACK")
189
+ raise
190
+
191
+ def mark_succeeded(self, job_id: str, *, result: Any = None, now: datetime | None = None) -> None:
192
+ now = _dt(now) or _utcnow()
193
+ payload = json.dumps(result) if result is not None else None
194
+ with self._lock:
195
+ self._conn.execute(
196
+ """
197
+ UPDATE jobs
198
+ SET status = 'succeeded', finished_at = ?, updated_at = ?, locked_by = NULL, locked_at = NULL,
199
+ last_error = NULL, result = ?
200
+ WHERE id = ?
201
+ """,
202
+ (_iso(now), _iso(now), payload, job_id),
203
+ )
204
+
205
+ def mark_failed(self, job: Job, *, error: str, now: datetime | None = None, retry_backoff_seconds: int = 0) -> str:
206
+ """Mark as pending (retry) or dead (exhausted). Returns new status."""
207
+ now = _dt(now) or _utcnow()
208
+ if job.attempts <= job.max_retries:
209
+ run_at = now + timedelta(seconds=max(0, retry_backoff_seconds) * max(1, job.attempts))
210
+ status = "pending"
211
+ finished_at = None
212
+ locked_by = None
213
+ locked_at = None
214
+ next_run = _iso(run_at)
215
+ else:
216
+ status = "dead"
217
+ finished_at = _iso(now)
218
+ locked_by = None
219
+ locked_at = None
220
+ next_run = _iso(job.run_at)
221
+
222
+ with self._lock:
223
+ self._conn.execute(
224
+ """
225
+ UPDATE jobs
226
+ SET status = ?, run_at = ?, finished_at = ?, updated_at = ?, locked_by = ?, locked_at = ?, last_error = ?
227
+ WHERE id = ?
228
+ """,
229
+ (status, next_run, finished_at, _iso(now), locked_by, locked_at, error[:4000], job.id),
230
+ )
231
+ return status
232
+
233
+ def cancel(self, job_id: str, *, now: datetime | None = None) -> Job | None:
234
+ now = _dt(now) or _utcnow()
235
+ with self._lock:
236
+ row = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
237
+ if not row:
238
+ return None
239
+ if row["status"] not in ("pending", "running"):
240
+ return self._row_to_job(row)
241
+ self._conn.execute(
242
+ """
243
+ UPDATE jobs SET status='cancelled', updated_at=?, finished_at=?, locked_by=NULL, locked_at=NULL
244
+ WHERE id = ?
245
+ """,
246
+ (_iso(now), _iso(now), job_id),
247
+ )
248
+ row = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
249
+ return self._row_to_job(row) if row else None
250
+
251
+ def retry_job(self, job_id: str, *, now: datetime | None = None) -> Job | None:
252
+ now = _dt(now) or _utcnow()
253
+ with self._lock:
254
+ row = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
255
+ if not row:
256
+ return None
257
+ self._conn.execute(
258
+ """
259
+ UPDATE jobs
260
+ SET status = 'pending', run_at = ?, updated_at = ?, finished_at = NULL,
261
+ locked_by = NULL, locked_at = NULL, last_error = NULL
262
+ WHERE id = ?
263
+ """,
264
+ (_iso(now), _iso(now), job_id),
265
+ )
266
+ row = self._conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
267
+ return self._row_to_job(row) if row else None
268
+
269
+ def recover_stale(self, *, timeout_seconds: int = 300, now: datetime | None = None) -> int:
270
+ now = _dt(now) or _utcnow()
271
+ cutoff = now - timedelta(seconds=timeout_seconds)
272
+ with self._lock:
273
+ cur = self._conn.execute(
274
+ """
275
+ UPDATE jobs
276
+ SET status = 'pending', updated_at = ?, locked_by = NULL, locked_at = NULL,
277
+ last_error = COALESCE(last_error, 'Recovered from stale running state')
278
+ WHERE status = 'running' AND locked_at IS NOT NULL AND locked_at < ?
279
+ """,
280
+ (_iso(now), _iso(cutoff)),
281
+ )
282
+ return cur.rowcount
283
+
284
+ def purge(self, *, status: str = "succeeded", older_than_seconds: int | None = None, now: datetime | None = None) -> int:
285
+ now = _dt(now) or _utcnow()
286
+ q = "DELETE FROM jobs WHERE status = ?"
287
+ params: list[Any] = [status]
288
+ if older_than_seconds is not None:
289
+ cutoff = now - timedelta(seconds=older_than_seconds)
290
+ q += " AND updated_at < ?"
291
+ params.append(_iso(cutoff))
292
+ with self._lock:
293
+ cur = self._conn.execute(q, params)
294
+ return cur.rowcount
295
+
296
+ def counts(self) -> dict[str, int]:
297
+ with self._lock:
298
+ rows = self._conn.execute("SELECT status, COUNT(*) as n FROM jobs GROUP BY status").fetchall()
299
+ out = {"pending": 0, "running": 0, "succeeded": 0, "failed": 0, "dead": 0, "cancelled": 0}
300
+ for r in rows:
301
+ out[str(r["status"])] = int(r["n"])
302
+ return out
303
+
304
+ def _row_to_job(self, row: sqlite3.Row) -> Job:
305
+ payload = json.loads(row["payload"])
306
+ result = json.loads(row["result"]) if row["result"] is not None else None
307
+ return Job(
308
+ id=row["id"],
309
+ name=row["name"],
310
+ payload=payload,
311
+ status=row["status"],
312
+ run_at=_dt(row["run_at"]), # type: ignore[arg-type]
313
+ attempts=int(row["attempts"]),
314
+ max_retries=int(row["max_retries"]),
315
+ timeout_seconds=int(row["timeout_seconds"]) if row["timeout_seconds"] is not None else None,
316
+ priority=int(row["priority"]) if "priority" in row.keys() and row["priority"] is not None else 0,
317
+ created_at=_dt(row["created_at"]), # type: ignore[arg-type]
318
+ updated_at=_dt(row["updated_at"]), # type: ignore[arg-type]
319
+ started_at=_dt(row["started_at"]),
320
+ finished_at=_dt(row["finished_at"]),
321
+ locked_by=row["locked_by"],
322
+ locked_at=_dt(row["locked_at"]),
323
+ last_error=row["last_error"],
324
+ result=result,
325
+ )