chimericmesh 0.2.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 (147) hide show
  1. chimericmesh/__init__.py +3 -0
  2. chimericmesh/__main__.py +119 -0
  3. chimericmesh/agent/__init__.py +21 -0
  4. chimericmesh/agent/codesearch.py +131 -0
  5. chimericmesh/agent/digest.py +131 -0
  6. chimericmesh/agent/errors.py +38 -0
  7. chimericmesh/agent/feed.py +47 -0
  8. chimericmesh/agent/limits.py +98 -0
  9. chimericmesh/agent/ports.py +32 -0
  10. chimericmesh/agent/routes.py +92 -0
  11. chimericmesh/agent/service.py +116 -0
  12. chimericmesh/agent/snippet.py +135 -0
  13. chimericmesh/agent/verify.py +215 -0
  14. chimericmesh/agent/watch.py +156 -0
  15. chimericmesh/api.py +626 -0
  16. chimericmesh/approvals/__init__.py +25 -0
  17. chimericmesh/approvals/errors.py +72 -0
  18. chimericmesh/approvals/format.py +76 -0
  19. chimericmesh/approvals/irc.py +54 -0
  20. chimericmesh/approvals/ledger.py +149 -0
  21. chimericmesh/approvals/limits.py +87 -0
  22. chimericmesh/approvals/manager.py +935 -0
  23. chimericmesh/approvals/matching.py +107 -0
  24. chimericmesh/approvals/models.py +251 -0
  25. chimericmesh/approvals/ports.py +36 -0
  26. chimericmesh/approvals/routes.py +220 -0
  27. chimericmesh/approvals/rulebook.py +337 -0
  28. chimericmesh/approvals/schema.py +64 -0
  29. chimericmesh/approvals/scope.py +104 -0
  30. chimericmesh/approvals/validate.py +215 -0
  31. chimericmesh/catalog/demo_apps.json +41 -0
  32. chimericmesh/catalog/legacy_apps.json +612 -0
  33. chimericmesh/commands.py +223 -0
  34. chimericmesh/connectors/__init__.py +1 -0
  35. chimericmesh/connectors/config.py +55 -0
  36. chimericmesh/connectors/framing.py +132 -0
  37. chimericmesh/connectors/limiter.py +42 -0
  38. chimericmesh/connectors/manager.py +252 -0
  39. chimericmesh/connectors/offsets.py +157 -0
  40. chimericmesh/connectors/schema.py +31 -0
  41. chimericmesh/connectors/submit.py +26 -0
  42. chimericmesh/connectors/syslog_tcp.py +141 -0
  43. chimericmesh/connectors/tailer.py +236 -0
  44. chimericmesh/connectors/tailread.py +288 -0
  45. chimericmesh/demo/__init__.py +1 -0
  46. chimericmesh/demo/agent.py +32 -0
  47. chimericmesh/demo/apps/__init__.py +1 -0
  48. chimericmesh/demo/apps/__main__.py +83 -0
  49. chimericmesh/demo/apps/common.py +163 -0
  50. chimericmesh/demo/apps/mail_bridge.py +48 -0
  51. chimericmesh/demo/apps/orders_api.py +31 -0
  52. chimericmesh/demo/apps/spooler.py +28 -0
  53. chimericmesh/demo/config.py +38 -0
  54. chimericmesh/demo/engine.py +68 -0
  55. chimericmesh/demo/env.py +46 -0
  56. chimericmesh/demo/hub.py +172 -0
  57. chimericmesh/demo/launcher.py +165 -0
  58. chimericmesh/demo/ports.py +44 -0
  59. chimericmesh/demo/routes.py +81 -0
  60. chimericmesh/demo/samples.py +32 -0
  61. chimericmesh/demo/scenario.py +95 -0
  62. chimericmesh/demo/supervisor.py +267 -0
  63. chimericmesh/demo/watch.py +46 -0
  64. chimericmesh/diagnostics.py +253 -0
  65. chimericmesh/discovery/__init__.py +17 -0
  66. chimericmesh/discovery/accept.py +131 -0
  67. chimericmesh/discovery/catalog.py +313 -0
  68. chimericmesh/discovery/collect.py +131 -0
  69. chimericmesh/discovery/dismissals.py +46 -0
  70. chimericmesh/discovery/engine.py +41 -0
  71. chimericmesh/discovery/errors.py +34 -0
  72. chimericmesh/discovery/expand.py +151 -0
  73. chimericmesh/discovery/manager.py +220 -0
  74. chimericmesh/discovery/match.py +177 -0
  75. chimericmesh/discovery/models.py +174 -0
  76. chimericmesh/discovery/parse.py +166 -0
  77. chimericmesh/discovery/probe.py +69 -0
  78. chimericmesh/discovery/routes.py +129 -0
  79. chimericmesh/discovery/runner.py +147 -0
  80. chimericmesh/discovery/schema.py +25 -0
  81. chimericmesh/discovery/text.py +53 -0
  82. chimericmesh/events.py +74 -0
  83. chimericmesh/fsperms.py +72 -0
  84. chimericmesh/hub.py +757 -0
  85. chimericmesh/listeners.py +162 -0
  86. chimericmesh/mcp_server.py +199 -0
  87. chimericmesh/mute/__init__.py +10 -0
  88. chimericmesh/mute/models.py +14 -0
  89. chimericmesh/mute/mutelist.py +51 -0
  90. chimericmesh/mute/routes.py +49 -0
  91. chimericmesh/mute/schema.py +29 -0
  92. chimericmesh/mute/store.py +94 -0
  93. chimericmesh/notify.py +47 -0
  94. chimericmesh/parsers/__init__.py +12 -0
  95. chimericmesh/parsers/formats.py +23 -0
  96. chimericmesh/parsers/irc.py +91 -0
  97. chimericmesh/parsers/logctx.py +143 -0
  98. chimericmesh/parsers/ncsa.py +57 -0
  99. chimericmesh/parsers/plain.py +17 -0
  100. chimericmesh/parsers/syslog.py +82 -0
  101. chimericmesh/parsers/syslogtext.py +62 -0
  102. chimericmesh/parsers/telnet.py +56 -0
  103. chimericmesh/parsers/w3c.py +58 -0
  104. chimericmesh/parsers/xferlog.py +31 -0
  105. chimericmesh/replay.py +108 -0
  106. chimericmesh/replay_irc.py +202 -0
  107. chimericmesh/services/__init__.py +39 -0
  108. chimericmesh/services/access.py +224 -0
  109. chimericmesh/services/asgi.py +107 -0
  110. chimericmesh/services/deps.py +42 -0
  111. chimericmesh/services/errors.py +49 -0
  112. chimericmesh/services/limiter.py +130 -0
  113. chimericmesh/services/models.py +160 -0
  114. chimericmesh/services/paths.py +139 -0
  115. chimericmesh/services/registry.py +638 -0
  116. chimericmesh/services/routes.py +161 -0
  117. chimericmesh/services/schema.py +48 -0
  118. chimericmesh/services/status.py +239 -0
  119. chimericmesh/services/tagging.py +63 -0
  120. chimericmesh/services/token.py +129 -0
  121. chimericmesh/services/validate.py +184 -0
  122. chimericmesh/store/__init__.py +43 -0
  123. chimericmesh/store/audit.py +89 -0
  124. chimericmesh/store/config.py +88 -0
  125. chimericmesh/store/connection.py +98 -0
  126. chimericmesh/store/errors.py +65 -0
  127. chimericmesh/store/events.py +430 -0
  128. chimericmesh/store/incidents.py +292 -0
  129. chimericmesh/store/migrations.py +109 -0
  130. chimericmesh/store/models.py +49 -0
  131. chimericmesh/store/ports.py +61 -0
  132. chimericmesh/store/proposals.py +215 -0
  133. chimericmesh/store/schema.py +102 -0
  134. chimericmesh/store/store.py +173 -0
  135. chimericmesh/store/tx.py +143 -0
  136. chimericmesh/store/writer.py +315 -0
  137. chimericmesh/web/__init__.py +1 -0
  138. chimericmesh/web/feed.py +212 -0
  139. chimericmesh/web/index.html +3775 -0
  140. chimericmesh/web/sse.py +74 -0
  141. chimericmesh/web/stream.py +64 -0
  142. chimericmesh-0.2.2.dist-info/METADATA +537 -0
  143. chimericmesh-0.2.2.dist-info/RECORD +147 -0
  144. chimericmesh-0.2.2.dist-info/WHEEL +5 -0
  145. chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
  146. chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
  147. chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,72 @@
