@chimp-labs/keel-surreal 0.0.0-stage → 0.1.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/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/dist/client.d.ts +189 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +725 -0
- package/dist/client.js.map +1 -0
- package/dist/helpers.d.ts +38 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/helpers.js +253 -0
- package/dist/helpers.js.map +1 -0
- package/dist/index.d.ts +99 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +135 -0
- package/dist/index.js.map +1 -0
- package/dist/kv-flags.d.ts +7 -0
- package/dist/kv-flags.d.ts.map +1 -0
- package/dist/kv-flags.js +109 -0
- package/dist/kv-flags.js.map +1 -0
- package/dist/messaging.d.ts +7 -0
- package/dist/messaging.d.ts.map +1 -0
- package/dist/messaging.js +245 -0
- package/dist/messaging.js.map +1 -0
- package/dist/migrations.d.ts +40 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +206 -0
- package/dist/migrations.js.map +1 -0
- package/dist/stores.d.ts +5 -0
- package/dist/stores.d.ts.map +1 -0
- package/dist/stores.js +448 -0
- package/dist/stores.js.map +1 -0
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +94 -0
- package/dist/utils.js.map +1 -0
- package/package.json +89 -3
package/dist/client.js
ADDED
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
import { Cause, Config, Context, Effect, Exit, Layer, Option, Queue, Redacted, Schema, Stream, } from "effect";
|
|
2
|
+
import { RecordId, Surreal, Table as SurrealTable, } from "surrealdb";
|
|
3
|
+
import { ActiveTxPostCommit, KeelErrorMetaSym, } from "@chimp-labs/keel";
|
|
4
|
+
import { errorMessage, escapeIdent } from "./helpers.js";
|
|
5
|
+
import { backoffSchedule } from "./utils.js";
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// SurrealClient Service + Fiber-Scoped Active Transaction Reference
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
export class SurrealClientError extends Schema.TaggedError()("SurrealClientError", {
|
|
10
|
+
operation: Schema.String,
|
|
11
|
+
cause: Schema.Unknown,
|
|
12
|
+
}) {
|
|
13
|
+
static [KeelErrorMetaSym] = {
|
|
14
|
+
category: "unavailable",
|
|
15
|
+
httpStatus: 503,
|
|
16
|
+
retryable: true,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
const normalizeHttpUrl = (url) => {
|
|
20
|
+
if (/^wss:\/\//i.test(url))
|
|
21
|
+
return `https://${url.slice(6)}`;
|
|
22
|
+
if (/^ws:\/\//i.test(url))
|
|
23
|
+
return `http://${url.slice(5)}`;
|
|
24
|
+
return url;
|
|
25
|
+
};
|
|
26
|
+
const normalizeWsUrl = (url) => {
|
|
27
|
+
if (/^https:\/\//i.test(url))
|
|
28
|
+
return `wss://${url.slice(8)}`;
|
|
29
|
+
if (/^http:\/\//i.test(url))
|
|
30
|
+
return `ws://${url.slice(7)}`;
|
|
31
|
+
return url;
|
|
32
|
+
};
|
|
33
|
+
const toHttpSqlEndpoint = (rawUrl) => {
|
|
34
|
+
const http = normalizeHttpUrl(rawUrl).replace(/\/+$/, "");
|
|
35
|
+
if (/\/sql$/i.test(http))
|
|
36
|
+
return http;
|
|
37
|
+
if (/\/rpc$/i.test(http))
|
|
38
|
+
return `${http.slice(0, -4)}/sql`;
|
|
39
|
+
return `${http}/sql`;
|
|
40
|
+
};
|
|
41
|
+
const encodeBasicAuth = (username, password) => {
|
|
42
|
+
const raw = `${username}:${password}`;
|
|
43
|
+
if (typeof Buffer !== "undefined") {
|
|
44
|
+
return Buffer.from(raw, "utf8").toString("base64");
|
|
45
|
+
}
|
|
46
|
+
const bytes = new TextEncoder().encode(raw);
|
|
47
|
+
let bin = "";
|
|
48
|
+
for (const byte of bytes) {
|
|
49
|
+
bin += String.fromCharCode(byte);
|
|
50
|
+
}
|
|
51
|
+
return btoa(bin);
|
|
52
|
+
};
|
|
53
|
+
const VALID_SURQL_VAR = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
54
|
+
const serializeSurqlLiteral = (value) => {
|
|
55
|
+
if (value === undefined)
|
|
56
|
+
return "NONE";
|
|
57
|
+
if (value === null)
|
|
58
|
+
return "NULL";
|
|
59
|
+
if (typeof value === "boolean")
|
|
60
|
+
return value ? "true" : "false";
|
|
61
|
+
if (typeof value === "number")
|
|
62
|
+
return Number.isFinite(value) ? String(value) : "NULL";
|
|
63
|
+
if (typeof value === "string")
|
|
64
|
+
return JSON.stringify(value);
|
|
65
|
+
if (value instanceof Date)
|
|
66
|
+
return `d${JSON.stringify(value.toISOString())}`;
|
|
67
|
+
if (value instanceof RecordId) {
|
|
68
|
+
const tbl = escapeIdent(String(value.table));
|
|
69
|
+
const id = typeof value.id === "number"
|
|
70
|
+
? String(value.id)
|
|
71
|
+
: escapeIdent(String(value.id));
|
|
72
|
+
return `${tbl}:${id}`;
|
|
73
|
+
}
|
|
74
|
+
if (Array.isArray(value)) {
|
|
75
|
+
return `[${value.map(serializeSurqlLiteral).join(", ")}]`;
|
|
76
|
+
}
|
|
77
|
+
if (typeof value === "object") {
|
|
78
|
+
if ("toISOString" in value &&
|
|
79
|
+
typeof value.toISOString === "function") {
|
|
80
|
+
return `d${JSON.stringify(value.toISOString())}`;
|
|
81
|
+
}
|
|
82
|
+
const entries = Object.entries(value)
|
|
83
|
+
.filter(([, v]) => v !== undefined)
|
|
84
|
+
.map(([k, v]) => `${JSON.stringify(k)}: ${serializeSurqlLiteral(v)}`);
|
|
85
|
+
return `{ ${entries.join(", ")} }`;
|
|
86
|
+
}
|
|
87
|
+
return JSON.stringify(String(value));
|
|
88
|
+
};
|
|
89
|
+
const formatSurqlWithVars = (surql, vars) => {
|
|
90
|
+
if (!vars)
|
|
91
|
+
return { sql: surql, letCount: 0 };
|
|
92
|
+
const entries = Object.entries(vars).filter(([, v]) => v !== undefined);
|
|
93
|
+
if (entries.length === 0)
|
|
94
|
+
return { sql: surql, letCount: 0 };
|
|
95
|
+
const lets = [];
|
|
96
|
+
for (const [key, val] of entries) {
|
|
97
|
+
if (!VALID_SURQL_VAR.test(key)) {
|
|
98
|
+
throw new Error(`Invalid SurrealQL variable name "${key}"`);
|
|
99
|
+
}
|
|
100
|
+
lets.push(`LET $${key} = ${serializeSurqlLiteral(val)};`);
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
sql: `${lets.join("\n")}\n${surql}`,
|
|
104
|
+
letCount: lets.length,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
const ensureTrailingSemicolon = (sql) => {
|
|
108
|
+
const trimmed = sql.trim();
|
|
109
|
+
if (trimmed.length === 0)
|
|
110
|
+
return "";
|
|
111
|
+
return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Formats an array of SurrealQL statements into a single atomic HTTP `/sql`
|
|
115
|
+
* transaction batch (`BEGIN TRANSACTION; ...; COMMIT TRANSACTION;`).
|
|
116
|
+
*/
|
|
117
|
+
export const buildSurrealHttpTransactionSql = (statements) => {
|
|
118
|
+
const parts = ["BEGIN TRANSACTION;"];
|
|
119
|
+
for (const stmt of statements) {
|
|
120
|
+
const formatted = formatSurqlWithVars(stmt.surql, stmt.vars);
|
|
121
|
+
const body = ensureTrailingSemicolon(formatted.sql);
|
|
122
|
+
if (body.length > 0) {
|
|
123
|
+
parts.push(body);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
parts.push("COMMIT TRANSACTION;");
|
|
127
|
+
return parts.join("\n");
|
|
128
|
+
};
|
|
129
|
+
const ActiveSurrealTx = Context.Reference("@chimp-labs/keel/ActiveSurrealTx", { defaultValue: () => undefined });
|
|
130
|
+
const ActiveHttpTx = Context.Reference("@chimp-labs/keel/ActiveHttpTx", { defaultValue: () => undefined });
|
|
131
|
+
const isTransientSurrealError = (err) => {
|
|
132
|
+
const msg = errorMessage(err.cause);
|
|
133
|
+
const lower = msg.toLowerCase();
|
|
134
|
+
if (lower.includes("already exists") || lower.includes("already contains")) {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
return /\bhttp\s*503\b|503\s+service|temporarily unavailable|server overloaded|cell.*saturated/i.test(msg);
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Acquires a scoped `LIVE SELECT` WebSocket subscription on `table` and buffers
|
|
141
|
+
* transformed events into an unbounded `Queue` BEFORE returning.
|
|
142
|
+
*
|
|
143
|
+
* Guarantees `sub.kill()` and `Queue.shutdown(queue)` on scope exit, and ends
|
|
144
|
+
* the queue cleanly on `KILLED` notifications.
|
|
145
|
+
*/
|
|
146
|
+
export const acquireLiveQueue = (raw, table, onEvent, onRelease) => Effect.gen(function* () {
|
|
147
|
+
if (!raw) {
|
|
148
|
+
return yield* new SurrealClientError({
|
|
149
|
+
operation: `live:${table}`,
|
|
150
|
+
cause: new Error(`LIVE SELECT on "${table}" requires a persistent WebSocket SurrealClientLive connection (not supported on stateless HTTP or custom transports)`),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
const queue = yield* Queue.unbounded();
|
|
154
|
+
const offer = (value) => {
|
|
155
|
+
Queue.offerUnsafe(queue, value);
|
|
156
|
+
};
|
|
157
|
+
yield* Effect.acquireRelease(Effect.tryPromise({
|
|
158
|
+
try: async () => {
|
|
159
|
+
const sub = await raw.live(new SurrealTable(table));
|
|
160
|
+
sub.subscribe((msg) => {
|
|
161
|
+
if (msg.action === "KILLED") {
|
|
162
|
+
Queue.endUnsafe(queue);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (msg.action === "CREATE" ||
|
|
166
|
+
msg.action === "UPDATE" ||
|
|
167
|
+
msg.action === "DELETE") {
|
|
168
|
+
onEvent({
|
|
169
|
+
action: msg.action,
|
|
170
|
+
recordId: msg.recordId,
|
|
171
|
+
value: msg.value,
|
|
172
|
+
}, offer);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
return sub;
|
|
176
|
+
},
|
|
177
|
+
catch: (cause) => new SurrealClientError({ operation: `live:${table}`, cause }),
|
|
178
|
+
}), (sub) => {
|
|
179
|
+
const kill = Effect.tryPromise(() => sub.kill()).pipe(Effect.ignore);
|
|
180
|
+
const release = onRelease
|
|
181
|
+
? Effect.sync(onRelease).pipe(Effect.andThen(kill))
|
|
182
|
+
: kill;
|
|
183
|
+
return release.pipe(Effect.ensuring(Queue.shutdown(queue)));
|
|
184
|
+
});
|
|
185
|
+
return queue;
|
|
186
|
+
});
|
|
187
|
+
export class SurrealClient extends Context.Service()("@chimp-labs/keel/SurrealClient") {
|
|
188
|
+
}
|
|
189
|
+
const makeDefaultRetrySchedule = () => backoffSchedule({
|
|
190
|
+
base: "50 millis",
|
|
191
|
+
maxDelay: "2 seconds",
|
|
192
|
+
jitter: true,
|
|
193
|
+
});
|
|
194
|
+
const applyMapError = (mapError, err) => (mapError ? mapError(err) : err);
|
|
195
|
+
const connectSurrealInstance = async (config, url, defaultAutoCreate) => {
|
|
196
|
+
const client = new Surreal(config.fetchImpl !== undefined ? { fetchImpl: config.fetchImpl } : undefined);
|
|
197
|
+
const auth = config.token !== undefined
|
|
198
|
+
? config.token
|
|
199
|
+
: config.username !== undefined && config.password !== undefined
|
|
200
|
+
? { username: config.username, password: config.password }
|
|
201
|
+
: undefined;
|
|
202
|
+
await client.connect(url, {
|
|
203
|
+
authentication: auth,
|
|
204
|
+
namespace: config.namespace,
|
|
205
|
+
database: config.database,
|
|
206
|
+
});
|
|
207
|
+
try {
|
|
208
|
+
if (config.autoCreate ?? defaultAutoCreate) {
|
|
209
|
+
const nsIdent = escapeIdent(config.namespace);
|
|
210
|
+
const dbIdent = escapeIdent(config.database);
|
|
211
|
+
await client.query(`DEFINE NAMESPACE IF NOT EXISTS ${nsIdent}`).collect();
|
|
212
|
+
await client.use({ namespace: config.namespace });
|
|
213
|
+
await client.query(`DEFINE DATABASE IF NOT EXISTS ${dbIdent}`).collect();
|
|
214
|
+
}
|
|
215
|
+
await client.use({
|
|
216
|
+
namespace: config.namespace,
|
|
217
|
+
database: config.database,
|
|
218
|
+
});
|
|
219
|
+
return client;
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
await client.close().catch(() => undefined);
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const runNestedOrRootTransaction = (acquireTx, effect, mapError) => Effect.gen(function* () {
|
|
227
|
+
const existingTx = yield* ActiveSurrealTx;
|
|
228
|
+
const outerPostCommit = yield* ActiveTxPostCommit;
|
|
229
|
+
if (existingTx !== undefined) {
|
|
230
|
+
// SurrealDB does not support nested SAVEPOINTs: isolate inner post-commit
|
|
231
|
+
// hooks (merging into outer only on success) and mark the active transaction
|
|
232
|
+
// rollback-only if the inner transaction fails so partial inner writes can
|
|
233
|
+
// never silently commit if the outer transaction catches the failure.
|
|
234
|
+
return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
235
|
+
const localPostCommit = [];
|
|
236
|
+
const exit = yield* restore(effect.pipe(Effect.provideService(ActiveTxPostCommit, localPostCommit))).pipe(Effect.exit);
|
|
237
|
+
if (Exit.isSuccess(exit)) {
|
|
238
|
+
if (outerPostCommit !== undefined) {
|
|
239
|
+
outerPostCommit.push(...localPostCommit);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
for (const hook of localPostCommit) {
|
|
243
|
+
yield* hook;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return exit.value;
|
|
247
|
+
}
|
|
248
|
+
existingTx.rollbackOnly = true;
|
|
249
|
+
return yield* Effect.failCause(exit.cause);
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
253
|
+
const handle = yield* acquireTx().pipe(Effect.mapError((err) => applyMapError(mapError, err)));
|
|
254
|
+
const txState = {
|
|
255
|
+
tx: handle.tx,
|
|
256
|
+
rollbackOnly: false,
|
|
257
|
+
};
|
|
258
|
+
const localPostCommit = [];
|
|
259
|
+
const runBody = Effect.gen(function* () {
|
|
260
|
+
const exit = yield* restore(effect.pipe(Effect.provideService(ActiveSurrealTx, txState), Effect.provideService(ActiveTxPostCommit, localPostCommit))).pipe(Effect.exit);
|
|
261
|
+
if (Exit.isSuccess(exit)) {
|
|
262
|
+
if (txState.rollbackOnly) {
|
|
263
|
+
yield* handle.cancel();
|
|
264
|
+
return yield* applyMapError(mapError, new SurrealClientError({
|
|
265
|
+
operation: "commit",
|
|
266
|
+
cause: new Error("Transaction marked rollback-only because a nested transaction failed (SurrealDB does not support savepoints)"),
|
|
267
|
+
}));
|
|
268
|
+
}
|
|
269
|
+
yield* handle
|
|
270
|
+
.commit()
|
|
271
|
+
.pipe(Effect.mapError((err) => applyMapError(mapError, err)));
|
|
272
|
+
if (outerPostCommit !== undefined) {
|
|
273
|
+
outerPostCommit.push(...localPostCommit);
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
for (const hook of localPostCommit) {
|
|
277
|
+
yield* hook;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return exit.value;
|
|
281
|
+
}
|
|
282
|
+
yield* handle.cancel();
|
|
283
|
+
return yield* Effect.failCause(exit.cause);
|
|
284
|
+
});
|
|
285
|
+
return handle.cleanup !== undefined
|
|
286
|
+
? yield* runBody.pipe(Effect.ensuring(handle.cleanup()))
|
|
287
|
+
: yield* runBody;
|
|
288
|
+
}));
|
|
289
|
+
});
|
|
290
|
+
const buildHttpHeaders = (config) => {
|
|
291
|
+
const headers = {
|
|
292
|
+
Accept: "application/json",
|
|
293
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
294
|
+
"Surreal-NS": config.namespace,
|
|
295
|
+
"Surreal-DB": config.database,
|
|
296
|
+
};
|
|
297
|
+
if (config.token !== undefined) {
|
|
298
|
+
headers.Authorization = `Bearer ${config.token}`;
|
|
299
|
+
}
|
|
300
|
+
else if (config.username !== undefined && config.password !== undefined) {
|
|
301
|
+
headers.Authorization = `Basic ${encodeBasicAuth(config.username, config.password)}`;
|
|
302
|
+
}
|
|
303
|
+
return headers;
|
|
304
|
+
};
|
|
305
|
+
const parseHttpSqlResponse = (payload, letCount) => {
|
|
306
|
+
if (Array.isArray(payload)) {
|
|
307
|
+
const items = payload;
|
|
308
|
+
for (const item of items) {
|
|
309
|
+
if (item && item.status === "ERR") {
|
|
310
|
+
throw new Error(String(item.result ?? item.detail ?? "SurrealDB query error"));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const effective = letCount > 0 && items.length > letCount ? items.slice(letCount) : items;
|
|
314
|
+
return effective.map((item) => item?.result);
|
|
315
|
+
}
|
|
316
|
+
if (typeof payload === "object" && payload !== null) {
|
|
317
|
+
const obj = payload;
|
|
318
|
+
if (obj.status === "ERR" || obj.code !== undefined) {
|
|
319
|
+
throw new Error(String(obj.description ??
|
|
320
|
+
obj.information ??
|
|
321
|
+
obj.detail ??
|
|
322
|
+
obj.result ??
|
|
323
|
+
"SurrealDB HTTP error"));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
throw new Error("Unexpected SurrealDB HTTP /sql response payload");
|
|
327
|
+
};
|
|
328
|
+
const makeSurrealHttpDirectLayer = (config) => Layer.effect(SurrealClient, Effect.gen(function* () {
|
|
329
|
+
const endpoint = toHttpSqlEndpoint(config.url);
|
|
330
|
+
const headers = buildHttpHeaders(config);
|
|
331
|
+
const maxRetries = config.maxRetries ?? 3;
|
|
332
|
+
const retrySchedule = makeDefaultRetrySchedule();
|
|
333
|
+
const runRawSql = (sql, letCount, operation) => {
|
|
334
|
+
const exec = Effect.tryPromise({
|
|
335
|
+
try: async () => {
|
|
336
|
+
const doFetch = config.fetchImpl ?? globalThis.fetch;
|
|
337
|
+
if (typeof doFetch !== "function") {
|
|
338
|
+
throw new Error("No fetch implementation available for HTTP transport");
|
|
339
|
+
}
|
|
340
|
+
const res = await doFetch(endpoint, {
|
|
341
|
+
method: "POST",
|
|
342
|
+
headers,
|
|
343
|
+
body: sql,
|
|
344
|
+
});
|
|
345
|
+
if (!res.ok) {
|
|
346
|
+
const body = await res.text().catch(() => "");
|
|
347
|
+
const statusMsg = `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ""}`;
|
|
348
|
+
throw new Error(body ? `${statusMsg}: ${body}` : statusMsg);
|
|
349
|
+
}
|
|
350
|
+
const payload = (await res.json());
|
|
351
|
+
return parseHttpSqlResponse(payload, letCount);
|
|
352
|
+
},
|
|
353
|
+
catch: (cause) => new SurrealClientError({ operation, cause }),
|
|
354
|
+
});
|
|
355
|
+
const retried = maxRetries <= 0
|
|
356
|
+
? exec
|
|
357
|
+
: exec.pipe(Effect.retry({
|
|
358
|
+
schedule: retrySchedule,
|
|
359
|
+
times: maxRetries,
|
|
360
|
+
while: isTransientSurrealError,
|
|
361
|
+
}));
|
|
362
|
+
return retried.pipe(Effect.mapError((err) => applyMapError(config.mapError, err)));
|
|
363
|
+
};
|
|
364
|
+
if (config.autoCreate === true) {
|
|
365
|
+
const nsIdent = escapeIdent(config.namespace);
|
|
366
|
+
const dbIdent = escapeIdent(config.database);
|
|
367
|
+
yield* runRawSql(`DEFINE NAMESPACE IF NOT EXISTS ${nsIdent};\nDEFINE DATABASE IF NOT EXISTS ${dbIdent};`, 0, "connect");
|
|
368
|
+
}
|
|
369
|
+
const executeQuery = (surql, vars) => Effect.suspend(() => {
|
|
370
|
+
let formatted;
|
|
371
|
+
try {
|
|
372
|
+
formatted = formatSurqlWithVars(surql, vars);
|
|
373
|
+
}
|
|
374
|
+
catch (cause) {
|
|
375
|
+
return Effect.fail(applyMapError(config.mapError, new SurrealClientError({ operation: "query", cause })));
|
|
376
|
+
}
|
|
377
|
+
return runRawSql(formatted.sql, formatted.letCount, "query");
|
|
378
|
+
});
|
|
379
|
+
const query = (surql, vars) => Effect.flatMap(ActiveHttpTx, (activeTx) => {
|
|
380
|
+
if (activeTx !== undefined) {
|
|
381
|
+
activeTx.statements.push(vars !== undefined ? { surql, vars } : { surql });
|
|
382
|
+
return Effect.succeed([]);
|
|
383
|
+
}
|
|
384
|
+
return executeQuery(surql, vars);
|
|
385
|
+
});
|
|
386
|
+
const queryDirect = (surql, vars) => executeQuery(surql, vars);
|
|
387
|
+
const live = (table) => Stream.fail(applyMapError(config.mapError, new SurrealClientError({
|
|
388
|
+
operation: `live:${table}`,
|
|
389
|
+
cause: new Error(`LIVE SELECT on "${table}" is not supported when transport === "http" (use transport: "ws" for persistent subscriptions)`),
|
|
390
|
+
})));
|
|
391
|
+
const withTransaction = (effect) => Effect.gen(function* () {
|
|
392
|
+
const existingTx = yield* ActiveHttpTx;
|
|
393
|
+
const outerPostCommit = yield* ActiveTxPostCommit;
|
|
394
|
+
if (existingTx !== undefined) {
|
|
395
|
+
return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
396
|
+
const localPostCommit = [];
|
|
397
|
+
const exit = yield* restore(effect.pipe(Effect.provideService(ActiveTxPostCommit, localPostCommit))).pipe(Effect.exit);
|
|
398
|
+
if (Exit.isSuccess(exit)) {
|
|
399
|
+
if (outerPostCommit !== undefined) {
|
|
400
|
+
outerPostCommit.push(...localPostCommit);
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
for (const hook of localPostCommit) {
|
|
404
|
+
yield* hook;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return exit.value;
|
|
408
|
+
}
|
|
409
|
+
existingTx.rollbackOnly = true;
|
|
410
|
+
return yield* Effect.failCause(exit.cause);
|
|
411
|
+
}));
|
|
412
|
+
}
|
|
413
|
+
return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
414
|
+
const txState = {
|
|
415
|
+
statements: [],
|
|
416
|
+
rollbackOnly: false,
|
|
417
|
+
};
|
|
418
|
+
const localPostCommit = [];
|
|
419
|
+
const exit = yield* restore(effect.pipe(Effect.provideService(ActiveHttpTx, txState), Effect.provideService(ActiveTxPostCommit, localPostCommit))).pipe(Effect.exit);
|
|
420
|
+
if (Exit.isSuccess(exit)) {
|
|
421
|
+
if (txState.rollbackOnly) {
|
|
422
|
+
txState.statements.length = 0;
|
|
423
|
+
return yield* applyMapError(config.mapError, new SurrealClientError({
|
|
424
|
+
operation: "commit",
|
|
425
|
+
cause: new Error("Transaction marked rollback-only because a nested transaction failed (SurrealDB does not support savepoints)"),
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
if (txState.statements.length > 0) {
|
|
429
|
+
let batchSql;
|
|
430
|
+
try {
|
|
431
|
+
batchSql = buildSurrealHttpTransactionSql(txState.statements);
|
|
432
|
+
}
|
|
433
|
+
catch (cause) {
|
|
434
|
+
return yield* applyMapError(config.mapError, new SurrealClientError({ operation: "commit", cause }));
|
|
435
|
+
}
|
|
436
|
+
yield* runRawSql(batchSql, 0, "commit");
|
|
437
|
+
}
|
|
438
|
+
if (outerPostCommit !== undefined) {
|
|
439
|
+
outerPostCommit.push(...localPostCommit);
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
for (const hook of localPostCommit) {
|
|
443
|
+
yield* hook;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return exit.value;
|
|
447
|
+
}
|
|
448
|
+
// Rollback: discard buffered statements without sending any HTTP request
|
|
449
|
+
txState.statements.length = 0;
|
|
450
|
+
return yield* Effect.failCause(exit.cause);
|
|
451
|
+
}));
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
query,
|
|
455
|
+
queryDirect,
|
|
456
|
+
...(config.skipBootstrapDdl !== undefined
|
|
457
|
+
? { skipBootstrapDdl: config.skipBootstrapDdl }
|
|
458
|
+
: {}),
|
|
459
|
+
live,
|
|
460
|
+
withTransaction,
|
|
461
|
+
};
|
|
462
|
+
}));
|
|
463
|
+
const makeSurrealWsLayer = (config) => Layer.effect(SurrealClient, Effect.gen(function* () {
|
|
464
|
+
const db = yield* Effect.acquireRelease(Effect.tryPromise({
|
|
465
|
+
try: () => connectSurrealInstance(config, config.url, true),
|
|
466
|
+
catch: (cause) => applyMapError(config.mapError, new SurrealClientError({ operation: "connect", cause })),
|
|
467
|
+
}), (client) => Effect.tryPromise(() => client.close()).pipe(Effect.ignore));
|
|
468
|
+
const maxRetries = config.maxRetries ?? 3;
|
|
469
|
+
const retrySchedule = makeDefaultRetrySchedule();
|
|
470
|
+
const runOnTarget = (target, surql, vars, allowRetry) => {
|
|
471
|
+
const exec = Effect.tryPromise({
|
|
472
|
+
try: () => target.query(surql, vars).collect(),
|
|
473
|
+
catch: (cause) => new SurrealClientError({ operation: "query", cause }),
|
|
474
|
+
});
|
|
475
|
+
const retried = !allowRetry || maxRetries <= 0
|
|
476
|
+
? exec
|
|
477
|
+
: exec.pipe(Effect.retry({
|
|
478
|
+
schedule: retrySchedule,
|
|
479
|
+
times: maxRetries,
|
|
480
|
+
while: isTransientSurrealError,
|
|
481
|
+
}));
|
|
482
|
+
return retried.pipe(Effect.mapError((err) => applyMapError(config.mapError, err)));
|
|
483
|
+
};
|
|
484
|
+
const query = (surql, vars) => Effect.flatMap(ActiveSurrealTx, (activeTx) => runOnTarget(activeTx?.tx ?? db, surql, vars, activeTx === undefined));
|
|
485
|
+
const queryDirect = (surql, vars) => runOnTarget(db, surql, vars, true);
|
|
486
|
+
const live = (table) => Stream.unwrap(acquireLiveQueue(db, table, (msg, offer) => {
|
|
487
|
+
offer({
|
|
488
|
+
action: msg.action,
|
|
489
|
+
recordId: msg.recordId,
|
|
490
|
+
value: msg.value,
|
|
491
|
+
});
|
|
492
|
+
}).pipe(Effect.mapError((err) => applyMapError(config.mapError, err)), Effect.map(Stream.fromQueue)));
|
|
493
|
+
const withTransaction = (effect) => runNestedOrRootTransaction(() => Effect.tryPromise({
|
|
494
|
+
try: () => db.beginTransaction(),
|
|
495
|
+
catch: (cause) => new SurrealClientError({ operation: "beginTransaction", cause }),
|
|
496
|
+
}).pipe(Effect.map((tx) => ({
|
|
497
|
+
tx,
|
|
498
|
+
commit: () => Effect.tryPromise({
|
|
499
|
+
try: () => tx.commit(),
|
|
500
|
+
catch: (cause) => new SurrealClientError({ operation: "commit", cause }),
|
|
501
|
+
}),
|
|
502
|
+
cancel: () => Effect.tryPromise(() => tx.cancel()).pipe(Effect.ignore),
|
|
503
|
+
}))), effect, config.mapError);
|
|
504
|
+
return {
|
|
505
|
+
raw: db,
|
|
506
|
+
query,
|
|
507
|
+
queryDirect,
|
|
508
|
+
...(config.skipBootstrapDdl !== undefined
|
|
509
|
+
? { skipBootstrapDdl: config.skipBootstrapDdl }
|
|
510
|
+
: {}),
|
|
511
|
+
live,
|
|
512
|
+
withTransaction,
|
|
513
|
+
};
|
|
514
|
+
}));
|
|
515
|
+
export const SurrealClientLive = (config) => config.transport === "http"
|
|
516
|
+
? makeSurrealHttpDirectLayer(config)
|
|
517
|
+
: makeSurrealWsLayer(config);
|
|
518
|
+
/**
|
|
519
|
+
* Stateless, request-safe HTTP `SurrealClient` layer designed for Cloudflare
|
|
520
|
+
* Workers and other short-lived serverless isolates.
|
|
521
|
+
*
|
|
522
|
+
* - Normalizes `ws://`/`wss://` URLs to `http://`/`https://` so `surrealdb`
|
|
523
|
+
* uses its stateless `HttpEngine` (`fetch` per query, full CBOR fidelity for
|
|
524
|
+
* `RecordId`/`DateTime`, zero persistent WebSocket held across requests).
|
|
525
|
+
* - Defaults `autoCreate` to `false` (serverless databases are pre-provisioned).
|
|
526
|
+
* - In `transactionMode: "scoped-ws"` (default), `withTransaction(...)` opens
|
|
527
|
+
* an ephemeral WebSocket strictly for the duration of that call and closes it
|
|
528
|
+
* before returning.
|
|
529
|
+
* - `live(...)` fails deterministically with `SurrealClientError` (use push
|
|
530
|
+
* queues / Durable Objects / webhooks instead of `LIVE SELECT` in Workers).
|
|
531
|
+
*/
|
|
532
|
+
export const SurrealClientHttpLive = (config) => Layer.effect(SurrealClient, Effect.gen(function* () {
|
|
533
|
+
const httpUrl = normalizeHttpUrl(config.url);
|
|
534
|
+
const wsUrl = config.wsUrl ?? normalizeWsUrl(config.url);
|
|
535
|
+
const transactionMode = config.transactionMode ?? "scoped-ws";
|
|
536
|
+
const db = yield* Effect.acquireRelease(Effect.tryPromise({
|
|
537
|
+
try: () => connectSurrealInstance(config, httpUrl, false),
|
|
538
|
+
catch: (cause) => applyMapError(config.mapError, new SurrealClientError({ operation: "connect", cause })),
|
|
539
|
+
}), (client) => Effect.tryPromise(() => client.close()).pipe(Effect.ignore));
|
|
540
|
+
const maxRetries = config.maxRetries ?? 3;
|
|
541
|
+
const retrySchedule = makeDefaultRetrySchedule();
|
|
542
|
+
const runOnTarget = (target, surql, vars, allowRetry) => {
|
|
543
|
+
const exec = Effect.tryPromise({
|
|
544
|
+
try: () => target.query(surql, vars).collect(),
|
|
545
|
+
catch: (cause) => new SurrealClientError({ operation: "query", cause }),
|
|
546
|
+
});
|
|
547
|
+
const retried = !allowRetry || maxRetries <= 0
|
|
548
|
+
? exec
|
|
549
|
+
: exec.pipe(Effect.retry({
|
|
550
|
+
schedule: retrySchedule,
|
|
551
|
+
times: maxRetries,
|
|
552
|
+
while: isTransientSurrealError,
|
|
553
|
+
}));
|
|
554
|
+
return retried.pipe(Effect.mapError((err) => applyMapError(config.mapError, err)));
|
|
555
|
+
};
|
|
556
|
+
const query = (surql, vars) => Effect.flatMap(ActiveSurrealTx, (activeTx) => runOnTarget(activeTx?.tx ?? db, surql, vars, activeTx === undefined));
|
|
557
|
+
const queryDirect = (surql, vars) => runOnTarget(db, surql, vars, true);
|
|
558
|
+
const live = (table) => Stream.fail(applyMapError(config.mapError, new SurrealClientError({
|
|
559
|
+
operation: `live:${table}`,
|
|
560
|
+
cause: new Error(`LIVE SELECT on "${table}" is not supported on SurrealClientHttpLive (use a persistent WebSocket SurrealClientLive or push messaging)`),
|
|
561
|
+
})));
|
|
562
|
+
const withTransaction = (effect) => {
|
|
563
|
+
if (transactionMode === "error") {
|
|
564
|
+
return Effect.fail(applyMapError(config.mapError, new SurrealClientError({
|
|
565
|
+
operation: "beginTransaction",
|
|
566
|
+
cause: new Error('Interactive transactions are disabled on SurrealClientHttpLive (transactionMode: "error")'),
|
|
567
|
+
})));
|
|
568
|
+
}
|
|
569
|
+
return runNestedOrRootTransaction(() => Effect.tryPromise({
|
|
570
|
+
try: async () => {
|
|
571
|
+
const scopedClient = await connectSurrealInstance({ ...config, autoCreate: false }, wsUrl, false);
|
|
572
|
+
try {
|
|
573
|
+
const tx = await scopedClient.beginTransaction();
|
|
574
|
+
return { scopedClient, tx };
|
|
575
|
+
}
|
|
576
|
+
catch (err) {
|
|
577
|
+
await scopedClient.close().catch(() => undefined);
|
|
578
|
+
throw err;
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
catch: (cause) => new SurrealClientError({ operation: "beginTransaction", cause }),
|
|
582
|
+
}).pipe(Effect.map(({ scopedClient, tx }) => ({
|
|
583
|
+
tx,
|
|
584
|
+
commit: () => Effect.tryPromise({
|
|
585
|
+
try: () => tx.commit(),
|
|
586
|
+
catch: (cause) => new SurrealClientError({ operation: "commit", cause }),
|
|
587
|
+
}),
|
|
588
|
+
cancel: () => Effect.tryPromise(() => tx.cancel()).pipe(Effect.ignore),
|
|
589
|
+
cleanup: () => Effect.tryPromise(() => scopedClient.close()).pipe(Effect.ignore),
|
|
590
|
+
}))), effect, config.mapError);
|
|
591
|
+
};
|
|
592
|
+
return {
|
|
593
|
+
query,
|
|
594
|
+
queryDirect,
|
|
595
|
+
...(config.skipBootstrapDdl !== undefined
|
|
596
|
+
? { skipBootstrapDdl: config.skipBootstrapDdl }
|
|
597
|
+
: {}),
|
|
598
|
+
live,
|
|
599
|
+
withTransaction,
|
|
600
|
+
};
|
|
601
|
+
}));
|
|
602
|
+
/**
|
|
603
|
+
* Builds a transport-agnostic `SurrealClient` layer from any custom query
|
|
604
|
+
* executor (e.g. a multi-tenant Cloudflare Worker RPC Service Binding such as
|
|
605
|
+
* `CHIMP_DATA`, an HTTP gateway, or an in-process proxy).
|
|
606
|
+
*
|
|
607
|
+
* Every stateless Keel store (`RelationalSurrealLive`, `DocumentSurrealLive`,
|
|
608
|
+
* `KvSurrealLive`, `CoordinationSurrealLive`, `FeatureFlagsSurrealLive`,
|
|
609
|
+
* `SearchSurrealLive`, and SurrealDB migrations) runs unchanged on top of this
|
|
610
|
+
* layer without needing a `surrealdb` WebSocket or `client.raw`.
|
|
611
|
+
*/
|
|
612
|
+
export const SurrealClientTransportLive = (transport) => {
|
|
613
|
+
const maxRetries = transport.maxRetries ?? 3;
|
|
614
|
+
const retrySchedule = makeDefaultRetrySchedule();
|
|
615
|
+
const wrapQuery = (eff) => {
|
|
616
|
+
const retried = maxRetries <= 0
|
|
617
|
+
? eff
|
|
618
|
+
: eff.pipe(Effect.retry({
|
|
619
|
+
schedule: retrySchedule,
|
|
620
|
+
times: maxRetries,
|
|
621
|
+
while: isTransientSurrealError,
|
|
622
|
+
}));
|
|
623
|
+
return retried.pipe(Effect.mapError((err) => applyMapError(transport.mapError, err)));
|
|
624
|
+
};
|
|
625
|
+
return Layer.succeed(SurrealClient, {
|
|
626
|
+
query: (surql, vars) => wrapQuery(transport.query(surql, vars)),
|
|
627
|
+
queryDirect: (surql, vars) => wrapQuery((transport.queryDirect ?? transport.query)(surql, vars)),
|
|
628
|
+
...(transport.skipBootstrapDdl !== undefined
|
|
629
|
+
? { skipBootstrapDdl: transport.skipBootstrapDdl }
|
|
630
|
+
: {}),
|
|
631
|
+
live: (table) => transport.live
|
|
632
|
+
? transport.live(table).pipe(Stream.mapError((err) => applyMapError(transport.mapError, err)))
|
|
633
|
+
: Stream.fail(applyMapError(transport.mapError, new SurrealClientError({
|
|
634
|
+
operation: `live:${table}`,
|
|
635
|
+
cause: new Error(`LIVE SELECT on "${table}" is not supported by this SurrealClientTransport`),
|
|
636
|
+
}))),
|
|
637
|
+
withTransaction: (effect) => transport.withTransaction
|
|
638
|
+
? transport.withTransaction(effect).pipe(Effect.mapError((err) => err instanceof SurrealClientError
|
|
639
|
+
? applyMapError(transport.mapError, err)
|
|
640
|
+
: err))
|
|
641
|
+
: Effect.fail(applyMapError(transport.mapError, new SurrealClientError({
|
|
642
|
+
operation: "beginTransaction",
|
|
643
|
+
cause: new Error("Interactive transactions are not supported by this SurrealClientTransport"),
|
|
644
|
+
}))),
|
|
645
|
+
});
|
|
646
|
+
};
|
|
647
|
+
/**
|
|
648
|
+
* Effect `Config` reading SurrealDB settings from the active `ConfigProvider`
|
|
649
|
+
* (defaults to `SURREAL_*` env vars). Keeps `password` and `token` wrapped in
|
|
650
|
+
* `Redacted<string>` so credentials never leak in logs or error output.
|
|
651
|
+
*/
|
|
652
|
+
export const surrealConfigFromEnv = (prefix = "SURREAL_") => Config.all({
|
|
653
|
+
url: Config.NonEmptyString(`${prefix}URL`),
|
|
654
|
+
namespace: Config.NonEmptyString(`${prefix}NAMESPACE`),
|
|
655
|
+
database: Config.NonEmptyString(`${prefix}DATABASE`),
|
|
656
|
+
username: Config.option(Config.NonEmptyString(`${prefix}USERNAME`)),
|
|
657
|
+
password: Config.option(Config.Redacted(`${prefix}PASSWORD`)),
|
|
658
|
+
token: Config.option(Config.Redacted(`${prefix}TOKEN`)),
|
|
659
|
+
transport: Config.Literals(["ws", "http"], `${prefix}TRANSPORT`).pipe(Config.withDefault("ws")),
|
|
660
|
+
autoCreate: Config.option(Config.Boolean(`${prefix}AUTO_CREATE`)),
|
|
661
|
+
maxRetries: Config.Int(`${prefix}MAX_RETRIES`).pipe(Config.withDefault(3)),
|
|
662
|
+
}).pipe(Config.map((raw) => ({
|
|
663
|
+
url: raw.url,
|
|
664
|
+
namespace: raw.namespace,
|
|
665
|
+
database: raw.database,
|
|
666
|
+
username: raw.username,
|
|
667
|
+
password: raw.password,
|
|
668
|
+
token: raw.token,
|
|
669
|
+
transport: raw.transport,
|
|
670
|
+
autoCreate: Option.getOrElse(raw.autoCreate, () => raw.transport !== "http"),
|
|
671
|
+
maxRetries: raw.maxRetries,
|
|
672
|
+
})));
|
|
673
|
+
export const toPlainSurrealClientConfig = (cfg) => ({
|
|
674
|
+
url: cfg.url,
|
|
675
|
+
namespace: cfg.namespace,
|
|
676
|
+
database: cfg.database,
|
|
677
|
+
...(Option.isSome(cfg.username) ? { username: cfg.username.value } : {}),
|
|
678
|
+
...(Option.isSome(cfg.password)
|
|
679
|
+
? { password: Redacted.value(cfg.password.value) }
|
|
680
|
+
: {}),
|
|
681
|
+
...(Option.isSome(cfg.token)
|
|
682
|
+
? { token: Redacted.value(cfg.token.value) }
|
|
683
|
+
: {}),
|
|
684
|
+
transport: cfg.transport,
|
|
685
|
+
autoCreate: cfg.autoCreate,
|
|
686
|
+
maxRetries: cfg.maxRetries,
|
|
687
|
+
});
|
|
688
|
+
/**
|
|
689
|
+
* Builds a `SurrealClient` layer from Effect's active `ConfigProvider`.
|
|
690
|
+
*/
|
|
691
|
+
export const makeSurrealClientConfigLive = (options) => Layer.unwrap(Effect.gen(function* () {
|
|
692
|
+
const cfg = yield* surrealConfigFromEnv(options?.prefix ?? "SURREAL_");
|
|
693
|
+
return SurrealClientLive(toPlainSurrealClientConfig(cfg));
|
|
694
|
+
}));
|
|
695
|
+
/**
|
|
696
|
+
* Zero-config `SurrealClient` layer driven by `SURREAL_*` config keys.
|
|
697
|
+
*/
|
|
698
|
+
export const SurrealClientConfigLive = makeSurrealClientConfigLive();
|
|
699
|
+
/**
|
|
700
|
+
* Builds a stateless HTTP `SurrealClient` layer from Effect's active `ConfigProvider`
|
|
701
|
+
* (defaults to `SURREAL_*` keys, with `autoCreate: false` unless explicitly set).
|
|
702
|
+
*/
|
|
703
|
+
export const makeSurrealClientHttpConfigLive = (options) => Layer.unwrap(Effect.gen(function* () {
|
|
704
|
+
const cfg = yield* surrealConfigFromEnv(options?.prefix ?? "SURREAL_");
|
|
705
|
+
return SurrealClientHttpLive({
|
|
706
|
+
...toPlainSurrealClientConfig(cfg),
|
|
707
|
+
...(options?.transactionMode !== undefined
|
|
708
|
+
? { transactionMode: options.transactionMode }
|
|
709
|
+
: {}),
|
|
710
|
+
...(options?.skipBootstrapDdl !== undefined
|
|
711
|
+
? { skipBootstrapDdl: options.skipBootstrapDdl }
|
|
712
|
+
: {}),
|
|
713
|
+
...(options?.fetchImpl !== undefined
|
|
714
|
+
? { fetchImpl: options.fetchImpl }
|
|
715
|
+
: {}),
|
|
716
|
+
...(options?.mapError !== undefined
|
|
717
|
+
? { mapError: options.mapError }
|
|
718
|
+
: {}),
|
|
719
|
+
});
|
|
720
|
+
}));
|
|
721
|
+
/**
|
|
722
|
+
* Zero-config stateless HTTP `SurrealClient` layer driven by `SURREAL_*` config keys.
|
|
723
|
+
*/
|
|
724
|
+
export const SurrealClientHttpConfigLive = makeSurrealClientHttpConfigLive();
|
|
725
|
+
//# sourceMappingURL=client.js.map
|