@trysqless/node 0.1.0 → 0.2.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
@@ -22,13 +22,13 @@ installation is a build step, not part of a cloud function's cold start.
22
22
  ## Develop from this repository
23
23
 
24
24
  Releases use `sdks/node/VERSION` as their version source. Changing that file on
25
- `main` triggers `.github/workflows/publish-node-sdk.yml`, which tests the SDK,
25
+ `main` triggers `.github/workflows/publish-sdk.yaml`, which tests the SDK,
26
26
  publishes to npm, requests npmmirror synchronization, and verifies installation
27
27
  from the mirror. A failed mirror synchronization can be retried without
28
28
  republishing the same version; changed package contents require a new version.
29
29
 
30
30
  After the first npm publication, configure a GitHub Actions trusted publisher for
31
- `cloudcarver/sqless`, workflow `publish-node-sdk.yml`, with direct publishing
31
+ `cloudcarver/sqless`, workflow `publish-sdk.yaml`, with direct publishing
32
32
  allowed. The workflow uses OIDC and does not need an npm token. Run
33
33
  `node scripts/publish.mjs --dry-run` in this directory to validate packaging
34
34
  without publishing.
@@ -59,7 +59,7 @@ try {
59
59
  await db.execute([
60
60
  { sql: 'CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, message TEXT)', parameters: [] },
61
61
  { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['hello'] },
62
- ], { write: true });
62
+ ]);
63
63
 