1
+ """Errors of the auto-approval module. REST maps each one to a status; none carries log text."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class ApprovalsError(Exception):
6
+ """Base class."""
7
+
8
+
9
+ class ProposalInvalid(ApprovalsError):
10
+ """A proposal or completion field is out of bounds (REST 422)."""
11
+
12
+ def __init__(self, field: str, reason: str) -> None:
13
+ self.field = field
14
+ self.reason = reason
15
+ super().__init__(f"{field}: {reason}")
16
+
17
+
18
+ class RuleInvalid(ApprovalsError):
19
+ """A rule field is out of bounds (REST 422)."""
20
+
21
+ def __init__(self, field: str, reason: str) -> None:
22
+ self.field = field
23
+ self.reason = reason
24
+ super().__init__(f"{field}: {reason}")
25
+
26
+
27
+ class ActiveProposalExists(ApprovalsError):
28
+ """The incident already has a pending or approved proposal (REST 409)."""
29
+
30
+ def __init__(self, proposal_id: str) -> None:
31
+ self.proposal_id = proposal_id
32
+ super().__init__(f"incident already has active proposal {proposal_id}")
33
+
34
+
35
+ class ProposalRateLimited(ApprovalsError):
36
+ """The service reached its proposals per hour (REST 429)."""
37
+
38
+ def __init__(self, retry_after: int) -> None:
39
+ self.retry_after = max(1, int(retry_after))
40
+ super().__init__(f"too many proposals for this service, retry in {self.retry_after}s")
41
+
42
+
43
+ class RuleNotFound(ApprovalsError):
44
+ """Unknown rule id (REST 404)."""
45
+
46
+
47
+ class RuleConflict(ApprovalsError):
48
+ """The rule is not in a state that allows the operation (REST 409)."""
49
+
50
+ def __init__(self, reason: str) -> None:
51
+ self.reason = reason
52
+ super().__init__(reason)
53
+
54
+
55
+ class RuleNotApplicable(ApprovalsError):
56
+ """A rule cannot be made from this proposal (REST 409)."""
57
+
58
+ def __init__(self, reason: str) -> None:
59
+ self.reason = reason
60
+ super().__init__(reason)
61
+
62
+
63
+ class RuleLimitReached(ApprovalsError):
64
+ """20 rules for the service or 100 in total (REST 409)."""
65
+
66
+
67
+ class ProposalExpired(ApprovalsError):
68
+ """A rule approval older than its validity cannot be completed (REST 409)."""
69
+
70
+
71
+ class ApprovalsNotMigrated(ApprovalsError):
72
+ """The store was opened without the approvals migrations."""
@@ -0,0 +1,76 @@
1
+ """Announcement text and audit detail builders. Pure and total: nothing here raises on any input."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ _CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
7
+ _SPACES = re.compile(r" {2,}")
8
+ _SURROGATE = re.compile("[\ud800-\udfff]")
9
+ MAX_LINE_BYTES = 400
10
+
11
+
12
+ def safe_text(value: object, limit: int) -> str:
13
+ """Remove control characters and lone surrogates, collapse spaces, cut to ``limit`` characters."""
14
+ try:
15
+ text = str(value)
16
+ except Exception: # noqa: BLE001 - a hostile __str__ must not escape
17
+ return ""
18
+ text = _SURROGATE.sub("", text)
19
+ text = _CONTROL.sub(" ", text)
20
+ text = _SPACES.sub(" ", text).strip()
21
+ return text[:max(0, limit)].rstrip()
22
+
23
+
24
+ def _cut_bytes(text: str, limit: int) -> str:
25
+ """Cut to at most ``limit`` UTF-8 bytes without splitting a character."""
26
+ raw = text.encode("utf-8", "ignore")
27
+ if len(raw) <= limit:
28
+ return text
29
+ return raw[:limit].decode("utf-8", "ignore")
30
+
31
+
32
+ def auto_approved_line(pid: str, rid: str, sid: str, action: str) -> str:
33
+ """``AUTO-APPROVED p3 by rule r1 (service api-gw): <action>. Revoke with !revoke r1``.
34
+
35
+ Never says "reply !approve": nobody has to answer. At most 400 UTF-8 bytes.
36
+ """
37
+ head = f"AUTO-APPROVED {safe_text(pid, 20)} by rule {safe_text(rid, 20)} (service {safe_text(sid, 40)}): "
38
+ tail = f". Revoke with !revoke {safe_text(rid, 20)}"
39
+ room = MAX_LINE_BYTES - len(head.encode("utf-8")) - len(tail.encode("utf-8"))
40
+ body = _cut_bytes(safe_text(action, 200), max(0, room)).rstrip()
41
+ return head + body + tail
42
+
43
+
44
+ def cooldown_note(prior_pid: str, rule_id: str) -> str:
45
+ return (f" (rule {safe_text(rule_id, 20)} did not auto-approve it: the earlier fix "
46
+ f"{safe_text(prior_pid, 20)} was completed shortly before this reopen)")
47
+
48
+
49
+ def rule_line(verb: str, rid: str, sid: str, actor: str, extra: str = "") -> str:
50
+ """One announcement for a rule or proposal event. ``actor`` and ``extra`` are cleaned and cut."""
51
+ who = safe_text(actor, 40) or "unknown"
52
+ more = safe_text(extra, 120)
53
+ rid, sid = safe_text(rid, 20), safe_text(sid, 40)
54
+ if verb == "created":
55
+ text = f"RULE {rid} created by {who} for {sid}"
56
+ elif verb == "revoked":
57
+ text = f"RULE {rid} revoked by {who}"
58
+ elif verb == "rule_paused":
59
+ text = f"RULE {rid} paused by {who}"
60
+ elif verb == "enabled":
61
+ text = f"RULE {rid} re-enabled by {who}"
62
+ elif verb == "suspended":
63
+ text = f"RULE {rid} suspended by {who}: {more}" if more else f"RULE {rid} suspended by {who}"
64
+ elif verb == "expired":
65
+ text = f"RULE {rid} expired ({who})"
66
+ elif verb == "paused":
67
+ text = f"AUTO-APPROVAL paused by {who}"
68
+ elif verb == "resumed":
69
+ text = f"AUTO-APPROVAL resumed by {who}"
70
+ elif verb == "withdrawn":
71
+ text = f"PROPOSAL {rid} withdrawn by {who}"
72
+ elif verb == "denied": # rid is the proposal id, sid the rule id
73
+ text = f"PROPOSAL {rid} denied by {who}: rule {sid} {more or 'is no longer active'}"
74
+ else:
75
+ text = f"RULE {rid} {safe_text(verb, 20)} by {who}"
76
+ return _cut_bytes(text, MAX_LINE_BYTES)
@@ -0,0 +1,54 @@
1
+ """Pure renderers for ``!rules`` and the replies of ``!revoke``, ``!pause`` and ``!withdraw`` (R8).
2
+
3
+ Every value that comes from a log or a user is cleaned and cut here, so the reply can never carry a
4
+ control character. ``commands.py`` adds the ``[mesh]`` prefix.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from collections.abc import Sequence
10
+
11
+ from .format import safe_text
12
+ from .models import Rule
13
+
14
+ MAX_LIST = 5
15
+ USAGE_REVOKE = "usage: !revoke <rule id>"
16
+ USAGE_WITHDRAW = "usage: !withdraw <proposal id>"
17
+ HELP_LINE = "rules: !rules !revoke <rid> !pause !withdraw <pid> (any registered nick)"
18
+ NAMES = ("rules", "revoke", "pause", "withdraw")
19
+
20
+
21
+ def rules_lines(rules: Sequence[Rule]) -> list[str]:
22
+ """At most five active rules: ``r1 api-gw signature "<cut to 40>" expires <yyyy-mm-dd>``."""
23
+ active = [r for r in rules if r.status == "active"][:MAX_LIST]
24
+ if not active:
25
+ return ["no active rules"]
26
+ return [f'{safe_text(r.id, 20)} {safe_text(r.service_id, 40)} {safe_text(r.match_type, 12)} '
27
+ f'"{safe_text(r.match_value, 40)}" expires {time.strftime("%Y-%m-%d", time.gmtime(r.expires_at))}'
28
+ for r in active]
29
+
30
+
31
+ def no_rule(rule_id: str) -> str:
32
+ return f"no rule with id {safe_text(rule_id, 30)}"
33
+
34
+
35
+ def no_proposal(proposal_id: str) -> str:
36
+ return f"no proposal with id {safe_text(proposal_id, 30)}"
37
+
38
+
39
+ def revoke_reply(rule_id: str, status_before: str) -> str:
40
+ rid = safe_text(rule_id, 30)
41
+ if status_before in ("revoked", "expired"):
42
+ return f"{rid} is already {status_before}"
43
+ return f"revoked {rid}"
44
+
45
+
46
+ def pause_reply(was_paused: bool) -> str:
47
+ return "auto-approval is already paused" if was_paused else "auto-approval paused"
48
+
49
+
50
+ def withdraw_reply(proposal_id: str, status_before: str) -> str:
51
+ pid = safe_text(proposal_id, 30)
52
+ if status_before != "pending":
53
+ return f"{pid} is already {safe_text(status_before, 12)}, nothing to withdraw"
54
+ return f"withdrawn {pid}"
@@ -0,0 +1,149 @@
1
+ """Usage ledger: the hour window, per-opening counts, completions and observed reopens (loop thread only).
2
+
3
+ The cooldown (R4.9, review H1) is one formula and nothing else:
4
+
5
+ cooldown_for(incident, opening) returns the id of a use U of this incident with
6
+ ``U.opening < opening`` and ``U.completed_at`` set, such that
7
+ ``reopen_at(incident, opening) - U.completed_at < cooldown``.
8
+
9
+ ``reopen_at`` is the first time the manager saw that opening and never changes, so the answer for a
10
+ given opening does not depend on when the question is asked.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable
15
+ from dataclasses import dataclass
16
+
17
+ from .matching import RuleUsage
18
+
19
+ HOUR = 3600.0
20
+ RETENTION = 31 * 86400.0
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class UsageRow:
25
+ rule_id: str
26
+ proposal_id: str
27
+ incident_id: str
28
+ opening: int
29
+ service_id: str | None
30
+ approved_at: float
31
+ completed_at: float | None
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class OpeningRow:
36
+ incident_id: str
37
+ opening: int
38
+ first_seen_at: float
39
+
40
+
41
+ @dataclass(slots=True)
42
+ class _Use:
43
+ token: int
44
+ rule_id: str
45
+ incident_id: str
46
+ opening: int
47
+ approved_at: float
48
+ proposal_id: str | None = None
49
+ completed_at: float | None = None
50
+
51
+
52
+ class UsageLedger:
53
+ def __init__(self) -> None:
54
+ self._uses: dict[int, _Use] = {}
55
+ self._by_proposal: dict[str, int] = {}
56
+ self._openings: dict[tuple[str, int], float] = {}
57
+ self._next = 0
58
+
59
+ def usage(self, rule_id: str, incident_id: str, opening: int, now: float) -> RuleUsage:
60
+ hour = per_opening = 0
61
+ for use in self._uses.values():
62
+ if use.rule_id != rule_id:
63
+ continue
64
+ if now - use.approved_at < HOUR:
65
+ hour += 1
66
+ if use.incident_id == incident_id and use.opening == opening:
67
+ per_opening += 1
68
+ return RuleUsage(hour=hour, incident_opening=per_opening)
69
+
70
+ def reserve(self, rule_id: str, incident_id: str, opening: int, now: float) -> int:
71
+ self._next += 1
72
+ self._uses[self._next] = _Use(self._next, rule_id, incident_id, opening, now)
73
+ return self._next
74
+
75
+ def release(self, token: int) -> None:
76
+ use = self._uses.pop(token, None)
77
+ if use is not None and use.proposal_id is not None:
78
+ self._by_proposal.pop(use.proposal_id, None)
79
+
80
+ def bind(self, token: int, proposal_id: str) -> None:
81
+ use = self._uses.get(token)
82
+ if use is not None:
83
+ use.proposal_id = proposal_id
84
+ self._by_proposal[proposal_id] = token
85
+
86
+ def completed(self, proposal_id: str, now: float) -> None:
87
+ token = self._by_proposal.get(proposal_id)
88
+ if token is not None and token in self._uses:
89
+ self._uses[token].completed_at = now
90
+
91
+ def note_opening(self, incident_id: str, opening: int, now: float) -> bool:
92
+ """Record the first sighting of an opening. True when it was new; the first time never moves."""
93
+ key = (incident_id, opening)
94
+ if key in self._openings:
95
+ return False
96
+ self._openings[key] = now
97
+ return True
98
+
99
+ def reopen_at(self, incident_id: str, opening: int) -> float | None:
100
+ return self._openings.get((incident_id, opening))
101
+
102
+ def cooldown_for(self, incident_id: str, opening: int, cooldown: float) -> str | None:
103
+ seen = self.reopen_at(incident_id, opening)
104
+ if seen is None:
105
+ return None
106
+ best: _Use | None = None
107
+ for use in self._uses.values():
108
+ if (use.incident_id != incident_id or use.opening >= opening or use.completed_at is None
109
+ or use.proposal_id is None):
110
+ continue
111
+ if seen - use.completed_at < cooldown and (best is None or use.completed_at > (best.completed_at or 0.0)):
112
+ best = use
113
+ return None if best is None else best.proposal_id
114
+
115
+ def approved_at(self, proposal_id: str) -> float | None:
116
+ token = self._by_proposal.get(proposal_id)
117
+ use = self._uses.get(token) if token is not None else None
118
+ return None if use is None else use.approved_at
119
+
120
+ def uses_of(self, incident_id: str) -> list[_Use]:
121
+ return [u for u in self._uses.values() if u.incident_id == incident_id]
122
+
123
+ def completed_uses(self) -> list[tuple[str, int, str]]:
124
+ """(incident id, opening, proposal id) of every completed use: the sweep watches these for reopens."""
125
+ return [(u.incident_id, u.opening, u.proposal_id) for u in self._uses.values()
126
+ if u.completed_at is not None and u.proposal_id is not None]
127
+
128
+ def incomplete_proposals(self) -> list[str]:
129
+ return [u.proposal_id for u in self._uses.values() if u.proposal_id and u.completed_at is None]
130
+
131
+ def seed(self, rows: Iterable[UsageRow], openings: Iterable[OpeningRow]) -> None:
132
+ for row in rows:
133
+ self._next += 1
134
+ use = _Use(self._next, row.rule_id, row.incident_id, row.opening, row.approved_at, row.proposal_id,
135
+ row.completed_at)
136
+ self._uses[self._next] = use
137
+ self._by_proposal[row.proposal_id] = self._next
138
+ for op in openings:
139
+ self._openings.setdefault((op.incident_id, op.opening), op.first_seen_at)
140
+
141
+ def prune(self, now: float) -> None:
142
+ for token, use in list(self._uses.items()):
143
+ if now - use.approved_at >= RETENTION:
144
+ del self._uses[token]
145
+ if use.proposal_id is not None:
146
+ self._by_proposal.pop(use.proposal_id, None)
147
+ for key, seen in list(self._openings.items()):
148
+ if now - seen >= RETENTION:
149
+ del self._openings[key]
@@ -0,0 +1,87 @@
1
+ """Proposal creation limits: one active proposal per incident and a per-service hourly rate (R9.3, R9.4)."""
2
+ from __future__ import annotations
3
+
4
+ from collections import deque
5
+ from collections.abc import Callable, Mapping, Sequence
6
+
7
+ from .errors import ActiveProposalExists, ProposalRateLimited
8
+
9
+ MAX_PROPOSALS_PER_SERVICE_HOUR = 10 # the one constant (R1.4, R9.4)
10
+ WINDOW_SECONDS = 3600.0
11
+ UNASSIGNED_KEY = "unassigned"
12
+
13
+
14
+ class ProposalLimits:
15
+ """Loop thread only. ``reserve`` runs in the same await-free block as rule evaluation."""
16
+
17
+ def __init__(self) -> None:
18
+ self._times: dict[str, deque[float]] = {}
19
+ self._tokens: dict[int, tuple[str, str, float]] = {} # token -> (service key, incident id, time)
20
+ self._by_incident: dict[str, int] = {} # incident id -> token of an in-flight reservation
21
+ self._next = 0
22
+
23
+ def _prune(self, key: str, now: float) -> deque[float]:
24
+ times = self._times.setdefault(key, deque())
25
+ while times and now - times[0] >= WINDOW_SECONDS:
26
+ times.popleft()
27
+ return times
28
+
29
+ def reserve(self, incident_id: str, service_key: str, now: float, *, enforce: bool,
30
+ active_of: Callable[[str], str | None]) -> int:
31
+ """Reserve one slot. With ``enforce`` false nothing is checked or reserved (token 0)."""
32
+ if not enforce:
33
+ return 0
34
+ if incident_id in self._by_incident:
35
+ holder = self._by_incident[incident_id]
36
+ raise ActiveProposalExists(f"in-flight-{holder}")
37
+ existing = active_of(incident_id)
38
+ if existing is not None:
39
+ raise ActiveProposalExists(existing)
40
+ key = service_key or UNASSIGNED_KEY
41
+ times = self._prune(key, now)
42
+ if len(times) >= MAX_PROPOSALS_PER_SERVICE_HOUR:
43
+ retry = int(WINDOW_SECONDS - (now - times[0])) + 1
44
+ raise ProposalRateLimited(retry)
45
+ self._next += 1
46
+ token = self._next
47
+ times.append(now)
48
+ self._tokens[token] = (key, incident_id, now)
49
+ self._by_incident[incident_id] = token
50
+ return token
51
+
52
+ def release(self, token: int) -> None:
53
+ """Free the slot of a reservation that did not commit."""
54
+ entry = self._tokens.pop(token, None)
55
+ if entry is None:
56
+ return
57
+ key, incident_id, at = entry
58
+ if self._by_incident.get(incident_id) == token:
59
+ del self._by_incident[incident_id]
60
+ times = self._times.get(key)
61
+ if times is not None:
62
+ try:
63
+ times.remove(at)
64
+ except ValueError:
65
+ pass
66
+
67
+ def commit(self, token: int) -> None:
68
+ """Keep the slot (it counts for an hour) and stop treating the incident as in flight."""
69
+ entry = self._tokens.pop(token, None)
70
+ if entry is None:
71
+ return
72
+ if self._by_incident.get(entry[1]) == token:
73
+ del self._by_incident[entry[1]]
74
+
75
+ def count(self, service_key: str, now: float) -> int:
76
+ return len(self._prune(service_key or UNASSIGNED_KEY, now))
77
+
78
+ def seed(self, created_by_service: Mapping[str, Sequence[float]], now: float | None = None) -> None:
79
+ """Load creation times of the last hour (restart). Older times are ignored when ``now`` is given."""
80
+ for key, stamps in created_by_service.items():
81
+ times = self._times.setdefault(key or UNASSIGNED_KEY, deque())
82
+ fresh = sorted(t for t in stamps if now is None or now - t < WINDOW_SECONDS)
83
+ for t in fresh:
84
+ times.append(t)
85
+ ordered = sorted(times)
86
+ times.clear()
87
+ times.extend(ordered)