@datafn/server 0.0.3 → 0.1.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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,10 @@
1
- import { DatafnSchema, DatafnPlugin } from '@datafn/core/types';
2
- import { Router } from '@superfunctions/http';
3
- import { Adapter, KVStoreAdapter, RedisAdapter, RowLevelNamespaceConfig } from '@superfunctions/db';
1
+ import { DatafnPlugin, DatafnSchema as DatafnSchema$1 } from '@datafn/core';
2
+ import { ObservationEvent, ObservabilityInput, ObservabilityConfigInput } from '@superfunctions/observability';
3
+ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types';
4
+ import { Route, Router } from '@superfunctions/http';
5
+ import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
6
+ import { DatafnError } from '@datafn/core/errors';
7
+ export { DatafnPlacementConstraint, DatafnPlacementConstraintContext, DatafnPlacementDecision, DatafnPlacementDecisionSource, DatafnPlacementLocation, DatafnPlacementRankingInput, DatafnPlacementRegionCandidate, DatafnPlacementSelectionInput, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, selectDatafnPlacementRegion } from './placement.js';
4
8
 
5
9
  /**
6
10
  * SearchProvider interface for server-side search integration.
@@ -18,6 +22,8 @@ interface SearchProvider {
18
22
  prefix?: boolean;
19
23
  fuzzy?: boolean | number;
20
24
  fieldBoosts?: Record<string, number>;
25
+ namespaceFilter?: string[];
26
+ regionFilter?: string[];
21
27
  signal?: AbortSignal;
22
28
  }): Promise<string[]>;
23
29
  searchAll?(params: {
@@ -29,6 +35,8 @@ interface SearchProvider {
29
35
  prefix?: boolean;
30
36
  fuzzy?: boolean | number;
31
37
  fieldBoosts?: Record<string, number>;
38
+ namespaceFilter?: string[];
39
+ regionFilter?: string[];
32
40
  signal?: AbortSignal;
33
41
  }): Promise<Array<{
34
42
  resource: string;
@@ -60,6 +68,288 @@ interface DatafnLogger {
60
68
  debug(message: string, context?: Record<string, unknown>): void;
61
69
  }
62
70
 
71
+ type DatafnPlacementState = "active" | "moving" | "tombstoned";
72
+ interface DatafnNamespacePlacement {
73
+ namespace: string;
74
+ regionId: string;
75
+ epoch: number;
76
+ state: DatafnPlacementState;
77
+ updatedAt: string;
78
+ cacheExpiresAt?: string;
79
+ destinationRef?: string;
80
+ movingToRegionId?: string;
81
+ previousRegionId?: string;
82
+ migration?: DatafnNamespaceMigrationState;
83
+ }
84
+ interface DatafnNamespaceMigrationState {
85
+ phase: "moving" | "resume-source" | "resume-target";
86
+ sourceRegionId: string;
87
+ targetRegionId: string;
88
+ sourceEpoch: number;
89
+ movingEpoch: number;
90
+ recoveryFence?: number;
91
+ recoveryOwnerId?: string;
92
+ recoveryLeaseExpiresAt?: number;
93
+ sourceDestinationRef?: string;
94
+ targetDestinationRef?: string;
95
+ sourcePreviousRegionId?: string;
96
+ }
97
+ interface DatafnPlacementWriteResult {
98
+ updated: boolean;
99
+ placement: DatafnNamespacePlacement;
100
+ }
101
+ /**
102
+ * Authoritative namespace-placement directory.
103
+ *
104
+ * Implementations must make get, putIfAbsent, and compareAndSet linearizable
105
+ * for one namespace. Permission-directory projections deliberately use a
106
+ * separate adapter and never decide database ownership.
107
+ */
108
+ interface DatafnPlacementDirectoryAdapter {
109
+ get(namespace: string): Promise<DatafnNamespacePlacement | null>;
110
+ putIfAbsent(placement: DatafnNamespacePlacement): Promise<{
111
+ inserted: boolean;
112
+ placement: DatafnNamespacePlacement;
113
+ }>;
114
+ compareAndSet(input: {
115
+ namespace: string;
116
+ expectedEpoch: number;
117
+ expectedState?: DatafnPlacementState;
118
+ next: DatafnNamespacePlacement;
119
+ }): Promise<DatafnPlacementWriteResult>;
120
+ }
121
+ interface DatafnRoutingAssertionClaims {
122
+ version: 1;
123
+ namespace: string;
124
+ regionId: string;
125
+ epoch: number;
126
+ requestId: string;
127
+ method: string;
128
+ path: string;
129
+ audience: string;
130
+ issuedAt: number;
131
+ expiresAt: number;
132
+ nonce: string;
133
+ bodyDigest?: string;
134
+ }
135
+ interface DatafnRoutingAssertionSigner {
136
+ sign(claims: DatafnRoutingAssertionClaims): Promise<string> | string;
137
+ }
138
+ interface DatafnRoutingAssertionVerifier {
139
+ verify(assertion: string): Promise<DatafnRoutingAssertionClaims> | DatafnRoutingAssertionClaims;
140
+ }
141
+ /** Atomically claims a signed request nonce until the assertion expires. */
142
+ interface DatafnRoutingReplayStore {
143
+ claim(nonce: string, expiresAt: number): Promise<boolean> | boolean;
144
+ }
145
+ type DatafnRoutingEventType = "placement_lookup" | "cache_hit" | "forward" | "mismatch" | "retry" | "moving" | "directory_unavailable" | "destination_unavailable" | "epoch_conflict" | "assertion_invalid";
146
+ interface DatafnRoutingEvent {
147
+ type: DatafnRoutingEventType;
148
+ requestId?: string;
149
+ namespaceHash?: string;
150
+ sourceRegion?: string;
151
+ targetRegion?: string;
152
+ epoch?: number;
153
+ state?: DatafnPlacementState;
154
+ attempt?: number;
155
+ retryable?: boolean;
156
+ durationMs?: number;
157
+ outcome?: string;
158
+ }
159
+ interface DatafnPlacementRuntimeConfig {
160
+ directory: DatafnPlacementDirectoryAdapter;
161
+ requireRoutingAssertion?: boolean;
162
+ assertionVerifier?: DatafnRoutingAssertionVerifier;
163
+ replayStore?: DatafnRoutingReplayStore;
164
+ assertionAudience?: string;
165
+ assertionHeader?: string;
166
+ /** Maximum signed request body size. Defaults to 5 MiB. */
167
+ maxBodyBytes?: number;
168
+ now?: () => number;
169
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
170
+ }
171
+ declare const DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
172
+ declare const DATAFN_ROUTING_INTERNAL_HEADERS: readonly ["x-datafn-routing-assertion", "x-datafn-routing-namespace", "x-datafn-routing-region", "x-datafn-routing-epoch"];
173
+ declare class DatafnRoutingError extends Error {
174
+ readonly code: "DATAFN_PLACEMENT_NOT_FOUND" | "DATAFN_PLACEMENT_UNAVAILABLE" | "DATAFN_REGION_MISMATCH" | "DATAFN_NAMESPACE_MOVING" | "DATAFN_CELL_UNAVAILABLE" | "DATAFN_ROUTING_ASSERTION_INVALID" | "DATAFN_ROUTING_RETRY_EXHAUSTED" | "DATAFN_PAYLOAD_TOO_LARGE";
175
+ readonly status: number;
176
+ readonly retryable: boolean;
177
+ readonly executionStarted: boolean;
178
+ readonly placement?: DatafnNamespacePlacement;
179
+ readonly internal: boolean;
180
+ constructor(input: {
181
+ code: DatafnRoutingError["code"];
182
+ message: string;
183
+ status: number;
184
+ retryable: boolean;
185
+ placement?: DatafnNamespacePlacement;
186
+ internal?: boolean;
187
+ executionStarted?: boolean;
188
+ });
189
+ toResponse(): Response;
190
+ }
191
+ declare function createConditionalKvDatafnPlacementDirectory(store: ConditionalKVStoreAdapter, options: {
192
+ /** Explicit acknowledgement that authoritative reads are linearizable. */
193
+ consistencyModel: "linearizable";
194
+ keyPrefix?: string;
195
+ }): DatafnPlacementDirectoryAdapter;
196
+ declare function createMemoryDatafnPlacementDirectory(): DatafnPlacementDirectoryAdapter;
197
+ declare function claimDatafnNamespacePlacement(input: {
198
+ directory: DatafnPlacementDirectoryAdapter;
199
+ namespace: string;
200
+ regionId: string;
201
+ destinationRef?: string;
202
+ cacheExpiresAt?: string;
203
+ now?: () => number;
204
+ }): Promise<{
205
+ claimed: boolean;
206
+ placement: DatafnNamespacePlacement;
207
+ }>;
208
+ interface DatafnPlacementValidationResult {
209
+ placement: DatafnNamespacePlacement;
210
+ assertion?: DatafnRoutingAssertionClaims;
211
+ }
212
+ declare function validateDatafnPlacement(input: {
213
+ namespace: string;
214
+ regionId: string;
215
+ runtime: DatafnPlacementRuntimeConfig;
216
+ request?: Request;
217
+ /** Trusted in-process execution has no externally supplied assertion. */
218
+ trustedInternal?: boolean;
219
+ }): Promise<DatafnPlacementValidationResult>;
220
+ interface DatafnGatewayCellRegistry<TTarget> {
221
+ resolve(input: {
222
+ regionId: string;
223
+ destinationRef?: string;
224
+ placement: DatafnNamespacePlacement;
225
+ }): Promise<TTarget> | TTarget;
226
+ }
227
+ interface DatafnGatewayDispatcher<TTarget> {
228
+ dispatch(input: {
229
+ target: TTarget;
230
+ request: Request;
231
+ assertion: string;
232
+ placement: DatafnNamespacePlacement;
233
+ attempt: 0 | 1;
234
+ }): Promise<Response>;
235
+ }
236
+ interface DatafnGatewayRouterConfig<TTarget> {
237
+ directory: DatafnPlacementDirectoryAdapter;
238
+ deriveNamespace(request: Request): Promise<string> | string;
239
+ cellRegistry: DatafnGatewayCellRegistry<TTarget>;
240
+ dispatcher: DatafnGatewayDispatcher<TTarget>;
241
+ assertionSigner: DatafnRoutingAssertionSigner;
242
+ assertionAudience?: string;
243
+ assertionTtlMs?: number;
244
+ cacheTtlMs?: number;
245
+ /** Maximum namespace placements retained by a gateway. Defaults to 10,000. */
246
+ maxCacheEntries?: number;
247
+ /** Maximum request body size accepted before dispatch. Defaults to 5 MiB. */
248
+ maxBodyBytes?: number;
249
+ now?: () => number;
250
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
251
+ }
252
+ interface DatafnGatewayRouter {
253
+ handle(request: Request): Promise<Response>;
254
+ invalidate(namespace: string): void;
255
+ clear(): void;
256
+ }
257
+ declare function createDatafnGatewayRouter<TTarget>(config: DatafnGatewayRouterConfig<TTarget>): DatafnGatewayRouter;
258
+ interface DatafnNamespaceMigrationHooks {
259
+ quiesceSource(input: DatafnNamespaceMigrationContext): Promise<void>;
260
+ drainPermissionDirectory(input: DatafnNamespaceMigrationContext): Promise<void>;
261
+ copyTenantData(input: DatafnNamespaceMigrationContext): Promise<void>;
262
+ validateTenantData(input: DatafnNamespaceMigrationContext): Promise<void>;
263
+ rebuildPermissionDirectory(input: DatafnNamespaceMigrationContext): Promise<void>;
264
+ warmTarget(input: DatafnNamespaceMigrationContext): Promise<void>;
265
+ resumeTarget(input: DatafnNamespaceMigrationContext): Promise<void>;
266
+ rollbackSource(input: DatafnNamespaceMigrationContext & {
267
+ cause: unknown;
268
+ }): Promise<void>;
269
+ }
270
+ interface DatafnNamespaceMigrationContext {
271
+ namespace: string;
272
+ sourceRegionId: string;
273
+ targetRegionId: string;
274
+ sourceEpoch: number;
275
+ movingEpoch: number;
276
+ /**
277
+ * Monotonic token that every external side-effect boundary must atomically
278
+ * compare and persist, rejecting lower tokens before applying the effect.
279
+ */
280
+ recoveryFence: number;
281
+ /** Durable lease owner paired with the monotonic recovery fence. */
282
+ recoveryOwnerId: string;
283
+ /** Live lease deadline; renewal updates this value while the hook is running. */
284
+ recoveryLeaseExpiresAt: number;
285
+ /** True when replaying idempotent hooks for a persisted recovery state. */
286
+ recovery?: boolean;
287
+ }
288
+ /**
289
+ * Minimal fenced move protocol. The directory enters `moving` before hooks run,
290
+ * so every cell fails closed while source writes are quiesced and data/outbox
291
+ * state is copied. A second CAS activates the target with explicit recovery
292
+ * state and a final CAS clears that state after the idempotent resume hook.
293
+ */
294
+ declare function migrateDatafnNamespace(input: {
295
+ directory: DatafnPlacementDirectoryAdapter;
296
+ namespace: string;
297
+ targetRegionId: string;
298
+ targetDestinationRef?: string;
299
+ hooks: DatafnNamespaceMigrationHooks;
300
+ now?: () => number;
301
+ /** Exclusive recovery lease duration. Defaults to 30 seconds. */
302
+ recoveryLeaseMs?: number;
303
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
304
+ }): Promise<DatafnNamespacePlacement>;
305
+ declare function createDatafnHmacRoutingAssertions(input: {
306
+ activeKeyId: string;
307
+ keys: Record<string, string | Uint8Array>;
308
+ now?: () => number;
309
+ clockSkewMs?: number;
310
+ }): DatafnRoutingAssertionSigner & DatafnRoutingAssertionVerifier;
311
+ /** In-memory replay protection for tests and single-process deployments. */
312
+ declare function createMemoryDatafnRoutingReplayStore(options?: {
313
+ now?: () => number;
314
+ }): DatafnRoutingReplayStore;
315
+ declare function withDatafnRoutingAssertion(request: Request, assertion: string, header?: string): Request;
316
+ declare function validateDatafnRoutingBodyLimit(value: number | undefined): number;
317
+
318
+ declare const DATAFN_MULTI_REGION_CAPABILITY: unique symbol;
319
+ interface DatafnMultiRegionDirectory {
320
+ store: IndexedDirectoryStoreAdapter;
321
+ }
322
+ interface DatafnMultiRegionPluginConfig {
323
+ regionId: string;
324
+ directory: IndexedDirectoryStoreAdapter | DatafnMultiRegionDirectory;
325
+ /**
326
+ * Optional authoritative namespace-placement runtime. When omitted, the
327
+ * plugin retains its existing permission-directory-only behavior.
328
+ */
329
+ placement?: DatafnPlacementRuntimeConfig;
330
+ }
331
+ interface DatafnMultiRegionRuntimeConfig {
332
+ regionId: string;
333
+ directory: IndexedDirectoryStoreAdapter;
334
+ placement?: DatafnPlacementRuntimeConfig;
335
+ }
336
+ interface DatafnPermissionDirectoryGrant {
337
+ id: string;
338
+ resourceType: string;
339
+ resourceNs: string;
340
+ resourceId: string | null;
341
+ principalId: string;
342
+ level?: string;
343
+ grantKind?: string;
344
+ sourceRef?: unknown;
345
+ grantedBy?: string;
346
+ grantedAt?: number;
347
+ revokedAt?: number | null;
348
+ resourceRegion: string;
349
+ }
350
+ declare function datafnMultiRegionPlugin(config: DatafnMultiRegionPluginConfig): DatafnPlugin & DatafnMultiRegionRuntimeConfig;
351
+ declare const createDatafnMultiRegionPlugin: typeof datafnMultiRegionPlugin;
352
+
63
353
  interface SearchResultItem {
64
354
  id: string;
65
355
  resource: string;
@@ -80,6 +370,7 @@ interface CrossResourceSearchParams {
80
370
  fieldBoosts?: Record<string, number>;
81
371
  filters?: Record<string, Record<string, unknown>>;
82
372
  select?: string[];
373
+ actorId?: string;
83
374
  signal?: AbortSignal;
84
375
  }
85
376
 
@@ -101,6 +392,51 @@ interface ExecutionTimingEvent {
101
392
  timestamp: string;
102
393
  }
103
394
 
395
+ type DataFnEventType = 'datafn.authorization.denied' | 'datafn.payload.rejected' | 'datafn.rate_limited' | 'datafn.request.failed' | 'datafn.retention.pruned' | 'datafn.retention.prune_failed';
396
+ type DataFnAction = 'status' | 'query' | 'mutation' | 'transact' | 'seed' | 'clone' | 'pull' | 'push' | 'reconcile' | 'search';
397
+ interface DataFnRequestEventMetadata extends Record<string, unknown> {
398
+ action?: DataFnAction;
399
+ path?: string;
400
+ method?: string;
401
+ }
402
+ interface DataFnAuthorizationDeniedMetadata extends DataFnRequestEventMetadata {
403
+ reason: 'internal-resource' | 'plugin-authorize' | 'authorize-callback';
404
+ }
405
+ interface DataFnPayloadRejectedMetadata extends DataFnRequestEventMetadata {
406
+ reason: 'payload-too-large' | 'invalid-json';
407
+ code: string;
408
+ }
409
+ interface DataFnRateLimitedMetadata extends DataFnRequestEventMetadata {
410
+ reason: 'rate-limit';
411
+ }
412
+ interface DataFnRequestFailedMetadata extends DataFnRequestEventMetadata {
413
+ error: string;
414
+ }
415
+ interface DataFnRetentionPrunedMetadata extends Record<string, unknown> {
416
+ mode: 'startup' | 'periodic';
417
+ target: 'changes' | 'idempotency';
418
+ deleted: number;
419
+ }
420
+ interface DataFnRetentionPruneFailedMetadata extends Record<string, unknown> {
421
+ mode: 'startup' | 'periodic';
422
+ error: string;
423
+ }
424
+ type DataFnAuthorizationDeniedEvent = ObservationEvent<'datafn', 'datafn.authorization.denied', DataFnAuthorizationDeniedMetadata>;
425
+ type DataFnPayloadRejectedEvent = ObservationEvent<'datafn', 'datafn.payload.rejected', DataFnPayloadRejectedMetadata>;
426
+ type DataFnRateLimitedEvent = ObservationEvent<'datafn', 'datafn.rate_limited', DataFnRateLimitedMetadata>;
427
+ type DataFnRequestFailedEvent = ObservationEvent<'datafn', 'datafn.request.failed', DataFnRequestFailedMetadata>;
428
+ type DataFnRetentionPrunedEvent = ObservationEvent<'datafn', 'datafn.retention.pruned', DataFnRetentionPrunedMetadata>;
429
+ type DataFnRetentionPruneFailedEvent = ObservationEvent<'datafn', 'datafn.retention.prune_failed', DataFnRetentionPruneFailedMetadata>;
430
+ interface DataFnEventMap {
431
+ 'datafn.authorization.denied': DataFnAuthorizationDeniedEvent;
432
+ 'datafn.payload.rejected': DataFnPayloadRejectedEvent;
433
+ 'datafn.rate_limited': DataFnRateLimitedEvent;
434
+ 'datafn.request.failed': DataFnRequestFailedEvent;
435
+ 'datafn.retention.pruned': DataFnRetentionPrunedEvent;
436
+ 'datafn.retention.prune_failed': DataFnRetentionPruneFailedEvent;
437
+ }
438
+ type DataFnEvent = DataFnEventMap[DataFnEventType];
439
+
104
440
  interface RetentionConfig {
105
441
  /** Number of days to retain change log entries. Default: unlimited. */
106
442
  changeLogDays?: number;
@@ -114,31 +450,32 @@ interface RetentionConfig {
114
450
  interface RateLimitConfig<TContext = any> {
115
451
  /** Enable rate limiting. Default: false. */
116
452
  enabled: boolean;
453
+ /** Store guarantee for rate limiting. Default: "strict" when stores.atomicKv exists, otherwise "local". */
454
+ mode?: "strict" | "best-effort" | "local";
117
455
  /** Max requests per window per client. Default: 100. */
118
456
  maxRequests?: number;
119
457
  /** Window duration in seconds. Default: 60. */
120
458
  windowSeconds?: number;
121
459
  /** Per-endpoint overrides */
122
- endpoints?: Partial<Record<'query' | 'mutation' | 'transact' | 'push' | 'pull' | 'clone' | 'reconcile' | 'seed', {
460
+ endpoints?: Partial<Record<'query' | 'mutation' | 'transact' | 'push' | 'pull' | 'clone' | 'reconcile' | 'seed' | 'search', {
123
461
  maxRequests: number;
124
462
  windowSeconds: number;
125
463
  }>>;
126
464
  /** Key extractor for identifying clients. Default: uses authContext userId or "anonymous". */
127
465
  keyExtractor?: (ctx: TContext) => string | Promise<string>;
128
466
  }
129
- interface ObservabilityConfig {
467
+ type ObservabilityConfig = ObservabilityInput<DataFnEvent> | (ObservabilityConfigInput<DataFnEvent> & {
130
468
  /** Emit execution timing events. Default: false. */
131
469
  timing?: boolean;
132
470
  /** Custom timing event handler. Default: console.debug. */
133
471
  onTiming?: (event: ExecutionTimingEvent) => void;
134
- }
472
+ });
135
473
 
136
474
  /**
137
475
  * SequenceStore - Pluggable sequence generation for serverSeq
138
476
  *
139
477
  * Supports multiple backends:
140
- * - Redis: Uses atomic INCR for high-performance sequence generation
141
- * - KV Store: Uses atomic incr if available
478
+ * - Atomic store: Uses atomic INCR for high-performance sequence generation
142
479
  * - Database: Uses CAS retry loop
143
480
  */
144
481
 
@@ -146,40 +483,35 @@ interface ObservabilityConfig {
146
483
  * Interface for sequence generation stores
147
484
  */
148
485
  interface SequenceStore {
486
+ /** Initialize durable backing storage before an enclosing transaction. */
487
+ ensureReady?(): Promise<void>;
149
488
  /** Get and increment sequence atomically, returns the next value */
150
489
  getNext(namespace: string): Promise<number>;
151
490
  /** Get and increment sequence atomically by count, returns array of contiguous values */
152
491
  getNextN(namespace: string, count: number): Promise<number[]>;
153
492
  /** Get current sequence value (without incrementing) */
154
493
  getCurrent(namespace: string): Promise<number>;
494
+ /** Ensure the current sequence is at least minSeq. */
495
+ ensureMinSeq?(namespace: string, minSeq: number): Promise<void>;
496
+ /** Return an equivalent store bound to a transaction-scoped adapter. */
497
+ withDb?(db: Adapter): SequenceStore;
155
498
  /** Check if the store is healthy/available */
156
499
  isHealthy?(): Promise<boolean>;
157
500
  }
158
501
  /**
159
- * Redis-based sequence store using atomic INCR
502
+ * Atomic-store-based sequence store using atomic INCR
160
503
  */
161
- declare class RedisSequenceStore implements SequenceStore {
162
- private redis;
504
+ declare class AtomicSequenceStore implements SequenceStore {
505
+ private atomicStore;
163
506
  private keyPrefix;
164
- constructor(redis: RedisAdapter);
507
+ constructor(atomicStore: AtomicKVStoreAdapter);
165
508
  private getKey;
166
509
  getNext(namespace: string): Promise<number>;
167
510
  getNextN(namespace: string, count: number): Promise<number[]>;
168
511
  getCurrent(namespace: string): Promise<number>;
512
+ ensureMinSeq(namespace: string, minSeq: number): Promise<void>;
169
513
  isHealthy(): Promise<boolean>;
170
514
  }
171
- /**
172
- * KV Store-based sequence store using atomic incr
173
- */
174
- declare class KVSequenceStore implements SequenceStore {
175
- private kvStore;
176
- private keyPrefix;
177
- constructor(kvStore: KVStoreAdapter);
178
- private getKey;
179
- getNext(namespace: string): Promise<number>;
180
- getNextN(namespace: string, count: number): Promise<number[]>;
181
- getCurrent(namespace: string): Promise<number>;
182
- }
183
515
  /**
184
516
  * Database-based sequence store using CAS retry loop
185
517
  * Uses the main database adapter
@@ -188,7 +520,9 @@ declare class DatabaseSequenceStore implements SequenceStore {
188
520
  private db;
189
521
  private logger?;
190
522
  private ensured;
191
- constructor(db: Adapter, logger?: DatafnLogger | undefined);
523
+ constructor(db: Adapter, logger?: DatafnLogger | undefined, ensured?: boolean);
524
+ withDb(db: Adapter): SequenceStore;
525
+ ensureReady(): Promise<void>;
192
526
  /**
193
527
  * DI-003: Ensure next_server_seq in meta is at least (minSeq + 1).
194
528
  * Called by ChainedSequenceStore during primary→database failover to prevent duplicate sequences.
@@ -207,15 +541,19 @@ declare class ChainedSequenceStore implements SequenceStore {
207
541
  private primary;
208
542
  private secondary;
209
543
  private logger?;
210
- /** DI-003: Track last-issued seq per namespace from the primary store */
211
544
  private lastKnownPrimarySeq;
212
- constructor(primary: SequenceStore, secondary: SequenceStore, logger?: DatafnLogger | undefined);
545
+ /** DI-003: Track last-issued seq per namespace from the primary store */
546
+ constructor(primary: SequenceStore, secondary: SequenceStore, logger?: DatafnLogger | undefined, lastKnownPrimarySeq?: Map<string, number>);
547
+ withDb(db: Adapter): SequenceStore;
548
+ ensureReady(): Promise<void>;
213
549
  getNext(namespace: string): Promise<number>;
214
550
  /**
215
551
  * DI-003: Sync the secondary (DB) store to start from at least lastKnownPrimarySeq+1.
216
- * Prevents duplicate sequences after Redis→DB failover.
552
+ * Prevents duplicate sequences after atomic-store→DB failover.
217
553
  */
218
554
  private syncSecondaryOnFailover;
555
+ private syncPrimaryIfBehindSecondary;
556
+ private persistPrimaryHighWater;
219
557
  getNextN(namespace: string, count: number): Promise<number[]>;
220
558
  getCurrent(namespace: string): Promise<number>;
221
559
  isHealthy(): Promise<boolean>;
@@ -223,22 +561,16 @@ declare class ChainedSequenceStore implements SequenceStore {
223
561
  /**
224
562
  * Database mapping configuration for routing operations to different databases
225
563
  */
226
- interface DbMapping {
227
- /** Which database to use for serverSeq generation (default: "db") */
228
- serverseq?: "redis" | "kv" | "db";
229
- /** Which database to use for rate limiting (default: "db") */
230
- ratelimiting?: "redis" | "kv" | "db";
231
- /** Which database to use for caching (default: "db") */
232
- cache?: "redis" | "kv" | "db";
564
+ interface SequenceStorePolicy {
565
+ mode?: "strict" | "db";
233
566
  }
234
567
  /**
235
568
  * Create appropriate sequence store based on configuration
236
569
  */
237
570
  declare function createSequenceStore(config: {
238
571
  db?: Adapter;
239
- redis?: RedisAdapter;
240
- kvStore?: KVStoreAdapter;
241
- dbMapping?: DbMapping;
572
+ stores?: RuntimeStores;
573
+ policy?: SequenceStorePolicy;
242
574
  logger?: DatafnLogger;
243
575
  }): SequenceStore | undefined;
244
576
 
@@ -271,6 +603,10 @@ interface WsAuthContext {
271
603
  actorId?: string;
272
604
  /** Optional resolved principal IDs for principal-targeted invalidation. */
273
605
  principalIds?: string[];
606
+ /** Owning region pinned during a routed handshake. */
607
+ regionId?: string;
608
+ /** Placement epoch pinned during a routed handshake. */
609
+ routingEpoch?: number;
274
610
  }
275
611
  /** WebSocket manager configuration (sourced from DatafnServerConfig.ws). */
276
612
  interface WsManagerConfig {
@@ -284,6 +620,32 @@ interface WsManagerConfig {
284
620
  heartbeatTimeoutMs?: number;
285
621
  }
286
622
 
623
+ type DatafnExecutorAction = "query" | "mutation" | "transact" | "search";
624
+ declare class DatafnExecutorError extends Error {
625
+ readonly code: string;
626
+ readonly details?: unknown;
627
+ readonly status: number;
628
+ constructor(error: DatafnError | {
629
+ code: string;
630
+ message: string;
631
+ details?: unknown;
632
+ }, status?: number);
633
+ }
634
+ /**
635
+ * Transport-neutral DataFn execution surface.
636
+ *
637
+ * Every operation enters the same route handlers used by HTTP, including schema
638
+ * validation, field authorization, namespace/actor resolution, hooks,
639
+ * idempotency, limits, configured authorization, and rate limiting.
640
+ */
641
+ interface DatafnExecutor<TContext = unknown> {
642
+ readonly schema: DatafnSchema;
643
+ query<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
644
+ mutate<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
645
+ transact<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
646
+ search(payload: CrossResourceSearchParams, context?: TContext): Promise<SearchResult>;
647
+ }
648
+
287
649
  type Spv2ReadMode = "v1" | "v2" | "dual";
288
650
  type Spv2WriteMode = "v2" | "dual";
289
651
  interface Spv2MigrationRuntimeConfig {
@@ -292,69 +654,224 @@ interface Spv2MigrationRuntimeConfig {
292
654
  warnOnLegacyApi?: boolean;
293
655
  }
294
656
 
657
+ type DatafnPublicLinkShareLevel = "viewer" | "editor" | "owner";
658
+ type DatafnPublicLinkShareScope = "record" | "resource";
659
+ interface DatafnPublicLinkRecord {
660
+ id: string;
661
+ principalId: string;
662
+ resource: string;
663
+ recordId?: string | null;
664
+ scope: DatafnPublicLinkShareScope;
665
+ level: DatafnPublicLinkShareLevel;
666
+ tokenHash: string;
667
+ expiresAt?: number | null;
668
+ revokedAt?: number | null;
669
+ resourceRegion?: string;
670
+ __ns?: string;
671
+ createdAt?: number;
672
+ createdBy?: string;
673
+ updatedAt?: number;
674
+ updatedBy?: string;
675
+ }
676
+ interface DatafnPublicLinkPrincipal {
677
+ linkId: string;
678
+ principalId: string;
679
+ actorId: string;
680
+ namespace: string;
681
+ resourceRegion?: string;
682
+ resource: string;
683
+ recordId?: string | null;
684
+ scope: DatafnPublicLinkShareScope;
685
+ level: DatafnPublicLinkShareLevel;
686
+ }
687
+ interface CreateDatafnPublicLinkInput {
688
+ resource: string;
689
+ recordId?: string | null;
690
+ scope?: DatafnPublicLinkShareScope;
691
+ level?: DatafnPublicLinkShareLevel;
692
+ expiresAt?: number | string | null;
693
+ }
694
+ interface DatafnPublicLinkGrant {
695
+ id: string;
696
+ token: string;
697
+ principalId: string;
698
+ resource: string;
699
+ recordId: string | null;
700
+ scope: DatafnPublicLinkShareScope;
701
+ level: DatafnPublicLinkShareLevel;
702
+ }
703
+ /** Authorization input accepted by the public-links plugin. */
704
+ interface DatafnPublicLinkAuthorizationInput {
705
+ action: DataFnAction;
706
+ context: unknown;
707
+ payload: unknown;
708
+ }
709
+ interface DatafnPublicLinksPluginConfig<TSession = unknown> {
710
+ authenticateOwner?: (request: Request) => Promise<TSession | null> | TSession | null;
711
+ getOwnerActorId(session: TSession): string | undefined;
712
+ getOwnerNamespace(actorId: string, session: TSession): string | Promise<string>;
713
+ modelName?: string;
714
+ principalPrefix?: string;
715
+ tokenHeader?: string;
716
+ directory?: IndexedDirectoryStoreAdapter;
717
+ resourceRegion?: string;
718
+ }
719
+ interface DatafnPublicLinksPlugin<TSession = unknown> extends DatafnPlugin {
720
+ readonly modelName: string;
721
+ readonly tokenHeader: string;
722
+ readonly internalResources: readonly string[];
723
+ readonly permissionDirectoryRuntime?: DatafnMultiRegionRuntimeConfig;
724
+ readToken(request: Request): string | null;
725
+ principalId(linkId: string): string;
726
+ withSchema(schema: DatafnSchema$1): DatafnSchema$1;
727
+ resolve(database: Adapter, token: string | null | undefined): Promise<DatafnPublicLinkPrincipal | null>;
728
+ authorize(input: DatafnPublicLinkAuthorizationInput): boolean | undefined;
729
+ routes(input: {
730
+ database: Adapter;
731
+ crossNamespaceDatabase?: Adapter;
732
+ schema: DatafnSchema$1;
733
+ }): Route[];
734
+ }
735
+ declare class DatafnPublicLinkInputError extends Error {
736
+ readonly path: string;
737
+ constructor(message: string, path: string);
738
+ }
295
739
  /**
296
- * Server configuration
740
+ * Adds the DataFn public-link storage resource to a schema for database codegen.
741
+ */
742
+ declare function withDatafnPublicLinksSchema(schema: DatafnSchema$1, options?: {
743
+ modelName?: string;
744
+ }): DatafnSchema$1;
745
+ /**
746
+ * Creates DataFn-native public-link route and principal resolution support.
747
+ */
748
+ declare function createDatafnPublicLinksPlugin<TSession = unknown>(config: DatafnPublicLinksPluginConfig<TSession>): DatafnPublicLinksPlugin<TSession>;
749
+ /**
750
+ * Reads the DataFn public-link credential from a request.
751
+ */
752
+ declare function readDatafnPublicLinkToken(request: Request, tokenHeader?: string): string | null;
753
+ /**
754
+ * Resolves a DataFn public-link token to its principal and namespace.
755
+ */
756
+ declare function resolveDatafnPublicLink(database: Adapter, token: string | null | undefined, options?: {
757
+ modelName?: string;
758
+ principalPrefix?: string;
759
+ directory?: IndexedDirectoryStoreAdapter;
760
+ }): Promise<DatafnPublicLinkPrincipal | null>;
761
+
762
+ /** Per-request data available to DataFn route response hooks. */
763
+ interface DatafnRouteHookInput<TContext = any> {
764
+ action: DataFnAction;
765
+ request: Request;
766
+ context: TContext & {
767
+ parsedBody?: unknown;
768
+ };
769
+ payload: unknown;
770
+ response: Response;
771
+ }
772
+ /** Transforms a DataFn HTTP response after route execution. */
773
+ type DatafnRouteResponseHook<TContext = any> = (input: DatafnRouteHookInput<TContext>) => Response | Promise<Response>;
774
+ /** Header tuple entries accepted by DataFn route header hooks. */
775
+ type DatafnRouteHeaderEntries = [string, string][];
776
+ /** Header input accepted by DataFn route header hooks. */
777
+ type DatafnRouteHeaderInput = Headers | Record<string, string> | DatafnRouteHeaderEntries;
778
+ /** Static or computed response headers applied after DataFn route hooks. */
779
+ type DatafnRouteHeaders<TContext = any> = DatafnRouteHeaderInput | ((input: DatafnRouteHookInput<TContext>) => DatafnRouteHeaderInput | null | undefined | Promise<DatafnRouteHeaderInput | null | undefined>);
780
+ /** Route lifecycle hooks for framework-level DataFn HTTP behavior. */
781
+ interface DatafnRouteHooks<TContext = any> {
782
+ afterResponse?: DatafnRouteResponseHook<TContext> | readonly DatafnRouteResponseHook<TContext>[];
783
+ headers?: DatafnRouteHeaders<TContext>;
784
+ }
785
+ type DatafnPluginRoutePlacementResult = string | Response;
786
+ /**
787
+ * Placement declaration required for custom plugin routes in regional-cell
788
+ * mode. Returning a Response lets authentication/not-found handling stop
789
+ * before any regional database access.
790
+ */
791
+ interface DatafnPluginRoutePlacement<TContext = any> {
792
+ resolveNamespace(request: Request, context: TContext): DatafnPluginRoutePlacementResult | Promise<DatafnPluginRoutePlacementResult>;
793
+ /** Transfers validated resolver state from the body-safe clone to the handler request. */
794
+ bindHandlerRequest?(placementRequest: Request, handlerRequest: Request, context: TContext): void | Promise<void>;
795
+ }
796
+ type DatafnComposableRoute<TContext = any> = Route<TContext> & {
797
+ meta?: Route<TContext>["meta"] & {
798
+ datafnPlacement?: "none" | DatafnPluginRoutePlacement<TContext>;
799
+ };
800
+ };
801
+ /** Data provided to server plugins before a DataFn action is authorized and executed. */
802
+ interface DatafnPluginAuthorizationInput<TContext = any> {
803
+ action: DataFnAction;
804
+ request: Request;
805
+ context: TContext & {
806
+ parsedBody?: unknown;
807
+ };
808
+ payload: unknown;
809
+ }
810
+ /** Server plugin authorization decisions are fail-closed only when false or an error is returned. */
811
+ type DatafnPluginAuthorizationResult = boolean | void;
812
+ /**
813
+ * Runtime configuration for a DataFn HTTP server.
297
814
  */
298
815
  interface DatafnServerConfig<TContext = any> {
299
- /** DataFn schema (will be validated at startup) */
816
+ /** DataFn schema used to validate resources, relations, fields, permissions, and generated routes at startup. */
300
817
  schema: DatafnSchema;
301
- /** Database adapter (required for persistence) */
818
+ /** Database adapter used for resource persistence, query execution, mutations, sync change logs, and internal tables. */
819
+ database?: Adapter;
820
+ /** @deprecated Use `database`. Retained for compatibility with the original DataFn server API. */
302
821
  db?: Adapter;
303
- /** Optional plugins */
304
- plugins?: DatafnPlugin[];
305
- /** Optional authorization callback */
822
+ /** Runtime plugins that extend schema, add internal resources, register routes, or provide DataFn capabilities. */
823
+ plugins?: DatafnPlugin$1[];
824
+ /** Public-link plugin instance used to register share-link routes and resolve link principals. */
825
+ publicLinks?: DatafnPublicLinksPlugin;
826
+ /** Authorizes each DataFn action after context creation and before route execution. */
306
827
  authorize?: (ctx: TContext, action: "status" | "query" | "mutation" | "transact" | "seed" | "clone" | "pull" | "push" | "reconcile" | "search", payload: unknown) => Promise<boolean> | boolean;
307
- /** Optional request context factory passed through to namespace, actor, auth, and route handlers. */
828
+ /** Static context or request-scoped context factory passed to authorization, namespace resolution, route handlers, and hooks. */
308
829
  context?: TContext | ((request: Request) => Promise<TContext> | TContext);
309
- /** Optional limits configuration */
830
+ /** Request, query, mutation, and validation limits enforced by DataFn routes. */
310
831
  limits?: {
832
+ /** Maximum number of records a query may request unless a route applies a stricter limit. */
311
833
  maxLimit?: number;
834
+ /** Maximum number of steps accepted in a single transact request. */
312
835
  maxTransactSteps?: number;
836
+ /** Maximum request body size in bytes before DataFn rejects the payload. */
313
837
  maxPayloadBytes?: number;
314
- /** Max changes returned per pull request. Default: 1000. */
838
+ /** Maximum number of changes returned by a pull request. Default: 1000. */
315
839
  maxPullLimit?: number;
316
- /** VAL-002: Max select tokens per query (default 50) */
840
+ /** Maximum number of select tokens accepted per query. Default: 50. */
317
841
  maxSelectTokens?: number;
318
- /** VAL-003: Max filter keys per nesting level (default 20) */
842
+ /** Maximum number of filter keys accepted at each nesting level. Default: 20. */
319
843
  maxFilterKeysPerLevel?: number;
320
- /** VAL-004: Max sort fields (default 10) */
844
+ /** Maximum number of sort fields accepted by a query. Default: 10. */
321
845
  maxSortFields?: number;
322
- /** VAL-005: Max aggregations (default 20) */
846
+ /** Maximum number of aggregate expressions accepted by a query. Default: 20. */
323
847
  maxAggregations?: number;
324
- /** VAL-006: Max ID length (default 255) */
848
+ /** Maximum resource or relation ID length accepted by routes. Default: 255. */
325
849
  maxIdLength?: number;
326
- /** FIX-SEC-006: Max batch size for push/mutation endpoints (default 500) */
850
+ /** Maximum number of items accepted by push and mutation batch endpoints. Default: 500. */
327
851
  maxBatchSize?: number;
328
- /** FIX-SRV-003: Max in-flight query concurrency for batch queries (default 20) */
852
+ /** Maximum number of concurrent query executions allowed inside a batch request. Default: 20. */
329
853
  maxBatchQueryConcurrency?: number;
330
854
  };
331
855
  /**
332
- * VAL-009: Debug mode for validation error messages.
333
- * When false, error messages are generic (no field names or schema details).
334
- * Default: process.env.NODE_ENV !== 'production'
856
+ * Enables detailed validation errors with field names and schema details.
857
+ * Defaults to true outside production and generic errors in production.
335
858
  */
336
859
  debug?: boolean;
337
860
  /**
338
- * VAL-001: Allow queries/mutations on resources with no authorization policy.
339
- * When false (default), resources without a policy return FORBIDDEN.
340
- * Set to true only for development/testing.
861
+ * Allows actions on resources that do not define authorization policies.
862
+ * When false, policy-less resources return FORBIDDEN.
341
863
  */
342
864
  allowUnknownResources?: boolean;
343
- /** Optional server time provider (for testing) */
865
+ /** Clock source used by server routes, sync, and retention logic; primarily useful for tests. */
344
866
  getServerTime?: () => number;
345
867
  /**
346
- * Optional flag to enable REST endpoint generation (default: false)
347
- * When true, generates REST wrappers:
348
- * - GET /datafn/resources/:resource (query wrapper)
349
- * - POST /datafn/resources/:resource (insert/merge wrapper)
350
- * - PATCH /datafn/resources/:resource/:id (merge wrapper)
351
- * - DELETE /datafn/resources/:resource/:id (delete wrapper)
868
+ * Enables REST wrappers around DataFn resources.
869
+ * Adds GET, POST, PATCH, and DELETE routes under /datafn/resources/:resource.
352
870
  */
353
871
  rest?: boolean;
354
872
  /**
355
- * Namespace provider for per-request data isolation.
356
- * Returns the namespace string used to scope all data operations.
357
- * Without this, all data shares the default "datafn" namespace.
873
+ * Resolves per-request namespace isolation and actor attribution.
874
+ * Without this, all data uses the default "datafn" namespace.
358
875
  *
359
876
  * @example
360
877
  * ```typescript
@@ -365,83 +882,44 @@ interface DatafnServerConfig<TContext = any> {
365
882
  * ```
366
883
  */
367
884
  namespaceProvider?: {
885
+ /** Returns the namespace that scopes all resource, relation, sync, and search operations for the request. */
368
886
  getNamespace: (ctx: TContext) => string | Promise<string>;
369
- /** Optional actor ID for audit attribution (separate from isolation). */
887
+ /** Returns the actor ID used for audit attribution and sync metadata, separate from namespace isolation. */
370
888
  getActorId?: (ctx: TContext) => string | undefined | Promise<string | undefined>;
371
889
  };
372
- /**
373
- * Optional Redis adapter for atomic operations (serverSeq, rate limiting, caching).
374
- * When provided with appropriate dbMapping, enables high-performance atomic operations.
375
- *
376
- * @example
377
- * ```typescript
378
- * redis: myRedisAdapter,
379
- * dbMapping: { serverseq: "redis" }
380
- * ```
381
- */
382
- redis?: RedisAdapter;
383
- /**
384
- * Optional KV store adapter for simple key-value operations.
385
- * Must support `incr()` to be used for serverSeq generation.
386
- *
387
- * @example
388
- * ```typescript
389
- * kvStore: myKVAdapter,
390
- * dbMapping: { serverseq: "kv" }
391
- * ```
392
- */
393
- kvStore?: KVStoreAdapter;
394
- /**
395
- * Database mapping configuration - specifies which database to use for each feature.
396
- * Defaults to using the main database ("db") for all features.
397
- *
398
- * @example
399
- * ```typescript
400
- * dbMapping: {
401
- * serverseq: "redis", // Use Redis for serverSeq (atomic INCR)
402
- * ratelimiting: "redis", // Use Redis for rate limiting
403
- * cache: "kv", // Use KV store for caching
404
- * }
405
- * ```
406
- */
407
- dbMapping?: DbMapping;
890
+ /** Runtime cache and atomic stores used for rate limiting, sync coordination, and optional server state. */
891
+ stores?: RuntimeStores;
892
+ /** Sequence-store policy used by sync to allocate and persist server sequence numbers. */
893
+ serverSeq?: SequenceStorePolicy;
408
894
  /**
409
895
  * Row-level namespace isolation configuration.
410
- * - Explicitly `false` → disabled.
411
- * - Object → used as-is for wrapping configuration.
896
+ * Pass false to disable database-level namespace wrapping, or an object to configure row-level scoping.
412
897
  */
413
898
  rowLevelNamespace?: false | RowLevelNamespaceConfig;
414
- /** Data retention configuration for __datafn_changes and __datafn_idempotency tables. */
899
+ /** Retention policy for __datafn_changes and __datafn_idempotency internal tables. */
415
900
  retention?: RetentionConfig;
416
- /** Rate limiting configuration (RATE-001 through RATE-005). */
901
+ /** Rate-limit policy for DataFn HTTP endpoints. */
417
902
  rateLimit?: RateLimitConfig<TContext>;
418
- /** Observability configuration (OBS-001 through OBS-004). */
903
+ /** HTTP route lifecycle hooks applied after context creation, authorization, and handler execution. */
904
+ routeHooks?: DatafnRouteHooks<TContext>;
905
+ /** Observability sink and options for DataFn request, rate-limit, authorization, sync, retention, and failure events. */
419
906
  observability?: ObservabilityConfig;
420
907
  /**
421
- * WebSocket limits and heartbeat configuration.
422
- * SCA-005: maxConnections / maxConnectionsPerNamespace
423
- * REL-007: heartbeatIntervalMs / heartbeatTimeoutMs
908
+ * WebSocket connection limits, per-namespace limits, and heartbeat timing used by the sync transport.
424
909
  */
425
910
  ws?: WsManagerConfig;
426
911
  /**
427
- * Graceful shutdown drain timeout in ms. Default: 10,000.
428
- * REL-009: Server waits up to this long for in-flight requests to complete.
912
+ * Graceful shutdown drain timeout in milliseconds.
913
+ * The server waits up to this long for in-flight requests to complete before closing.
429
914
  */
430
915
  shutdownTimeoutMs?: number;
431
916
  /**
432
- * LOG-001: Pluggable logger. Default: console-based (JSON in prod, pretty in dev).
433
- */
434
- logger?: DatafnLogger;
435
- /**
436
- * COMP-001: SPV2 migration compatibility flags.
437
- * - readMode: v2 (default), dual, or v1 (rollback mode)
438
- * - writeMode: v2 (default) or dual
439
- * - warnOnLegacyApi: emit deterministic deprecation warnings for shareWith.userId
917
+ * SPV2 migration compatibility settings for read mode, write mode, and legacy share API warnings.
440
918
  */
441
919
  spv2Migration?: Spv2MigrationRuntimeConfig;
442
920
  /**
443
- * Optional search provider for full-text and semantic search queries.
444
- * When provided, search queries are routed to this provider instead of requiring a searchfn plugin.
921
+ * Search provider for full-text and semantic search queries.
922
+ * When provided, search routes and mutation index updates use this provider.
445
923
  */
446
924
  searchProvider?: SearchProvider;
447
925
  }
@@ -450,6 +928,10 @@ interface DatafnServerConfig<TContext = any> {
450
928
  */
451
929
  interface DatafnServer<TContext = any> {
452
930
  router: Router<TContext>;
931
+ /** Validated schema used by both HTTP and in-process execution. */
932
+ readonly schema: DatafnSchema;
933
+ /** Transport-neutral execution surface for trusted adapters such as McpFn. */
934
+ readonly executor: DatafnExecutor<TContext>;
453
935
  search(params: CrossResourceSearchParams & {
454
936
  namespace?: string;
455
937
  }, ctx?: TContext): Promise<SearchResult>;
@@ -457,6 +939,10 @@ interface DatafnServer<TContext = any> {
457
939
  /** SEC-001: addClient requires auth context. Reject unauthenticated connections with close code 4401 before calling. */
458
940
  /** SCA-005: Returns false (and closes with code 4503) when connection limits are exceeded. */
459
941
  addClient(client: WebSocketClient, authContext: WsAuthContext): boolean;
942
+ /** Validates and pins namespace placement during a canonical-gateway handshake. */
943
+ addRoutedClient(client: WebSocketClient, authContext: WsAuthContext, handshakeRequest?: Request): Promise<boolean>;
944
+ /** Closes stale sessions so clients reconnect through the canonical gateway. */
945
+ fenceNamespace(namespace: string, minimumEpoch?: number): number;
460
946
  removeClient(client: WebSocketClient): void;
461
947
  handleMessage(client: WebSocketClient, data: string): void;
462
948
  /** REL-007: Called by WS transport on native pong frame receipt. */
@@ -477,6 +963,40 @@ interface DatafnServer<TContext = any> {
477
963
  */
478
964
  declare function createDatafnServer<TContext = any>(config: DatafnServerConfig<TContext>): Promise<DatafnServer<TContext>>;
479
965
 
966
+ /**
967
+ * DataFn app declaration shared by code generation and server runtime.
968
+ */
969
+ interface DatafnAppConfig {
970
+ schema: DatafnSchema$1;
971
+ plugins?: DatafnPlugin[];
972
+ }
973
+ /**
974
+ * Runtime server config accepted by DatafnApp.createServer.
975
+ */
976
+ interface DatafnAppServerConfig<TContext = any> extends Omit<DatafnServerConfig<TContext>, "schema" | "plugins"> {
977
+ /** Optional schema override; when omitted, the schema declared in datafn(...) is used. */
978
+ schema?: DatafnSchema$1;
979
+ /** Runtime plugins merged with declaration-time plugins, replacing plugins with the same identity. */
980
+ plugins?: DatafnPlugin[];
981
+ }
982
+ /**
983
+ * Side-effect-free DataFn app object that can expose schema or create a server.
984
+ */
985
+ interface DatafnApp {
986
+ readonly schema: DatafnSchema$1;
987
+ readonly plugins: readonly DatafnPlugin[];
988
+ getSchema(): DatafnSchema$1;
989
+ /**
990
+ * Creates a DataFn server runtime from the side-effect-free app declaration.
991
+ * The server config supplies persistence, context, authorization, namespace isolation, plugins, limits, hooks, search, and observability.
992
+ */
993
+ createServer<TContext = any>(config: DatafnAppServerConfig<TContext>): Promise<DatafnServer<TContext>>;
994
+ }
995
+ /**
996
+ * Creates a side-effect-free DataFn app definition for codegen and runtime use.
997
+ */
998
+ declare function datafn(config: DatafnAppConfig): DatafnApp;
999
+
480
1000
  /**
481
1001
  * GET /datafn/status endpoint
482
1002
  * Returns server metadata, capabilities, limits, and schema hash
@@ -494,4 +1014,4 @@ interface StatusResult {
494
1014
  serverTimeMs: number;
495
1015
  }
496
1016
 
497
- 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 };
1017
+ export { AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteResponseHook, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type RateLimitConfig, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, claimDatafnNamespacePlacement, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, migrateDatafnNamespace, readDatafnPublicLinkToken, resolveDatafnPublicLink, validateDatafnPlacement, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRoutingAssertion };