hookstride-cli 0.3.0__py3-none-any.whl → 0.3.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.
Potentially problematic release.
This version of hookstride-cli might be problematic. Click here for more details.
- hookstride_cli/__init__.py +1 -1
- hookstride_cli/console.py +72 -23
- hookstride_cli/listen.py +218 -0
- hookstride_cli/main.py +346 -14
- hookstride_cli-0.3.2.dist-info/METADATA +412 -0
- hookstride_cli-0.3.2.dist-info/RECORD +8 -0
- hookstride_cli-0.3.0.dist-info/METADATA +0 -136
- hookstride_cli-0.3.0.dist-info/RECORD +0 -7
- {hookstride_cli-0.3.0.dist-info → hookstride_cli-0.3.2.dist-info}/WHEEL +0 -0
- {hookstride_cli-0.3.0.dist-info → hookstride_cli-0.3.2.dist-info}/entry_points.txt +0 -0
hookstride_cli/__init__.py
CHANGED
hookstride_cli/console.py
CHANGED
|
@@ -27,15 +27,16 @@ from . import main as cli
|
|
|
27
27
|
# Write actions are intentionally allowlisted, never automatically unlocked.
|
|
28
28
|
ALLOWED_COMMANDS: dict[str, set[str]] = {
|
|
29
29
|
"auth": {"status"},
|
|
30
|
+
"actions": {"list", "context", "workspaces", "preview", "apply"},
|
|
30
31
|
"projects": {"list", "use", "create", "update"},
|
|
31
32
|
"destinations": {"list", "create", "update"},
|
|
32
33
|
"keys": {"list"},
|
|
33
|
-
"events": {"list", "show"},
|
|
34
|
+
"events": {"list", "show", "send", "export"},
|
|
34
35
|
"billing": {"status", "history"},
|
|
35
36
|
"incoming": {"sources", "routes", "bindings", "registration-keys"},
|
|
36
37
|
"config": {"show"},
|
|
37
38
|
}
|
|
38
|
-
ROOT_COMMANDS = {"status", "stats"}
|
|
39
|
+
ROOT_COMMANDS = {"status", "stats", "metrics", "listen"}
|
|
39
40
|
|
|
40
41
|
# Aliases that feel like a familiar operator console.
|
|
41
42
|
SHOW_TARGETS: dict[str, tuple[str, ...] | None] = {
|
|
@@ -51,17 +52,18 @@ SHOW_TARGETS: dict[str, tuple[str, ...] | None] = {
|
|
|
51
52
|
"bindings": ("incoming", "bindings"),
|
|
52
53
|
"registration-keys": ("incoming", "registration-keys"),
|
|
53
54
|
"stats": ("stats",),
|
|
55
|
+
"metrics": ("metrics",),
|
|
54
56
|
"status": ("status",),
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
SAFE_HISTORY_COMMANDS = frozenset(
|
|
58
60
|
[
|
|
59
|
-
"help", "?", "clear", "exit", "quit", "back", "status", "stats",
|
|
61
|
+
"help", "?", "clear", "exit", "quit", "back", "status", "stats", "metrics",
|
|
60
62
|
"history", "auth login", "auth logout", "auth status",
|
|
61
63
|
"projects list", "destinations list", "keys list", "billing status",
|
|
62
64
|
"billing history", "events list", "incoming sources",
|
|
63
65
|
"incoming routes", "incoming bindings", "incoming registration-keys",
|
|
64
|
-
"config show",
|
|
66
|
+
"config show", "actions list", "actions context", "actions workspaces",
|
|
65
67
|
*(f"show {name}" for name in SHOW_TARGETS),
|
|
66
68
|
"set env dev", "set env production",
|
|
67
69
|
]
|
|
@@ -69,7 +71,7 @@ SAFE_HISTORY_COMMANDS = frozenset(
|
|
|
69
71
|
COMMAND_COMPLETIONS = sorted(
|
|
70
72
|
{
|
|
71
73
|
*SAFE_HISTORY_COMMANDS,
|
|
72
|
-
"use ", "projects use ", "events show ", "events list --status ",
|
|
74
|
+
"actions preview ", "actions apply ", "metrics --days ", "listen ", "use ", "projects use ", "events show ", "events send ", "events list --status ",
|
|
73
75
|
"events list --origin ", "events list --page ", "set project ",
|
|
74
76
|
"projects create --name ", "projects update ",
|
|
75
77
|
"destinations create --name ", "destinations update ",
|
|
@@ -85,6 +87,14 @@ def _project_uuid(value: str) -> str:
|
|
|
85
87
|
raise cli.CLIError("Expected a valid project UUID.") from None
|
|
86
88
|
|
|
87
89
|
|
|
90
|
+
def _is_project_uuid(value: str) -> bool:
|
|
91
|
+
try:
|
|
92
|
+
_project_uuid(value)
|
|
93
|
+
return True
|
|
94
|
+
except cli.CLIError:
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
|
|
88
98
|
def _saved_project(environment: str) -> str | None:
|
|
89
99
|
settings = cli._read_config().get("projects", {})
|
|
90
100
|
value = settings.get(environment) if isinstance(settings, dict) else None
|
|
@@ -106,19 +116,15 @@ def _history_safe(line: str) -> bool:
|
|
|
106
116
|
return True
|
|
107
117
|
tokens = line.split()
|
|
108
118
|
if len(tokens) == 2 and tokens[0] == "use":
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return True
|
|
112
|
-
except cli.CLIError:
|
|
113
|
-
return False
|
|
119
|
+
return (tokens[1].isascii() and tokens[1].isdecimal()
|
|
120
|
+
and len(tokens[1]) <= 6) or _is_project_uuid(tokens[1])
|
|
114
121
|
if len(tokens) == 3 and tokens[:2] in (
|
|
115
122
|
["projects", "use"], ["set", "project"], ["events", "show"],
|
|
116
123
|
):
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return False
|
|
124
|
+
return ((tokens[:2] != ["events", "show"]
|
|
125
|
+
and tokens[2].isascii() and tokens[2].isdecimal()
|
|
126
|
+
and len(tokens[2]) <= 6)
|
|
127
|
+
or _is_project_uuid(tokens[2]))
|
|
122
128
|
return False
|
|
123
129
|
|
|
124
130
|
|
|
@@ -130,6 +136,27 @@ class SafeMemoryHistory(InMemoryHistory):
|
|
|
130
136
|
super().append_string(string)
|
|
131
137
|
|
|
132
138
|
|
|
139
|
+
|
|
140
|
+
def _missing_send_destination(args: list[str]) -> bool:
|
|
141
|
+
"""Check the required send argument before Typer can exit the console."""
|
|
142
|
+
# We deliberately inspect only known options. Unknown options remain
|
|
143
|
+
# Click's responsibility, without interpreting their values as a key.
|
|
144
|
+
index = 2
|
|
145
|
+
valued = {"--type", "--payload-file", "--timeout"}
|
|
146
|
+
while index < len(args):
|
|
147
|
+
token = args[index]
|
|
148
|
+
if token in {"--help", "-h"}:
|
|
149
|
+
return False
|
|
150
|
+
if token in valued:
|
|
151
|
+
index += 2
|
|
152
|
+
continue
|
|
153
|
+
if token in {"--wait", "--no-wait"} or token.startswith("--"):
|
|
154
|
+
index += 1
|
|
155
|
+
continue
|
|
156
|
+
return False # A positional destination argument was supplied.
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
|
|
133
160
|
class HookstrideConsole:
|
|
134
161
|
def __init__(self, session: cli.Session) -> None:
|
|
135
162
|
self.session = session
|
|
@@ -197,7 +224,8 @@ class HookstrideConsole:
|
|
|
197
224
|
"[bold]show projects[/bold] List accessible projects\n"
|
|
198
225
|
"[bold]projects create --name N --account UUID[/bold] Create a project\n"
|
|
199
226
|
"[bold]projects update UUID --name N[/bold] Rename a project\n"
|
|
200
|
-
"[bold]use
|
|
227
|
+
"[bold]use 1[/bold] Select by number from 'show projects'\n"
|
|
228
|
+
"[bold]use UUID[/bold] Or select by full project ID\n"
|
|
201
229
|
"[bold]back[/bold] Leave the active project context\n"
|
|
202
230
|
"[bold]set env dev[/bold] Switch to development API\n"
|
|
203
231
|
"[bold]set env production[/bold] Switch to production API\n"
|
|
@@ -210,8 +238,12 @@ class HookstrideConsole:
|
|
|
210
238
|
"[bold]show events[/bold] View recent events\n"
|
|
211
239
|
"[bold]events list --status failed[/bold] Filter delivery history\n"
|
|
212
240
|
"[bold]events show UUID[/bold] Inspect a delivery and attempts\n"
|
|
241
|
+
"[bold]events send DEST_UUID --wait[/bold] Send one signed delivery test\n"
|
|
242
|
+
"[bold]metrics --days 7[/bold] Inspect queue health and delivery results\n"
|
|
243
|
+
"[bold]actions list[/bold] List permitted confirmed actions\n"
|
|
213
244
|
"[bold]show billing[/bold] View plan and credits\n"
|
|
214
245
|
"[bold]show payments[/bold] View payment history\n"
|
|
246
|
+
"[bold]listen 8000 --path /webhooks --source UUID[/bold] Local preview (opt-in)\n"
|
|
215
247
|
"[bold]show sources[/bold] Inspect incoming sources\n"
|
|
216
248
|
"[bold]show keys[/bold] List masked keys\n"
|
|
217
249
|
"[bold]json projects list[/bold] Print the complete JSON response\n"
|
|
@@ -304,9 +336,13 @@ class HookstrideConsole:
|
|
|
304
336
|
group = args[0]
|
|
305
337
|
action = args[1] if len(args) > 1 else None
|
|
306
338
|
if _requires_project(group, action) and not self.project:
|
|
307
|
-
raise cli.CLIError("No project selected. Run 'show projects' then 'use UUID'.")
|
|
339
|
+
raise cli.CLIError("No project selected. Run 'show projects' then 'use 1' or 'use UUID'.")
|
|
308
340
|
if _requires_token(group, action) and not self._current_token():
|
|
309
341
|
raise cli.CLIError("No management token for this environment. Run 'auth login'.")
|
|
342
|
+
if args[:2] == ["events", "show"] and len(args) == 2:
|
|
343
|
+
raise cli.CLIError("Usage: events show EVENT_UUID.")
|
|
344
|
+
if args[:2] == ["events", "send"] and _missing_send_destination(args):
|
|
345
|
+
raise cli.CLIError("Usage: events send DESTINATION_UUID [--wait].")
|
|
310
346
|
options = ["--env", self.environment, "--api-url", self.session.origin]
|
|
311
347
|
if self.project:
|
|
312
348
|
options += ["--project", self.project]
|
|
@@ -320,16 +356,26 @@ class HookstrideConsole:
|
|
|
320
356
|
standalone_mode=False,
|
|
321
357
|
)
|
|
322
358
|
except click.exceptions.Exit as exc:
|
|
323
|
-
#
|
|
324
|
-
|
|
359
|
+
# The nested CLI must never terminate the interactive console.
|
|
360
|
+
if exc.exit_code == 0:
|
|
361
|
+
return
|
|
362
|
+
# 'status' already displayed a red Offline panel.
|
|
325
363
|
if group == "status" and not json_output and exc.exit_code == 1:
|
|
326
364
|
return
|
|
327
365
|
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
366
|
+
except SystemExit as exc:
|
|
367
|
+
# Some Typer/Click error paths raise SystemExit instead of Exit.
|
|
368
|
+
# Do not let them unwind run() and clear in-memory authentication.
|
|
369
|
+
if exc.code in (0, None):
|
|
370
|
+
return
|
|
371
|
+
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
328
372
|
except (click.ClickException, click.Abort):
|
|
329
373
|
# Click errors can quote user-provided arguments; don't echo them.
|
|
330
374
|
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
331
375
|
if args[:2] == ["projects", "use"]:
|
|
332
|
-
|
|
376
|
+
# The CLI resolves numeric choices against the authorized project
|
|
377
|
+
# list, validates the project, and persists its *UUID* only.
|
|
378
|
+
self.project = _saved_project(self.environment)
|
|
333
379
|
self.session.project = self.project
|
|
334
380
|
|
|
335
381
|
def execute_line(self, line: str) -> bool:
|
|
@@ -353,7 +399,7 @@ class HookstrideConsole:
|
|
|
353
399
|
elif command == "back" and len(parts) == 1:
|
|
354
400
|
self.project = None
|
|
355
401
|
self.session.project = None
|
|
356
|
-
self._write("[dim]Project context cleared. Run 'use
|
|
402
|
+
self._write("[dim]Project context cleared. Run 'show projects' then 'use 1' or 'use UUID'.[/dim]")
|
|
357
403
|
elif command == "set" and len(parts) == 3 and parts[1].lower() == "env":
|
|
358
404
|
self._set_environment(parts[2].lower())
|
|
359
405
|
elif command == "set" and len(parts) == 3 and parts[1].lower() == "project":
|
|
@@ -431,6 +477,8 @@ def _env_hint(token: str | None) -> str:
|
|
|
431
477
|
def _allowed_cli(parts: list[str]) -> bool:
|
|
432
478
|
if not parts:
|
|
433
479
|
return False
|
|
480
|
+
if parts[0] == "listen":
|
|
481
|
+
return True
|
|
434
482
|
if parts[0] in ROOT_COMMANDS:
|
|
435
483
|
return len(parts) == 1
|
|
436
484
|
return (
|
|
@@ -442,12 +490,13 @@ def _allowed_cli(parts: list[str]) -> bool:
|
|
|
442
490
|
|
|
443
491
|
def _requires_project(group: str, action: str | None) -> bool:
|
|
444
492
|
return group in {
|
|
445
|
-
"destinations", "keys", "events", "billing", "incoming",
|
|
493
|
+
"destinations", "keys", "events", "billing", "incoming", "listen",
|
|
446
494
|
} or group == "stats"
|
|
447
495
|
|
|
448
496
|
|
|
449
497
|
def _requires_token(group: str, action: str | None) -> bool:
|
|
450
|
-
return group != "status" and not (group == "config" and action == "show")
|
|
498
|
+
return (group != "status" and not (group == "config" and action == "show")
|
|
499
|
+
and not (group == "events" and action == "send"))
|
|
451
500
|
|
|
452
501
|
|
|
453
502
|
def run_console(session: cli.Session) -> None:
|
hookstride_cli/listen.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Opt-in local preview: outbound polling and numeric loopback-only HTTP delivery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from urllib.parse import unquote
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
MAX_EVENT_BYTES = 64 * 1024
|
|
15
|
+
MAX_RESPONSE_BYTES = 400 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ListenStopped(Exception):
|
|
19
|
+
"""A fixed, credential-free failure suitable for terminal output."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RetryPoll(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def local_url(port: int, path: str) -> str:
|
|
27
|
+
decoded = unquote(path)
|
|
28
|
+
if not 1 <= port <= 65535 or not re.fullmatch(r"/[A-Za-z0-9._~/%-]*", path):
|
|
29
|
+
raise ListenStopped("Use a valid loopback port and an absolute HTTP path.")
|
|
30
|
+
if (
|
|
31
|
+
decoded.startswith("//")
|
|
32
|
+
or ".." in decoded.split("/")
|
|
33
|
+
or "\\" in decoded
|
|
34
|
+
or any(ord(ch) < 32 or ord(ch) == 127 for ch in decoded)
|
|
35
|
+
):
|
|
36
|
+
raise ListenStopped("Use a plain local receiver path without traversal.")
|
|
37
|
+
return f"http://127.0.0.1:{port}{path}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def api_call(client, path, body, *, method="POST"):
|
|
41
|
+
try:
|
|
42
|
+
with client.stream(method, path, json=body) as response:
|
|
43
|
+
if response.status_code in (401, 403, 404):
|
|
44
|
+
raise ListenStopped(
|
|
45
|
+
"Access ended, session expired, or local forwarding is not enabled."
|
|
46
|
+
)
|
|
47
|
+
if response.status_code in (409, 429) or response.status_code >= 500:
|
|
48
|
+
raise RetryPoll()
|
|
49
|
+
if response.status_code == 410:
|
|
50
|
+
raw = bytearray()
|
|
51
|
+
for chunk in response.iter_bytes(chunk_size=8192):
|
|
52
|
+
raw.extend(chunk)
|
|
53
|
+
if len(raw) > 4096:
|
|
54
|
+
break
|
|
55
|
+
try:
|
|
56
|
+
reason = json.loads(raw).get("reason")
|
|
57
|
+
except (ValueError, AttributeError):
|
|
58
|
+
reason = None
|
|
59
|
+
messages = {
|
|
60
|
+
"queue_full": "Local session stopped: preview queue is full. Use a faster receiver.",
|
|
61
|
+
"payload_too_large": "Local session stopped: event exceeds the local payload limit.",
|
|
62
|
+
"delivery_limit": "Local session stopped: delivery retry limit reached.",
|
|
63
|
+
}
|
|
64
|
+
raise ListenStopped(messages.get(reason, "Local session expired or revoked."))
|
|
65
|
+
if not 200 <= response.status_code < 300:
|
|
66
|
+
raise ListenStopped("Local forwarding API rejected the request.")
|
|
67
|
+
raw = bytearray()
|
|
68
|
+
for chunk in response.iter_bytes(chunk_size=8192):
|
|
69
|
+
raw.extend(chunk)
|
|
70
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
71
|
+
raise ListenStopped("Forwarding response exceeds the safety limit.")
|
|
72
|
+
data = json.loads(raw)
|
|
73
|
+
if not isinstance(data, dict):
|
|
74
|
+
raise ValueError
|
|
75
|
+
return data
|
|
76
|
+
except (httpx.HTTPError, httpx.InvalidURL):
|
|
77
|
+
raise RetryPoll() from None
|
|
78
|
+
except (ValueError, TypeError):
|
|
79
|
+
raise ListenStopped("Invalid forwarding response.") from None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def checked_event(item, source_id):
|
|
83
|
+
try:
|
|
84
|
+
event = item["event"]
|
|
85
|
+
event_id = str(uuid.UUID(event["id"]))
|
|
86
|
+
if str(uuid.UUID(event["source_id"])) != source_id:
|
|
87
|
+
raise ValueError
|
|
88
|
+
if not isinstance(event["type"], str) or len(event["type"]) > 160:
|
|
89
|
+
raise ValueError
|
|
90
|
+
if not isinstance(event["data"], dict):
|
|
91
|
+
raise ValueError
|
|
92
|
+
body = json.dumps(event, ensure_ascii=True, separators=(",", ":")).encode()
|
|
93
|
+
if len(body) > MAX_EVENT_BYTES:
|
|
94
|
+
raise ListenStopped("Event exceeds the local payload limit.")
|
|
95
|
+
attempt = item["attempt"]
|
|
96
|
+
if type(attempt) is not int or not 1 <= attempt <= 20:
|
|
97
|
+
raise ValueError
|
|
98
|
+
return event_id, body, attempt
|
|
99
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
100
|
+
raise ListenStopped("Invalid forwarding event.") from None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def run_listener(*, origin, token, project_id, source_id, target, ttl, report, resume=None):
|
|
104
|
+
"""Keep credentials in memory. Never use local HTTP proxies or print bodies."""
|
|
105
|
+
base = f"/control/v1/projects/{project_id}/local-sessions/"
|
|
106
|
+
session_id = None
|
|
107
|
+
stopped = False
|
|
108
|
+
with (
|
|
109
|
+
httpx.Client(
|
|
110
|
+
base_url=origin,
|
|
111
|
+
headers={"Authorization": "Bearer " + token, "Accept": "application/json"},
|
|
112
|
+
timeout=25,
|
|
113
|
+
follow_redirects=False,
|
|
114
|
+
) as api,
|
|
115
|
+
httpx.Client(
|
|
116
|
+
timeout=httpx.Timeout(5, connect=2), follow_redirects=False, trust_env=False
|
|
117
|
+
) as receiver,
|
|
118
|
+
):
|
|
119
|
+
try:
|
|
120
|
+
try:
|
|
121
|
+
if resume:
|
|
122
|
+
active = api_call(api, base, None, method="GET").get("sessions", [])
|
|
123
|
+
if not isinstance(active, list) or any(not isinstance(i, dict) for i in active):
|
|
124
|
+
raise ListenStopped("Invalid session list response.")
|
|
125
|
+
created = next(
|
|
126
|
+
(
|
|
127
|
+
item
|
|
128
|
+
for item in active
|
|
129
|
+
if item.get("id") == resume and item.get("source_id") == source_id
|
|
130
|
+
),
|
|
131
|
+
None,
|
|
132
|
+
)
|
|
133
|
+
if not created:
|
|
134
|
+
raise ListenStopped(
|
|
135
|
+
"Session is no longer active for this token and source."
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
created = api_call(api, base, {"source_id": source_id, "ttl_seconds": ttl})
|
|
139
|
+
except RetryPoll:
|
|
140
|
+
raise ListenStopped(
|
|
141
|
+
"Could not start a session. Check API connectivity and try again."
|
|
142
|
+
) from None
|
|
143
|
+
try:
|
|
144
|
+
session_id = str(uuid.UUID(created["id"]))
|
|
145
|
+
expires = datetime.fromisoformat(created["expires_at"].replace("Z", "+00:00"))
|
|
146
|
+
if expires.tzinfo is None or expires <= datetime.now(UTC):
|
|
147
|
+
raise ValueError
|
|
148
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
149
|
+
raise ListenStopped("Invalid session response.") from None
|
|
150
|
+
report(f"Connected · {target} · Ctrl+C to stop")
|
|
151
|
+
report(f"Session · {session_id} · new verified events only")
|
|
152
|
+
pending_ack = None
|
|
153
|
+
failures = 0
|
|
154
|
+
while datetime.now(UTC) < expires:
|
|
155
|
+
try:
|
|
156
|
+
# A dropped ACK response must not cause a second local POST
|
|
157
|
+
# in this process. ACK is idempotent; repeat it before polling.
|
|
158
|
+
if pending_ack:
|
|
159
|
+
api_call(api, f"{base}{session_id}/events/{pending_ack}/ack/", {})
|
|
160
|
+
report(f"Forwarded · {pending_ack}")
|
|
161
|
+
pending_ack = None
|
|
162
|
+
result = api_call(api, f"{base}{session_id}/poll/", {"wait_seconds": 0})
|
|
163
|
+
events = result.get("events")
|
|
164
|
+
if not isinstance(events, list) or len(events) > 5:
|
|
165
|
+
raise ListenStopped("Invalid event batch.")
|
|
166
|
+
if failures:
|
|
167
|
+
report("Reconnected")
|
|
168
|
+
failures = 0
|
|
169
|
+
if not events:
|
|
170
|
+
time.sleep(2) # Pace empty polls without holding API workers.
|
|
171
|
+
continue
|
|
172
|
+
for item in events:
|
|
173
|
+
if datetime.now(UTC) >= expires:
|
|
174
|
+
raise ListenStopped("Session expired. Start a new session to continue.")
|
|
175
|
+
event_id, body, attempt = checked_event(item, source_id)
|
|
176
|
+
report(f"Received · {event_id} · attempt {attempt}")
|
|
177
|
+
try:
|
|
178
|
+
with receiver.stream(
|
|
179
|
+
"POST",
|
|
180
|
+
target,
|
|
181
|
+
content=body,
|
|
182
|
+
headers={
|
|
183
|
+
"Content-Type": "application/json",
|
|
184
|
+
"X-Hookstride-Local-Event-Id": event_id,
|
|
185
|
+
"X-Hookstride-Local-Session-Id": session_id,
|
|
186
|
+
},
|
|
187
|
+
) as response:
|
|
188
|
+
code = response.status_code
|
|
189
|
+
# Never consume/print an untrusted receiver body.
|
|
190
|
+
except (httpx.HTTPError, httpx.InvalidURL):
|
|
191
|
+
report(
|
|
192
|
+
f"Receiver timeout or connection failure · {event_id} · will retry"
|
|
193
|
+
)
|
|
194
|
+
continue
|
|
195
|
+
if not 200 <= code < 300:
|
|
196
|
+
report(f"Receiver HTTP {code} · {event_id} · will retry")
|
|
197
|
+
continue
|
|
198
|
+
pending_ack = event_id
|
|
199
|
+
api_call(api, f"{base}{session_id}/events/{event_id}/ack/", {})
|
|
200
|
+
report(f"Forwarded · {event_id}")
|
|
201
|
+
pending_ack = None
|
|
202
|
+
except RetryPoll:
|
|
203
|
+
failures += 1
|
|
204
|
+
report("Connection interrupted · reconnecting")
|
|
205
|
+
time.sleep(min(2 ** min(failures, 4), 15))
|
|
206
|
+
raise ListenStopped("Session expired. Start a new session to continue.")
|
|
207
|
+
except KeyboardInterrupt:
|
|
208
|
+
stopped = True
|
|
209
|
+
report("Stopping")
|
|
210
|
+
finally:
|
|
211
|
+
if session_id:
|
|
212
|
+
try:
|
|
213
|
+
api_call(api, f"{base}{session_id}/revoke/", {})
|
|
214
|
+
report("Session revoked")
|
|
215
|
+
except (RetryPoll, ListenStopped):
|
|
216
|
+
report("Revocation not confirmed · session will expire automatically")
|
|
217
|
+
if stopped:
|
|
218
|
+
report("Disconnected")
|