64
64
  const { results } = await db.execute([
65
65
  { sql: 'SELECT id, message FROM notes WHERE message = ?', parameters: ['hello'] },
@@ -71,6 +71,24 @@ try {
71
71
  ```
72
72
 
73
73
  Keep one client at process scope in an HTTP server and close it during shutdown.
74
+ 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
+
76
+ ```js
77
+ const { eventIds } = await db.executeWithEvents(
78
+ [{ sql: "INSERT INTO orders(id) VALUES (?)", parameters: [orderId] }],
79
+ [{
80
+ webhook: "https://example.com/order-events?source=checkout",
81
+ method: "PATCH",
82
+ headers: { "X-Topic": "order.created" },
83
+ payload: { orderId },
84
+ }],
85
+ );
86
+ ```
87
+
88
+ 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
+
90
+ 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
+
74
92
  Concurrent `execute()` calls share one authenticated WebSocket and a bounded
75
93
  session pool. An idle connection does not issue SQL probes or keep database
76
94
  compute running. `isClosed()` reports connection loss; reconnect explicitly for
@@ -114,14 +132,13 @@ Explicit sessions and automatic requests share this same pool limit.
114
132
  | Client | `execute(statements, options?)` | `{ results, transaction? }` for a complete batch |
115
133
  | Client | `executeScript(script, parameterSets?, options?)` | The same result for a SQL script |
116
134
  | Client | `openSession()` | A reserved session for sequential, interactive work |
117
- | Client or session | `getTransaction(transactionId)` | A transaction receipt |
118
135
  | Client or session | `isClosed()` | Whether the connection/session has closed |
119
136
  | Client or session | `close()` | Release the connection/session; safe to call twice |
120
137
  | Session | `execute(statements, options?)` | Execute statements on the reserved session |
121
138
  | Session | `executeScript(script, parameterSets?, options?)` | Execute a script on the reserved session |
122
- | Session | `begin({ transactionId }?)` | Begin a write transaction and return its receipt |
123
- | Session | `commit()` | Commit and return the receipt |
124
- | Session | `rollback()` | Roll back and return the receipt |
139
+ | Session | `begin()` | Begin a write transaction; resolves without a value |
140
+ | Session | `commit()` | Commit; resolves without a value |
141
+ | Session | `rollback()` | Roll back; resolves without a value |
125
142
 
126
143
  A statement contains `sql`, `parameters`, and optional `maxRows`. Each result
127
144
  contains `columns`, array-valued `rows`, `rowsAffected`, `truncated`, and optional
@@ -129,12 +146,9 @@ contains `columns`, array-valued `rows`, `rowsAffected`, `truncated`, and option
129
146
  parameter array per SQL statement, including empty arrays for statements without
130
147
  parameters.
131
148
 
132
- Client execution options accept `write: true` to generate a transaction UUID, or
133
- an explicit `transactionId`. SQLess determines read/write behavior from SQL;
134
- `write` does not change server-side permissions. Supply your own UUID when you
135
- need to look up a write whose response might be lost. Session execution options
136
- accept `transactionId`; inside an active transaction, normally omit it and use
137
- the ID returned by `begin()`.
149
+ SQLess determines read/write behavior from SQL. Execution methods take only
150
+ SQL statements and parameters; they do not accept write hints or transaction IDs.
151
+ Transactions belong to a reserved session and cannot be resumed on another one.
138
152
 
139
153
  Integers outside JavaScript's safe range are returned as `bigint`. Pass `bigint`
140
154
  for large integer parameters to preserve their exact value. Inputs support
@@ -148,12 +162,11 @@ Await each operation on a reserved session before starting the next one:
148
162
  ```js
149
163
  const session = await db.openSession();
150
164
  try {
151
- const transaction = await session.begin();
165
+ await session.begin();
152
166
  await session.execute([
153
167
  { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['transactional'] },
154
168
  ]);
155
- const receipt = await session.commit();
156
- console.log(transaction.id, receipt.state);
169
+ await session.commit();
157
170
  } finally {
158
171
  session.close();
159
172
  }
@@ -165,27 +178,20 @@ accepted COMMIT, closing the session cannot undo it. The pooled client methods
165
178
  reject an unfinished interactive transaction and close that session instead of
166
179
  lending it to another caller.
167
180
 
168
- For an uncertain write, retain its UUID before sending SQL:
169
-
170
- ```js
171
- import { randomUUID } from 'node:crypto';
172
-
173
- const transactionId = randomUUID();
174
- await db.execute([
175
- { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['receipt example'] },
176
- ], { transactionId });
177
-
178
- // This may also be queried on a newly connected client after transport loss.
179
- const receipt = await db.getTransaction(transactionId);
180
- console.log(receipt.state);
181
- ```
181
+ Connection loss or a timeout during COMMIT can leave its outcome unknown. The
182
+ SDK never replays SQL and has no persistent transaction status API. Applications
183
+ that need safe retries must provide their own business operation keys and atomic
184
+ uniqueness checks. Closing a session rolls back unfinished work; a commit that
185
+ has already completed remains durable even if its reply was lost.
182
186
 
183
- Connection loss or a timeout is not proof that a write failed. Inspect the
184
- transaction receipt instead of blindly retrying SQL. Receipt states are
185
- `active`, `committing`, `committed`, `rolled_back`, and `unknown`.
187
+ The server ignores unknown JSON fields, including `transactionId` sent by older
188
+ SDKs for `{ write: true }` or `session.begin()`. It samples compatibility warnings
189
+ without logging field values. This does not restore transaction receipts or the
190
+ removed `getTransaction()`/`status` operation; applications using those must be
191
+ updated. Invalid known-field types and malformed requests are still rejected.
186
192
 
187
193
  Server errors reject with `SQLessError`, exposing `code`, optional
188
- `statementIndex`, and optional `transaction`. Connection, timeout, and queue
194
+ `statementIndex`. Connection, timeout, and queue
189
195
  errors reject with `Error`. Requests are limited to 4 MiB and responses to 9 MiB.
190
196
 
191
197
  ## Tests
package/errors.js CHANGED
@@ -4,6 +4,5 @@ export class SQLessError extends Error {
4
4
  this.name = 'SQLessError';
5
5
  this.code = response.error.code;
6
6
  this.statementIndex = response.error.statementIndex;
7
- this.transaction = response.transaction;
8
7
  }
9
8
  }
package/index.d.ts CHANGED
@@ -14,25 +14,17 @@ export interface StatementResult {
14
14
  truncated: boolean;
15
15
  }
16
16
 
17
- export interface Transaction {
18
- id: string;
19
- databaseId: string;
20
- createdAt: string;
21
- state: 'active' | 'committing' | 'committed' | 'rolled_back' | 'unknown';
22
- remoteTxid?: string;
23
- reason?: string;
24
- }
17
+ export type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
18
+ export type WebhookEvent = {
19
+ webhook: string;
20
+ method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
21
+ headers?: Record<string, string>;
22
+ } & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
23
+ export interface ExecuteOptions { events: WebhookEvent[] }
25
24
 
26
25
  export interface SQLResult {
26
+ eventIds?: string[];
27
27
  results: StatementResult[];
28
- transaction?: Transaction;
29
- }
30
-
31
- export interface ExecuteOptions {
32
- /** Generate a transaction UUID before sending a complete write batch. */
33
- write?: boolean;
34
- /** Supply your own UUID to query the receipt after an uncertain outcome. */
35
- transactionId?: string;
36
28
  }
37
29
 
38
30
  export type ConnectOptions = {
@@ -48,15 +40,14 @@ export class SQLessError extends Error {
48
40
  private constructor();
49
41
  readonly code: string;
50
42
  readonly statementIndex?: number;
51
- readonly transaction?: Transaction;
52
43
  }
53
44
 
54
45
  export class SQLessClient {
55
46
  private constructor();
56
47
  static connect(options: string | ConnectOptions): Promise<SQLessClient>;
57
48
  execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
49
+ executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
58
50
  executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
59
- getTransaction(transactionId: string): Promise<Transaction>;
60
51
  openSession(): Promise<SQLessSession>;
61
52
  isClosed(): boolean;
62
53
  close(): void;
@@ -64,12 +55,12 @@ export class SQLessClient {
64
55
 
65
56
  /** A reserved pool slot. Calls on a session must be awaited sequentially. */
66
57
  export interface SQLessSession {
67
- execute(statements: Statement[], options?: Pick<ExecuteOptions, 'transactionId'>): Promise<SQLResult>;
68
- executeScript(script: string, parameterSets?: SQLValue[][], options?: Pick<ExecuteOptions, 'transactionId'>): Promise<SQLResult>;
69
- begin(options?: Pick<ExecuteOptions, 'transactionId'>): Promise<Transaction>;
70
- commit(): Promise<Transaction>;
71
- rollback(): Promise<Transaction>;
72
- getTransaction(transactionId: string): Promise<Transaction>;
58
+ execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
59
+ executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
60
+ executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
61
+ begin(): Promise<void>;
62
+ commit(): Promise<void>;
63
+ rollback(): Promise<void>;
73
64
  isClosed(): boolean;
74
65
  /** Releases the slot and aborts uncommitted work; cannot undo an accepted COMMIT. */
75
66
  close(): void;
package/index.js CHANGED
@@ -1,10 +1,17 @@
1
- import { randomUUID } from 'node:crypto';
2
1
  import { Connection } from './transport.js';
3
2
 
4
3
  export { SQLessError } from './errors.js';
5
4
 
6
- const result = response => ({ results: response.results ?? [], ...(response.transaction ? { transaction: response.transaction } : {}) });
7
- const receipt = ({ write = false, transactionId } = {}) => ({ transactionId: transactionId ?? (write ? randomUUID() : undefined) });
5
+ const result = response => ({ results: response.results ?? [], ...(response.eventIds && { eventIds: response.eventIds }) });
6
+
7
+ function execution(options) {
8
+ if (options?.events === undefined) return { op: 'execute' };
9
+ const { events } = options;
10
+ if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
11
+ const extended = events.some(e => e.method != null || Object.keys(e.headers ?? {}).length > 0 ||
12
+ e.body != null || e.payload === undefined || !e.webhook.startsWith('https://'));
13
+ return { op: extended ? 'execute_with_http_events' : 'execute_with_events', events };
14
+ }
8
15
 
9
16
  // Transport objects never leave this module. Clients and leased sessions share
10
17
  // the same bounded pool; opening an interactive session reserves one pool slot.
@@ -18,15 +25,16 @@ export class SQLessClient {
18
25
  constructor(connection) { this.#connection = connection; }
19
26
 
20
27
  async execute(statements, options) {
21
- return result(await this.#connection.request({ op: 'execute', statements, ...receipt(options) }));
28
+ return result(await this.#connection.request({ ...execution(options), statements }));
22
29
  }
23
30
 
24
- async executeScript(script, parameterSets, options) {
25
- return result(await this.#connection.request({ op: 'execute', script, parameterSets, ...receipt(options) }));
31
+ async executeWithEvents(statements, events) {
32
+ if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
33
+ return this.execute(statements, { events });
26
34
  }
27
35
 
28
- async getTransaction(transactionId) {
29
- return (await this.#connection.request({ op: 'status', transactionId })).transaction;
36
+ async executeScript(script, parameterSets, options) {
37
+ return result(await this.#connection.request({ ...execution(options), script, parameterSets }));
30
38
  }
31
39
 
32
40
  async openSession() {
@@ -47,24 +55,22 @@ class SQLessSession {
47
55
  this.#session = session;
48
56
  }
49
57
 
50
- async execute(statements, { transactionId } = {}) {
51
- return result(await this.#session.call({ op: 'execute', statements, transactionId }));
58
+ async execute(statements, options) {
59
+ return result(await this.#session.call({ ...execution(options), statements }));
52
60
  }
53
61
 
54
- async executeScript(script, parameterSets, { transactionId } = {}) {
55
- return result(await this.#session.call({ op: 'execute', script, parameterSets, transactionId }));
62
+ async executeWithEvents(statements, events) {
63
+ if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
64
+ return this.execute(statements, { events });
56
65
  }
57
66
 
58
- async begin({ transactionId = randomUUID() } = {}) {
59
- return (await this.executeScript('BEGIN IMMEDIATE', undefined, { transactionId })).transaction;
67
+ async executeScript(script, parameterSets, options) {
68
+ return result(await this.#session.call({ ...execution(options), script, parameterSets }));
60
69
  }
61
70
 
62
- async commit() { return (await this.executeScript('COMMIT')).transaction; }
63
- async rollback() { return (await this.executeScript('ROLLBACK')).transaction; }
64
-
65
- async getTransaction(transactionId) {
66
- return (await this.#session.call({ op: 'status', transactionId })).transaction;
67
- }
71
+ async begin() { await this.executeScript('BEGIN IMMEDIATE'); }
72
+ async commit() { await this.executeScript('COMMIT'); }
73
+ async rollback() { await this.executeScript('ROLLBACK'); }
68
74
 
69
75
  isClosed() { return this.#session.closed; }
70
76
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trysqless/node",
3
- "version": "0.1.0",
3
+ "version": "0.2.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,9 +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
- // A status lookup's receipt belongs to the requested transaction, not
70
- // necessarily the transaction currently running on this session.
71
- if (pending.op === 'execute' || response.sessionState === 'closed') this.state = response.sessionState;
69
+ if (pending.op === 'execute' || pending.op === 'execute_with_events' || pending.op === 'execute_with_http_events' || response.sessionState === 'closed') this.state = response.sessionState;
72
70
  this.pending = null; clearTimeout(pending.timer);
73
71
  if (response.error) pending.reject(new SQLessError(response)); else pending.resolve(response);
74
72
  if (response.sessionState === 'closed') this.close(new Error('SQLess session closed'));