xtr-webhook 4.0.2__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.
Files changed (56) hide show
  1. xtr_webhook/.agents/skills/xtr-webhook/SKILL.md +350 -0
  2. xtr_webhook/.agents/skills/xtr-webhook/references/signature-formats.md +189 -0
  3. xtr_webhook/__init__.py +10 -0
  4. xtr_webhook/_endpoint_paths.py +22 -0
  5. xtr_webhook/_standard_webhooks_signature.py +76 -0
  6. xtr_webhook/bundle/__init__.py +15 -0
  7. xtr_webhook/bundle/_routed_parsers.py +70 -0
  8. xtr_webhook/bundle/no_private_network_config.py +59 -0
  9. xtr_webhook/bundle/route_config.py +34 -0
  10. xtr_webhook/bundle/webhook_bundle.py +262 -0
  11. xtr_webhook/bundle/webhook_config.py +80 -0
  12. xtr_webhook/client/__init__.py +23 -0
  13. xtr_webhook/client/abstract_request_parser.py +248 -0
  14. xtr_webhook/client/request_parser.py +272 -0
  15. xtr_webhook/client/request_parser_interface.py +90 -0
  16. xtr_webhook/controller/__init__.py +12 -0
  17. xtr_webhook/controller/_built_parsers.py +65 -0
  18. xtr_webhook/controller/webhook_controller.py +140 -0
  19. xtr_webhook/exception/__init__.py +25 -0
  20. xtr_webhook/exception/delivery_error.py +38 -0
  21. xtr_webhook/exception/invalid_argument_error.py +18 -0
  22. xtr_webhook/exception/logic_error.py +15 -0
  23. xtr_webhook/exception/reject_webhook_error.py +52 -0
  24. xtr_webhook/exception/webhook_error.py +9 -0
  25. xtr_webhook/exception/webhook_runtime_error.py +16 -0
  26. xtr_webhook/messenger/__init__.py +14 -0
  27. xtr_webhook/messenger/send_webhook_handler.py +49 -0
  28. xtr_webhook/messenger/send_webhook_message.py +36 -0
  29. xtr_webhook/py.typed +0 -0
  30. xtr_webhook/recipe/__init__.py +18 -0
  31. xtr_webhook/recipe/files/config/routes/webhook.py.tmpl +25 -0
  32. xtr_webhook/recipe/files/config/webhook.py.tmpl +33 -0
  33. xtr_webhook/recipe/manifest.toml +35 -0
  34. xtr_webhook/routing/__init__.py +11 -0
  35. xtr_webhook/routing/_endpoints.py +38 -0
  36. xtr_webhook/routing/webhook_route_loader.py +31 -0
  37. xtr_webhook/server/__init__.py +39 -0
  38. xtr_webhook/server/header_signature_configurator.py +128 -0
  39. xtr_webhook/server/headers_configurator.py +92 -0
  40. xtr_webhook/server/json_body_configurator.py +80 -0
  41. xtr_webhook/server/json_payload_serializer.py +45 -0
  42. xtr_webhook/server/outgoing_request.py +35 -0
  43. xtr_webhook/server/payload_serializer_interface.py +34 -0
  44. xtr_webhook/server/request_configurator_interface.py +39 -0
  45. xtr_webhook/server/signature_format.py +65 -0
  46. xtr_webhook/server/transport.py +106 -0
  47. xtr_webhook/server/transport_interface.py +40 -0
  48. xtr_webhook/subscriber.py +41 -0
  49. xtr_webhook/testing/__init__.py +18 -0
  50. xtr_webhook/testing/_parser_cases.py +141 -0
  51. xtr_webhook/testing/parser_case.py +37 -0
  52. xtr_webhook-4.0.2.dist-info/METADATA +704 -0
  53. xtr_webhook-4.0.2.dist-info/RECORD +56 -0
  54. xtr_webhook-4.0.2.dist-info/WHEEL +4 -0
  55. xtr_webhook-4.0.2.dist-info/entry_points.txt +6 -0
  56. xtr_webhook-4.0.2.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,128 @@
