@trysqless/node 0.3.0 → 0.4.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 +31 -1
- package/index.d.ts +29 -1
- package/index.js +33 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,6 +90,8 @@ Cancellation stops future attempts of a pending or retrying event in the same lo
|
|
|
90
90
|
|
|
91
91
|
The native database gateway accepts `POST /api/v1/queue/batch` with `{ eventOps }` and `POST /api/v1/sql/event-ops` with `{ statements, eventOps }`. Use the database hostname and bearer token. Deploy the migration, Buffer, control plane, Compute and gateway changes before using the new calls.
|
|
92
92
|
|
|
93
|
+
All databases in a tenant share an outstanding task limit. A full queue rejects the entire operation with `SQLessError.code === 'EVENT_QUEUE_FULL'` (HTTP 409). An explicit transaction reports this at commit. At capacity, a batch can cancel an unclaimed task before enqueueing its replacement. Delayed tasks and retries retain one slot until terminal cleanup.
|
|
94
|
+
|
|
93
95
|
### Enqueue with SQL
|
|
94
96
|
|
|
95
97
|
Use `executeWithEvents` to publish a webhook with a SQL transaction. The result includes `eventIds`. Inside an interactive session, these IDs are provisional until the enclosing commit succeeds.
|
|
@@ -110,7 +112,35 @@ Webhooks accept public HTTP and HTTPS URLs. The default method is `POST`. Suppor
|
|
|
110
112
|
|
|
111
113
|
Use an RFC 3339 timestamp in `startedAt` to schedule the first attempt. For example, `startedAt: new Date(Date.now() + 300_000).toISOString()` schedules delivery in five minutes. The initial pending event reports this time in `nextAttemptAt`. The scheduled-event wire operation is `execute_with_scheduled_events`, with native HTTP endpoint `POST /api/v1/sql/scheduled-events`.
|
|
112
114
|
|
|
113
|
-
SQLess sends the saved request after commit
|
|
115
|
+
SQLess sends the saved request after commit and reuses it for retries. Deliveries can be duplicated and can arrive in any order. SQLess supplies transport headers such as `Host` and `Content-Length`, and sends the same `Idempotency-Key` and `X-SQLess-Event-ID` on each attempt. Record the event ID and the corresponding business change in one transaction before acknowledging completion. By default a 2xx response acknowledges delivery. Other statuses and connection errors retry.
|
|
116
|
+
|
|
117
|
+
`handlers` belongs to the event and works with every enqueue method. An exact status takes precedence over its class, regardless of the order of the rules. Each status code or class can appear once. JavaScript and TypeScript can both import `WebhookResponseAction`. TypeScript also exports the `WebhookResponseHandler` type.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { WebhookResponseAction, type WebhookResponseHandler } from '@trysqless/node';
|
|
121
|
+
|
|
122
|
+
const handlers = [
|
|
123
|
+
{ statusCode: '2xx', action: WebhookResponseAction.Success },
|
|
124
|
+
{ statusCode: '202', action: WebhookResponseAction.DeferTask },
|
|
125
|
+
{ statusCode: '403', action: WebhookResponseAction.Fail },
|
|
126
|
+
{ statusCode: '404', action: WebhookResponseAction.Retry, retryAfter: '120s' },
|
|
127
|
+
] satisfies WebhookResponseHandler[];
|
|
128
|
+
|
|
129
|
+
await db.queue.enqueue({ webhook: exportUrl, payload: { exportId }, handlers });
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
| Action | Queue outcome |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| `success` | Mark the event delivered. |
|
|
135
|
+
| `retry` | Record the delivery error and schedule another attempt. |
|
|
136
|
+
| `deferTask` | Defer the next delivery and clear `lastError`. Each delivery increments `attempts`. |
|
|
137
|
+
| `fail` | Mark the event failed immediately and record the HTTP status. |
|
|
138
|
+
|
|
139
|
+
For `Retry` and `DeferTask`, a valid HTTP `Retry-After` header takes precedence. Without one, the queue uses the matched handler's `retryAfter` if supplied, then its default backoff. In the example, a 404 response without a header schedules the next attempt in two minutes. The default delay starts at 30 seconds, increases exponentially for 30 minutes, then becomes one hour. All delays have a 30-second minimum and share a 24-hour deadline starting at the first attempt that needs another delivery. If the receiver keeps deferring until the deadline, the queue records a completion timeout.
|
|
140
|
+
|
|
141
|
+
Existing callers can also use the legacy `responsePolicy` map. Supply one policy format per event. The SDK encodes events with either format using `enqueue_with_response_policy`. Direct wire clients can send it in `eventOps` through `queue_batch` or `execute_with_event_ops`, or through the corresponding HTTP endpoints.
|
|
142
|
+
|
|
143
|
+
For webhooks using only request methods, headers or custom bodies, direct clients can use `execute_with_http_events` over WebSocket or `POST /api/v1/sql/http-events` on a native database endpoint.
|
|
114
144
|
|
|
115
145
|
Concurrent `execute()` calls share one authenticated WebSocket and a bounded
|
|
116
146
|
session pool. An idle connection does not issue SQL probes or keep database
|
package/index.d.ts
CHANGED
|
@@ -15,13 +15,41 @@ export interface StatementResult {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
export type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
|
|
18
|
+
export const WebhookResponseAction: {
|
|
19
|
+
/** Acknowledge delivery. */
|
|
20
|
+
readonly Success: 'success';
|
|
21
|
+
/** Deliver the same event later and clear its lastError. */
|
|
22
|
+
readonly DeferTask: 'deferTask';
|
|
23
|
+
/** Record the delivery error and schedule another attempt. */
|
|
24
|
+
readonly Retry: 'retry';
|
|
25
|
+
/** End delivery and record the HTTP status as the failure reason. */
|
|
26
|
+
readonly Fail: 'fail';
|
|
27
|
+
};
|
|
28
|
+
export type WebhookResponseAction = (typeof WebhookResponseAction)[keyof typeof WebhookResponseAction];
|
|
29
|
+
type StatusClass = 1 | 2 | 3 | 4 | 5;
|
|
30
|
+
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
31
|
+
export type WebhookStatusCode = `${StatusClass}xx` | `${StatusClass}${Digit}${Digit}`;
|
|
32
|
+
/** An exact status overrides its class, regardless of rule order. */
|
|
33
|
+
export type WebhookResponseHandler = { statusCode: WebhookStatusCode } & (
|
|
34
|
+
| { action: typeof WebhookResponseAction.Success | typeof WebhookResponseAction.Fail; retryAfter?: never }
|
|
35
|
+
| {
|
|
36
|
+
action: typeof WebhookResponseAction.Retry | typeof WebhookResponseAction.DeferTask;
|
|
37
|
+
/** Positive duration such as "120s", used when the receiver omits a valid Retry-After header. */
|
|
38
|
+
retryAfter?: string;
|
|
39
|
+
}
|
|
40
|
+
);
|
|
41
|
+
/** @deprecated Use WebhookResponseHandler[] for new events. */
|
|
42
|
+
export type WebhookResponsePolicy = Partial<Record<WebhookStatusCode, WebhookResponseAction>>;
|
|
18
43
|
export type WebhookEvent = {
|
|
19
44
|
webhook: string;
|
|
20
45
|
/** Earliest delivery time, in RFC 3339 format. */
|
|
21
46
|
startedAt?: string;
|
|
22
47
|
method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
23
48
|
headers?: Record<string, string>;
|
|
24
|
-
} & (
|
|
49
|
+
} & (
|
|
50
|
+
| { handlers?: readonly WebhookResponseHandler[]; responsePolicy?: never }
|
|
51
|
+
| { handlers?: never; responsePolicy?: WebhookResponsePolicy }
|
|
52
|
+
) & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
|
|
25
53
|
export interface ExecuteOptions { events: WebhookEvent[] }
|
|
26
54
|
|
|
27
55
|
export interface CancelOptions { ifFinished?: 'error' | 'skip' }
|
package/index.js
CHANGED
|
@@ -2,13 +2,43 @@ import { Connection } from './transport.js';
|
|
|
2
2
|
|
|
3
3
|
export { SQLessError } from './errors.js';
|
|
4
4
|
|
|
5
|
+
export const WebhookResponseAction = Object.freeze({
|
|
6
|
+
Success: 'success',
|
|
7
|
+
DeferTask: 'deferTask',
|
|
8
|
+
Retry: 'retry',
|
|
9
|
+
Fail: 'fail',
|
|
10
|
+
});
|
|
11
|
+
|
|
5
12
|
const result = response => ({ results: response.results ?? [], ...(response.eventIds && { eventIds: response.eventIds }) });
|
|
6
13
|
|
|
14
|
+
function hasResponsePolicy(event) {
|
|
15
|
+
if (event?.handlers != null) {
|
|
16
|
+
if (!Array.isArray(event.handlers)) throw new TypeError('handlers must be an array');
|
|
17
|
+
if (event.responsePolicy != null) throw new TypeError('specify either handlers or responsePolicy');
|
|
18
|
+
return event.handlers.length > 0;
|
|
19
|
+
}
|
|
20
|
+
const policy = event?.responsePolicy;
|
|
21
|
+
if (policy == null) return false;
|
|
22
|
+
if (typeof policy !== 'object' || Array.isArray(policy)) throw new TypeError('responsePolicy must be an object');
|
|
23
|
+
return Object.keys(policy).length > 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function wireOperation(op) {
|
|
27
|
+
if (op.op === 'enqueue' && hasResponsePolicy(op.event)) {
|
|
28
|
+
return { ...op, op: 'enqueue_with_response_policy' };
|
|
29
|
+
}
|
|
30
|
+
return op;
|
|
31
|
+
}
|
|
32
|
+
|
|
7
33
|
function execution(options) {
|
|
8
34
|
if (options?.eventOps !== undefined) throw new TypeError('pass eventOps in the execute request object');
|
|
9
35
|
if (options?.events === undefined) return { op: 'execute' };
|
|
10
36
|
const { events } = options;
|
|
11
37
|
if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
|
|
38
|
+
if (events.some(hasResponsePolicy)) {
|
|
39
|
+
const eventOps = events.map(event => wireOperation({ op: 'enqueue', event }));
|
|
40
|
+
return { op: 'execute_with_event_ops', eventOps };
|
|
41
|
+
}
|
|
12
42
|
if (events.some(e => e.startedAt != null)) return { op: 'execute_with_scheduled_events', events };
|
|
13
43
|
const extended = events.some(e => e.method != null || Object.keys(e.headers ?? {}).length > 0 ||
|
|
14
44
|
e.body != null || e.payload === undefined || !e.webhook.startsWith('https://'));
|
|
@@ -18,9 +48,10 @@ function execution(options) {
|
|
|
18
48
|
function queueRequest(eventOps, statements) {
|
|
19
49
|
if (!Array.isArray(eventOps) || !eventOps.length) throw new TypeError('eventOps must be a nonempty array');
|
|
20
50
|
if (statements !== undefined && !Array.isArray(statements)) throw new TypeError('statements must be an array');
|
|
51
|
+
const ops = eventOps.map(wireOperation);
|
|
21
52
|
return statements?.length
|
|
22
|
-
? { op: 'execute_with_event_ops', statements, eventOps }
|
|
23
|
-
: { op: 'queue_batch', eventOps };
|
|
53
|
+
? { op: 'execute_with_event_ops', statements, eventOps: ops }
|
|
54
|
+
: { op: 'queue_batch', eventOps: ops };
|
|
24
55
|
}
|
|
25
56
|
|
|
26
57
|
function executeRequest(input, options) {
|