Repository navigation
Expand file tree
/
Copy pathidempotency.py
More file actions
62 lines (50 loc) · 2.16 KB
/
Copy pathidempotency.py
File metadata and controls
62 lines (50 loc) · 2.16 KB
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
"""Idempotency service that wraps an :class:`IdempotencyStore`.
Per PLAN.md §5.3, the dedupe key is the triple
``(issue_key, webhook_event_id, change_id)`` rather than the
``(issue_key, webhook_event_id)`` pair the earlier implementation used:
Atlassian retries occasionally re-emit the same ``webhook_event_id``
with different content (a follow-up edit hot on the heels of the
first), and including a per-event-kind change discriminator
(``comment.id`` for comment events, ``changelog.id`` for issue
updates, ``issue.fields.created`` for issue-created) prevents the
second event from being collapsed into the first.
The discriminator lives on :attr:`NormalizedJiraEvent.change_id` —
this service is intentionally a thin shim so the per-event-kind
mapping is owned by the domain model, not the application layer.
"""
from __future__ import annotations
import hashlib
from datetime import timedelta
from typing import Final
from agent.contracts.clock import Clock
from agent.contracts.idempotency import IdempotencyStore
from agent.domain.events import NormalizedJiraEvent
DEFAULT_TTL: Final[timedelta] = timedelta(days=14)
class IdempotencyService:
"""Compute deterministic dedupe keys and persist them with TTL."""
def __init__(
self,
store: IdempotencyStore,
clock: Clock,
*,
ttl: timedelta = DEFAULT_TTL,
) -> None:
self._store = store
self._clock = clock
self._ttl = ttl
def dedupe_key(self, event: NormalizedJiraEvent) -> str:
digest = hashlib.sha256()
digest.update(event.event_kind.encode())
digest.update(b"|")
digest.update(event.issue_key.encode())
digest.update(b"|")
digest.update(event.webhook_event_id.encode())
change_id = event.change_id
if change_id:
digest.update(b"|")
digest.update(change_id.encode())
return digest.hexdigest()
def claim(self, event: NormalizedJiraEvent) -> bool:
"""Return ``True`` if this is the first time we have seen ``event``."""
expires_at = self._clock.now() + self._ttl
return self._store.try_register(self.dedupe_key(event), expires_at=expires_at)