@reddb-io/client 1.29.3 → 1.30.1

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.
@@ -26,6 +26,8 @@ export type AuthOptions =
26
26
  | { username: string; password: string; loginUrl?: string }
27
27
 
28
28
  export interface ConnectOptions {
29
+ /** Optional WebSocket constructor override. */
30
+ WebSocketImpl?: typeof globalThis.WebSocket
29
31
  /** Authentication credentials for the HTTP transport. */
30
32
  auth?: AuthOptions
31
33
  }
@@ -376,7 +378,12 @@ export interface RedDBTransaction {
376
378
  ): Promise<T>
377
379
  }
378
380
 
381
+ export type ReadOptions = { consistency: 'strong' | 'local' }
382
+ | { consistency: 'bounded_staleness'; maxLagMs: number }
383
+
379
384
  export class RedDB {
385
+ queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
386
+ queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
380
387
  readonly cache: CacheClient
381
388
  readonly queue: QueueClient
382
389
  readonly documents: DocumentClient
package/index.d.ts CHANGED
@@ -19,6 +19,8 @@ export interface TlsOptions {
19
19
  }
20
20
 
21
21
  export interface ConnectOptions {
22
+ /** WebSocket constructor for runtimes without a global WebSocket. */
23
+ WebSocketImpl?: new (url: string, protocols?: string | string[]) => object
22
24
  /** Authentication credentials for remote transports. */
23
25
  auth?: AuthOptions
24
26
  /** TLS options for `reds://` / `grpcs://` connections. */
@@ -372,7 +374,12 @@ export interface RedDBTransaction {
372
374
  ): Promise<T>
373
375
  }
374
376
 
377
+ export type ReadOptions = { consistency: 'strong' | 'local' }
378
+ | { consistency: 'bounded_staleness'; maxLagMs: number }
379
+
375
380
  export class RedDB {
381
+ queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
382
+ queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
376
383
  readonly cache: CacheClient
377
384
  readonly queue: QueueClient
378
385
  readonly documents: DocumentClient
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/client",
3
- "version": "1.29.3",
3
+ "version": "1.30.1",
4
4
  "description": "Thin remote-only RedDB driver. Pure JavaScript — no install scripts, no native binary. Speaks RedWire/gRPC/HTTP. Embedded URIs (memory://, file://, red:///path) are rejected — use @reddb-io/sdk for those.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -44,6 +44,14 @@
44
44
  "types": "./index.d.ts",
45
45
  "import": "./src/index.js"
46
46
  },
47
+ "./routing": {
48
+ "types": "./routing.d.ts",
49
+ "import": "./src/core/routing.js"
50
+ },
51
+ "./topology": {
52
+ "types": "./topology.d.ts",
53
+ "import": "./src/core/topology.js"
54
+ },
47
55
  "./package.json": "./package.json"
48
56
  },
49
57
  "types": "./index.d.ts",
@@ -52,7 +60,9 @@
52
60
  "index.d.ts",
53
61
  "index.browser.d.ts",
54
62
  "README.md",
55
- "LICENSE"
63
+ "LICENSE",
64
+ "routing.d.ts",
65
+ "topology.d.ts"
56
66
  ],
