@engini/sdk 0.18.0 → 0.20.0
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.
- package/README.md +81 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +6 -0
- package/dist/errors.d.ts +108 -2
- package/dist/errors.js +95 -2
- package/dist/http.d.ts +17 -0
- package/dist/http.js +47 -5
- package/dist/index.d.ts +6 -3
- package/dist/index.js +2 -2
- package/dist/resources/index.d.ts +4 -0
- package/dist/resources/index.js +2 -0
- package/dist/resources/opa.d.ts +175 -0
- package/dist/resources/opa.js +322 -0
- package/dist/resources/triggers.d.ts +355 -0
- package/dist/resources/triggers.js +851 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Triggers resource — trigger types, trigger instances, events and destinations.
|
|
3
|
+
*
|
|
4
|
+
* A **trigger instance** (`ti_…`) is an entity, not a workflow step: it wraps a hidden
|
|
5
|
+
* system workflow the SDK never sees. You create one from a *trigger type*
|
|
6
|
+
* (`types.list`), then enable, disable, reconfigure or delete it.
|
|
7
|
+
*
|
|
8
|
+
* There are two ways to receive the events it produces, and they need opposite code:
|
|
9
|
+
*
|
|
10
|
+
* - **A destination** is the delivery path. The account registers HTTPS endpoints and
|
|
11
|
+
* Engini POSTs signed events to them; the receiving process verifies the signature
|
|
12
|
+
* with `verifyWebhook`.
|
|
13
|
+
* - **`TriggersResource.subscribe`** is a *second read path* over the same events, for
|
|
14
|
+
* local development. It is not a delivery mechanism, and the stream is deliberately
|
|
15
|
+
* bounded — see that method's doc comment.
|
|
16
|
+
*/
|
|
17
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
18
|
+
import { triggersCreateDestination, triggersCreateTrigger, triggersDeleteDestination, triggersDeleteTrigger, triggersDisableTrigger, triggersEnableTrigger, triggersGetDefaultDestination, triggersGetDestination, triggersGetTrigger, triggersGetTriggerEvent, triggersGetTriggerType, triggersListDestinations, triggersListTriggerEvents, triggersListTriggerTypes, triggersListTriggers, triggersPutDefaultDestination, triggersReplayTriggerEvent, triggersRotateDestinationSecret, triggersUpdateDestination, triggersUpdateTrigger, } from "@engini/client";
|
|
19
|
+
import { call, errorForStatus } from "../http.js";
|
|
20
|
+
import { collect, paginate } from "../pagination.js";
|
|
21
|
+
import { EnginiAPIError, EnginiAuthError, EnginiClientError, EnginiNetworkError, EnginiRateLimitError, EnginiTriggerGapError, EnginiTriggerStreamLimitError, EnginiTriggerSubscribeFailedError, EnginiWebhookSignatureError, } from "../errors.js";
|
|
22
|
+
/**
|
|
23
|
+
* The endpoint's own path, used only by `subscribe`: every other operation goes
|
|
24
|
+
* through a generated op that carries its own URL.
|
|
25
|
+
*/
|
|
26
|
+
const SUBSCRIBE_PATH = "/v1/triggers/subscribe";
|
|
27
|
+
/**
|
|
28
|
+
* The server writes `: heartbeat\n\n` every 20 seconds of inactivity, so silence for
|
|
29
|
+
* more than twice that means the socket is dead even though nothing closed it.
|
|
30
|
+
* Doubling rather than shaving it keeps one dropped heartbeat from churning a healthy
|
|
31
|
+
* connection.
|
|
32
|
+
*/
|
|
33
|
+
const HEARTBEAT_TIMEOUT_MS = 45_000;
|
|
34
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
35
|
+
const RECONNECT_BASE_DELAY_MS = 1_000;
|
|
36
|
+
const RECONNECT_MAX_DELAY_MS = 30_000;
|
|
37
|
+
const MAX_RECONNECTS = 10;
|
|
38
|
+
/**
|
|
39
|
+
* A connection clears the reconnect budget only if it both lasted this long AND
|
|
40
|
+
* actually carried something. Elapsed time alone is not evidence: the heartbeat
|
|
41
|
+
* watchdog fires at 45s, so *every* watchdog-terminated attempt would out-last a 30s
|
|
42
|
+
* threshold and reset the counter — and an endpoint that accepts the socket, flushes
|
|
43
|
+
* the headers and then goes permanently silent (a misrouted baseUrl, a proxy holding
|
|
44
|
+
* the socket open) would reconnect for ever, never yielding an event and never
|
|
45
|
+
* honouring `maxReconnects`. Pairing the two keeps an idle-but-healthy subscription
|
|
46
|
+
* alive — the server sends a heartbeat every 20s, so ~180 frames an hour — while
|
|
47
|
+
* counting both accept-and-drop and accept-and-go-silent as failures.
|
|
48
|
+
*/
|
|
49
|
+
const HEALTHY_STREAM_MS = 30_000;
|
|
50
|
+
/**
|
|
51
|
+
* An upper bound on an honoured `Retry-After`. The server sends 30; the header can also
|
|
52
|
+
* carry an HTTP-date, and an absurd or hostile one would otherwise overflow
|
|
53
|
+
* `setTimeout`'s 32-bit delay and wrap round to an immediate retry — the opposite of
|
|
54
|
+
* waiting. (In Python the same value would park a thread for years.)
|
|
55
|
+
*/
|
|
56
|
+
const MAX_RETRY_AFTER_MS = 300_000;
|
|
57
|
+
const SIGNATURE_HEADER_SCHEME = "v1";
|
|
58
|
+
const DEFAULT_REPLAY_TOLERANCE_SECONDS = 300;
|
|
59
|
+
/** Exponential backoff in milliseconds, capped. `attempt` is 1-based. */
|
|
60
|
+
const backoffMs = (attempt) => Math.min(RECONNECT_BASE_DELAY_MS * 2 ** (attempt - 1), RECONNECT_MAX_DELAY_MS);
|
|
61
|
+
/**
|
|
62
|
+
* The reconnect count for the attempt about to be made.
|
|
63
|
+
*
|
|
64
|
+
* A connection clears the budget when it both lasted a while and actually carried
|
|
65
|
+
* something. Elapsed time alone would clear it for every watchdog-terminated attempt —
|
|
66
|
+
* the watchdog fires at 45s, comfortably past the 30s threshold — so an endpoint that
|
|
67
|
+
* accepts the socket and then says nothing for ever would reconnect for ever, never
|
|
68
|
+
* yielding an event and never honouring `maxReconnects`. Requiring a frame keeps the
|
|
69
|
+
* idle-but-healthy case working, because heartbeats are frames.
|
|
70
|
+
*/
|
|
71
|
+
const nextAttempt = (reconnects, started, progress) => progress.sawFrame && Date.now() - started >= HEALTHY_STREAM_MS ? 1 : reconnects + 1;
|
|
72
|
+
/**
|
|
73
|
+
* The reconnect backoff, behind an indirection so tests can collapse it.
|
|
74
|
+
*
|
|
75
|
+
* Spying on the global timer instead would also collapse undici's own connection
|
|
76
|
+
* timeouts, which then fire against a torn-down parser. Python's tests monkeypatch
|
|
77
|
+
* `time.sleep` for exactly the same reason. Not public surface — `index.ts` does not
|
|
78
|
+
* re-export it.
|
|
79
|
+
*/
|
|
80
|
+
export const backoffTimer = {
|
|
81
|
+
sleep: (ms) => new Promise((resolve) => {
|
|
82
|
+
setTimeout(resolve, ms);
|
|
83
|
+
}),
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Map the trigger wire codes onto their typed errors.
|
|
87
|
+
*
|
|
88
|
+
* Returns the error untouched for anything else, exactly as `opa.ts` does. The
|
|
89
|
+
* discriminator is `errorCode`, not the status: 409 and 429 already map to a class
|
|
90
|
+
* several unrelated conditions share, and only the code separates them. `410` has no
|
|
91
|
+
* row in `STATUS_TO_ERROR` at all, so `SINCE_PRUNED` arrives here as a bare
|
|
92
|
+
* `EnginiAPIError`.
|
|
93
|
+
*/
|
|
94
|
+
function retype(err) {
|
|
95
|
+
if (!(err instanceof EnginiAPIError))
|
|
96
|
+
return err;
|
|
97
|
+
const options = { errorCode: err.errorCode, details: err.details, retryAfter: err.retryAfter };
|
|
98
|
+
switch (err.errorCode) {
|
|
99
|
+
case "SINCE_PRUNED":
|
|
100
|
+
return new EnginiTriggerGapError(err.message, options);
|
|
101
|
+
case "TRIGGER_SUBSCRIBE_FAILED":
|
|
102
|
+
return new EnginiTriggerSubscribeFailedError(err.message, options);
|
|
103
|
+
case "TRIGGER_STREAM_LIMIT_EXCEEDED":
|
|
104
|
+
return new EnginiTriggerStreamLimitError(err.message, options);
|
|
105
|
+
default:
|
|
106
|
+
return err;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** `call` plus the trigger-specific retype. */
|
|
110
|
+
async function tcall(operation, options) {
|
|
111
|
+
try {
|
|
112
|
+
return await call(operation, options);
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
throw retype(err);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Verify a delivered trigger webhook and return its parsed event.
|
|
120
|
+
*
|
|
121
|
+
* Module-level on purpose: the process receiving webhooks is usually a bare HTTP
|
|
122
|
+
* handler with no Engini client, and requiring one to check a signature would be the
|
|
123
|
+
* wrong dependency.
|
|
124
|
+
*
|
|
125
|
+
* @param payload The **raw** request body, exactly as received. A body that was
|
|
126
|
+
* JSON-parsed and re-serialised will not verify — the signature covers the bytes on
|
|
127
|
+
* the wire, not an equivalent document.
|
|
128
|
+
* @param signatureHeader The `X-Engini-Signature` header value, `t=<unix>,v1=<lowercase hex>`.
|
|
129
|
+
* @param secret The destination's signing secret, the whole `esec_…` string.
|
|
130
|
+
* @param options.tolerance Replay window in seconds either side of `t`. Defaults to the
|
|
131
|
+
* server's recommended 300.
|
|
132
|
+
* @returns The parsed event body — so verifying and reading it is one call, not two.
|
|
133
|
+
* @throws EnginiWebhookSignatureError On *any* rejection: absent or malformed header,
|
|
134
|
+
* unknown scheme version, bad signature, or a timestamp outside the tolerance. It
|
|
135
|
+
* throws rather than returning `false` because a boolean is silently ignorable, and
|
|
136
|
+
* an ignored signature check is the one failure mode a webhook receiver cannot afford.
|
|
137
|
+
*
|
|
138
|
+
* Every delivery attempt is signed afresh, so a retry of the same event carries a
|
|
139
|
+
* different `t` and signature. Deduplicate on the `X-Engini-Event-Id` header, never on
|
|
140
|
+
* the signature.
|
|
141
|
+
*/
|
|
142
|
+
export function verifyWebhook(payload, signatureHeader, secret, options = {}) {
|
|
143
|
+
const tolerance = options.tolerance ?? DEFAULT_REPLAY_TOLERANCE_SECONDS;
|
|
144
|
+
if (!secret) {
|
|
145
|
+
// Misuse, not a rejection, and deliberately a different class: a receiver catching
|
|
146
|
+
// EnginiWebhookSignatureError would turn an unset secret into a quiet 400 on every
|
|
147
|
+
// delivery, which reads as "the sender is broken". An unconfigured verifier should
|
|
148
|
+
// fail loudly instead.
|
|
149
|
+
throw new EnginiClientError("verifyWebhook needs the destination's signing secret; an empty one would compute " +
|
|
150
|
+
"an HMAC under an empty key.");
|
|
151
|
+
}
|
|
152
|
+
if (!signatureHeader) {
|
|
153
|
+
throw new EnginiWebhookSignatureError("No X-Engini-Signature header on the request.");
|
|
154
|
+
}
|
|
155
|
+
let timestamp;
|
|
156
|
+
const candidates = [];
|
|
157
|
+
for (const part of signatureHeader.split(",")) {
|
|
158
|
+
const trimmed = part.trim();
|
|
159
|
+
const eq = trimmed.indexOf("=");
|
|
160
|
+
if (eq < 0)
|
|
161
|
+
throw new EnginiWebhookSignatureError("Malformed X-Engini-Signature header.");
|
|
162
|
+
const key = trimmed.slice(0, eq);
|
|
163
|
+
const value = trimmed.slice(eq + 1);
|
|
164
|
+
if (key === "t")
|
|
165
|
+
timestamp = value;
|
|
166
|
+
else if (key === SIGNATURE_HEADER_SCHEME)
|
|
167
|
+
candidates.push(value);
|
|
168
|
+
}
|
|
169
|
+
if (timestamp === undefined || candidates.length === 0) {
|
|
170
|
+
throw new EnginiWebhookSignatureError("X-Engini-Signature is missing a 't' timestamp or a 'v1' signature.");
|
|
171
|
+
}
|
|
172
|
+
const body = typeof payload === "string" ? Buffer.from(payload, "utf8") : Buffer.from(payload);
|
|
173
|
+
const expected = createHmac("sha256", Buffer.from(secret, "utf8"))
|
|
174
|
+
// The key is the UTF-8 bytes of the FULL `esec_…` string. Stripping the prefix or
|
|
175
|
+
// base64-decoding the suffix both look right and both fail.
|
|
176
|
+
.update(Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), body]))
|
|
177
|
+
.digest("hex");
|
|
178
|
+
const expectedBytes = Buffer.from(expected, "utf8");
|
|
179
|
+
// The signature is checked before the timestamp: until the MAC verifies, `t` is
|
|
180
|
+
// attacker-controlled and says nothing.
|
|
181
|
+
const matched = candidates.some((candidate) => {
|
|
182
|
+
const got = Buffer.from(candidate, "utf8");
|
|
183
|
+
// `timingSafeEqual` throws on unequal lengths, so the length check has to come
|
|
184
|
+
// first — and a length mismatch is already a mismatch, no timing to leak.
|
|
185
|
+
return got.length === expectedBytes.length && timingSafeEqual(got, expectedBytes);
|
|
186
|
+
});
|
|
187
|
+
if (!matched) {
|
|
188
|
+
throw new EnginiWebhookSignatureError("The X-Engini-Signature signature does not match.");
|
|
189
|
+
}
|
|
190
|
+
if (!/^-?\d+$/.test(timestamp)) {
|
|
191
|
+
throw new EnginiWebhookSignatureError("X-Engini-Signature carries a non-numeric 't'.");
|
|
192
|
+
}
|
|
193
|
+
const signedAt = Number(timestamp);
|
|
194
|
+
if (Math.abs(Math.floor(Date.now() / 1000) - signedAt) > tolerance) {
|
|
195
|
+
throw new EnginiWebhookSignatureError(`The webhook timestamp is outside the ${tolerance}s replay tolerance.`);
|
|
196
|
+
}
|
|
197
|
+
let event;
|
|
198
|
+
try {
|
|
199
|
+
event = JSON.parse(body.toString("utf8"));
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
throw new EnginiWebhookSignatureError("The webhook body is not valid JSON.");
|
|
203
|
+
}
|
|
204
|
+
if (event === null || typeof event !== "object" || Array.isArray(event)) {
|
|
205
|
+
// A correctly signed `5` or `[]` is still not an event, and returning it typed as
|
|
206
|
+
// one hands the caller something that will fail on first access.
|
|
207
|
+
throw new EnginiWebhookSignatureError("The webhook body is not a JSON object.");
|
|
208
|
+
}
|
|
209
|
+
return event;
|
|
210
|
+
}
|
|
211
|
+
/** The catalog of what can be triggered. Accessed as `client.triggers.types`. */
|
|
212
|
+
class TriggerTypesResource {
|
|
213
|
+
client;
|
|
214
|
+
constructor(client) {
|
|
215
|
+
this.client = client;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Every trigger type visible to the account, paginated.
|
|
219
|
+
*
|
|
220
|
+
* `connectionId` narrows the catalog to the types that connection can actually serve.
|
|
221
|
+
*/
|
|
222
|
+
async list(params = {}) {
|
|
223
|
+
const transport = this.client._transport;
|
|
224
|
+
return collect(paginate((offset, top) => tcall(triggersListTriggerTypes, {
|
|
225
|
+
client: transport,
|
|
226
|
+
query: {
|
|
227
|
+
offset,
|
|
228
|
+
top,
|
|
229
|
+
applicationSlug: params.applicationSlug,
|
|
230
|
+
search: params.search,
|
|
231
|
+
connectionId: params.connectionId,
|
|
232
|
+
},
|
|
233
|
+
})));
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* One trigger type, with its `config_schema`, `payload_schema` and parameters.
|
|
237
|
+
*
|
|
238
|
+
* `parameters` says which knobs this type actually honours — whether it schedules,
|
|
239
|
+
* whether it takes listen columns, which event types it offers — so read it before
|
|
240
|
+
* building a `create` call rather than sending fields the type will reject.
|
|
241
|
+
*/
|
|
242
|
+
async get(triggerSlug, params = {}) {
|
|
243
|
+
return tcall(triggersGetTriggerType, {
|
|
244
|
+
client: this.client._transport,
|
|
245
|
+
path: { triggerSlug },
|
|
246
|
+
query: { applicationSlug: params.applicationSlug },
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** Captured events and their delivery history. Accessed as `client.triggers.events`. */
|
|
251
|
+
class TriggerEventsResource {
|
|
252
|
+
client;
|
|
253
|
+
constructor(client) {
|
|
254
|
+
this.client = client;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Every captured event for one trigger, newest first.
|
|
258
|
+
*
|
|
259
|
+
* With no `top`, drains the whole log, 100 events per page. Pass `top` to fetch a
|
|
260
|
+
* single bounded page instead — unlike `TriggersResource.list`'s `include: "workflow"`
|
|
261
|
+
* workaround, this endpoint's `top`/`offset` are not affected by server bug
|
|
262
|
+
* 13003703309, so one page of exactly `top` rows is a real cap, not a client-side
|
|
263
|
+
* slice of a fully-drained result (which would fetch everything just to throw most of
|
|
264
|
+
* it away).
|
|
265
|
+
*/
|
|
266
|
+
async list(triggerId, params = {}) {
|
|
267
|
+
const transport = this.client._transport;
|
|
268
|
+
const fetchPage = (offset, top) => tcall(triggersListTriggerEvents, {
|
|
269
|
+
client: transport,
|
|
270
|
+
path: { triggerId },
|
|
271
|
+
query: { offset, top },
|
|
272
|
+
});
|
|
273
|
+
if (params.top !== undefined) {
|
|
274
|
+
return (await fetchPage(0, params.top)).items ?? [];
|
|
275
|
+
}
|
|
276
|
+
return collect(paginate(fetchPage));
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* One event plus its delivery attempts.
|
|
280
|
+
*
|
|
281
|
+
* The result is **nested** — `.event` and `.attempts` — not a flat event. This is
|
|
282
|
+
* also the only place a real delivery state can be read: the `delivery` field on a
|
|
283
|
+
* streamed event always reads `"pending"`.
|
|
284
|
+
*/
|
|
285
|
+
async get(eventId) {
|
|
286
|
+
return tcall(triggersGetTriggerEvent, {
|
|
287
|
+
client: this.client._transport,
|
|
288
|
+
path: { eventId },
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Re-deliver a captured event to its destination.
|
|
293
|
+
*
|
|
294
|
+
* Throws `EnginiConflictError` with `errorCode === "DESTINATION_DISABLED"` when the
|
|
295
|
+
* destination was auto-disabled by consecutive failures; re-enable it with
|
|
296
|
+
* `destinations.update(name, { status: "active" })` first.
|
|
297
|
+
*/
|
|
298
|
+
async replay(eventId) {
|
|
299
|
+
return tcall(triggersReplayTriggerEvent, {
|
|
300
|
+
client: this.client._transport,
|
|
301
|
+
path: { eventId },
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Registered HTTPS delivery endpoints. Accessed as `client.triggers.destinations`.
|
|
307
|
+
*
|
|
308
|
+
* Distinct from `client.triggers.destination` (singular), which is the account default
|
|
309
|
+
* and a different pair of endpoints. Nested rather than flattened precisely so the two
|
|
310
|
+
* cannot be confused.
|
|
311
|
+
*/
|
|
312
|
+
class TriggerDestinationsResource {
|
|
313
|
+
client;
|
|
314
|
+
constructor(client) {
|
|
315
|
+
this.client = client;
|
|
316
|
+
}
|
|
317
|
+
/** Every destination on the account, the default first. Never includes secrets. */
|
|
318
|
+
async list() {
|
|
319
|
+
const transport = this.client._transport;
|
|
320
|
+
return collect(paginate((offset, top) => tcall(triggersListDestinations, { client: transport, query: { offset, top } })));
|
|
321
|
+
}
|
|
322
|
+
/** One destination by name, including its failure counters and status. */
|
|
323
|
+
async get(name) {
|
|
324
|
+
return tcall(triggersGetDestination, {
|
|
325
|
+
client: this.client._transport,
|
|
326
|
+
path: { name },
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Register a destination. **The response carries its signing secret.**
|
|
331
|
+
*
|
|
332
|
+
* The result is nested: `.destination` and `.signing_secret`. That secret is shown
|
|
333
|
+
* exactly once, with no overlap window — store it now and never log it. It is the key
|
|
334
|
+
* `verifyWebhook` needs.
|
|
335
|
+
*/
|
|
336
|
+
async create(params) {
|
|
337
|
+
return tcall(triggersCreateDestination, {
|
|
338
|
+
client: this.client._transport,
|
|
339
|
+
body: {
|
|
340
|
+
name: params.name,
|
|
341
|
+
url: params.url,
|
|
342
|
+
is_default: params.isDefault,
|
|
343
|
+
max_consecutive_failures: params.maxConsecutiveFailures,
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Change a destination's URL, default flag, status or failure budget.
|
|
349
|
+
*
|
|
350
|
+
* `status: "active"` is how an `"auto_disabled"` destination is brought back after it
|
|
351
|
+
* tripped its consecutive-failure budget.
|
|
352
|
+
*/
|
|
353
|
+
async update(name, params) {
|
|
354
|
+
return tcall(triggersUpdateDestination, {
|
|
355
|
+
client: this.client._transport,
|
|
356
|
+
path: { name },
|
|
357
|
+
body: {
|
|
358
|
+
url: params.url,
|
|
359
|
+
is_default: params.isDefault,
|
|
360
|
+
status: params.status,
|
|
361
|
+
max_consecutive_failures: params.maxConsecutiveFailures,
|
|
362
|
+
},
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Delete a destination, optionally re-pointing its triggers at another.
|
|
367
|
+
*
|
|
368
|
+
* Without `reassignTo` a destination that triggers still reference is a 409
|
|
369
|
+
* `DESTINATION_IN_USE` rather than a silent orphaning.
|
|
370
|
+
*
|
|
371
|
+
* The query parameter really is `reassign_to`, snake_case — unlike every other query
|
|
372
|
+
* parameter on this surface.
|
|
373
|
+
*/
|
|
374
|
+
async delete(name, params = {}) {
|
|
375
|
+
await tcall(triggersDeleteDestination, {
|
|
376
|
+
client: this.client._transport,
|
|
377
|
+
path: { name },
|
|
378
|
+
query: { reassign_to: params.reassignTo },
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Issue a new signing secret, invalidating the current one immediately.
|
|
383
|
+
*
|
|
384
|
+
* **There is no overlap window**: deliveries signed with the old secret stop verifying
|
|
385
|
+
* the moment this resolves, so deploy the new secret to the receiver first. Returns
|
|
386
|
+
* the same nested `.destination` / `.signing_secret` shape as `create`.
|
|
387
|
+
*/
|
|
388
|
+
async rotateSecret(name) {
|
|
389
|
+
return tcall(triggersRotateDestinationSecret, {
|
|
390
|
+
client: this.client._transport,
|
|
391
|
+
path: { name },
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* The account's default destination. Accessed as `client.triggers.destination`.
|
|
397
|
+
*
|
|
398
|
+
* `/v1/triggers/destination` (singular) and `/v1/triggers/destinations` (plural) are
|
|
399
|
+
* different endpoints; these two methods are the singular pair.
|
|
400
|
+
*/
|
|
401
|
+
class DefaultDestinationResource {
|
|
402
|
+
client;
|
|
403
|
+
constructor(client) {
|
|
404
|
+
this.client = client;
|
|
405
|
+
}
|
|
406
|
+
/** The account's default destination, or a 404 when none is set. */
|
|
407
|
+
async get() {
|
|
408
|
+
return tcall(triggersGetDefaultDestination, { client: this.client._transport });
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Set (or re-point) the account default in one call.
|
|
412
|
+
*
|
|
413
|
+
* Creating a default returns the nested `.destination` / `.signing_secret` shape,
|
|
414
|
+
* secret included and shown once; re-pointing an existing one returns the destination
|
|
415
|
+
* alone, with no secret. Check for the secret rather than assuming which happened.
|
|
416
|
+
*/
|
|
417
|
+
async put(params) {
|
|
418
|
+
return tcall(triggersPutDefaultDestination, {
|
|
419
|
+
client: this.client._transport,
|
|
420
|
+
body: {
|
|
421
|
+
url: params.url,
|
|
422
|
+
name: params.name,
|
|
423
|
+
max_consecutive_failures: params.maxConsecutiveFailures,
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const writeBody = (params) => ({
|
|
429
|
+
connection_id: params.connectionId,
|
|
430
|
+
connection_name: params.connectionName,
|
|
431
|
+
config: params.config,
|
|
432
|
+
schedule: params.schedule,
|
|
433
|
+
poll_interval_minutes: params.pollIntervalMinutes,
|
|
434
|
+
listen_columns: params.listenColumns,
|
|
435
|
+
destination_id: params.destinationId,
|
|
436
|
+
dedupe_window_hours: params.dedupeWindowHours,
|
|
437
|
+
});
|
|
438
|
+
export class TriggersResource {
|
|
439
|
+
client;
|
|
440
|
+
types;
|
|
441
|
+
events;
|
|
442
|
+
destinations;
|
|
443
|
+
destination;
|
|
444
|
+
constructor(client) {
|
|
445
|
+
this.client = client;
|
|
446
|
+
this.types = new TriggerTypesResource(client);
|
|
447
|
+
this.events = new TriggerEventsResource(client);
|
|
448
|
+
this.destinations = new TriggerDestinationsResource(client);
|
|
449
|
+
this.destination = new DefaultDestinationResource(client);
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Also reachable as `client.triggers.verifyWebhook`, for callers that happen to have
|
|
453
|
+
* a client to hand. The module-level export is the real one.
|
|
454
|
+
*/
|
|
455
|
+
verifyWebhook = verifyWebhook;
|
|
456
|
+
// ---- instances ---------------------------------------------------------------------
|
|
457
|
+
/**
|
|
458
|
+
* Create a trigger instance from a trigger type.
|
|
459
|
+
*
|
|
460
|
+
* Pass `connectionId` or `connectionName`; with neither, the server uses the account's
|
|
461
|
+
* default connection for the application and answers `MISSING_DEFAULT_CONNECTION`
|
|
462
|
+
* (500) when there is none.
|
|
463
|
+
*
|
|
464
|
+
* Which of `schedule` / `pollIntervalMinutes` / `listenColumns` apply is per trigger
|
|
465
|
+
* type — read `types.get(slug).parameters` first.
|
|
466
|
+
*/
|
|
467
|
+
async create(params) {
|
|
468
|
+
return tcall(triggersCreateTrigger, {
|
|
469
|
+
client: this.client._transport,
|
|
470
|
+
body: {
|
|
471
|
+
trigger_slug: params.triggerSlug,
|
|
472
|
+
application_slug: params.applicationSlug,
|
|
473
|
+
...writeBody(params),
|
|
474
|
+
},
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Every trigger instance on the account, paginated.
|
|
479
|
+
*
|
|
480
|
+
* `status` is one of `enabled`, `disabled` or `errored`.
|
|
481
|
+
*
|
|
482
|
+
* `include: "workflow"` additionally returns designer-built triggers — and **returns a
|
|
483
|
+
* single page of at most `top` rows instead of paginating.** That is a WORKAROUND for
|
|
484
|
+
* server bug 13003703309, not the contract: the server appends designer triggers with
|
|
485
|
+
* `Take(top)` and no `Skip(offset)`, so page 2 re-returns page 1's rows while
|
|
486
|
+
* `totalCount` keeps climbing — auto-pagination would duplicate rows and never
|
|
487
|
+
* terminate. When 13003703309 lands, delete this branch and let every call paginate.
|
|
488
|
+
*/
|
|
489
|
+
async list(params = {}) {
|
|
490
|
+
const transport = this.client._transport;
|
|
491
|
+
const top = params.top ?? 100;
|
|
492
|
+
const fetchPage = (offset, pageSize) => tcall(triggersListTriggers, {
|
|
493
|
+
client: transport,
|
|
494
|
+
query: {
|
|
495
|
+
offset,
|
|
496
|
+
top: pageSize,
|
|
497
|
+
applicationSlug: params.applicationSlug,
|
|
498
|
+
connectionId: params.connectionId,
|
|
499
|
+
status: params.status,
|
|
500
|
+
include: params.include,
|
|
501
|
+
},
|
|
502
|
+
});
|
|
503
|
+
if (params.include !== undefined) {
|
|
504
|
+
return (await fetchPage(0, top)).items ?? [];
|
|
505
|
+
}
|
|
506
|
+
return collect(paginate(fetchPage, { top }));
|
|
507
|
+
}
|
|
508
|
+
/** One trigger instance, with its status, schedule and last-error detail. */
|
|
509
|
+
async get(triggerId) {
|
|
510
|
+
return tcall(triggersGetTrigger, {
|
|
511
|
+
client: this.client._transport,
|
|
512
|
+
path: { triggerId },
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Change a trigger's connection, config, schedule or destination.
|
|
517
|
+
*
|
|
518
|
+
* Merges: anything omitted is left alone. `trigger_slug` is not changeable — the type
|
|
519
|
+
* a trigger was created from is fixed.
|
|
520
|
+
*/
|
|
521
|
+
async update(triggerId, params) {
|
|
522
|
+
return tcall(triggersUpdateTrigger, {
|
|
523
|
+
client: this.client._transport,
|
|
524
|
+
path: { triggerId },
|
|
525
|
+
body: writeBody(params),
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Enable a trigger and clear its `status_reason`.
|
|
530
|
+
*
|
|
531
|
+
* Throws `EnginiTriggerSubscribeFailedError` (502) when Engini could not register the
|
|
532
|
+
* subscription with the provider — the trigger stays disabled.
|
|
533
|
+
*/
|
|
534
|
+
async enable(triggerId) {
|
|
535
|
+
return tcall(triggersEnableTrigger, {
|
|
536
|
+
client: this.client._transport,
|
|
537
|
+
path: { triggerId },
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
/** Stop a trigger capturing events. Not a delete; its event history stays. */
|
|
541
|
+
async disable(triggerId) {
|
|
542
|
+
return tcall(triggersDisableTrigger, {
|
|
543
|
+
client: this.client._transport,
|
|
544
|
+
path: { triggerId },
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
/** Permanently delete a trigger instance and its hidden system workflow. */
|
|
548
|
+
async delete(triggerId) {
|
|
549
|
+
await tcall(triggersDeleteTrigger, {
|
|
550
|
+
client: this.client._transport,
|
|
551
|
+
path: { triggerId },
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
// ---- stream ------------------------------------------------------------------------
|
|
555
|
+
/**
|
|
556
|
+
* Open the SSE response, throwing the mapped typed error on a non-2xx.
|
|
557
|
+
*
|
|
558
|
+
* Written by hand rather than through the generated op: hey-api emitted
|
|
559
|
+
* `triggersSubscribeTriggerEvents` as a plain `.get()` typed `unknown`, because the
|
|
560
|
+
* OpenAPI document declares no `content` block on this 200 at all. Its `.sse()` reader
|
|
561
|
+
* exists but is unreachable until the spec gains `text/event-stream`.
|
|
562
|
+
*/
|
|
563
|
+
async openStream(query, signal, progress) {
|
|
564
|
+
const config = this.client._transport.getConfig();
|
|
565
|
+
const doFetch = (config.fetch ?? globalThis.fetch);
|
|
566
|
+
let response;
|
|
567
|
+
try {
|
|
568
|
+
// Inside the guard: `Headers` throws a bare TypeError on a malformed configured
|
|
569
|
+
// header value, which would escape a method whose contract is typed errors.
|
|
570
|
+
const headers = new Headers(config.headers);
|
|
571
|
+
headers.set("accept", "text/event-stream");
|
|
572
|
+
const base = String(config.baseUrl ?? "").replace(/\/$/, "");
|
|
573
|
+
const search = query.toString();
|
|
574
|
+
const url = `${base}${SUBSCRIBE_PATH}${search === "" ? "" : `?${search}`}`;
|
|
575
|
+
response = await doFetch(url, { method: "GET", headers, signal });
|
|
576
|
+
}
|
|
577
|
+
catch (err) {
|
|
578
|
+
throw new EnginiNetworkError(err instanceof Error ? err.message : String(err));
|
|
579
|
+
}
|
|
580
|
+
if (response.ok)
|
|
581
|
+
return response;
|
|
582
|
+
// A non-2xx is still the server talking, so it does not count as silence.
|
|
583
|
+
progress.sawFrame = true;
|
|
584
|
+
// 410 SINCE_PRUNED and 429 TRIGGER_STREAM_LIMIT_EXCEEDED arrive here as an ordinary
|
|
585
|
+
// JSON error body: the server throws them before it writes the SSE prelude, so there
|
|
586
|
+
// is no control frame for either.
|
|
587
|
+
let body;
|
|
588
|
+
try {
|
|
589
|
+
body = await response.json();
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
body = undefined;
|
|
593
|
+
}
|
|
594
|
+
throw retype(errorForStatus(response.status, body, response.headers));
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Yield `["event", …]` / `["control", …]` frames until the stream ends.
|
|
598
|
+
*
|
|
599
|
+
* Returning normally means the socket ended without a control frame. That is the
|
|
600
|
+
* *expected* case, not an error: the gateway caps every stream at exactly one hour of
|
|
601
|
+
* wall-clock time and the response headers were flushed at connect, so nothing can be
|
|
602
|
+
* written at the deadline — the body is simply truncated. It is indistinguishable from
|
|
603
|
+
* a network blip by design, and handled the same way.
|
|
604
|
+
*/
|
|
605
|
+
async *streamOnce(query, heartbeatTimeoutMs, progress) {
|
|
606
|
+
const controller = new AbortController();
|
|
607
|
+
// The heartbeat watchdog. The server promises a frame every 20s, so silence past the
|
|
608
|
+
// timeout means the socket is dead even though nothing closed it; aborting turns that
|
|
609
|
+
// into the same resumable ending as a dropped connection.
|
|
610
|
+
let watchdog;
|
|
611
|
+
const armWatchdog = (ms) => {
|
|
612
|
+
if (watchdog !== undefined)
|
|
613
|
+
clearTimeout(watchdog);
|
|
614
|
+
watchdog = setTimeout(() => controller.abort(), ms);
|
|
615
|
+
};
|
|
616
|
+
const disarmWatchdog = () => {
|
|
617
|
+
if (watchdog !== undefined)
|
|
618
|
+
clearTimeout(watchdog);
|
|
619
|
+
watchdog = undefined;
|
|
620
|
+
};
|
|
621
|
+
// Connect is held to its own, shorter bound before the heartbeat one takes over,
|
|
622
|
+
// matching Python's `httpx.Timeout(read, connect=…)`. Reusing the 45s heartbeat
|
|
623
|
+
// timeout for the handshake would wait four times longer than intended on a host
|
|
624
|
+
// that is simply not answering.
|
|
625
|
+
armWatchdog(CONNECT_TIMEOUT_MS);
|
|
626
|
+
let response;
|
|
627
|
+
try {
|
|
628
|
+
response = await this.openStream(query, controller.signal, progress);
|
|
629
|
+
}
|
|
630
|
+
finally {
|
|
631
|
+
disarmWatchdog();
|
|
632
|
+
}
|
|
633
|
+
if (response.body === null) {
|
|
634
|
+
throw new EnginiNetworkError("The trigger event stream returned no response body.");
|
|
635
|
+
}
|
|
636
|
+
const reader = response.body.getReader();
|
|
637
|
+
const decoder = new TextDecoder();
|
|
638
|
+
let buffer = "";
|
|
639
|
+
let eventName;
|
|
640
|
+
let dataLines = [];
|
|
641
|
+
try {
|
|
642
|
+
for (;;) {
|
|
643
|
+
let chunk;
|
|
644
|
+
// Armed around the read and disarmed the moment it returns, so it measures
|
|
645
|
+
// *server silence* — which is what its docstring promises — rather than wall
|
|
646
|
+
// clock. Left armed across the `yield` it would also count the consumer's own
|
|
647
|
+
// handling time, and a caller that pauses on a breakpoint for 45s would tear
|
|
648
|
+
// down a perfectly healthy stream. This is what `httpx.Timeout(read=…)` does
|
|
649
|
+
// for Python, and the only way the two languages agree.
|
|
650
|
+
armWatchdog(heartbeatTimeoutMs);
|
|
651
|
+
try {
|
|
652
|
+
chunk = await reader.read();
|
|
653
|
+
}
|
|
654
|
+
catch (err) {
|
|
655
|
+
throw new EnginiNetworkError(err instanceof Error ? err.message : String(err));
|
|
656
|
+
}
|
|
657
|
+
finally {
|
|
658
|
+
disarmWatchdog();
|
|
659
|
+
}
|
|
660
|
+
if (chunk.done)
|
|
661
|
+
return;
|
|
662
|
+
progress.sawFrame = true;
|
|
663
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
664
|
+
for (;;) {
|
|
665
|
+
// The SSE grammar terminates a line with CRLF, LF *or* a bare CR, and
|
|
666
|
+
// `httpx.iter_lines` gives Python all three — so splitting on "\n" alone
|
|
667
|
+
// would have made a bare-CR server yield nothing here and everything there.
|
|
668
|
+
const match = /\r\n|\r|\n/.exec(buffer);
|
|
669
|
+
if (match === null)
|
|
670
|
+
break;
|
|
671
|
+
// A trailing lone CR may still turn out to be the front of a CRLF split
|
|
672
|
+
// across chunks; leave it in the buffer until the next read settles it.
|
|
673
|
+
if (match[0] === "\r" && match.index === buffer.length - 1)
|
|
674
|
+
break;
|
|
675
|
+
const line = buffer.slice(0, match.index);
|
|
676
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
677
|
+
if (line === "") {
|
|
678
|
+
if (dataLines.length > 0) {
|
|
679
|
+
// A frame that will not parse throws rather than being dropped. Silently
|
|
680
|
+
// skipping it would advance nothing and say nothing — the invisible gap
|
|
681
|
+
// the `since` cursor exists to prevent. `EnginiNetworkError` is the right
|
|
682
|
+
// shape because it is resumable: the retry re-reads from the last cursor,
|
|
683
|
+
// so a one-off mangled frame heals itself and a persistent one still ends
|
|
684
|
+
// up thrown once the reconnect budget runs out.
|
|
685
|
+
let parsed;
|
|
686
|
+
try {
|
|
687
|
+
parsed = JSON.parse(dataLines.join("\n"));
|
|
688
|
+
}
|
|
689
|
+
catch {
|
|
690
|
+
throw new EnginiNetworkError("The trigger event stream sent a data frame that is not valid JSON.");
|
|
691
|
+
}
|
|
692
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
693
|
+
throw new EnginiNetworkError("The trigger event stream sent a data frame that is not a JSON object.");
|
|
694
|
+
}
|
|
695
|
+
yield [
|
|
696
|
+
eventName === "control" ? "control" : "event",
|
|
697
|
+
parsed,
|
|
698
|
+
];
|
|
699
|
+
}
|
|
700
|
+
eventName = undefined;
|
|
701
|
+
dataLines = [];
|
|
702
|
+
}
|
|
703
|
+
else if (line.startsWith(":")) {
|
|
704
|
+
// `: heartbeat` — liveness only. Having reached it at all is what rearmed
|
|
705
|
+
// the watchdog, so there is nothing else to do.
|
|
706
|
+
}
|
|
707
|
+
else if (line.startsWith("event:")) {
|
|
708
|
+
eventName = line.slice("event:".length).trim();
|
|
709
|
+
}
|
|
710
|
+
else if (line.startsWith("data:")) {
|
|
711
|
+
const value = line.slice("data:".length);
|
|
712
|
+
dataLines.push(value.startsWith(" ") ? value.slice(1) : value);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
finally {
|
|
718
|
+
disarmWatchdog();
|
|
719
|
+
// `abort()` first: it is synchronous and guaranteed, so the socket is released
|
|
720
|
+
// even though the cancel below may never settle.
|
|
721
|
+
controller.abort();
|
|
722
|
+
// Deliberately not awaited. This runs from the generator's `return()`, i.e. on
|
|
723
|
+
// the caller's `break`, and `cancel()` on a body whose source never settles can
|
|
724
|
+
// hang — which would hang the caller's loop exit instead of just leaking the
|
|
725
|
+
// socket. Requesting the cancel is what releases it; waiting for it is not.
|
|
726
|
+
void reader.cancel().catch(() => undefined);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Stream trigger events as they are captured, as an async iterator.
|
|
731
|
+
*
|
|
732
|
+
* This is a **second read path for local development**, not a delivery mechanism —
|
|
733
|
+
* production delivery is a destination plus `verifyWebhook`.
|
|
734
|
+
*
|
|
735
|
+
* Every stream ends, so this one resumes. The gateway caps each connection at exactly
|
|
736
|
+
* one hour of wall-clock time — an absolute cap, not an idle one, which the 20-second
|
|
737
|
+
* heartbeat does not defer — and the cut arrives as an abrupt truncation with no
|
|
738
|
+
* control frame. A pod draining sends `control{reason:"draining", reconnect:true}`
|
|
739
|
+
* instead. All three of those are the same thing here: reconnect with `?since=<last
|
|
740
|
+
* event id>`, which streams events strictly *after* that one, so the seam neither
|
|
741
|
+
* duplicates nor skips.
|
|
742
|
+
*
|
|
743
|
+
* Two endings are not resumable and stop hard:
|
|
744
|
+
*
|
|
745
|
+
* - `control{reason:"revoked", reconnect:false}` → `EnginiAuthError`.
|
|
746
|
+
* - `410 SINCE_PRUNED` on the resume → `EnginiTriggerGapError`. Never a silent restart
|
|
747
|
+
* from "now": the point of the cursor is that a gap is visible. Read the missed
|
|
748
|
+
* window with `events.list` and subscribe again.
|
|
749
|
+
*
|
|
750
|
+
* A `429 TRIGGER_STREAM_LIMIT_EXCEEDED` waits out its `Retry-After` (the server sends
|
|
751
|
+
* 30s) and resumes; the account allows 10 concurrent streams.
|
|
752
|
+
*
|
|
753
|
+
* Each yielded event is the parsed frame: `id`, `trigger_id`, `occurred_at`, `payload`,
|
|
754
|
+
* `payload_truncated`, `payload_hash`, `delivery`.
|
|
755
|
+
*
|
|
756
|
+
* **`delivery` is always the literal `"pending"` here** — the stream writer builds its
|
|
757
|
+
* view without querying delivery attempts, so the field is its default for every event,
|
|
758
|
+
* including ones already delivered, failed or dead-lettered. It is not a delivery
|
|
759
|
+
* state; call `events.get(id)` for the real one.
|
|
760
|
+
*
|
|
761
|
+
* @param params.autoResume Set `false` to stop at the first ending instead of
|
|
762
|
+
* reconnecting. The unrecoverable endings still throw.
|
|
763
|
+
* @param params.maxReconnects Consecutive failed reconnects before giving up. The
|
|
764
|
+
* counter resets on every event actually delivered, so a stream that is working never
|
|
765
|
+
* exhausts it.
|
|
766
|
+
* @param params.heartbeatTimeoutMs Milliseconds of total silence before the socket is
|
|
767
|
+
* treated as dead.
|
|
768
|
+
*/
|
|
769
|
+
async *subscribe(params = {}) {
|
|
770
|
+
const autoResume = params.autoResume ?? true;
|
|
771
|
+
const maxReconnects = params.maxReconnects ?? MAX_RECONNECTS;
|
|
772
|
+
const heartbeatTimeoutMs = params.heartbeatTimeoutMs ?? HEARTBEAT_TIMEOUT_MS;
|
|
773
|
+
let cursor = params.since;
|
|
774
|
+
let reconnects = 0;
|
|
775
|
+
for (;;) {
|
|
776
|
+
const started = Date.now();
|
|
777
|
+
const progress = { sawFrame: false };
|
|
778
|
+
const query = new URLSearchParams();
|
|
779
|
+
if (params.triggerId !== undefined)
|
|
780
|
+
query.set("triggerId", params.triggerId);
|
|
781
|
+
if (params.triggerSlug !== undefined)
|
|
782
|
+
query.set("triggerSlug", params.triggerSlug);
|
|
783
|
+
if (params.applicationSlug !== undefined)
|
|
784
|
+
query.set("applicationSlug", params.applicationSlug);
|
|
785
|
+
if (cursor !== undefined)
|
|
786
|
+
query.set("since", cursor);
|
|
787
|
+
try {
|
|
788
|
+
for await (const [kind, frame] of this.streamOnce(query, heartbeatTimeoutMs, progress)) {
|
|
789
|
+
if (kind === "control") {
|
|
790
|
+
if (frame.reconnect !== true) {
|
|
791
|
+
// `!== ""` as well as the type check: Python coerces an empty reason to
|
|
792
|
+
// "revoked", and the two must not report different `errorCode`s for the
|
|
793
|
+
// same frame.
|
|
794
|
+
const reason = typeof frame.reason === "string" && frame.reason !== "" ? frame.reason : "revoked";
|
|
795
|
+
throw new EnginiAuthError(`The trigger event stream was closed by the server (${reason}) and must not be resumed.`, { errorCode: reason });
|
|
796
|
+
}
|
|
797
|
+
break;
|
|
798
|
+
}
|
|
799
|
+
if (typeof frame.id === "string" && frame.id !== "")
|
|
800
|
+
cursor = frame.id;
|
|
801
|
+
// An event delivered proves the connection healthy, so the reconnect budget is
|
|
802
|
+
// about consecutive failures, not lifetime ones — an hourly gateway cut must
|
|
803
|
+
// never exhaust it.
|
|
804
|
+
reconnects = 0;
|
|
805
|
+
yield frame;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
catch (err) {
|
|
809
|
+
if (err instanceof EnginiRateLimitError) {
|
|
810
|
+
// The base class, not `EnginiTriggerStreamLimitError`: a 429 whose body is not
|
|
811
|
+
// the JSON error envelope — an ingress or CDN limiter, or a future server code
|
|
812
|
+
// — carries no `errorCode` to retype on, and would otherwise kill the
|
|
813
|
+
// subscription on the one condition this loop knows how to wait out, with the
|
|
814
|
+
// parsed `Retry-After` sitting on the error unused.
|
|
815
|
+
if (!autoResume)
|
|
816
|
+
throw err;
|
|
817
|
+
reconnects = nextAttempt(reconnects, started, progress);
|
|
818
|
+
if (reconnects > maxReconnects)
|
|
819
|
+
throw err;
|
|
820
|
+
// A floor, not a replacement: a stale `Retry-After` date parses to 0, and
|
|
821
|
+
// honouring that literally would retry back-to-back against a server that just
|
|
822
|
+
// said "slow down".
|
|
823
|
+
const delay = Math.max((err.retryAfter ?? 0) * 1000, backoffMs(reconnects));
|
|
824
|
+
await backoffTimer.sleep(Math.min(delay, MAX_RETRY_AFTER_MS));
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
if (err instanceof EnginiNetworkError) {
|
|
828
|
+
// A dead socket or the watchdog firing — including, in practice, the gateway's
|
|
829
|
+
// one-hour cut, which truncates the body and so surfaces as a read failure.
|
|
830
|
+
// Resumable. With resume off this still throws rather than returning quietly:
|
|
831
|
+
// "do not reconnect" is not "pretend the stream ended normally".
|
|
832
|
+
if (!autoResume)
|
|
833
|
+
throw err;
|
|
834
|
+
reconnects = nextAttempt(reconnects, started, progress);
|
|
835
|
+
if (reconnects > maxReconnects)
|
|
836
|
+
throw err;
|
|
837
|
+
await backoffTimer.sleep(backoffMs(reconnects));
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
throw err;
|
|
841
|
+
}
|
|
842
|
+
if (!autoResume)
|
|
843
|
+
return;
|
|
844
|
+
reconnects = nextAttempt(reconnects, started, progress);
|
|
845
|
+
if (reconnects > maxReconnects) {
|
|
846
|
+
throw new EnginiNetworkError(`The trigger event stream could not be resumed after ${maxReconnects} consecutive attempts.`);
|
|
847
|
+
}
|
|
848
|
+
await backoffTimer.sleep(backoffMs(reconnects));
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|