File size: 1,228 Bytes
a9f2957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
Background job worker — processes pending jobs from the database.

BUG: json.loads() is called without try/except.  When a job payload is
malformed (e.g. truncated JSON), this function raises an exception.
The job remains 'pending' and the worker is restarted, causing an
infinite crash-loop.

Fix: wrap the json.loads call in try/except and mark bad jobs as 'failed'
so the worker can continue processing the rest of the queue.
"""

import json
import logging
import os
import sqlite3

logger = logging.getLogger("worker")

_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app.db")


def process_jobs() -> None:
    """Fetch and process all pending jobs.  Crashes on malformed payloads."""
    conn = sqlite3.connect(_DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute(
        "SELECT * FROM jobs WHERE status='pending' ORDER BY id"
    ).fetchall()

    for row in rows:
        data = json.loads(row["payload"])  # BUG: no try/except — raises on bad JSON
        logger.info("Processed job %s: item=%s", row["id"], data.get("item"))
        conn.execute(
            "UPDATE jobs SET status='completed' WHERE id=?", (row["id"],)
        )
        conn.commit()

    conn.close()