@trysqless/node 0.2.1 → 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 +21 -0
- package/index.d.ts +18 -0
- package/index.js +50 -3
- package/package.json +1 -1
- package/transport.js +1 -1
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
|
package/index.d.ts
CHANGED
|
@@ -24,10 +24,23 @@ export type WebhookEvent = {
|
|
|
24
24
|
} & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
|
|
25
25
|
export interface ExecuteOptions { events: WebhookEvent[] }
|
|
26
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
|
+
|
|
27
39
|
export interface SQLResult {
|
|
28
40
|
eventIds?: string[];
|
|
29
41
|
results: StatementResult[];
|
|
30
42
|
}
|
|
43
|
+
export interface EventExecutionResult extends SQLResult { eventIds: string[] }
|
|
31
44
|
|
|
32
45
|
export type ConnectOptions = {
|
|
33
46
|
sessions?: number;
|
|
@@ -46,7 +59,9 @@ export class SQLessError extends Error {
|
|
|
46
59
|
|
|
47
60
|
export class SQLessClient {
|
|
48
61
|
private constructor();
|
|
62
|
+
readonly queue: EventQueue;
|
|
49
63
|
static connect(options: string | ConnectOptions): Promise<SQLessClient>;
|
|
64
|
+
execute(request: EventExecution): Promise<EventExecutionResult>;
|
|
50
65
|
execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
|
|
51
66
|
executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
|
|
52
67
|
executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
|
|
@@ -57,6 +72,9 @@ export class SQLessClient {
|
|
|
57
72
|
|
|
58
73
|
/** A reserved pool slot. Calls on a session must be awaited sequentially. */
|
|
59
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>;
|
|
60
78
|
execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
|
|
61
79
|
executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
|
|
62
80
|
executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
|
package/index.js
CHANGED
|
@@ -5,6 +5,7 @@ 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');
|
|
@@ -14,6 +15,48 @@ function execution(options) {
|
|
|
14
15
|
return { op: extended ? 'execute_with_http_events' : 'execute_with_events', events };
|
|
15
16
|
}
|
|
16
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
|
+
|
|
17
60
|
// Transport objects never leave this module. Clients and leased sessions share
|
|
18
61
|
// the same bounded pool; opening an interactive session reserves one pool slot.
|
|
19
62
|
export class SQLessClient {
|
|
@@ -23,10 +66,13 @@ export class SQLessClient {
|
|
|
23
66
|
return new SQLessClient(await Connection.connect(options));
|
|
24
67
|
}
|
|
25
68
|
|
|
26
|
-
constructor(connection) {
|
|
69
|
+
constructor(connection) {
|
|
70
|
+
this.#connection = connection;
|
|
71
|
+
this.queue = new EventQueue(request => connection.request(request));
|
|
72
|
+
}
|
|
27
73
|
|
|
28
74
|
async execute(statements, options) {
|
|
29
|
-
return result(await this.#connection.request(
|
|
75
|
+
return result(await this.#connection.request(executeRequest(statements, options)));
|
|
30
76
|
}
|
|
31
77
|
|
|
32
78
|
async executeWithEvents(statements, events) {
|
|
@@ -54,10 +100,11 @@ class SQLessSession {
|
|
|
54
100
|
constructor(connection, session) {
|
|
55
101
|
this.#connection = connection;
|
|
56
102
|
this.#session = session;
|
|
103
|
+
this.queue = new EventQueue(request => session.call(request));
|
|
57
104
|
}
|
|
58
105
|
|
|
59
106
|
async execute(statements, options) {
|
|
60
|
-
return result(await this.#session.call(
|
|
107
|
+
return result(await this.#session.call(executeRequest(statements, options)));
|
|
61
108
|
}
|
|
62
109
|
|
|
63
110
|
async executeWithEvents(statements, events) {
|
package/package.json
CHANGED
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
|
|
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'));
|