@datafn/server 0.0.2
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 +765 -0
- package/dist/index.cjs +13170 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +577 -0
- package/dist/index.d.ts +577 -0
- package/dist/index.js +13163 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
import { Router } from '@superfunctions/http';
|
|
2
|
+
import { Adapter, RedisAdapter, KVStoreAdapter, RowLevelNamespaceConfig } from '@superfunctions/db';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Pluggable logger interface and default implementation.
|
|
6
|
+
* LOG-001 / Decision #14
|
|
7
|
+
*/
|
|
8
|
+
interface DatafnLogger {
|
|
9
|
+
info(message: string, context?: Record<string, unknown>): void;
|
|
10
|
+
warn(message: string, context?: Record<string, unknown>): void;
|
|
11
|
+
error(message: string, context?: Record<string, unknown>): void;
|
|
12
|
+
debug(message: string, context?: Record<string, unknown>): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Execution Timing Middleware (OBS-001 through OBS-004)
|
|
17
|
+
* Provides structured phase-level timing for query, mutation, and sync operations.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Timing event emitted after each operation completes.
|
|
21
|
+
* Contains phase-by-phase duration breakdown.
|
|
22
|
+
* MUST NOT include record data, filter values, or credentials.
|
|
23
|
+
*/
|
|
24
|
+
interface ExecutionTimingEvent {
|
|
25
|
+
endpoint: string;
|
|
26
|
+
resource?: string;
|
|
27
|
+
operation?: string;
|
|
28
|
+
phases: Record<string, number>;
|
|
29
|
+
totalMs: number;
|
|
30
|
+
timestamp: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type DatafnPermissionsPolicy = {
|
|
34
|
+
read?: {
|
|
35
|
+
fields: string[];
|
|
36
|
+
};
|
|
37
|
+
write?: {
|
|
38
|
+
fields: string[];
|
|
39
|
+
};
|
|
40
|
+
ownerField?: string;
|
|
41
|
+
};
|
|
42
|
+
type DatafnFieldSchema = {
|
|
43
|
+
name: string;
|
|
44
|
+
type: "string" | "number" | "boolean" | "object" | "array" | "date" | "file" | "json";
|
|
45
|
+
required?: boolean;
|
|
46
|
+
nullable?: boolean;
|
|
47
|
+
readonly?: boolean;
|
|
48
|
+
default?: unknown;
|
|
49
|
+
enum?: unknown[];
|
|
50
|
+
min?: number;
|
|
51
|
+
max?: number;
|
|
52
|
+
minLength?: number;
|
|
53
|
+
maxLength?: number;
|
|
54
|
+
pattern?: string;
|
|
55
|
+
unique?: boolean | string;
|
|
56
|
+
encrypt?: boolean;
|
|
57
|
+
volatile?: boolean;
|
|
58
|
+
};
|
|
59
|
+
type DatafnResourceSchema = {
|
|
60
|
+
name: string;
|
|
61
|
+
version: number;
|
|
62
|
+
idPrefix?: string;
|
|
63
|
+
isRemoteOnly?: boolean;
|
|
64
|
+
fields: DatafnFieldSchema[];
|
|
65
|
+
indices?: {
|
|
66
|
+
base?: string[];
|
|
67
|
+
search?: string[];
|
|
68
|
+
vector?: string[];
|
|
69
|
+
} | string[];
|
|
70
|
+
permissions?: DatafnPermissionsPolicy;
|
|
71
|
+
capabilities?: unknown;
|
|
72
|
+
};
|
|
73
|
+
type DatafnRelationSchema = {
|
|
74
|
+
from: string | string[];
|
|
75
|
+
to: string | string[];
|
|
76
|
+
type: "one-many" | "many-one" | "many-many" | "htree";
|
|
77
|
+
relation?: string;
|
|
78
|
+
inverse?: string;
|
|
79
|
+
cache?: boolean;
|
|
80
|
+
metadata?: Array<{
|
|
81
|
+
name: string;
|
|
82
|
+
type: "string" | "number" | "boolean" | "date" | "object" | "json";
|
|
83
|
+
}>;
|
|
84
|
+
fkField?: string;
|
|
85
|
+
pathField?: string;
|
|
86
|
+
joinTable?: string;
|
|
87
|
+
joinColumns?: {
|
|
88
|
+
from: string;
|
|
89
|
+
to: string;
|
|
90
|
+
};
|
|
91
|
+
/** Relation-level capabilities (e.g. "timestamps", "audit") for many-many join rows. */
|
|
92
|
+
capabilities?: string[];
|
|
93
|
+
};
|
|
94
|
+
type DatafnSchema = {
|
|
95
|
+
version?: number;
|
|
96
|
+
capabilities?: unknown;
|
|
97
|
+
resources: DatafnResourceSchema[];
|
|
98
|
+
relations?: DatafnRelationSchema[];
|
|
99
|
+
namespaced?: boolean;
|
|
100
|
+
};
|
|
101
|
+
type DatafnHookContext = {
|
|
102
|
+
env: "client" | "server";
|
|
103
|
+
schema: DatafnSchema;
|
|
104
|
+
context?: unknown;
|
|
105
|
+
};
|
|
106
|
+
type DatafnPlugin = {
|
|
107
|
+
name: string;
|
|
108
|
+
runsOn: Array<"client" | "server">;
|
|
109
|
+
beforeQuery?: (ctx: DatafnHookContext, q: unknown) => Promise<unknown> | unknown;
|
|
110
|
+
afterQuery?: (ctx: DatafnHookContext, q: unknown, result: unknown) => Promise<unknown> | unknown;
|
|
111
|
+
beforeMutation?: (ctx: DatafnHookContext, m: unknown | unknown[]) => Promise<unknown> | unknown;
|
|
112
|
+
afterMutation?: (ctx: DatafnHookContext, m: unknown | unknown[], result: unknown) => Promise<void> | void;
|
|
113
|
+
beforeSync?: (ctx: DatafnHookContext, phase: "seed" | "clone" | "pull" | "push" | "cloneUp" | "reconcile", payload: unknown) => Promise<unknown> | unknown;
|
|
114
|
+
afterSync?: (ctx: DatafnHookContext, phase: "seed" | "clone" | "pull" | "push" | "cloneUp" | "reconcile", payload: unknown, result: unknown) => Promise<void> | void;
|
|
115
|
+
};
|
|
116
|
+
interface RetentionConfig {
|
|
117
|
+
/** Number of days to retain change log entries. Default: unlimited. */
|
|
118
|
+
changeLogDays?: number;
|
|
119
|
+
/** Number of days to retain idempotency records. Default: unlimited. */
|
|
120
|
+
idempotencyDays?: number;
|
|
121
|
+
/** Whether to run pruning on server startup. Default: false. */
|
|
122
|
+
pruneOnStartup?: boolean;
|
|
123
|
+
/** Interval in milliseconds for periodic pruning. Minimum: 60000. Default: disabled. */
|
|
124
|
+
pruneIntervalMs?: number;
|
|
125
|
+
}
|
|
126
|
+
interface RateLimitConfig<TContext = any> {
|
|
127
|
+
/** Enable rate limiting. Default: false. */
|
|
128
|
+
enabled: boolean;
|
|
129
|
+
/** Max requests per window per client. Default: 100. */
|
|
130
|
+
maxRequests?: number;
|
|
131
|
+
/** Window duration in seconds. Default: 60. */
|
|
132
|
+
windowSeconds?: number;
|
|
133
|
+
/** Per-endpoint overrides */
|
|
134
|
+
endpoints?: Partial<Record<'query' | 'mutation' | 'transact' | 'push' | 'pull' | 'clone' | 'reconcile' | 'seed', {
|
|
135
|
+
maxRequests: number;
|
|
136
|
+
windowSeconds: number;
|
|
137
|
+
}>>;
|
|
138
|
+
/** Key extractor for identifying clients. Default: uses authContext userId or "anonymous". */
|
|
139
|
+
keyExtractor?: (ctx: TContext) => string | Promise<string>;
|
|
140
|
+
}
|
|
141
|
+
interface ObservabilityConfig {
|
|
142
|
+
/** Emit execution timing events. Default: false. */
|
|
143
|
+
timing?: boolean;
|
|
144
|
+
/** Custom timing event handler. Default: console.debug. */
|
|
145
|
+
onTiming?: (event: ExecutionTimingEvent) => void;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* SearchProvider interface for server-side search integration.
|
|
150
|
+
* Defined locally to avoid TS2709 when emitting declarations.
|
|
151
|
+
* Shape must stay compatible with @datafn/core SearchProvider.
|
|
152
|
+
*/
|
|
153
|
+
interface SearchProvider {
|
|
154
|
+
readonly name: string;
|
|
155
|
+
search(params: {
|
|
156
|
+
resource: string;
|
|
157
|
+
query: string;
|
|
158
|
+
type?: "fullText" | "semantic";
|
|
159
|
+
fields?: string[];
|
|
160
|
+
limit?: number;
|
|
161
|
+
prefix?: boolean;
|
|
162
|
+
fuzzy?: boolean | number;
|
|
163
|
+
fieldBoosts?: Record<string, number>;
|
|
164
|
+
signal?: AbortSignal;
|
|
165
|
+
}): Promise<string[]>;
|
|
166
|
+
searchAll?(params: {
|
|
167
|
+
query: string;
|
|
168
|
+
resources?: string[];
|
|
169
|
+
fields?: string[];
|
|
170
|
+
limit?: number;
|
|
171
|
+
limitPerResource?: number;
|
|
172
|
+
prefix?: boolean;
|
|
173
|
+
fuzzy?: boolean | number;
|
|
174
|
+
fieldBoosts?: Record<string, number>;
|
|
175
|
+
signal?: AbortSignal;
|
|
176
|
+
}): Promise<Array<{
|
|
177
|
+
resource: string;
|
|
178
|
+
id: string;
|
|
179
|
+
score: number;
|
|
180
|
+
}>>;
|
|
181
|
+
updateIndices(params: {
|
|
182
|
+
resource: string;
|
|
183
|
+
records: Record<string, unknown>[];
|
|
184
|
+
operation: "upsert" | "delete";
|
|
185
|
+
}): Promise<void>;
|
|
186
|
+
initialize?(config: {
|
|
187
|
+
resources: Array<{
|
|
188
|
+
name: string;
|
|
189
|
+
searchFields: string[];
|
|
190
|
+
}>;
|
|
191
|
+
}): Promise<void>;
|
|
192
|
+
dispose?(): Promise<void>;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
interface SearchResultItem {
|
|
196
|
+
id: string;
|
|
197
|
+
resource: string;
|
|
198
|
+
score: number;
|
|
199
|
+
data: Record<string, unknown>;
|
|
200
|
+
}
|
|
201
|
+
interface SearchResult {
|
|
202
|
+
results: SearchResultItem[];
|
|
203
|
+
}
|
|
204
|
+
interface CrossResourceSearchParams {
|
|
205
|
+
query: string;
|
|
206
|
+
resources?: string[];
|
|
207
|
+
fields?: string[];
|
|
208
|
+
limit?: number;
|
|
209
|
+
limitPerResource?: number;
|
|
210
|
+
prefix?: boolean;
|
|
211
|
+
fuzzy?: boolean | number;
|
|
212
|
+
fieldBoosts?: Record<string, number>;
|
|
213
|
+
filters?: Record<string, Record<string, unknown>>;
|
|
214
|
+
select?: string[];
|
|
215
|
+
signal?: AbortSignal;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* SequenceStore - Pluggable sequence generation for serverSeq
|
|
220
|
+
*
|
|
221
|
+
* Supports multiple backends:
|
|
222
|
+
* - Redis: Uses atomic INCR for high-performance sequence generation
|
|
223
|
+
* - KV Store: Uses atomic incr if available
|
|
224
|
+
* - Database: Uses CAS retry loop
|
|
225
|
+
*/
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Interface for sequence generation stores
|
|
229
|
+
*/
|
|
230
|
+
interface SequenceStore {
|
|
231
|
+
/** Get and increment sequence atomically, returns the next value */
|
|
232
|
+
getNext(namespace: string): Promise<number>;
|
|
233
|
+
/** Get and increment sequence atomically by count, returns array of contiguous values */
|
|
234
|
+
getNextN(namespace: string, count: number): Promise<number[]>;
|
|
235
|
+
/** Get current sequence value (without incrementing) */
|
|
236
|
+
getCurrent(namespace: string): Promise<number>;
|
|
237
|
+
/** Check if the store is healthy/available */
|
|
238
|
+
isHealthy?(): Promise<boolean>;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Redis-based sequence store using atomic INCR
|
|
242
|
+
*/
|
|
243
|
+
declare class RedisSequenceStore implements SequenceStore {
|
|
244
|
+
private redis;
|
|
245
|
+
private keyPrefix;
|
|
246
|
+
constructor(redis: RedisAdapter);
|
|
247
|
+
private getKey;
|
|
248
|
+
getNext(namespace: string): Promise<number>;
|
|
249
|
+
getNextN(namespace: string, count: number): Promise<number[]>;
|
|
250
|
+
getCurrent(namespace: string): Promise<number>;
|
|
251
|
+
isHealthy(): Promise<boolean>;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* KV Store-based sequence store using atomic incr
|
|
255
|
+
*/
|
|
256
|
+
declare class KVSequenceStore implements SequenceStore {
|
|
257
|
+
private kvStore;
|
|
258
|
+
private keyPrefix;
|
|
259
|
+
constructor(kvStore: KVStoreAdapter);
|
|
260
|
+
private getKey;
|
|
261
|
+
getNext(namespace: string): Promise<number>;
|
|
262
|
+
getNextN(namespace: string, count: number): Promise<number[]>;
|
|
263
|
+
getCurrent(namespace: string): Promise<number>;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Database-based sequence store using CAS retry loop
|
|
267
|
+
* Uses the main database adapter
|
|
268
|
+
*/
|
|
269
|
+
declare class DatabaseSequenceStore implements SequenceStore {
|
|
270
|
+
private db;
|
|
271
|
+
private logger?;
|
|
272
|
+
private ensured;
|
|
273
|
+
constructor(db: Adapter, logger?: DatafnLogger | undefined);
|
|
274
|
+
/**
|
|
275
|
+
* DI-003: Ensure next_server_seq in meta is at least (minSeq + 1).
|
|
276
|
+
* Called by ChainedSequenceStore during primary→database failover to prevent duplicate sequences.
|
|
277
|
+
*/
|
|
278
|
+
ensureMinSeq(namespace: string, minSeq: number): Promise<void>;
|
|
279
|
+
getNext(namespace: string): Promise<number>;
|
|
280
|
+
getNextN(namespace: string, count: number): Promise<number[]>;
|
|
281
|
+
getCurrent(namespace: string): Promise<number>;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Chained sequence store that tries primary store first, then uses database.
|
|
285
|
+
* DI-003: Tracks the last known primary sequence per namespace so that on failover
|
|
286
|
+
* the DB store is synced to avoid duplicate sequences.
|
|
287
|
+
*/
|
|
288
|
+
declare class ChainedSequenceStore implements SequenceStore {
|
|
289
|
+
private primary;
|
|
290
|
+
private secondary;
|
|
291
|
+
private logger?;
|
|
292
|
+
/** DI-003: Track last-issued seq per namespace from the primary store */
|
|
293
|
+
private lastKnownPrimarySeq;
|
|
294
|
+
constructor(primary: SequenceStore, secondary: SequenceStore, logger?: DatafnLogger | undefined);
|
|
295
|
+
getNext(namespace: string): Promise<number>;
|
|
296
|
+
/**
|
|
297
|
+
* DI-003: Sync the secondary (DB) store to start from at least lastKnownPrimarySeq+1.
|
|
298
|
+
* Prevents duplicate sequences after Redis→DB failover.
|
|
299
|
+
*/
|
|
300
|
+
private syncSecondaryOnFailover;
|
|
301
|
+
getNextN(namespace: string, count: number): Promise<number[]>;
|
|
302
|
+
getCurrent(namespace: string): Promise<number>;
|
|
303
|
+
isHealthy(): Promise<boolean>;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Database mapping configuration for routing operations to different databases
|
|
307
|
+
*/
|
|
308
|
+
interface DbMapping {
|
|
309
|
+
/** Which database to use for serverSeq generation (default: "db") */
|
|
310
|
+
serverseq?: "redis" | "kv" | "db";
|
|
311
|
+
/** Which database to use for rate limiting (default: "db") */
|
|
312
|
+
ratelimiting?: "redis" | "kv" | "db";
|
|
313
|
+
/** Which database to use for caching (default: "db") */
|
|
314
|
+
cache?: "redis" | "kv" | "db";
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Create appropriate sequence store based on configuration
|
|
318
|
+
*/
|
|
319
|
+
declare function createSequenceStore(config: {
|
|
320
|
+
db?: Adapter;
|
|
321
|
+
redis?: RedisAdapter;
|
|
322
|
+
kvStore?: KVStoreAdapter;
|
|
323
|
+
dbMapping?: DbMapping;
|
|
324
|
+
logger?: DatafnLogger;
|
|
325
|
+
}): SequenceStore | undefined;
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* WebSocket Handler for DataFn Sync
|
|
329
|
+
*
|
|
330
|
+
* Implements the server-side protocol for:
|
|
331
|
+
* - Client registration (hello) with namespace tracking
|
|
332
|
+
* - Cursor notifications (push -> broadcast) scoped to namespace or targeted principals
|
|
333
|
+
*
|
|
334
|
+
* SEC-001: Auth required via addClient authContext parameter
|
|
335
|
+
* SEC-002: Namespace is server-derived, never client-supplied
|
|
336
|
+
* SCA-005: Connection limits enforced at addClient time (close code 4503)
|
|
337
|
+
* SCA-006: Namespace-scoped Map<namespace, Set<client>> for O(1) broadcast
|
|
338
|
+
* REL-007: Native WS ping/pong heartbeat; dead connections closed automatically
|
|
339
|
+
*/
|
|
340
|
+
interface WebSocketClient {
|
|
341
|
+
send(data: string): void;
|
|
342
|
+
close?(code?: number, reason?: string): void;
|
|
343
|
+
/** Native WS ping frame (e.g. ws.ping() in the 'ws' library). */
|
|
344
|
+
ping?(): void;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Auth context passed during WS connection setup.
|
|
348
|
+
* Namespace is server-derived from the auth context provider.
|
|
349
|
+
*/
|
|
350
|
+
interface WsAuthContext {
|
|
351
|
+
namespace: string;
|
|
352
|
+
/** Optional actor identity for principal-targeted invalidation. */
|
|
353
|
+
actorId?: string;
|
|
354
|
+
/** Optional resolved principal IDs for principal-targeted invalidation. */
|
|
355
|
+
principalIds?: string[];
|
|
356
|
+
}
|
|
357
|
+
/** WebSocket manager configuration (sourced from DatafnServerConfig.ws). */
|
|
358
|
+
interface WsManagerConfig {
|
|
359
|
+
/** Maximum total simultaneous WS connections. Default: 10,000 */
|
|
360
|
+
maxConnections?: number;
|
|
361
|
+
/** Maximum connections per namespace. Default: 100 */
|
|
362
|
+
maxConnectionsPerNamespace?: number;
|
|
363
|
+
/** Heartbeat ping interval in ms. Default: 30,000 */
|
|
364
|
+
heartbeatIntervalMs?: number;
|
|
365
|
+
/** Max time to wait for pong before closing dead connection. Default: 10,000 */
|
|
366
|
+
heartbeatTimeoutMs?: number;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
type Spv2ReadMode = "v1" | "v2" | "dual";
|
|
370
|
+
type Spv2WriteMode = "v2" | "dual";
|
|
371
|
+
interface Spv2MigrationRuntimeConfig {
|
|
372
|
+
readMode?: Spv2ReadMode;
|
|
373
|
+
writeMode?: Spv2WriteMode;
|
|
374
|
+
warnOnLegacyApi?: boolean;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Server configuration
|
|
379
|
+
*/
|
|
380
|
+
interface DatafnServerConfig<TContext = any> {
|
|
381
|
+
/** DataFn schema (will be validated at startup) */
|
|
382
|
+
schema: DatafnSchema;
|
|
383
|
+
/** Database adapter (required for persistence) */
|
|
384
|
+
db?: Adapter;
|
|
385
|
+
/** Optional plugins */
|
|
386
|
+
plugins?: DatafnPlugin[];
|
|
387
|
+
/** Optional authorization callback */
|
|
388
|
+
authorize?: (ctx: TContext, action: "status" | "query" | "mutation" | "transact" | "seed" | "clone" | "pull" | "push" | "reconcile" | "search", payload: unknown) => Promise<boolean> | boolean;
|
|
389
|
+
/** Optional limits configuration */
|
|
390
|
+
limits?: {
|
|
391
|
+
maxLimit?: number;
|
|
392
|
+
maxTransactSteps?: number;
|
|
393
|
+
maxPayloadBytes?: number;
|
|
394
|
+
/** Max changes returned per pull request. Default: 1000. */
|
|
395
|
+
maxPullLimit?: number;
|
|
396
|
+
/** VAL-002: Max select tokens per query (default 50) */
|
|
397
|
+
maxSelectTokens?: number;
|
|
398
|
+
/** VAL-003: Max filter keys per nesting level (default 20) */
|
|
399
|
+
maxFilterKeysPerLevel?: number;
|
|
400
|
+
/** VAL-004: Max sort fields (default 10) */
|
|
401
|
+
maxSortFields?: number;
|
|
402
|
+
/** VAL-005: Max aggregations (default 20) */
|
|
403
|
+
maxAggregations?: number;
|
|
404
|
+
/** VAL-006: Max ID length (default 255) */
|
|
405
|
+
maxIdLength?: number;
|
|
406
|
+
/** FIX-SEC-006: Max batch size for push/mutation endpoints (default 500) */
|
|
407
|
+
maxBatchSize?: number;
|
|
408
|
+
/** FIX-SRV-003: Max in-flight query concurrency for batch queries (default 20) */
|
|
409
|
+
maxBatchQueryConcurrency?: number;
|
|
410
|
+
};
|
|
411
|
+
/**
|
|
412
|
+
* VAL-009: Debug mode for validation error messages.
|
|
413
|
+
* When false, error messages are generic (no field names or schema details).
|
|
414
|
+
* Default: process.env.NODE_ENV !== 'production'
|
|
415
|
+
*/
|
|
416
|
+
debug?: boolean;
|
|
417
|
+
/**
|
|
418
|
+
* VAL-001: Allow queries/mutations on resources with no authorization policy.
|
|
419
|
+
* When false (default), resources without a policy return FORBIDDEN.
|
|
420
|
+
* Set to true only for development/testing.
|
|
421
|
+
*/
|
|
422
|
+
allowUnknownResources?: boolean;
|
|
423
|
+
/** Optional server time provider (for testing) */
|
|
424
|
+
getServerTime?: () => number;
|
|
425
|
+
/**
|
|
426
|
+
* Optional flag to enable REST endpoint generation (default: false)
|
|
427
|
+
* When true, generates REST wrappers:
|
|
428
|
+
* - GET /datafn/resources/:resource (query wrapper)
|
|
429
|
+
* - POST /datafn/resources/:resource (insert/merge wrapper)
|
|
430
|
+
* - PATCH /datafn/resources/:resource/:id (merge wrapper)
|
|
431
|
+
* - DELETE /datafn/resources/:resource/:id (delete wrapper)
|
|
432
|
+
*/
|
|
433
|
+
rest?: boolean;
|
|
434
|
+
/**
|
|
435
|
+
* Namespace provider for per-request data isolation.
|
|
436
|
+
* Returns the namespace string used to scope all data operations.
|
|
437
|
+
* Without this, all data shares the default "datafn" namespace.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```typescript
|
|
441
|
+
* namespaceProvider: {
|
|
442
|
+
* getNamespace: (ctx) => ns(ctx.orgId, ctx.userId),
|
|
443
|
+
* getActorId: (ctx) => ctx.userId,
|
|
444
|
+
* }
|
|
445
|
+
* ```
|
|
446
|
+
*/
|
|
447
|
+
namespaceProvider?: {
|
|
448
|
+
getNamespace: (ctx: TContext) => string | Promise<string>;
|
|
449
|
+
/** Optional actor ID for audit attribution (separate from isolation). */
|
|
450
|
+
getActorId?: (ctx: TContext) => string | Promise<string>;
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Optional Redis adapter for atomic operations (serverSeq, rate limiting, caching).
|
|
454
|
+
* When provided with appropriate dbMapping, enables high-performance atomic operations.
|
|
455
|
+
*
|
|
456
|
+
* @example
|
|
457
|
+
* ```typescript
|
|
458
|
+
* redis: myRedisAdapter,
|
|
459
|
+
* dbMapping: { serverseq: "redis" }
|
|
460
|
+
* ```
|
|
461
|
+
*/
|
|
462
|
+
redis?: RedisAdapter;
|
|
463
|
+
/**
|
|
464
|
+
* Optional KV store adapter for simple key-value operations.
|
|
465
|
+
* Must support `incr()` to be used for serverSeq generation.
|
|
466
|
+
*
|
|
467
|
+
* @example
|
|
468
|
+
* ```typescript
|
|
469
|
+
* kvStore: myKVAdapter,
|
|
470
|
+
* dbMapping: { serverseq: "kv" }
|
|
471
|
+
* ```
|
|
472
|
+
*/
|
|
473
|
+
kvStore?: KVStoreAdapter;
|
|
474
|
+
/**
|
|
475
|
+
* Database mapping configuration - specifies which database to use for each feature.
|
|
476
|
+
* Defaults to using the main database ("db") for all features.
|
|
477
|
+
*
|
|
478
|
+
* @example
|
|
479
|
+
* ```typescript
|
|
480
|
+
* dbMapping: {
|
|
481
|
+
* serverseq: "redis", // Use Redis for serverSeq (atomic INCR)
|
|
482
|
+
* ratelimiting: "redis", // Use Redis for rate limiting
|
|
483
|
+
* cache: "kv", // Use KV store for caching
|
|
484
|
+
* }
|
|
485
|
+
* ```
|
|
486
|
+
*/
|
|
487
|
+
dbMapping?: DbMapping;
|
|
488
|
+
/**
|
|
489
|
+
* Row-level namespace isolation configuration.
|
|
490
|
+
* - Explicitly `false` → disabled.
|
|
491
|
+
* - Object → used as-is for wrapping configuration.
|
|
492
|
+
*/
|
|
493
|
+
rowLevelNamespace?: false | RowLevelNamespaceConfig;
|
|
494
|
+
/** Data retention configuration for __datafn_changes and __datafn_idempotency tables. */
|
|
495
|
+
retention?: RetentionConfig;
|
|
496
|
+
/** Rate limiting configuration (RATE-001 through RATE-005). */
|
|
497
|
+
rateLimit?: RateLimitConfig<TContext>;
|
|
498
|
+
/** Observability configuration (OBS-001 through OBS-004). */
|
|
499
|
+
observability?: ObservabilityConfig;
|
|
500
|
+
/**
|
|
501
|
+
* WebSocket limits and heartbeat configuration.
|
|
502
|
+
* SCA-005: maxConnections / maxConnectionsPerNamespace
|
|
503
|
+
* REL-007: heartbeatIntervalMs / heartbeatTimeoutMs
|
|
504
|
+
*/
|
|
505
|
+
ws?: WsManagerConfig;
|
|
506
|
+
/**
|
|
507
|
+
* Graceful shutdown drain timeout in ms. Default: 10,000.
|
|
508
|
+
* REL-009: Server waits up to this long for in-flight requests to complete.
|
|
509
|
+
*/
|
|
510
|
+
shutdownTimeoutMs?: number;
|
|
511
|
+
/**
|
|
512
|
+
* LOG-001: Pluggable logger. Default: console-based (JSON in prod, pretty in dev).
|
|
513
|
+
*/
|
|
514
|
+
logger?: DatafnLogger;
|
|
515
|
+
/**
|
|
516
|
+
* COMP-001: SPV2 migration compatibility flags.
|
|
517
|
+
* - readMode: v2 (default), dual, or v1 (rollback mode)
|
|
518
|
+
* - writeMode: v2 (default) or dual
|
|
519
|
+
* - warnOnLegacyApi: emit deterministic deprecation warnings for shareWith.userId
|
|
520
|
+
*/
|
|
521
|
+
spv2Migration?: Spv2MigrationRuntimeConfig;
|
|
522
|
+
/**
|
|
523
|
+
* Optional search provider for full-text and semantic search queries.
|
|
524
|
+
* When provided, search queries are routed to this provider instead of requiring a searchfn plugin.
|
|
525
|
+
*/
|
|
526
|
+
searchProvider?: SearchProvider;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Server instance
|
|
530
|
+
*/
|
|
531
|
+
interface DatafnServer<TContext = any> {
|
|
532
|
+
router: Router<TContext>;
|
|
533
|
+
search(params: CrossResourceSearchParams & {
|
|
534
|
+
namespace?: string;
|
|
535
|
+
}, ctx?: TContext): Promise<SearchResult>;
|
|
536
|
+
websocketHandler: {
|
|
537
|
+
/** SEC-001: addClient requires auth context. Reject unauthenticated connections with close code 4401 before calling. */
|
|
538
|
+
/** SCA-005: Returns false (and closes with code 4503) when connection limits are exceeded. */
|
|
539
|
+
addClient(client: WebSocketClient, authContext: WsAuthContext): boolean;
|
|
540
|
+
removeClient(client: WebSocketClient): void;
|
|
541
|
+
handleMessage(client: WebSocketClient, data: string): void;
|
|
542
|
+
/** REL-007: Called by WS transport on native pong frame receipt. */
|
|
543
|
+
handlePong(client: WebSocketClient): void;
|
|
544
|
+
};
|
|
545
|
+
/**
|
|
546
|
+
* Graceful shutdown:
|
|
547
|
+
* 1. Rejects new requests with 503
|
|
548
|
+
* 2. Sends WS close frame 1001 to all clients
|
|
549
|
+
* 3. Waits for in-flight requests to complete (up to shutdownTimeoutMs)
|
|
550
|
+
* 4. Clears timers
|
|
551
|
+
* REL-009
|
|
552
|
+
*/
|
|
553
|
+
close(): Promise<void>;
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Create a DataFn server
|
|
557
|
+
*/
|
|
558
|
+
declare function createDatafnServer<TContext = any>(config: DatafnServerConfig<TContext>): Promise<DatafnServer<TContext>>;
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* GET /datafn/status endpoint
|
|
562
|
+
* Returns server metadata, capabilities, limits, and schema hash
|
|
563
|
+
*/
|
|
564
|
+
|
|
565
|
+
interface StatusResult {
|
|
566
|
+
schemaHash: string;
|
|
567
|
+
capabilities: string[];
|
|
568
|
+
limits: {
|
|
569
|
+
maxLimit: number;
|
|
570
|
+
maxTransactSteps?: number;
|
|
571
|
+
maxPayloadBytes?: number;
|
|
572
|
+
maxPullLimit?: number;
|
|
573
|
+
};
|
|
574
|
+
serverTimeMs: number;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
export { ChainedSequenceStore, type CrossResourceSearchParams, DatabaseSequenceStore, type DatafnServer, type DatafnServerConfig, type DbMapping, KVSequenceStore, RedisSequenceStore, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type StatusResult, createDatafnServer, createSequenceStore };
|