1
+ """The signature that proves a webhook came from here, and was not replayed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ from typing import TYPE_CHECKING, final
8
+
9
+ from typing_extensions import override
10
+
11
+ from xtr_webhook._standard_webhooks_signature import sign
12
+ from xtr_webhook.exception import InvalidArgumentError, LogicError
13
+
14
+ from .request_configurator_interface import RequestConfiguratorInterface
15
+ from .signature_format import SignatureFormat
16
+
17
+ if TYPE_CHECKING:
18
+ from xtr_remote_event import RemoteEvent
19
+
20
+ from .outgoing_request import OutgoingRequest
21
+
22
+ __all__ = ["HeaderSignatureConfigurator"]
23
+
24
+
25
+ @final
26
+ class HeaderSignatureConfigurator(RequestConfiguratorInterface):
27
+ """Signs what the earlier configurators built, into one header.
28
+
29
+ It runs last, because it signs their output: the body one wrote and the
30
+ timestamp another wrote. Under the transitional format it emits both
31
+ signatures, space separated, so a receiver mid-migration accepts whichever it
32
+ already understands and neither sender nor receiver has to change on the same
33
+ day.
34
+ """
35
+
36
+ __slots__ = (
37
+ "_algorithm",
38
+ "_signature_format",
39
+ "_signature_header_name",
40
+ "_timestamp_header_name",
41
+ )
42
+
43
+ def __init__(
44
+ self,
45
+ algorithm: str = "sha256",
46
+ signature_header_name: str = "Webhook-Signature",
47
+ signature_format: SignatureFormat | str = SignatureFormat.LEGACY,
48
+ timestamp_header_name: str = "Webhook-Timestamp",
49
+ ) -> None:
50
+ """Configure what signs, under which name and format.
51
+
52
+ Args:
53
+ algorithm: The digest the legacy signature is made with, named in the
54
+ signature itself so a receiver knows what to recompute. The
55
+ Standard Webhooks signature is always SHA-256; the scheme fixes it.
56
+ signature_header_name: The header the signatures go in.
57
+ signature_format: Which signatures to emit. The string a configuration
58
+ carries is accepted.
59
+ timestamp_header_name: The header the signed timestamp is read back
60
+ from, which
61
+ :class:`HeadersConfigurator <xtr_webhook.server.HeadersConfigurator>`
62
+ must have written under the same name.
63
+
64
+ Raises:
65
+ InvalidArgumentError: When this runtime cannot make ``algorithm``, or
66
+ when ``signature_format`` names no format. Both are caught here
67
+ rather than at the first delivery: a sender that cannot sign is
68
+ misconfigured, and finding out mid-send means a webhook already on
69
+ its way.
70
+ """
71
+ if algorithm not in hashlib.algorithms_available:
72
+ raise InvalidArgumentError(f'The signing algorithm "{algorithm}" is not available.')
73
+
74
+ self._algorithm = algorithm
75
+ self._signature_header_name = signature_header_name
76
+ self._signature_format = SignatureFormat.parse(signature_format)
77
+ self._timestamp_header_name = timestamp_header_name
78
+
79
+ @override
80
+ def configure(self, event: RemoteEvent, secret: str, request: OutgoingRequest) -> None:
81
+ """Sign ``request`` and write the signatures into its header.
82
+
83
+ Args:
84
+ event: The event being sent, whose name and id the legacy signature
85
+ covers.
86
+ secret: The receiving subscriber's secret.
87
+ request: The request being built, whose body must already be set.
88
+
89
+ Raises:
90
+ InvalidArgumentError: When ``secret`` is empty. An empty key still
91
+ signs, so this would otherwise send perfectly formed webhooks no
92
+ receiver can accept.
93
+ LogicError: When the body has not been set, or when a format that signs
94
+ the timestamp runs before whatever writes it. Both are an order the
95
+ chain was built in, not something a delivery can fix.
96
+ """
97
+ if not secret:
98
+ raise InvalidArgumentError("A non-empty secret is required.")
99
+
100
+ body = request.body
101
+ if body is None:
102
+ raise LogicError("The body must be set.")
103
+
104
+ signatures: list[str] = []
105
+
106
+ if self._signature_format is not SignatureFormat.STANDARD:
107
+ # Name, id and body run together with nothing between them: the digest
108
+ # covers exactly these bytes in this order, and a receiver rebuilds it
109
+ # the same way.
110
+ digest = hmac.new(
111
+ secret.encode(),
112
+ event.name.encode() + event.id.encode() + body,
113
+ self._algorithm,
114
+ )
115
+ signatures.append(f"{self._algorithm}={digest.hexdigest()}")
116
+
117
+ if self._signature_format is not SignatureFormat.LEGACY:
118
+ timestamp = request.headers.get(self._timestamp_header_name)
119
+ if timestamp is None:
120
+ raise LogicError(
121
+ f'The "{self._timestamp_header_name}" header must be set when emitting a '
122
+ 'Standard Webhooks signature; ensure "HeadersConfigurator" runs before this '
123
+ "configurator.",
124
+ )
125
+
126
+ signatures.append(sign(event.id, timestamp, body, secret))
127
+
128
+ request.headers[self._signature_header_name] = " ".join(signatures)
@@ -0,0 +1,92 @@
1
+ """The headers that say which event this is, and when it was sent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, final
6
+
7
+ from typing_extensions import override
8
+ from xtr_clock import Clock
9
+
10
+ from .request_configurator_interface import RequestConfiguratorInterface
11
+ from .signature_format import SignatureFormat
12
+
13
+ if TYPE_CHECKING:
14
+ from xtr_clock import ClockInterface
15
+ from xtr_remote_event import RemoteEvent
16
+
17
+ from .outgoing_request import OutgoingRequest
18
+
19
+ __all__ = ["HeadersConfigurator"]
20
+
21
+
22
+ @final
23
+ class HeadersConfigurator(RequestConfiguratorInterface):
24
+ """Writes the id, the timestamp and — unless the format forbids it — the event.
25
+
26
+ The timestamp is what lets a receiver refuse a delivery captured yesterday, so
27
+ it is sent whatever the format; under the Standard Webhooks format it is also
28
+ signed, which is what makes refusing one safe.
29
+
30
+ The event name is the exception. That format's signature covers no header at
31
+ all, so a name sent as one is a value the receiver cannot trust; it travels in
32
+ the payload instead, written there by
33
+ :class:`JsonBodyConfigurator <xtr_webhook.server.JsonBodyConfigurator>`.
34
+ """
35
+
36
+ __slots__ = (
37
+ "_clock",
38
+ "_event_header_name",
39
+ "_id_header_name",
40
+ "_signature_format",
41
+ "_timestamp_header_name",
42
+ )
43
+
44
+ def __init__(
45
+ self,
46
+ event_header_name: str = "Webhook-Event",
47
+ id_header_name: str = "Webhook-Id",
48
+ timestamp_header_name: str = "Webhook-Timestamp",
49
+ clock: ClockInterface | None = None,
50
+ signature_format: SignatureFormat | str = SignatureFormat.LEGACY,
51
+ ) -> None:
52
+ """Configure the names and the format this sends under.
53
+
54
+ Args:
55
+ event_header_name: The header the event's name goes in.
56
+ id_header_name: The header the event's id goes in.
57
+ timestamp_header_name: The header the send time goes in. The signer
58
+ reads it back under this same name, so changing one means changing
59
+ both.
60
+ clock: Where the send time comes from. ``None`` reads whichever clock
61
+ is in force when the request is configured, so a test can freeze it
62
+ without the configurator having been built inside the frozen scope.
63
+ signature_format: What the webhook will be signed with, which decides
64
+ whether the event name may be sent as a header. The string a
65
+ configuration carries is accepted.
66
+
67
+ Raises:
68
+ InvalidArgumentError: When ``signature_format`` names no format.
69
+ """
70
+ self._event_header_name = event_header_name
71
+ self._id_header_name = id_header_name
72
+ self._timestamp_header_name = timestamp_header_name
73
+ self._clock = clock
74
+ self._signature_format = SignatureFormat.parse(signature_format)
75
+
76
+ @override
77
+ def configure(self, event: RemoteEvent, secret: str, request: OutgoingRequest) -> None:
78
+ """Write the identifying headers into ``request``.
79
+
80
+ Args:
81
+ event: The event being sent.
82
+ secret: Unused — nothing here is signed.
83
+ request: The request being built.
84
+ """
85
+ del secret
86
+
87
+ clock = self._clock or Clock.get()
88
+ request.headers[self._id_header_name] = event.id
89
+ request.headers[self._timestamp_header_name] = str(int(clock.now().timestamp()))
90
+
91
+ if self._signature_format is not SignatureFormat.STANDARD:
92
+ request.headers[self._event_header_name] = event.name
@@ -0,0 +1,80 @@
1
+ """The payload written into the body, as the bytes that get signed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, final
6
+
7
+ from typing_extensions import override
8
+
9
+ from .request_configurator_interface import RequestConfiguratorInterface
10
+ from .signature_format import SignatureFormat
11
+
12
+ if TYPE_CHECKING:
13
+ from xtr_remote_event import RemoteEvent
14
+
15
+ from .outgoing_request import OutgoingRequest
16
+ from .payload_serializer_interface import PayloadSerializerInterface
17
+
18
+ __all__ = ["JsonBodyConfigurator"]
19
+
20
+ _TYPE_KEY = "type"
21
+ """Where the Standard Webhooks format expects to read the event's name."""
22
+
23
+
24
+ @final
25
+ class JsonBodyConfigurator(RequestConfiguratorInterface):
26
+ """Writes the payload as the body, and says the body is JSON.
27
+
28
+ Under any format but the legacy one the event's name is written into the
29
+ payload first, because that format's signature covers the body and nothing
30
+ else: a name carried there is a name the receiver can act on. A payload that
31
+ already says what it is keeps what it says — the application knows its own
32
+ events better than their source name does.
33
+
34
+ The payload is copied before that key is added. The event is a record of
35
+ something that happened, and whoever dispatched it may still be holding the
36
+ dict; sending a webhook must not edit it.
37
+ """
38
+
39
+ __slots__ = ("_serializer", "_signature_format")
40
+
41
+ def __init__(
42
+ self,
43
+ serializer: PayloadSerializerInterface,
44
+ signature_format: SignatureFormat | str = SignatureFormat.LEGACY,
45
+ ) -> None:
46
+ """Configure what writes the payload, and under which format.
47
+
48
+ Args:
49
+ serializer: What turns the payload into the bytes that are sent and
50
+ signed.
51
+ signature_format: What the webhook will be signed with, which decides
52
+ whether the event's name is written into the payload. The string a
53
+ configuration carries is accepted.
54
+
55
+ Raises:
56
+ InvalidArgumentError: When ``signature_format`` names no format.
57
+ """
58
+ self._serializer = serializer
59
+ self._signature_format = SignatureFormat.parse(signature_format)
60
+
61
+ @override
62
+ def configure(self, event: RemoteEvent, secret: str, request: OutgoingRequest) -> None:
63
+ """Write the serialized payload into ``request`` as its body.
64
+
65
+ Args:
66
+ event: The event being sent.
67
+ secret: Unused — the body is signed by the signer, not here.
68
+ request: The request being built.
69
+ """
70
+ del secret
71
+
72
+ payload: dict[str, object] = event.payload
73
+
74
+ if self._signature_format is not SignatureFormat.LEGACY:
75
+ payload = dict(payload)
76
+ if _TYPE_KEY not in payload:
77
+ payload[_TYPE_KEY] = event.name
78
+
79
+ request.body = self._serializer.serialize(payload)
80
+ request.headers["Content-Type"] = "application/json"
@@ -0,0 +1,45 @@
1
+ """The payload written as JSON, which is what a receiver expects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, final
6
+
7
+ import msgspec
8
+ from typing_extensions import override
9
+
10
+ from .payload_serializer_interface import PayloadSerializerInterface
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Mapping
14
+
15
+ __all__ = ["JsonPayloadSerializer"]
16
+
17
+
18
+ @final
19
+ class JsonPayloadSerializer(PayloadSerializerInterface):
20
+ """Writes the payload as compact JSON, keys in the order they were added.
21
+
22
+ The default, because a webhook is JSON unless a receiver says otherwise. It
23
+ adds no whitespace and reorders nothing: the bytes are the signed message, so
24
+ two runs over the same payload have to produce the same ones, and a receiver
25
+ that signs what arrived has to arrive at the same digest.
26
+ """
27
+
28
+ __slots__ = ()
29
+
30
+ @override
31
+ def serialize(self, payload: Mapping[str, object]) -> bytes:
32
+ """Return ``payload`` as JSON.
33
+
34
+ Args:
35
+ payload: What to write.
36
+
37
+ Returns:
38
+ The compact JSON encoding.
39
+
40
+ Raises:
41
+ TypeError: When the payload holds a value JSON has no form for. It is
42
+ not wrapped: the payload came from the application, and what a
43
+ serializer refuses is the serializer's own vocabulary.
44
+ """
45
+ return msgspec.json.encode(payload)
@@ -0,0 +1,35 @@
1
+ """The request a webhook is built into, before anything sends it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import final
7
+
8
+ __all__ = ["OutgoingRequest"]
9
+
10
+
11
+ @final
12
+ @dataclass(slots=True)
13
+ class OutgoingRequest:
14
+ """What the configurators write a webhook into, one after another.
15
+
16
+ Mutable where almost everything else here is frozen, because building a
17
+ webhook is a sequence: one configurator writes the headers that identify the
18
+ event, the next writes the body, and the signer reads both back to sign what
19
+ the earlier two produced. Each hands the same request on.
20
+
21
+ It is a plain pair of values rather than a client's request type, so the whole
22
+ sending side can be written, and tested, without an HTTP client installed —
23
+ the transport turns one of these into whatever it sends.
24
+
25
+ Attributes:
26
+ headers: The headers to send, by name. A configurator writes the ones it
27
+ owns and leaves the rest, so the order the chain runs in decides only
28
+ what can be read back, never what survives.
29
+ body: The exact bytes to send. ``None`` until a configurator sets them;
30
+ bytes rather than text because a signature covers what goes out, and
31
+ re-encoding text can change it.
32
+ """
33
+
34
+ headers: dict[str, str] = field(default_factory=dict)
35
+ body: bytes | None = None
@@ -0,0 +1,34 @@
1
+ """How a payload becomes the bytes a webhook is signed over."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Mapping
9
+
10
+ __all__ = ["PayloadSerializerInterface"]
11
+
12
+
13
+ @runtime_checkable
14
+ class PayloadSerializerInterface(Protocol):
15
+ """Turns a payload into the exact bytes that are sent and signed.
16
+
17
+ Its own contract rather than a parameter on the body configurator, because an
18
+ application sending events whose payloads carry dates, decimals or domain
19
+ objects has to decide how those are written, and that decision must be made
20
+ once: the signature covers the bytes this returns, so anything that rewrites
21
+ them afterwards breaks it.
22
+ """
23
+
24
+ def serialize(self, payload: Mapping[str, object]) -> bytes:
25
+ """Return the bytes ``payload`` is sent as.
26
+
27
+ Args:
28
+ payload: What to write. Never modified — the caller may be holding
29
+ the event's own payload.
30
+
31
+ Returns:
32
+ The bytes to send, which are also the bytes signed.
33
+ """
34
+ ...
@@ -0,0 +1,39 @@
1
+ """What one step of building an outgoing webhook looks like."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
6
+
7
+ if TYPE_CHECKING:
8
+ from xtr_remote_event import RemoteEvent
9
+
10
+ from .outgoing_request import OutgoingRequest
11
+
12
+ __all__ = ["RequestConfiguratorInterface"]
13
+
14
+
15
+ @runtime_checkable
16
+ class RequestConfiguratorInterface(Protocol):
17
+ """One step of turning an event into the request that carries it.
18
+
19
+ Sending a webhook is several decisions — which headers name the event, how the
20
+ payload is written, what signs it — and a receiver dictates them separately.
21
+ Keeping each a configurator of its own means an application that needs a header
22
+ one receiver insists on adds a step rather than replacing the sender.
23
+
24
+ The steps run in order and share one request, so a later one can read what an
25
+ earlier one wrote. That is what lets the signer sign the body and the timestamp
26
+ the two before it produced.
27
+ """
28
+
29
+ def configure(self, event: RemoteEvent, secret: str, request: OutgoingRequest) -> None:
30
+ """Write this step's part of ``event`` into ``request``.
31
+
32
+ Args:
33
+ event: The event being sent.
34
+ secret: The receiving subscriber's secret. Every step is handed it, so
35
+ a step that signs needs nothing else; a step that does not, ignores
36
+ it.
37
+ request: The request being built, written into in place.
38
+ """
39
+ ...
@@ -0,0 +1,65 @@
1
+ """The signature scheme a sender emits and a receiver requires."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+ from xtr_webhook.exception import InvalidArgumentError
8
+
9
+ __all__ = ["SignatureFormat"]
10
+
11
+
12
+ class SignatureFormat(StrEnum):
13
+ """Which signature a webhook carries, and therefore what the signature covers.
14
+
15
+ The two schemes sign different things, so the choice reaches further than the
16
+ header's spelling: one covers a header and the other covers a timestamp. Both
17
+ ends of a webhook have to have made the same choice, which is why the sender's
18
+ configurators and the receiver's parser each take this.
19
+
20
+ The members *are* their strings, so a configuration file, an option mapping or
21
+ an environment variable carries ``"standard"`` and is understood without a
22
+ conversion step — while code that reads them still gets a closed set.
23
+
24
+ Attributes:
25
+ LEGACY: This project's historical ``"<algorithm>=<hex>"`` signature, over the
26
+ event name, the id and the body. The event name travels in the
27
+ ``Webhook-Event`` header, which the signature covers. The default, so an
28
+ existing pair of endpoints keeps working.
29
+ STANDARD: The Standard Webhooks ``"v1,<base64>"`` signature, over the id, the
30
+ timestamp and the body (https://www.standardwebhooks.com/). It covers no
31
+ header, so the event name travels in the payload's ``type`` key and the
32
+ ``Webhook-Event`` header is not sent at all. Signing the timestamp is what
33
+ lets a receiver bound replays.
34
+ TRANSITIONAL: Both signatures, space separated, with the event name in both the
35
+ header and the payload. For a migration window: a receiver accepts either,
36
+ and only the Standard Webhooks entry bounds replays.
37
+ """
38
+
39
+ LEGACY = "legacy"
40
+ STANDARD = "standard"
41
+ TRANSITIONAL = "transitional"
42
+
43
+ @classmethod
44
+ def parse(cls, value: SignatureFormat | str) -> SignatureFormat:
45
+ """Return the member ``value`` stands for.
46
+
47
+ The single door for anything arriving from outside — a config option, a
48
+ bundle definition, a caller's keyword — so a typo is refused once, here,
49
+ instead of reaching a signer as an unknown scheme and going out unsigned.
50
+
51
+ Args:
52
+ value: A member, or the string one carries.
53
+
54
+ Returns:
55
+ The member named by ``value``; a member passes through unchanged.
56
+
57
+ Raises:
58
+ InvalidArgumentError: When no member carries that string.
59
+ """
60
+ try:
61
+ return cls(value)
62
+ except ValueError as error:
63
+ raise InvalidArgumentError(
64
+ f'"{value}" is not a signature format; use "legacy", "standard" or "transitional".',
65
+ ) from error
@@ -0,0 +1,106 @@
1
+ """The delivery itself: build the request, post it, judge the answer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, final
6
+
7
+ from typing_extensions import override
8
+
9
+ from xtr_webhook.exception import DeliveryError, LogicError
10
+
11
+ from .outgoing_request import OutgoingRequest
12
+ from .transport_interface import TransportInterface
13
+
14
+ if TYPE_CHECKING:
15
+ from xtr_http_client_contracts import HttpClientInterface
16
+ from xtr_remote_event import RemoteEvent
17
+
18
+ from xtr_webhook.subscriber import Subscriber
19
+
20
+ from .request_configurator_interface import RequestConfiguratorInterface
21
+
22
+ __all__ = ["Transport"]
23
+
24
+ _ACCEPTED = range(200, 300)
25
+ """The answers that count as delivered: success, nothing else."""
26
+
27
+
28
+ @final
29
+ class Transport(TransportInterface):
30
+ """Runs the configurator chain over a fresh request and posts what it built.
31
+
32
+ The order is fixed — headers, body, signer — because the signer reads back
33
+ what the other two wrote: the body it signs and the timestamp it covers must
34
+ already be there. The request is fresh per send so nothing of one delivery
35
+ leaks into the next.
36
+
37
+ Any answer outside 200-299 raises: a delivery runs inside a message handler,
38
+ and the error is what makes the bus retry it and, once the attempts are
39
+ spent, keep the message instead of dropping it. A redirect counts as refused
40
+ too, and is never followed — following one would carry a signed body to an
41
+ address nobody vetted.
42
+
43
+ The client is taken, not built, and given no option but the refusal to
44
+ follow a redirect: how long a delivery may take is the client's
45
+ configuration, as are its connections and whatever it is wrapped in.
46
+ """
47
+
48
+ __slots__ = ("_body", "_client", "_headers", "_signer")
49
+
50
+ def __init__(
51
+ self,
52
+ client: HttpClientInterface,
53
+ headers: RequestConfiguratorInterface,
54
+ body: RequestConfiguratorInterface,
55
+ signer: RequestConfiguratorInterface,
56
+ ) -> None:
57
+ """Configure what builds each part, and what carries the result.
58
+
59
+ Args:
60
+ client: What posts the built request.
61
+ headers: The step that writes the headers naming the event.
62
+ body: The step that writes the payload into the body.
63
+ signer: The step that signs what the other two wrote. It runs last.
64
+ """
65
+ self._client = client
66
+ self._headers = headers
67
+ self._body = body
68
+ self._signer = signer
69
+
70
+ @override
71
+ async def send(self, subscriber: Subscriber, event: RemoteEvent) -> None:
72
+ """Deliver ``event`` to ``subscriber``.
73
+
74
+ Args:
75
+ subscriber: Where the webhook goes, and the secret it is signed
76
+ with.
77
+ event: What to deliver.
78
+
79
+ Raises:
80
+ LogicError: When the chain never wrote a body. A chain that builds
81
+ nothing to send is a wiring mistake, caught before anything
82
+ leaves.
83
+ DeliveryError: When the receiver answered with a status outside
84
+ 200-299.
85
+ TransportError: When no answer came — the client's own error,
86
+ passed on so the bus retries the delivery as it would a refusal.
87
+ """
88
+ request = OutgoingRequest()
89
+ self._headers.configure(event, subscriber.secret, request)
90
+ self._body.configure(event, subscriber.secret, request)
91
+ self._signer.configure(event, subscriber.secret, request)
92
+
93
+ body = request.body
94
+ if body is None:
95
+ raise LogicError("The body must be set.")
96
+
97
+ async with await self._client.request(
98
+ "POST",
99
+ subscriber.url,
100
+ headers=dict(request.headers),
101
+ body=body,
102
+ max_redirects=0,
103
+ ) as response:
104
+ status_code = response.get_status_code()
105
+ if status_code not in _ACCEPTED:
106
+ raise DeliveryError(status_code, subscriber.url)
@@ -0,0 +1,40 @@
1
+ """What delivers a built webhook to one subscriber."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
6
+
7
+ if TYPE_CHECKING:
8
+ from xtr_remote_event import RemoteEvent
9
+
10
+ from xtr_webhook.subscriber import Subscriber
11
+
12
+ __all__ = ["TransportInterface"]
13
+
14
+
15
+ @runtime_checkable
16
+ class TransportInterface(Protocol):
17
+ """Sends one event to one subscriber, or raises.
18
+
19
+ Its own contract rather than the transport class itself, because the send
20
+ handler and the bundle wire against *something that delivers*, and a test —
21
+ or an application with an unusual receiver — swaps in its own without
22
+ touching how deliveries are queued.
23
+
24
+ Returning nothing is the point: a delivery either happened or raised a
25
+ :class:`DeliveryError <xtr_webhook.exception.DeliveryError>`, and the error
26
+ is what makes the message bus retry it.
27
+ """
28
+
29
+ async def send(self, subscriber: Subscriber, event: RemoteEvent) -> None:
30
+ """Deliver ``event`` to ``subscriber``.
31
+
32
+ Args:
33
+ subscriber: Where the webhook goes, and the secret it is signed
34
+ with.
35
+ event: What to deliver.
36
+
37
+ Raises:
38
+ DeliveryError: When the receiver did not accept it.
39
+ """
40
+ ...