aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/json_serializer.py
blob: 7e51358436fbf7ae733df32898f0b85fde591d6d (plain) (blame)
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
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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Serialize Huey messages as JSON without reconstructing arbitrary Python objects."""

import json
import uuid
from datetime import datetime
from typing import Any

from huey.registry import Message
from huey.serializer import Serializer
from huey.utils import SKIPPED, Error


class JSONSerializer(Serializer):
    """A deliberately restricted, non-pickle serializer for our Huey tasks.

    JSON has no native UUID, datetime, tuple or Huey message representation.
    Each non-primitive value is encoded with a fixed tag and decoded using an
    allowlist; no module imports, user-supplied classes or object constructors
    are evaluated. Unsupported objects fail closed rather than being pickled.
    """

    def _serialize(self, data: Any) -> bytes:
        return json.dumps(
            self._encode(data),
            ensure_ascii=False,
            allow_nan=False,
            separators=(",", ":"),
        ).encode("utf-8")

    def _deserialize(self, data: bytes) -> Any:
        def reject_nonfinite(value: str) -> None:
            raise ValueError(f"Invalid non-finite JSON value: {value}")

        return self._decode(json.loads(data, parse_constant=reject_nonfinite))

    @classmethod
    def _encode(cls, value: Any) -> Any:
        match value:
            case _ if value is None or type(value) in {str, int, float, bool}:
                return value

            case uuid.UUID():
                return {"type": "uuid", "value": str(value)}

            case datetime():
                return {"type": "datetime", "value": value.isoformat()}

            case Message():
                return {"type": "message", "value": [cls._encode(v) for v in value]}

            case Error():
                return {"type": "error", "value": cls._encode(value.metadata)}

            case _ if value is SKIPPED:
                return {"type": "skipped", "value": None}

            case tuple():
                return {"type": "tuple", "value": [cls._encode(v) for v in value]}

            case list():
                return {"type": "list", "value": [cls._encode(v) for v in value]}

            case dict() if all(isinstance(k, str) for k in value):
                return {
                    "type": "dict",
                    "value": [[k, cls._encode(v)] for k, v in value.items()],
                }

            case _:
                raise TypeError(f"Unsupported Huey JSON value: {type(value).__name__}")

    @classmethod
    def _decode(cls, value: Any) -> Any:
        if value is None or type(value) in {str, int, float, bool}:
            return value

        if not isinstance(value, dict) or set(value) != {"type", "value"}:
            raise ValueError("Invalid Huey JSON data")

        match value["type"], value["value"]:
            case "uuid", str() as payload:
                return uuid.UUID(payload)

            case "datetime", str() as payload:
                return datetime.fromisoformat(payload)

            case "message", list() as payload:
                if len(payload) != len(Message._fields):
                    raise ValueError("Invalid Huey JSON message field count")
                return Message(*(cls._decode(v) for v in payload))

            case "error", payload:
                metadata = cls._decode(payload)
                if not isinstance(metadata, dict):
                    raise TypeError("Invalid Huey JSON error metadata")
                return Error(metadata)

            case "skipped", None:
                return SKIPPED

            case ("tuple" | "list") as kind, list() as payload:
                items = [cls._decode(v) for v in payload]
                return tuple(items) if kind == "tuple" else items

            case "dict", list() as payload:
                result: dict[str, Any] = {}

                for pair in payload:
                    match pair:
                        case list([str() as key, encoded]):
                            if key in result:
                                raise ValueError("Duplicate Huey JSON dictionary key")
                            result[key] = cls._decode(encoded)

                        case _:
                            raise ValueError("Invalid Huey JSON dictionary entry")

                return result

            case _:
                raise ValueError("Unsupported Huey JSON type")