@trysqless/node 0.2.0 → 0.3.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,27 @@ 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
+ ### Enqueue with SQL
94
+
74
95
  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
96
 
76
97
  ```js
@@ -87,6 +108,8 @@ const { eventIds } = await db.executeWithEvents(
87
108
 
88
109
  Webhooks accept public HTTP and HTTPS URLs. The default method is `POST`. Supported methods are `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` and `OPTIONS`. Supply `payload` for JSON, `body` for raw UTF-8 text, or omit both for an empty request. Put query parameters in the URL. Use `headers` for application headers and content types. Header names and values total at most 32 KiB per event. Use HTTPS for credentials.
89
110
 
111
+ 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
+
90
113
  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.
91
114
 
92
115
  Concurrent `execute()` calls share one authenticated WebSocket and a bounded
package/index.d.ts CHANGED
@@ -17,15 +17,30 @@ export interface StatementResult {
17
17
  export type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
18
18
  export type WebhookEvent = {
19
19
  webhook: string;
20
+ /** Earliest delivery time, in RFC 3339 format. */
21
+ startedAt?: string;
20
22
  method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
21
23
  headers?: Record<string, string>;
22
24
  } & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
23
25
  export interface ExecuteOptions { events: WebhookEvent[] }
24
26
 
27
+ export interface CancelOptions { ifFinished?: 'error' | 'skip' }
28
+ export type EventOp =
29
+ | { op: 'enqueue'; event: WebhookEvent }
30
+ | ({ op: 'cancel'; eventId: string } & CancelOptions);
31
+ export interface EventExecution { statements?: Statement[]; eventOps: EventOp[] }
32
+ export interface EventQueue {
33
+ enqueue(event: WebhookEvent): Promise<string>;
34
+ cancel(eventId: string, options?: CancelOptions): Promise<void>;
35
+ /** Applies operations in order. Only enqueues contribute to eventIds. */
36
+ batch(ops: EventOp[]): Promise<{ eventIds: string[] }>;
37
+ }
38
+
25
39
  export interface SQLResult {
26
40
  eventIds?: string[];
27
41
  results: StatementResult[];
28
42
  }
43
+ export interface EventExecutionResult extends SQLResult { eventIds: string[] }
29
44
 
30
45
  export type ConnectOptions = {
31
46
  sessions?: number;
@@ -44,7 +59,9 @@ export class SQLessError extends Error {
44
59
 
45
60
  export class SQLessClient {
46
61
  private constructor();
62
+ readonly queue: EventQueue;
47
63
  static connect(options: string | ConnectOptions): Promise<SQLessClient>;
64
+ execute(request: EventExecution): Promise<EventExecutionResult>;
48
65
  execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
49
66
  executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
50
67
  executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
@@ -55,6 +72,9 @@ export class SQLessClient {
55
72
 
56
73
  /** A reserved pool slot. Calls on a session must be awaited sequentially. */
57
74
  export interface SQLessSession {
75
+ /** Queue calls inside BEGIN take effect on the enclosing commit. */
76
+ readonly queue: EventQueue;
77
+ execute(request: EventExecution): Promise<EventExecutionResult>;
58
78
  execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
59
79
  executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
60
80
  executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
package/index.js CHANGED
@@ -5,14 +5,58 @@ export { SQLessError } from './errors.js';
5
5
  const result = response => ({ results: response.results ?? [], ...(response.eventIds && { eventIds: response.eventIds }) });
6
6
 
7
7
  function execution(options) {
8
+ if (options?.eventOps !== undefined) throw new TypeError('pass eventOps in the execute request object');
8
9
  if (options?.events === undefined) return { op: 'execute' };
9
10
  const { events } = options;
10
11
  if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
12
+ if (events.some(e => e.startedAt != null)) return { op: 'execute_with_scheduled_events', events };
11
13
  const extended = events.some(e => e.method != null || Object.keys(e.headers ?? {}).length > 0 ||
12
14
  e.body != null || e.payload === undefined || !e.webhook.startsWith('https://'));
13
15
  return { op: extended ? 'execute_with_http_events' : 'execute_with_events', events };
14
16
  }
15
17
 
18
+ function queueRequest(eventOps, statements) {
19
+ if (!Array.isArray(eventOps) || !eventOps.length) throw new TypeError('eventOps must be a nonempty array');
20
+ if (statements !== undefined && !Array.isArray(statements)) throw new TypeError('statements must be an array');
21
+ return statements?.length
22
+ ? { op: 'execute_with_event_ops', statements, eventOps }
23
+ : { op: 'queue_batch', eventOps };
24
+ }
25
+
26
+ function executeRequest(input, options) {
27
+ if (Array.isArray(input)) return { ...execution(options), statements: input };
28
+ if (!input || typeof input !== 'object' || options !== undefined ||
29
+ Object.keys(input).some(key => key !== 'statements' && key !== 'eventOps')) {
30
+ throw new TypeError('expected a request containing only statements and eventOps');
31
+ }
32
+ return queueRequest(input.eventOps, input.statements);
33
+ }
34
+
35
+ class EventQueue {
36
+ #send;
37
+ constructor(send) { this.#send = send; }
38
+
39
+ async batch(ops) {
40
+ const request = queueRequest(ops);
41
+ const enqueued = ops.filter(op => op.op === 'enqueue').length;
42
+ const response = await this.#send(request);
43
+ const eventIds = response.eventIds ?? [];
44
+ if (eventIds.length !== enqueued) {
45
+ throw new Error('SQLess queue receipt is incomplete; do not replay automatically');
46
+ }
47
+ return { eventIds };
48
+ }
49
+
50
+ async enqueue(event) {
51
+ const { eventIds } = await this.batch([{ op: 'enqueue', event }]);
52
+ return eventIds[0];
53
+ }
54
+
55
+ async cancel(eventId, { ifFinished } = {}) {
56
+ await this.batch([{ op: 'cancel', eventId, ifFinished }]);
57
+ }
58
+ }
59
+
16
60
  // Transport objects never leave this module. Clients and leased sessions share
17
61
  // the same bounded pool; opening an interactive session reserves one pool slot.
18
62
  export class SQLessClient {
@@ -22,10 +66,13 @@ export class SQLessClient {
22
66
  return new SQLessClient(await Connection.connect(options));
23
67
  }
24
68
 
25
- constructor(connection) { this.#connection = connection; }
69
+ constructor(connection) {
70
+ this.#connection = connection;
71
+ this.queue = new EventQueue(request => connection.request(request));
72
+ }
26
73
 
27
74
  async execute(statements, options) {
28
- return result(await this.#connection.request({ ...execution(options), statements }));
75
+ return result(await this.#connection.request(executeRequest(statements, options)));
29
76
  }
30
77
 
31
78
  async executeWithEvents(statements, events) {
@@ -53,10 +100,11 @@ class SQLessSession {
53
100
  constructor(connection, session) {
54
101
  this.#connection = connection;
55
102
  this.#session = session;
103
+ this.queue = new EventQueue(request => session.call(request));
56
104
  }
57
105
 
58
106
  async execute(statements, options) {
59
- return result(await this.#session.call({ ...execution(options), statements }));
107
+ return result(await this.#session.call(executeRequest(statements, options)));
60
108
  }
61
109
 
62
110
  async executeWithEvents(statements, events) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trysqless/node",
3
- "version": "0.2.0",
3
+ "version": "0.3.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' || 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'));