@trysqless/node 0.2.1 → 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 CHANGED
@@ -71,6 +71,29 @@ try {
71
71
  ```
72
72
 
73
73
  Keep one client at process scope in an HTTP server and close it during shutdown.
74
+
75
+ ### Queue operations
76
+
77
+ Each buffered logical database owns a webhook queue. `await db.queue.enqueue(event)` commits a standalone event and returns its ID. `await db.queue.cancel(eventId)` commits a standalone cancellation. Both work while Compute sleeps. Use a batch when cancellation and replacement must succeed together.
78
+
79
+ ```js
80
+ const eventOps = [
81
+ { op: 'cancel', eventId: oldEventId },
82
+ { op: 'enqueue', event: { webhook: reminderUrl, startedAt: dueAt, payload: { reminderId } } },
83
+ ];
84
+ const { eventIds } = await db.queue.batch(eventOps);
85
+ ```
86
+
87
+ To commit SQL and the queue batch together, call `db.execute({ statements, eventOps })`. Each enqueue contributes one ID to `eventIds` in input order. Within an explicit transaction, use `session.queue.enqueue`, `session.queue.cancel`, `session.queue.batch`, or `session.execute({ statements, eventOps })`. You can store the provisional enqueue ID in a later SQL statement in the same transaction. The enclosing commit decides cancellation outcomes and makes the entire batch visible. Rollback discards it. Calls through `db.queue` always commit independently.
88
+
89
+ Cancellation stops future attempts of a pending or retrying event in the same logical queue. A worker that has already claimed delivery causes `EVENT_DELIVERING`. A finished event causes `EVENT_FINISHED`. Pass `{ ifFinished: 'skip' }` to skip delivered, failed, or cancelled events. An absent event causes `EVENT_NOT_FOUND`. A rejected operation aborts the whole commit. At most 32 operations and 256 KiB of webhook input are accepted per transaction. A lost commit response may indicate a committed batch. Verify application state before replaying.
90
+
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
+
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
+
95
+ ### Enqueue with SQL
96
+
74
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.
75
98
 
76
99
  ```js
@@ -89,7 +112,35 @@ Webhooks accept public HTTP and HTTPS URLs. The default method is `POST`. Suppor
89
112
 
90
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`.
91
114
 
92
- SQLess sends the saved request after commit, and reuses it for retries. Deliveries can be duplicated and can arrive in any order. Return 2xx after recording the stable `Idempotency-Key` and processing the request. SQLess supplies `Idempotency-Key`, `X-SQLess-Event-ID` and transport headers such as `Host` and `Content-Length`. Failed attempts back off exponentially for 30 minutes, then retry hourly for up to 24 hours from the first failure. The database task queue records the final outcome. Clients implementing the wire protocol directly can use `execute_with_http_events` over WebSocket or `POST /api/v1/sql/http-events` on a native database endpoint so older peers reject an unsupported request before executing SQL.
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.
93
144
 
94
145
  Concurrent `execute()` calls share one authenticated WebSocket and a bounded
95
146
  session pool. An idle connection does not issue SQL probes or keep database
package/index.d.ts CHANGED
@@ -15,19 +15,60 @@ 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
- } & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
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
 
55
+ export interface CancelOptions { ifFinished?: 'error' | 'skip' }
56
+ export type EventOp =
57
+ | { op: 'enqueue'; event: WebhookEvent }
58
+ | ({ op: 'cancel'; eventId: string } & CancelOptions);
59
+ export interface EventExecution { statements?: Statement[]; eventOps: EventOp[] }
60
+ export interface EventQueue {
61
+ enqueue(event: WebhookEvent): Promise<string>;
62
+ cancel(eventId: string, options?: CancelOptions): Promise<void>;
63
+ /** Applies operations in order. Only enqueues contribute to eventIds. */
64
+ batch(ops: EventOp[]): Promise<{ eventIds: string[] }>;
65
+ }
66
+
27
67
  export interface SQLResult {
28
68
  eventIds?: string[];
29
69
  results: StatementResult[];
30
70
  }
71
+ export interface EventExecutionResult extends SQLResult { eventIds: string[] }
31
72
 
32
73
  export type ConnectOptions = {
33
74
  sessions?: number;
@@ -46,7 +87,9 @@ export class SQLessError extends Error {
46
87
 
47
88
  export class SQLessClient {
48
89
  private constructor();
90
+ readonly queue: EventQueue;
49
91
  static connect(options: string | ConnectOptions): Promise<SQLessClient>;
92
+ execute(request: EventExecution): Promise<EventExecutionResult>;
50
93
  execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
51
94
  executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
52
95
  executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
@@ -57,6 +100,9 @@ export class SQLessClient {
57
100
 
58
101
  /** A reserved pool slot. Calls on a session must be awaited sequentially. */
59
102
  export interface SQLessSession {
103
+ /** Queue calls inside BEGIN take effect on the enclosing commit. */
104
+ readonly queue: EventQueue;
105
+ execute(request: EventExecution): Promise<EventExecutionResult>;
60
106
  execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
61
107
  executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
62
108
  executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
package/index.js CHANGED
@@ -2,18 +2,92 @@ 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) {
34
+ if (options?.eventOps !== undefined) throw new TypeError('pass eventOps in the execute request object');
8
35
  if (options?.events === undefined) return { op: 'execute' };
9
36
  const { events } = options;
10
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
+ }
11
42
  if (events.some(e => e.startedAt != null)) return { op: 'execute_with_scheduled_events', events };
12
43
  const extended = events.some(e => e.method != null || Object.keys(e.headers ?? {}).length > 0 ||
13
44
  e.body != null || e.payload === undefined || !e.webhook.startsWith('https://'));
14
45
  return { op: extended ? 'execute_with_http_events' : 'execute_with_events', events };
15
46
  }
16
47
 
48
+ function queueRequest(eventOps, statements) {
49
+ if (!Array.isArray(eventOps) || !eventOps.length) throw new TypeError('eventOps must be a nonempty array');
50
+ if (statements !== undefined && !Array.isArray(statements)) throw new TypeError('statements must be an array');
51
+ const ops = eventOps.map(wireOperation);
52
+ return statements?.length
53
+ ? { op: 'execute_with_event_ops', statements, eventOps: ops }
54
+ : { op: 'queue_batch', eventOps: ops };
55
+ }
56
+
57
+ function executeRequest(input, options) {
58
+ if (Array.isArray(input)) return { ...execution(options), statements: input };
59
+ if (!input || typeof input !== 'object' || options !== undefined ||
60
+ Object.keys(input).some(key => key !== 'statements' && key !== 'eventOps')) {
61
+ throw new TypeError('expected a request containing only statements and eventOps');
62
+ }
63
+ return queueRequest(input.eventOps, input.statements);
64
+ }
65
+
66
+ class EventQueue {
67
+ #send;
68
+ constructor(send) { this.#send = send; }
69
+
70
+ async batch(ops) {
71
+ const request = queueRequest(ops);
72
+ const enqueued = ops.filter(op => op.op === 'enqueue').length;
73
+ const response = await this.#send(request);
74
+ const eventIds = response.eventIds ?? [];
75
+ if (eventIds.length !== enqueued) {
76
+ throw new Error('SQLess queue receipt is incomplete; do not replay automatically');
77
+ }
78
+ return { eventIds };
79
+ }
80
+
81
+ async enqueue(event) {
82
+ const { eventIds } = await this.batch([{ op: 'enqueue', event }]);
83
+ return eventIds[0];
84
+ }
85
+
86
+ async cancel(eventId, { ifFinished } = {}) {
87
+ await this.batch([{ op: 'cancel', eventId, ifFinished }]);
88
+ }
89
+ }
90
+
17
91
  // Transport objects never leave this module. Clients and leased sessions share
18
92
  // the same bounded pool; opening an interactive session reserves one pool slot.
19
93
  export class SQLessClient {
@@ -23,10 +97,13 @@ export class SQLessClient {
23
97
  return new SQLessClient(await Connection.connect(options));
24
98
  }
25
99
 
26
- constructor(connection) { this.#connection = connection; }
100
+ constructor(connection) {
101
+ this.#connection = connection;
102
+ this.queue = new EventQueue(request => connection.request(request));
103
+ }
27
104
 
28
105
  async execute(statements, options) {
29
- return result(await this.#connection.request({ ...execution(options), statements }));
106
+ return result(await this.#connection.request(executeRequest(statements, options)));
30
107
  }
31
108
 
32
109
  async executeWithEvents(statements, events) {
@@ -54,10 +131,11 @@ class SQLessSession {
54
131
  constructor(connection, session) {
55
132
  this.#connection = connection;
56
133
  this.#session = session;
134
+ this.queue = new EventQueue(request => session.call(request));
57
135
  }
58
136
 
59
137
  async execute(statements, options) {
60
- return result(await this.#session.call({ ...execution(options), statements }));
138
+ return result(await this.#session.call(executeRequest(statements, options)));
61
139
  }
62
140
 
63
141
  async executeWithEvents(statements, events) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trysqless/node",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Method-based Node.js SDK for SQLess over authenticated WebSocket",
5
5
  "repository": {
6
6
  "type": "git",
package/transport.js CHANGED
@@ -66,7 +66,7 @@ class Session {
66
66
  this.chunks = []; this.bytes = 0; this.expected = null;
67
67
  const pending = this.pending;
68
68
  if (response.version !== 1 || response.id !== pending.id) throw new Error('SQLess response identity mismatch');
69
- if (pending.op === 'execute' || pending.op === 'execute_with_events' || pending.op === 'execute_with_http_events' || pending.op === 'execute_with_scheduled_events' || response.sessionState === 'closed') this.state = response.sessionState;
69
+ if (pending.op === 'execute' || pending.op.startsWith('execute_with_') || pending.op === 'queue_batch' || response.sessionState === 'closed') this.state = response.sessionState;
70
70
  this.pending = null; clearTimeout(pending.timer);
71
71
  if (response.error) pending.reject(new SQLessError(response)); else pending.resolve(response);
72
72
  if (response.sessionState === 'closed') this.close(new Error('SQLess session closed'));