57
67
  "engines": {
58
68
  "node": ">=18"
package/routing.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /** Shared connection lifecycle for runtime-specific transports. */
2
+ export interface RoutingTransport {
3
+ binaryQueryParams?: boolean
4
+ call(method: string, params?: Record<string, unknown>): Promise<any>
5
+ close(): Promise<void> | void
6
+ }
7
+ export interface RoutingReadOptions {
8
+ consistency: 'strong' | 'local' | 'bounded_staleness'
9
+ maxLagMs?: number
10
+ }
11
+ export class RoutingClient implements RoutingTransport {
12
+ constructor(seed: string, client: RoutingTransport,
13
+ dial: (address: string, signal: AbortSignal) => Promise<RoutingTransport>,
14
+ protocol: string, options?: { forcePrimary?: boolean; now?: () => number })
15
+ binaryQueryParams: boolean
16
+ initialize(): Promise<this>
17
+ call(method: string, params?: Record<string, unknown>): Promise<any>
18
+ queryWithOptions(sql: string, options: RoutingReadOptions, params?: unknown[]): Promise<any>
19
+ close(): Promise<void>
20
+ }
package/src/core/reddb.js CHANGED
@@ -134,6 +134,15 @@ export class RedDB {
134
134
  return this.query(sql, ...params)
135
135
  }
136
136
 
137
+ /** Explicit read routing. Generic query/execute always use the primary. */
138
+ queryWithOptions(sql, options, ...params) {
139
+ if (typeof this.client.queryWithOptions !== 'function') {
140
+ throw new RedDBError('CONSISTENCY_UNSUPPORTED', 'this transport does not support explicit read consistency')
141
+ }
142
+ const wireParams = normalizeQueryParams(params, this.client.binaryQueryParams === true)
143
+ return this.client.queryWithOptions(sql, options, wireParams).then(normalizeExactNumbers)
144
+ }
145
+
137
146
  /** Insert one row. Returns `{ affected, rid, id }`; `id` is a legacy alias for `rid`. */
138
147
  async insert(collection, payload) {
139
148
  let result = await this.client.call('insert', { collection, payload: serializeJsonValue(payload) })
@@ -0,0 +1,374 @@
1
+ import { RedDBError } from './errors.js'
2
+ import { isReplicaQuery, isSessionQuery, topologyAddress, transactionCommand } from './topology.js'
3
+ import { parseUri } from './url.js'
4
+ import { mergeAuthFromUri } from './auth.js'
5
+
6
+ export async function connectRouted(uri, options, connectDirect) {
7
+ const db = await connectDirect(uri, options)
8
+ const parsed = parseUri(uri)
9
+ let protocol = { redws: 'ws', redwss: 'wss' }[parsed.kind] ?? parsed.kind
10
+ if (protocol === 'red' && (options.tls || ['true', '1'].includes(parsed.params?.get('tls')))) protocol = 'reds'
11
+ const seed = topologyAddress(`${protocol}://${parsed.host}:${parsed.port}${parsed.path ?? ''}`, protocol)
12
+ const auth = mergeAuthFromUri(parsed, options.auth)
13
+ const dial = async (address, signal) => {
14
+ const target = new URL(address)
15
+ target.search = parsed.params?.toString() ?? ''
16
+ return (await connectDirect(target.href, { ...options, auth, signal }, true)).client
17
+ }
18
+ const router = new RoutingClient(seed, db.client, dial, protocol, {
19
+ forcePrimary: parsed.params?.get('route') === 'primary',
20
+ })
21
+ try {
22
+ db.client = await router.initialize()
23
+ // Helper clients retain the low-level transport supplied at construction.
24
+ // Build a fresh facade so every helper shares the routing lifecycle.
25
+ return new db.constructor(db.client)
26
+ } catch (error) {
27
+ await router.close().catch(() => {})
28
+ throw error
29
+ }
30
+ }
31
+
32
+ const READ_METHODS = new Set(['get', 'cache.get', 'cache.exists'])
33
+ const connectionError = (error) => /^(?:NETWORK|IO|CLOSED|CONNECTION_CLOSED|WS_TRANSPORT|GRPC_14|HTTP_503|ECONN|EPIPE|ETIMEDOUT|ERR_HTTP2)/.test(error?.code ?? '')
34
+ || error instanceof TypeError && /fetch failed|network/i.test(error.message)
35
+
36
+ /** Same routing lifecycle for TCP/TLS, HTTP(S), gRPC(S), and WS(S).
37
+ * Refresh runs before the next operation after 30 seconds or an I/O error.
38
+ * Writes are never replayed, including after a primary change.
39
+ */
40
+ export class RoutingClient {
41
+ constructor(seed, client, dial, protocol, { forcePrimary = false, now = Date.now } = {}) {
42
+ this.seed = seed
43
+ this.primary = seed
44
+ this.protocol = protocol
45
+ this.dial = dial
46
+ this.clients = new Map([[seed, Promise.resolve(client)]])
47
+ this.active = new Map()
48
+ this.queues = new Map()
49
+ this.streams = new Set()
50
+ this.replicas = []
51
+ this.replicaLagMs = new Map()
52
+ this.nextReplica = 0
53
+ this.refreshAt = 0
54
+ this.now = now
55
+ this.forcePrimary = forcePrimary
56
+ this.transactionEndpoint = null
57
+ this.sessionEndpoint = null
58
+ this.sessionError = null
59
+ this.refreshing = null
60
+ this.closed = false
61
+ this.binaryQueryParams = client.binaryQueryParams === true
62
+ }
63
+
64
+ async initialize() {
65
+ await this.refresh()
66
+ return this
67
+ }
68
+
69
+ async endpoint(address) {
70
+ if (this.closed) throw new RedDBError('CLOSED', 'connection is closed')
71
+ if (!this.clients.has(address)) {
72
+ const pending = this.connectEndpoint(address).catch((error) => {
73
+ this.clients.delete(address)
74
+ throw error
75
+ })
76
+ this.clients.set(address, pending)
77
+ }
78
+ return this.clients.get(address)
79
+ }
80
+
81
+ async connectEndpoint(address) {
82
+ const controller = new AbortController()
83
+ let client
84
+ let ready = false
85
+ let timer
86
+ const connect = this.dial(address, controller.signal).then(async (transport) => {
87
+ client = transport
88
+ if (controller.signal.aborted || this.closed) {
89
+ await client.close()
90
+ throw new RedDBError('CLOSED', 'connection was closed while connecting')
91
+ }
92
+ if (['http', 'https', 'grpc', 'grpcs'].includes(this.protocol)) {
93
+ await client.call('health', { signal: controller.signal })
94
+ }
95
+ return client
96
+ })
97
+ try {
98
+ const endpoint = await Promise.race([connect, new Promise((_, reject) => {
99
+ timer = setTimeout(() => {
100
+ controller.abort()
101
+ reject(new RedDBError('ETIMEDOUT', 'endpoint connection timed out'))
102
+ }, 5000)
103
+ })])
104
+ ready = true
105
+ return endpoint
106
+ } finally {
107
+ clearTimeout(timer)
108
+ if (!ready) { controller.abort(); await client?.close() }
109
+ }
110
+ }
111
+
112
+ async refresh() {
113
+ if (this.transactionEndpoint || this.sessionEndpoint || this.closed) return
114
+ if (this.refreshing) return this.refreshing
115
+ this.refreshing = this.refreshMembership().finally(() => { this.refreshing = null })
116
+ return this.refreshing
117
+ }
118
+
119
+ async refreshMembership() {
120
+ this.refreshAt = this.now() + 30_000
121
+ const candidates = [...new Set([this.primary, this.seed, ...this.replicas])]
122
+ for (let index = 0; index < Math.min(candidates.length, 258); index++) {
123
+ const address = candidates[index]
124
+ try {
125
+ const topology = await this.discover(address)
126
+ if (!topology || topology.version !== 1) continue
127
+ const primary = topologyAddress(topology.primary?.addr, this.protocol)
128
+ if (!primary) continue
129
+ // A replica bootstrap tells us where the primary is. Ask that primary
130
+ // for its full authenticated advertisement in the same refresh.
131
+ if (primary !== address && !candidates.includes(primary)) candidates.push(primary)
132
+ await this.endpoint(primary)
133
+ const replicaCandidates = (Array.isArray(topology.replicas) ? topology.replicas.slice(0, 256) : [])
134
+ .filter((replica) => replica.healthy === true && replica.rebootstrapping !== true)
135
+ .map((replica) => ({ ...replica, addr: topologyAddress(replica.addr, this.protocol) }))
136
+ .filter((replica) => replica.addr && replica.addr !== primary)
137
+ const ready = await Promise.allSettled(replicaCandidates.map(async (replica) => {
138
+ await this.endpoint(replica.addr)
139
+ return replica
140
+ }))
141
+ const replicas = ready.filter((result) => result.status === 'fulfilled').map((result) => result.value)
142
+ const replicaLagMs = new Map(replicas.map((replica) => [replica.addr, replica.lag_ms]))
143
+ this.primary = primary
144
+ this.replicaLagMs = replicaLagMs
145
+ this.replicas = replicas.map((replica) => replica.addr)
146
+ if (primary === address) {
147
+ await this.prune()
148
+ return
149
+ }
150
+ } catch (error) {
151
+ // Old servers have no discovery RPC. Keep the seed usable; the next
152
+ // refresh also probes known replicas if the writer is unavailable.
153
+ if (error?.code === 'HTTP_401' || error?.code === 'GRPC_16') throw error
154
+ }
155
+ }
156
+ }
157
+
158
+ async discover(address) {
159
+ const controller = new AbortController()
160
+ let client
161
+ let finished = false
162
+ let timer
163
+ const request = this.dial(address, controller.signal).then(async (transport) => {
164
+ client = transport
165
+ if (finished) { await client.close(); return null }
166
+ return client.call('topology', { transport: this.protocol, signal: controller.signal })
167
+ })
168
+ try {
169
+ return await Promise.race([request, new Promise((_, reject) => {
170
+ timer = setTimeout(() => {
171
+ controller.abort()
172
+ reject(new RedDBError('ETIMEDOUT', 'topology refresh timed out'))
173
+ }, 5000)
174
+ })])
175
+ } finally {
176
+ finished = true
177
+ clearTimeout(timer)
178
+ controller.abort()
179
+ await client?.close()
180
+ }
181
+ }
182
+
183
+ async prune() {
184
+ for (const [address, pending] of this.clients) {
185
+ if (address === this.seed || address === this.primary || this.replicas.includes(address)
186
+ || this.active.get(address)) continue
187
+ this.clients.delete(address)
188
+ this.queues.delete(address)
189
+ this.active.delete(address)
190
+ await pending.then((client) => client.close()).catch(() => {})
191
+ }
192
+ }
193
+
194
+ async invoke(address, method, params) {
195
+ this.active.set(address, (this.active.get(address) ?? 0) + 1)
196
+ try {
197
+ const client = await this.endpoint(address)
198
+ if (!client.binaryQueryParams) return await client.call(method, params)
199
+ const previous = this.queues.get(address) ?? Promise.resolve()
200
+ const result = previous.then(() => {
201
+ if (this.sessionError) throw this.sessionError
202
+ return client.call(method, params)
203
+ })
204
+ this.queues.set(address, result.catch(() => {}))
205
+ return await result
206
+ } finally {
207
+ this.active.set(address, this.active.get(address) - 1)
208
+ }
209
+ }
210
+
211
+ queryWithOptions(sql, options, params) {
212
+ return this.call('query', { sql, params, readOptions: options ?? { consistency: 'strong' } })
213
+ }
214
+
215
+ async call(method, params = {}) {
216
+ if (this.closed) throw new RedDBError('CLOSED', 'connection is closed')
217
+ if (this.sessionError) throw this.sessionError
218
+ if (!this.transactionEndpoint && !this.sessionEndpoint && this.now() >= this.refreshAt) await this.refresh()
219
+ const command = method === 'query' ? transactionCommand(params.sql ?? '') : null
220
+ const options = params.readOptions
221
+ if (options != null && (typeof options !== 'object' || !['strong', 'local', 'bounded_staleness'].includes(options.consistency)
222
+ || options.consistency === 'bounded_staleness'
223
+ && (!Number.isFinite(options.maxLagMs) || options.maxLagMs < 0))) {
224
+ throw new RedDBError('CONSISTENCY_UNSUPPORTED', 'unsupported read consistency')
225
+ }
226
+ const read = READ_METHODS.has(method) || method === 'query' && options != null && isReplicaQuery(params.sql)
227
+ const replicas = options?.consistency === 'strong' ? []
228
+ : options?.consistency === 'bounded_staleness'
229
+ ? this.replicas.filter((replica) => this.replicaLagMs.get(replica) <= options.maxLagMs)
230
+ : this.replicas
231
+ const address = this.transactionEndpoint ?? this.sessionEndpoint ?? (
232
+ read && !this.forcePrimary && replicas.length
233
+ ? replicas[this.nextReplica++ % replicas.length] : this.primary
234
+ )
235
+ if (command === 'BEGIN' || command === 'START TRANSACTION') this.transactionEndpoint = address
236
+ if (method === 'query' && isSessionQuery(params.sql)) this.sessionEndpoint = address
237
+ try {
238
+ const result = await this.invoke(address, method, params)
239
+ if (command === 'COMMIT' || command === 'ROLLBACK') this.transactionEndpoint = null
240
+ return result
241
+ } catch (error) {
242
+ if (!connectionError(error)) throw error
243
+ this.refreshAt = 0
244
+ if (this.transactionEndpoint || this.sessionEndpoint) throw error
245
+ // Only proven reads can be retried. A write may already be committed.
246
+ if (!this.active.get(address)) {
247
+ const failed = this.clients.get(address)
248
+ this.clients.delete(address)
249
+ this.queues.delete(address)
250
+ await failed?.then((client) => client.close()).catch(() => {})
251
+ }
252
+ if (!read) throw error
253
+ this.replicas = this.replicas.filter((replica) => replica !== address)
254
+ await this.refresh()
255
+ return this.invoke(this.primary, method, params)
256
+ }
257
+ }
258
+
259
+ async streamSelect(options) {
260
+ const { session, finish } = await this.openStream('streamSelect', options)
261
+ return {
262
+ async *[Symbol.asyncIterator]() {
263
+ let completed = false
264
+ try {
265
+ for await (const frame of session) {
266
+ // The public Node/Web wrappers stop consuming at the terminal
267
+ // frame; release before yielding rather than waiting for next().
268
+ if (frame.type === 'end') { completed = true; await finish() }
269
+ yield frame
270
+ if (frame.type === 'end') return
271
+ }
272
+ completed = true
273
+ }
274
+ catch (error) { await finish(error); throw error }
275
+ finally { await finish(undefined, !completed) }
276
+ },
277
+ async cancel(reason) {
278
+ try { return await session.cancel(reason) }
279
+ catch (error) { await finish(error); throw error }
280
+ finally { await finish(undefined, true) }
281
+ },
282
+ }
283
+ }
284
+
285
+ async streamInput(options) {
286
+ const { session, finish } = await this.openStream('streamInput', options)
287
+ return {
288
+ async write(row) {
289
+ try { return await session.write(row) }
290
+ catch (error) { await finish(error); throw error }
291
+ },
292
+ async close() {
293
+ try { return await session.close() }
294
+ catch (error) { await finish(error); throw error }
295
+ finally { await finish() }
296
+ },
297
+ async cancel(reason) {
298
+ try { return await session.cancel(reason) }
299
+ catch (error) { await finish(error); throw error }
300
+ finally { await finish(undefined, true) }
301
+ },
302
+ }
303
+ }
304
+
305
+ async openStream(method, options) {
306
+ if (this.closed) throw new RedDBError('CLOSED', 'connection is closed')
307
+ if (this.sessionError) throw this.sessionError
308
+ if (this.now() >= this.refreshAt) await this.refresh()
309
+ const pinned = this.transactionEndpoint ?? this.sessionEndpoint
310
+ const address = pinned ?? this.primary
311
+ // Independent streams own a connection until completion. Session streams
312
+ // must share their pinned connection and hold its binary request queue.
313
+ let client
314
+ let unlock
315
+ let session
316
+ let finished = false
317
+ this.active.set(address, (this.active.get(address) ?? 0) + 1)
318
+ const stop = async () => {
319
+ try { await session?.cancel() }
320
+ finally { await finish(undefined, true) }
321
+ }
322
+ const finish = async (error, aborted = false) => {
323
+ if (finished) return
324
+ finished = true
325
+ this.streams.delete(stop)
326
+ if (connectionError(error)) this.refreshAt = 0
327
+ this.active.set(address, this.active.get(address) - 1)
328
+ try {
329
+ if (pinned && client?.binaryQueryParams && (error || aborted)) {
330
+ // StreamCancel does not drain terminal frames. Retire this session
331
+ // rather than let its next query consume a stale stream reply.
332
+ this.sessionError = new RedDBError('SESSION_CLOSED', 'binary session closed after an interrupted stream')
333
+ await client.close()
334
+ } else if (!pinned) await client?.close()
335
+ } finally { unlock?.() }
336
+ }
337
+ this.streams.add(stop)
338
+ try {
339
+ client = pinned ? await this.endpoint(address) : await this.dial(address)
340
+ if (finished || this.closed) {
341
+ if (!pinned) await client.close()
342
+ throw new RedDBError('CLOSED', 'connection is closed')
343
+ }
344
+ if (pinned && client.binaryQueryParams) {
345
+ const previous = this.queues.get(address) ?? Promise.resolve()
346
+ const released = new Promise((resolve) => { unlock = resolve })
347
+ this.queues.set(address, previous.then(() => released))
348
+ await previous
349
+ }
350
+ session = await client[method](options)
351
+ if (finished || this.closed) {
352
+ await session.cancel()
353
+ throw new RedDBError('CLOSED', 'connection is closed')
354
+ }
355
+ return { session, finish }
356
+ } catch (error) {
357
+ await finish(error)
358
+ throw error
359
+ }
360
+ }
361
+
362
+ async close() {
363
+ this.closed = true
364
+ const results = await Promise.allSettled([...this.streams].map((stop) => stop()).concat([...this.clients.values()].map(async (pending) => {
365
+ const client = await pending
366
+ await client.close()
367
+ })))
368
+ this.clients.clear()
369
+ this.active.clear()
370
+ this.queues.clear()
371
+ const failed = results.find((result) => result.status === 'rejected')
372
+ if (failed) throw failed.reason
373
+ }
374
+ }
@@ -0,0 +1,146 @@
1
+ import { RedDBError } from './errors.js'
2
+
3
+ const MAX_REPLICAS = 256
4
+ // Canonical contract: reddb-wire::routing; checked by shared conformance fixtures.
5
+ export const TOPOLOGY_TRANSPORT_METADATA_KEY = 'x-reddb-topology-transport'
6
+ const decoder = new TextDecoder('utf-8', { fatal: true })
7
+
8
+ /** Canonical v1 topology shared by gRPC and RedWire, including WS. */
9
+ export function decodeTopology(bytes) {
10
+ if (bytes.length < 5) throw new RedDBError('PROTOCOL', 'truncated topology')
11
+ if (bytes[0] !== 1) return null
12
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
13
+ const end = 5 + view.getUint32(1, true)
14
+ if (end !== bytes.length) throw new RedDBError('PROTOCOL', 'invalid topology length')
15
+ let offset = 5
16
+ function take(size) {
17
+ if (size > end - offset) throw new RedDBError('PROTOCOL', 'truncated topology field')
18
+ const start = offset
19
+ offset += size
20
+ return start
21
+ }
22
+ const uint32 = () => view.getUint32(take(4), true)
23
+ const uint64 = () => view.getBigUint64(take(8), true).toString()
24
+ function string() {
25
+ const size = uint32()
26
+ if (size > 4096) throw new RedDBError('PROTOCOL', 'topology address too long')
27
+ const start = take(size)
28
+ return decoder.decode(bytes.subarray(start, start + size))
29
+ }
30
+ const epoch = uint64()
31
+ const primary = { addr: string(), region: string() }
32
+ const count = uint32()
33
+ if (count > MAX_REPLICAS) throw new RedDBError('PROTOCOL', 'too many topology replicas')
34
+ const replicas = []
35
+ for (let index = 0; index < count; index++) {
36
+ replicas.push({
37
+ addr: string(), region: string(), healthy: bytes[take(1)] === 1,
38
+ lag_ms: uint32(), last_applied_lsn: uint64(), rebootstrapping: false,
39
+ })
40
+ }
41
+ if (end - offset >= count) {
42
+ for (const replica of replicas) replica.rebootstrapping = bytes[take(1)] !== 0
43
+ }
44
+ return { version: 1, epoch, primary, replicas }
45
+ }
46
+
47
+ export function topologyAddress(address, protocol) {
48
+ if (typeof address !== 'string' || address.length === 0 || address.length > 4096) return null
49
+ try {
50
+ const uri = new URL(address.includes('://') ? address : `${protocol}://${address}`)
51
+ if (uri.protocol !== `${protocol}:` || !uri.hostname || uri.username || uri.password
52
+ || uri.search || uri.hash) return null
53
+ return uri.href.replace(/\/$/, '')
54
+ } catch {
55
+ return null
56
+ }
57
+ }
58
+
59
+ /** Only a single, conservatively classified SELECT may leave the writer.
60
+ * Unknown functions, CTEs, locking reads and session statements stay there.
61
+ */
62
+ function sqlTokens(sql) {
63
+ if (typeof sql !== 'string' || sql.length > 1_048_576) return null
64
+ const tokens = []
65
+ let index = 0
66
+ while (index < sql.length) {
67
+ const tail = sql.slice(index)
68
+ const whitespace = /^\s+/.exec(tail)
69
+ if (whitespace) { index += whitespace[0].length; continue }
70
+ if (tail.startsWith('--')) {
71
+ const end = sql.indexOf('\n', index + 2)
72
+ index = end < 0 ? sql.length : end + 1
73
+ continue
74
+ }
75
+ if (tail.startsWith('/*')) {
76
+ let depth = 1
77
+ index += 2
78
+ while (index < sql.length && depth > 0) {
79
+ if (sql.startsWith('/*', index)) { depth++; index += 2 }
80
+ else if (sql.startsWith('*/', index)) { depth--; index += 2 }
81
+ else index++
82
+ if (depth > 64) return null
83
+ }
84
+ if (depth !== 0) return null
85
+ continue
86
+ }
87
+ const char = sql[index]
88
+ if (char === "'" || char === '"' || char === '`') {
89
+ const quote = char
90
+ index++
91
+ let closed = false
92
+ while (index < sql.length) {
93
+ if (sql[index] === '\\') return null
94
+ if (sql[index++] === quote) {
95
+ if (sql[index] === quote) { index++; continue }
96
+ closed = true
97
+ break
98
+ }
99
+ }
100
+ if (!closed) return null
101
+ tokens.push(quote === "'" ? '#value' : '#identifier')
102
+ continue
103
+ }
104
+ if (char.charCodeAt(0) > 127) return null
105
+ const word = /^[A-Za-z_][A-Za-z_0-9]*/.exec(tail)
106
+ if (word) { tokens.push(word[0].toUpperCase()); index += word[0].length }
107
+ else { tokens.push(char); index++ }
108
+ }
109
+ if (tokens.at(-1) === ';') tokens.pop()
110
+ return tokens
111
+ }
112
+
113
+ export function isReplicaQuery(sql) {
114
+ const tokens = sqlTokens(sql)
115
+ if (!tokens || tokens[0] !== 'SELECT') return false
116
+ const forbidden = new Set([';', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'ALTER', 'DROP',
117
+ 'INTO', 'FOR', 'LOCK', 'CALL', 'EXECUTE', 'SET', 'QUEUE', 'COPY', '[', ']'])
118
+ const functions = new Set(['COUNT', 'SUM', 'MIN', 'MAX', 'AVG', 'LOWER', 'UPPER',
119
+ 'LENGTH', 'COALESCE', 'ABS', 'ROUND', 'CAST', 'IN', 'EXISTS'])
120
+ for (let token = 0; token < tokens.length; token++) {
121
+ if (forbidden.has(tokens[token])) return false
122
+ if (tokens[token + 1] === '(' && /^(?:[A-Z_]|#identifier)/.test(tokens[token])
123
+ && !functions.has(tokens[token]) && !['SELECT', 'WHERE', 'AND', 'OR', 'NOT', 'FROM'].includes(tokens[token])) {
124
+ return false
125
+ }
126
+ }
127
+ return true
128
+ }
129
+
130
+ export function transactionCommand(sql) {
131
+ const tokens = sqlTokens(sql)
132
+ if (!tokens?.length) return null
133
+ if (tokens[0] === 'BEGIN') return 'BEGIN'
134
+ if (tokens[0] === 'START' && tokens[1] === 'TRANSACTION') return 'START TRANSACTION'
135
+ if (tokens.includes(';')) return null
136
+ if (['COMMIT', 'ROLLBACK'].includes(tokens[0]) && tokens.includes('CHAIN')) return 'BEGIN'
137
+ if (tokens[0] === 'COMMIT') return 'COMMIT'
138
+ if (tokens[0] === 'ROLLBACK' && !tokens.includes('TO')) return 'ROLLBACK'
139
+ return null
140
+ }
141
+
142
+ export function isSessionQuery(sql) {
143
+ const tokens = sqlTokens(sql)
144
+ return tokens && (tokens.includes(';')
145
+ || ['SET', 'USE', 'PREPARE', 'DECLARE', 'LISTEN'].includes(tokens[0]))
146
+ }
package/src/core/url.js CHANGED
@@ -92,6 +92,7 @@ function parseRedWebSocketUrl(uri, scheme) {
92
92
  const params = parsed.searchParams
93
93
  return {
94
94
  kind: tls ? 'redwss' : 'redws',
95
+ path: parsed.pathname !== '/' ? parsed.pathname : undefined,
95
96
  host: parsed.hostname,
96
97
  port: parsed.port ? Number(parsed.port) : (tls ? 443 : 80),
97
98
  tls,
package/src/grpc.js CHANGED
@@ -8,21 +8,32 @@
8
8
 
9
9
  import { connect as connectHttp2 } from 'node:http2'
10
10
  import { Buffer } from 'node:buffer'
11
+ import { readFile } from 'node:fs/promises'
11
12
 
12
13
  import { RedDBError } from './protocol.js'
13
14
  import { normalizeQueryResult } from './core/result.js'
14
15
  import { normalizeExactNumbers, serializeJsonValue } from './core/serialization.js'
16
+ import { decodeTopology, TOPOLOGY_TRANSPORT_METADATA_KEY } from './core/topology.js'
15
17
 
16
18
  const SERVICE = '/reddb.v1.RedDb'
17
19
 
18
20
  export class GrpcRpcClient {
19
- constructor({ baseUrl, token }) {
21
+ static async connect(options) {
22
+ const tls = { ...options.tls }
23
+ for (const key of ['ca', 'cert', 'key']) {
24
+ const value = tls[key]
25
+ if (typeof value === 'string' && !value.includes('-----BEGIN')) tls[key] = await readFile(value)
26
+ }
27
+ return new GrpcRpcClient({ ...options, tls })
28
+ }
29
+
30
+ constructor({ baseUrl, token, tls }) {
20
31
  if (typeof baseUrl !== 'string' || baseUrl.length === 0) {
21
32
  throw new TypeError('GrpcRpcClient: baseUrl required')
22
33
  }
23
34
  this.baseUrl = baseUrl.replace(/\/$/, '')
24
35
  this.token = token ?? null
25
- this.session = connectHttp2(this.baseUrl)
36
+ this.session = connectHttp2(this.baseUrl, tls)
26
37
  this.session.on('error', () => {})
27
38
  }
28
39
 
@@ -36,6 +47,11 @@ export class GrpcRpcClient {
36
47
 
37
48
  async call(method, params = {}) {
38
49
  switch (method) {
50
+ case 'topology':
51
+ return this.#rpc('Topology', new Uint8Array(), (bytes) => {
52
+ const field = readFields(bytes).find((field) => field.no === 1 && field.wire === 2)
53
+ return field ? decodeTopology(field.value) : null
54
+ }, { [TOPOLOGY_TRANSPORT_METADATA_KEY]: params.transport ?? (this.baseUrl.startsWith('https:') ? 'grpcs' : 'grpc') }, params.signal)
39
55
  case 'query':
40
56
  return normalizeQueryReply(await this.#rpc(
41
57
  'Query',
@@ -71,17 +87,22 @@ export class GrpcRpcClient {
71
87
  }
72
88
  }
73
89
 
74
- #rpc(name, payload, decode) {
90
+ #rpc(name, payload, decode, metadata = {}, signal) {
75
91
  return new Promise((resolve, reject) => {
76
92
  const headers = {
77
93
  ':method': 'POST',
78
94
  ':path': `${SERVICE}/${name}`,
79
95
  'content-type': 'application/grpc',
80
96
  te: 'trailers',
97
+ ...metadata,
81
98
  }
82
99
  if (this.token) headers.authorization = `Bearer ${this.token}`
83
100
 
84
101
  const req = this.session.request(headers)
102
+ const abort = () => req.destroy(new RedDBError('ETIMEDOUT', 'topology refresh cancelled'))
103
+ if (signal?.aborted) abort()
104
+ else signal?.addEventListener('abort', abort, { once: true })
105
+ req.on('close', () => signal?.removeEventListener('abort', abort))
85
106
  const chunks = []
86
107
  let responseHeaders = null
87
108
  let trailers = null
package/src/http.js CHANGED
@@ -76,7 +76,7 @@ export class HttpRpcClient {
76
76
  )
77
77
  }
78
78
  const { url, init } = route(this.baseUrl, params)
79
- const response = await fetch(url, this.attachAuth(init))
79
+ const response = await fetch(url, this.attachAuth({ ...init, signal: params.signal ?? init.signal }))
80
80
  if (method === 'query') {
81
81
  // Keep the whole envelope: `statement` and `affected_rows` sit next to
82
82
  // `result`, which is all the generic unwrap below would return.
@@ -319,6 +319,10 @@ async function parseResponse(response, { envelope = false } = {}) {
319
319
  // ---------------------------------------------------------------------------
320
320
 
321
321
  const ROUTES = {
322
+ topology: (base, { transport = new URL(base).protocol.slice(0, -1) }) => ({
323
+ url: `${base}/v1/topology?transport=${encodeURIComponent(transport)}`,
324
+ init: { method: 'GET' },
325
+ }),
322
326
  health: (base) => ({ url: `${base}/health`, init: { method: 'GET' } }),
323
327
  version: (base) => ({ url: `${base}/admin/version`, init: { method: 'GET' } }),
324
328
  query: (base, { sql, params }) => ({
@@ -43,6 +43,7 @@ import {
43
43
  import { HttpRpcClient } from './http.js'
44
44
  import { connectRedwireWs, REDWIRE_WS_PATH } from './redwire-ws.js'
45
45
  import { createSelectStream, createInputStream } from './streaming-web.js'
46
+ import { connectRouted } from './core/routing.js'
46
47
 
47
48
  export { RedDBError, EmbeddedNotSupported, EMBEDDED_REJECTION_MESSAGE, isEmbeddedUri }
48
49
  export { RowReadable, RowWritable } from './streaming-web.js'
@@ -96,6 +97,10 @@ function browserTransportError(scheme) {
96
97
  * @returns {Promise<RedDB>}
97
98
  */
98
99
  export async function connect(uri, options = {}) {
100
+ return connectRouted(uri, options, connectDirect)
101
+ }
102
+
103
+ async function connectDirect(uri, options = {}, discovery = false) {
99
104
  // Reject embedded shapes upfront with the same wording the Node entry and
100
105
  // the Rust binary use, before the URL parser would map them to kind=embedded.
101
106
  rejectEmbeddedUri(uri)
@@ -109,7 +114,7 @@ export async function connect(uri, options = {}) {
109
114
 
110
115
  if (parsed.kind === 'http' || parsed.kind === 'https') {
111
116
  const merged = mergeAuthFromUri(parsed, options.auth)
112
- const baseUrl = `${parsed.kind}://${parsed.host}:${parsed.port}`
117
+ const baseUrl = `${parsed.kind}://${parsed.host}:${parsed.port}${parsed.path ?? ''}`
113
118
  let token = merged.token
114
119
  if (!token && merged.username && merged.password) {
115
120
  const loginUrl = merged.loginUrl ?? `${baseUrl}/auth/login`
@@ -120,7 +125,7 @@ export async function connect(uri, options = {}) {
120
125
  token = session.token
121
126
  }
122
127
  const client = new HttpRpcClient({ baseUrl, token })
123
- await client.call('query', { sql: 'SELECT 1' })
128
+ if (!discovery) await client.call('query', { sql: 'SELECT 1', signal: options.signal })
124
129
  return new RedDB(client)
125
130
  }
126
131
 
@@ -143,8 +148,8 @@ export async function connect(uri, options = {}) {
143
148
  }
144
149
  const auth = token ? { kind: 'bearer', token } : { kind: 'anonymous' }
145
150
  const wsScheme = parsed.tls === false ? 'ws' : 'wss'
146
- const url = `${wsScheme}://${parsed.host}:${parsed.port}${REDWIRE_WS_PATH}`
147
- const client = await connectRedwireWs({ url, auth })
151
+ const url = `${wsScheme}://${parsed.host}:${parsed.port}${parsed.path ?? REDWIRE_WS_PATH}`
152
+ const client = await connectRedwireWs({ url, auth, signal: options.signal, WebSocketImpl: options.WebSocketImpl })
148
153
  return new RedDB(client)
149
154
  }
150
155
 
package/src/index.js CHANGED
@@ -42,6 +42,8 @@ import {
42
42
  import { HttpRpcClient } from './http.js'
43
43
  import { GrpcRpcClient } from './grpc.js'
44
44
  import { connectRedwire } from './redwire.js'
45
+ import { connectRedwireWs, REDWIRE_WS_PATH } from './redwire-ws.js'
46
+ import { connectRouted } from './core/routing.js'
45
47
  import { createSelectStream, createInputStream } from './streaming.js'
46
48
 
47
49
  export { RedDBError, EmbeddedNotSupported, EMBEDDED_REJECTION_MESSAGE, isEmbeddedUri }
@@ -77,6 +79,10 @@ const NODE_STREAMING = { createSelectStream, createInputStream }
77
79
  * @returns {Promise<RedDB>}
78
80
  */
79
81
  export async function connect(uri, options = {}) {
82
+ return connectRouted(uri, options, connectDirect)
83
+ }
84
+
85
+ async function connectDirect(uri, options = {}, discovery = false) {
80
86
  // Reject embedded shapes upfront with the same wording the Rust
81
87
  // binary uses, before the URL parser would map them to kind=embedded.
82
88
  rejectEmbeddedUri(uri)
@@ -91,8 +97,24 @@ export async function connect(uri, options = {}) {
91
97
 
92
98
  const merged = mergeAuthFromUri(parsed, options.auth)
93
99
 
100
+ if (parsed.kind === 'redws' || parsed.kind === 'redwss') {
101
+ const scheme = parsed.kind === 'redws' ? 'ws' : 'wss'
102
+ let token = merged.token
103
+ if (!token && merged.username && merged.password) {
104
+ const loginUrl = merged.loginUrl ?? `${scheme === 'ws' ? 'http' : 'https'}://${parsed.host}:${parsed.port}/auth/login`
105
+ token = (await login(loginUrl, { username: merged.username, password: merged.password })).token
106
+ }
107
+ const client = await connectRedwireWs({
108
+ url: `${scheme}://${parsed.host}:${parsed.port}${parsed.path ?? REDWIRE_WS_PATH}`,
109
+ auth: token ? { kind: 'bearer', token } : { kind: 'anonymous' },
110
+ WebSocketImpl: options.WebSocketImpl,
111
+ signal: options.signal,
112
+ })
113
+ return new RedDB(client)
114
+ }
115
+
94
116
  if (parsed.kind === 'http' || parsed.kind === 'https') {
95
- const baseUrl = `${parsed.kind}://${parsed.host}:${parsed.port}`
117
+ const baseUrl = `${parsed.kind}://${parsed.host}:${parsed.port}${parsed.path ?? ''}`
96
118
  let token = merged.token
97
119
  if (!token && merged.username && merged.password) {
98
120
  const loginUrl = merged.loginUrl ?? `${baseUrl}/auth/login`
@@ -103,7 +125,7 @@ export async function connect(uri, options = {}) {
103
125
  token = session.token
104
126
  }
105
127
  const client = new HttpRpcClient({ baseUrl, token })
106
- await client.call('query', { sql: 'SELECT 1' })
128
+ if (!discovery) await client.call('query', { sql: 'SELECT 1', signal: options.signal })
107
129
  return new RedDB(client)
108
130
  }
109
131
 
@@ -118,9 +140,10 @@ export async function connect(uri, options = {}) {
118
140
  token = session.token
119
141
  }
120
142
  const scheme = parsed.kind === 'grpcs' ? 'https' : 'http'
121
- const client = new GrpcRpcClient({
143
+ const client = await GrpcRpcClient.connect({
122
144
  baseUrl: `${scheme}://${parsed.host}:${parsed.port}`,
123
145
  token,
146
+ tls: buildTlsOpts(parsed, options.tls),
124
147
  })
125
148
  return new RedDB(client)
126
149
  }
@@ -141,6 +164,7 @@ export async function connect(uri, options = {}) {
141
164
  host: parsed.host,
142
165
  port: parsed.port,
143
166
  auth,
167
+ signal: options.signal,
144
168
  ...(tls ? { tls } : {}),
145
169
  })
146
170
  return new RedDB(client)
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { RedDBError } from './protocol.js'
20
20
  import { normalizeQueryResult } from './core/result.js'
21
+ import { decodeTopology } from './core/topology.js'
21
22
 
22
23
  const MAGIC = 0xfe
23
24
  const SUPPORTED_VERSION = 0x01
@@ -26,6 +27,7 @@ const MAX_FRAME_SIZE = 16 * 1024 * 1024
26
27
  const KNOWN_FLAGS = 0b00000011
27
28
 
28
29
  export const MessageKind = Object.freeze({
30
+ Topology: 0x32,
29
31
  Query: 0x01,
30
32
  Result: 0x02,
31
33
  Error: 0x03,
@@ -59,7 +61,7 @@ export const MessageKind = Object.freeze({
59
61
  StreamCancel: 0x2D,
60
62
  })
61
63
 
62
- export const Features = Object.freeze({ PARAMS: 0x0000_0001 })
64
+ export const Features = Object.freeze({ PARAMS: 0x0000_0001, TOPOLOGY: 0x0000_0002 })
63
65
 
64
66
  export const ValueTag = Object.freeze({
65
67
  Null: 0x00, Bool: 0x01, Int: 0x02, Float: 0x03, Text: 0x04,
@@ -134,6 +136,14 @@ export function setZstdProvider(mod) {
134
136
  * @returns {Promise<RedWireClient>}
135
137
  */
136
138
  export async function connectRedwireOverSocket(socket, opts = {}) {
139
+ const abort = () => socket.end()
140
+ if (opts.signal?.aborted) { abort(); throw new RedDBError('CLOSED', 'connection cancelled') }
141
+ opts.signal?.addEventListener('abort', abort, { once: true })
142
+ try { return await handshakeOverSocket(socket, opts) }
143
+ finally { opts.signal?.removeEventListener('abort', abort) }
144
+ }
145
+
146
+ async function handshakeOverSocket(socket, opts) {
137
147
  const auth = opts.auth ?? { kind: 'anonymous' }
138
148
  const reader = new FrameReader(socket)
139
149
 
@@ -244,6 +254,18 @@ export class RedWireClient {
244
254
  }
245
255
 
246
256
  async call(method, params = {}) {
257
+ if (method === 'topology') {
258
+ if ((this.serverFeatures & Features.TOPOLOGY) === 0) return null
259
+ const corr = this.#corr()
260
+ await writeFrame(this.socket, MessageKind.Topology, corr,
261
+ new TextEncoder().encode(params.transport ?? 'red'))
262
+ const response = await this.reader.next()
263
+ if (response.kind === MessageKind.Error) {
264
+ throw new RedDBError('ENGINE', new TextDecoder().decode(response.payload))
265
+ }
266
+ if (response.kind !== MessageKind.Result) throw new RedDBError('PROTOCOL', 'expected topology Result')
267
+ return decodeTopology(response.payload)
268
+ }
247
269
  if (method === 'query') return this.#query(params.sql ?? '', params.params)
248
270
  if (method === 'insert') return this.#insert({ collection: params.collection, payload: params.payload })
249
271
  if (method === 'bulk_insert') return this.#insert({ collection: params.collection, payloads: params.payloads })
package/src/redwire-ws.js CHANGED
@@ -162,8 +162,12 @@ export async function connectRedwireWs(opts = {}) {
162
162
 
163
163
  const ws = new WS(url, subprotocol)
164
164
  if ('binaryType' in ws) ws.binaryType = 'arraybuffer'
165
- await waitOpen(ws)
165
+ const abort = () => ws.close()
166
+ if (opts.signal?.aborted) { abort(); throw new RedDBError('CLOSED', 'connection cancelled') }
167
+ opts.signal?.addEventListener('abort', abort, { once: true })
168
+ try { await waitOpen(ws) }
169
+ finally { opts.signal?.removeEventListener('abort', abort) }
166
170
 
167
171
  const duplex = new WebSocketDuplex(ws)
168
- return await connectRedwireOverSocket(duplex, { auth, clientName })
172
+ return await connectRedwireOverSocket(duplex, { auth, clientName, signal: opts.signal })
169
173
  }
package/src/redwire.js CHANGED
@@ -85,13 +85,14 @@ export async function connectRedwire(opts) {
85
85
  throw new TypeError('connectRedwire: port required (1-65535)')
86
86
  }
87
87
  socket = opts.tls
88
- ? await openTlsSocket(host, port, opts.tls)
89
- : await openSocket(host, port)
88
+ ? await openTlsSocket(host, port, opts.tls, opts.signal)
89
+ : await openSocket(host, port, opts.signal)
90
90
  }
91
91
 
92
92
  return await connectRedwireOverSocket(socket, {
93
93
  auth: opts.auth,
94
94
  clientName: opts.clientName,
95
+ signal: opts.signal,
95
96
  })
96
97
  }
97
98
 
@@ -99,26 +100,31 @@ export async function connectRedwire(opts) {
99
100
  // Socket helpers — node:net / node:tls work on Node, Bun, and Deno via shim
100
101
  // ---------------------------------------------------------------------------
101
102
 
102
- async function openSocket(host, port) {
103
+ async function openSocket(host, port, signal) {
103
104
  const { Socket } = await import('node:net')
104
105
  return await new Promise((resolve, reject) => {
105
106
  const sock = new Socket()
107
+ const abort = () => sock.destroy(new Error('topology connection cancelled'))
108
+ signal?.addEventListener('abort', abort, { once: true })
106
109
  const onErr = (err) => {
107
110
  sock.removeListener('connect', onOk)
111
+ signal?.removeEventListener('abort', abort)
108
112
  reject(err)
109
113
  }
110
114
  const onOk = () => {
111
115
  sock.removeListener('error', onErr)
116
+ signal?.removeEventListener('abort', abort)
112
117
  sock.setNoDelay(true)
113
118
  resolve(sock)
114
119
  }
115
120
  sock.once('error', onErr)
116
121
  sock.once('connect', onOk)
122
+ if (signal?.aborted) { abort(); return }
117
123
  sock.connect(port, host)
118
124
  })
119
125
  }
120
126
 
121
- async function openTlsSocket(host, port, tlsOpts) {
127
+ async function openTlsSocket(host, port, tlsOpts, signal) {
122
128
  const tls = await import('node:tls')
123
129
  const fs = await import('node:fs/promises')
124
130
  const resolveBytes = async (input) => {
@@ -140,6 +146,7 @@ async function openTlsSocket(host, port, tlsOpts) {
140
146
  servername: tlsOpts.servername ?? host,
141
147
  rejectUnauthorized: tlsOpts.rejectUnauthorized !== false,
142
148
  ALPNProtocols: ['redwire/1'],
149
+ signal,
143
150
  })
144
151
  const onErr = (err) => {
145
152
  sock.removeListener('secureConnect', onOk)
package/topology.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface TopologyEndpoint { addr: string; region: string }
2
+ export interface TopologyReplica extends TopologyEndpoint {
3
+ healthy: boolean
4
+ lag_ms: number
5
+ last_applied_lsn: string
6
+ rebootstrapping: boolean
7
+ }
8
+ export interface Topology {
9
+ version: 1
10
+ epoch: string
11
+ primary: TopologyEndpoint
12
+ replicas: TopologyReplica[]
13
+ }
14
+ export function decodeTopology(bytes: Uint8Array): Topology | null
15
+ export function topologyAddress(address: unknown, protocol: string): string | null
16
+ export function isReplicaQuery(sql: string): boolean
17
+ export function transactionCommand(sql: string): string | null
18
+ export function isSessionQuery(sql: string): boolean
19
+ export const TOPOLOGY_TRANSPORT_METADATA_KEY: 'x-reddb-topology-transport'