@lunora/do 1.0.0-alpha.31 → 1.0.0-alpha.32

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.mts CHANGED
@@ -2407,6 +2407,11 @@ interface MaterializeResult {
2407
2407
  /** `id → projected-value JSON` — the post-tick membership, to feed back as `baseline` next tick. */
2408
2408
  nextBaseline: Map<string, string>;
2409
2409
  }
2410
+ /** The outcome of one incremental materialize pass. No baseline: incremental applies only the pulled slice, never a full-membership diff. */
2411
+ interface IncrementalMaterializeResult {
2412
+ /** Number of `CdcChange`s applied (upserts + tombstone deletes) for the pulled slice. */
2413
+ applied: number;
2414
+ }
2410
2415
  /**
2411
2416
  * Diff `pulled` against `baseline` and apply the delta to `writer`. Returns the
2412
2417
  * applied count and the next baseline. A steady-state tick (membership unchanged)
@@ -2417,6 +2422,36 @@ declare const materializeExternalRows: (writer: DatabaseWriterLike, pulled: Read
2417
2422
  table: string;
2418
2423
  }) => Promise<MaterializeResult>;
2419
2424
  /**
2425
+ * Apply an **incremental** slice (plan 136): the freshly-pulled rows changed since
2426
+ * the watermark, upsert-only. Unlike {@link materializeExternalRows} this reads no
2427
+ * baseline and never diffs the full membership — an absent row means "unchanged
2428
+ * since the watermark", NOT "deleted". Each pulled row is projected with the SAME
2429
+ * {@link projectExternalSourceRow} full-pull uses, so an incrementally-upserted row
2430
+ * is byte-identical to how the next reconcile sweep's full-pull would store it (no
2431
+ * spurious update on reconcile).
2432
+ *
2433
+ * Delete visibility comes from `deletedIds` — the ids the caller resolved from the
2434
+ * source's soft-delete tombstone column. Every other pulled row is an `insert`,
2435
+ * which {@link applyCdcChanges} upserts (insert, or replace on conflict), so a
2436
+ * changed existing row is updated and a genuinely new row is inserted without the
2437
+ * caller tracking which is which.
2438
+ *
2439
+ * **Content short-circuit.** An incremental cursor query uses `>= watermark` (so
2440
+ * rows sharing the boundary value are never skipped), which means a steady-state
2441
+ * tick re-pulls the boundary row(s) unchanged. Blindly upserting them would append
2442
+ * a `__cdc_log` entry, broadcast a spurious `update` to every `defineShape`
2443
+ * subscriber, re-run search/aggregate/rank sync, and fire `onWrite` (a Vectorize
2444
+ * re-embed = real cost) on every tick — and `replace` would reset `_creationTime`.
2445
+ * So each row is diffed against its stored projection (the SAME
2446
+ * {@link projectExternalSourceRow} + {@link stableStringify} full-pull uses) and
2447
+ * skipped when byte-identical — mirroring the full-pull diff's steady-state no-op.
2448
+ */
2449
+ declare const materializeExternalRowsIncremental: (writer: DatabaseWriterLike, pulled: ReadonlyArray<Record<string, unknown>>, options: {
2450
+ columns?: ReadonlyArray<string>;
2451
+ deletedIds?: ReadonlySet<string>;
2452
+ table: string;
2453
+ }) => Promise<IncrementalMaterializeResult>;
2454
+ /**
2420
2455
  * Read the materialized table's current membership as the canonical full-pull
2421
2456
  * baseline (`id → canonical JSON`). Reuses the shape scanner (`selectShapeRows`)
2422
2457
  * and the SAME {@link projectExternalSourceRow} + {@link stableStringify} the diff
@@ -2445,14 +2480,23 @@ interface SourceClientLike {
2445
2480
  type SourceRefresh = "manual" | {
2446
2481
  everyMs: number;
2447
2482
  };
2483
+ /** The incremental cursor config (plan 136): the watermark column + the watermark-parameterized pull query. */
2484
+ interface SourceCursorLike {
2485
+ column: string;
2486
+ query: string;
2487
+ }
2448
2488
  /** The runtime `.source(...)` config the poll loop reads — a structural mirror of `@lunora/server`'s `ExternalSourceDefinition` (only the fields the tick uses). */
2449
2489
  interface ExternalSourceLike {
2450
2490
  binding: string;
2451
2491
  columns?: ReadonlyArray<string>;
2492
+ cursor?: SourceCursorLike;
2452
2493
  idColumn?: string;
2453
2494
  map?: (row: Record<string, unknown>) => Record<string, unknown>;
2495
+ mode?: string;
2454
2496
  query: string;
2497
+ reconcileEveryMs?: number;
2455
2498
  refresh?: SourceRefresh;
2499
+ softDeleteColumn?: string;
2456
2500
  tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
2457
2501
  }
2458
2502
  /**
@@ -2482,6 +2526,39 @@ declare const isSourceDue: (refresh: SourceRefresh | undefined, lastPolledMs: nu
2482
2526
  */
2483
2527
  declare const pullExternalSourceTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string) => Promise<MaterializeResult>;
2484
2528
  /**
2529
+ * Whether an upstream row is a soft-delete tombstone under `column`. A set
2530
+ * `deleted_at` (any non-null value, e.g. a timestamp), an `is_deleted = true`, or a
2531
+ * non-zero flag all read as deleted; `null` / `undefined` / `false` / `0` mean
2532
+ * live. Note an **empty string** reads as deleted (`"" !== 0`), so an upstream that
2533
+ * clears the column to `""` rather than `NULL` for a live row would mis-signal —
2534
+ * use `NULL` for live rows. The incremental query MUST return tombstoned rows
2535
+ * (don't filter `WHERE deleted_at IS NULL`) or the delete is never observed.
2536
+ */
2537
+ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => boolean;
2538
+ /**
2539
+ * Run one **incremental** tick (plan 136). Reads the durable watermark for
2540
+ * `(table, shardKey)`; on the first ever poll or when the `reconcileEveryMs` sweep
2541
+ * is due it runs a **full-pull** (seed/GC: {@link runExternalSourceTick} observes
2542
+ * deletes and re-establishes membership), otherwise it pulls only rows past the
2543
+ * watermark via `cursor.query` and upserts them ({@link materializeExternalRowsIncremental},
2544
+ * tombstones → deletes). Either way it advances the watermark to the max cursor
2545
+ * value seen and persists it (and the reconcile timestamp).
2546
+ *
2547
+ * **Crash safety** is by ordering + idempotency, NOT an atomic transaction across
2548
+ * the two write channels (the apply goes through the `writer`; the watermark write
2549
+ * is a raw `sql` write): the watermark advances only AFTER a fully-applied slice,
2550
+ * so a crash between the apply and the watermark write leaves the watermark behind
2551
+ * and the next tick re-pulls the same `>= watermark` slice — which the upsert
2552
+ * short-circuits (unchanged rows) or re-applies idempotently. It only ever replays,
2553
+ * never skips (same self-healing argument as `advanceClientWatermark`).
2554
+ *
2555
+ * Requires `source.cursor` (validated at `defineSchema` for incremental mode); a
2556
+ * missing cursor throws rather than silently degrading to a stuck watermark.
2557
+ */
2558
+ declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
2559
+ applied: number;
2560
+ }>;
2561
+ /**
2485
2562
  * Reserved `functionPath` prefix for admin introspection RPCs. These travel
2486
2563
  * over the same `/_lunora/rpc` → shard `/rpc` path as ordinary functions, but
2487
2564
  * `ShardDO` intercepts them before user dispatch and serves them from the
@@ -6704,4 +6781,4 @@ interface WhereSqlStrategy {
6704
6781
  * `undefined` when the input imposes no constraint (empty `where`).
6705
6782
  */
6706
6783
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
6707
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
6784
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.d.ts CHANGED
@@ -2407,6 +2407,11 @@ interface MaterializeResult {
2407
2407
  /** `id → projected-value JSON` — the post-tick membership, to feed back as `baseline` next tick. */
2408
2408
  nextBaseline: Map<string, string>;
2409
2409
  }
2410
+ /** The outcome of one incremental materialize pass. No baseline: incremental applies only the pulled slice, never a full-membership diff. */
2411
+ interface IncrementalMaterializeResult {
2412
+ /** Number of `CdcChange`s applied (upserts + tombstone deletes) for the pulled slice. */
2413
+ applied: number;
2414
+ }
2410
2415
  /**
2411
2416
  * Diff `pulled` against `baseline` and apply the delta to `writer`. Returns the
2412
2417
  * applied count and the next baseline. A steady-state tick (membership unchanged)
@@ -2417,6 +2422,36 @@ declare const materializeExternalRows: (writer: DatabaseWriterLike, pulled: Read
2417
2422
  table: string;
2418
2423
  }) => Promise<MaterializeResult>;
2419
2424
  /**
2425
+ * Apply an **incremental** slice (plan 136): the freshly-pulled rows changed since
2426
+ * the watermark, upsert-only. Unlike {@link materializeExternalRows} this reads no
2427
+ * baseline and never diffs the full membership — an absent row means "unchanged
2428
+ * since the watermark", NOT "deleted". Each pulled row is projected with the SAME
2429
+ * {@link projectExternalSourceRow} full-pull uses, so an incrementally-upserted row
2430
+ * is byte-identical to how the next reconcile sweep's full-pull would store it (no
2431
+ * spurious update on reconcile).
2432
+ *
2433
+ * Delete visibility comes from `deletedIds` — the ids the caller resolved from the
2434
+ * source's soft-delete tombstone column. Every other pulled row is an `insert`,
2435
+ * which {@link applyCdcChanges} upserts (insert, or replace on conflict), so a
2436
+ * changed existing row is updated and a genuinely new row is inserted without the
2437
+ * caller tracking which is which.
2438
+ *
2439
+ * **Content short-circuit.** An incremental cursor query uses `>= watermark` (so
2440
+ * rows sharing the boundary value are never skipped), which means a steady-state
2441
+ * tick re-pulls the boundary row(s) unchanged. Blindly upserting them would append
2442
+ * a `__cdc_log` entry, broadcast a spurious `update` to every `defineShape`
2443
+ * subscriber, re-run search/aggregate/rank sync, and fire `onWrite` (a Vectorize
2444
+ * re-embed = real cost) on every tick — and `replace` would reset `_creationTime`.
2445
+ * So each row is diffed against its stored projection (the SAME
2446
+ * {@link projectExternalSourceRow} + {@link stableStringify} full-pull uses) and
2447
+ * skipped when byte-identical — mirroring the full-pull diff's steady-state no-op.
2448
+ */
2449
+ declare const materializeExternalRowsIncremental: (writer: DatabaseWriterLike, pulled: ReadonlyArray<Record<string, unknown>>, options: {
2450
+ columns?: ReadonlyArray<string>;
2451
+ deletedIds?: ReadonlySet<string>;
2452
+ table: string;
2453
+ }) => Promise<IncrementalMaterializeResult>;
2454
+ /**
2420
2455
  * Read the materialized table's current membership as the canonical full-pull
2421
2456
  * baseline (`id → canonical JSON`). Reuses the shape scanner (`selectShapeRows`)
2422
2457
  * and the SAME {@link projectExternalSourceRow} + {@link stableStringify} the diff
@@ -2445,14 +2480,23 @@ interface SourceClientLike {
2445
2480
  type SourceRefresh = "manual" | {
2446
2481
  everyMs: number;
2447
2482
  };
2483
+ /** The incremental cursor config (plan 136): the watermark column + the watermark-parameterized pull query. */
2484
+ interface SourceCursorLike {
2485
+ column: string;
2486
+ query: string;
2487
+ }
2448
2488
  /** The runtime `.source(...)` config the poll loop reads — a structural mirror of `@lunora/server`'s `ExternalSourceDefinition` (only the fields the tick uses). */
2449
2489
  interface ExternalSourceLike {
2450
2490
  binding: string;
2451
2491
  columns?: ReadonlyArray<string>;
2492
+ cursor?: SourceCursorLike;
2452
2493
  idColumn?: string;
2453
2494
  map?: (row: Record<string, unknown>) => Record<string, unknown>;
2495
+ mode?: string;
2454
2496
  query: string;
2497
+ reconcileEveryMs?: number;
2455
2498
  refresh?: SourceRefresh;
2499
+ softDeleteColumn?: string;
2456
2500
  tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
2457
2501
  }
2458
2502
  /**
@@ -2482,6 +2526,39 @@ declare const isSourceDue: (refresh: SourceRefresh | undefined, lastPolledMs: nu
2482
2526
  */
2483
2527
  declare const pullExternalSourceTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string) => Promise<MaterializeResult>;
2484
2528
  /**
2529
+ * Whether an upstream row is a soft-delete tombstone under `column`. A set
2530
+ * `deleted_at` (any non-null value, e.g. a timestamp), an `is_deleted = true`, or a
2531
+ * non-zero flag all read as deleted; `null` / `undefined` / `false` / `0` mean
2532
+ * live. Note an **empty string** reads as deleted (`"" !== 0`), so an upstream that
2533
+ * clears the column to `""` rather than `NULL` for a live row would mis-signal —
2534
+ * use `NULL` for live rows. The incremental query MUST return tombstoned rows
2535
+ * (don't filter `WHERE deleted_at IS NULL`) or the delete is never observed.
2536
+ */
2537
+ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => boolean;
2538
+ /**
2539
+ * Run one **incremental** tick (plan 136). Reads the durable watermark for
2540
+ * `(table, shardKey)`; on the first ever poll or when the `reconcileEveryMs` sweep
2541
+ * is due it runs a **full-pull** (seed/GC: {@link runExternalSourceTick} observes
2542
+ * deletes and re-establishes membership), otherwise it pulls only rows past the
2543
+ * watermark via `cursor.query` and upserts them ({@link materializeExternalRowsIncremental},
2544
+ * tombstones → deletes). Either way it advances the watermark to the max cursor
2545
+ * value seen and persists it (and the reconcile timestamp).
2546
+ *
2547
+ * **Crash safety** is by ordering + idempotency, NOT an atomic transaction across
2548
+ * the two write channels (the apply goes through the `writer`; the watermark write
2549
+ * is a raw `sql` write): the watermark advances only AFTER a fully-applied slice,
2550
+ * so a crash between the apply and the watermark write leaves the watermark behind
2551
+ * and the next tick re-pulls the same `>= watermark` slice — which the upsert
2552
+ * short-circuits (unchanged rows) or re-applies idempotently. It only ever replays,
2553
+ * never skips (same self-healing argument as `advanceClientWatermark`).
2554
+ *
2555
+ * Requires `source.cursor` (validated at `defineSchema` for incremental mode); a
2556
+ * missing cursor throws rather than silently degrading to a stuck watermark.
2557
+ */
2558
+ declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
2559
+ applied: number;
2560
+ }>;
2561
+ /**
2485
2562
  * Reserved `functionPath` prefix for admin introspection RPCs. These travel
2486
2563
  * over the same `/_lunora/rpc` → shard `/rpc` path as ordinary functions, but
2487
2564
  * `ShardDO` intercepts them before user dispatch and serves them from the
@@ -6704,4 +6781,4 @@ interface WhereSqlStrategy {
6704
6781
  * `undefined` when the input imposes no constraint (empty `where`).
6705
6782
  */
6706
6783
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
6707
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
6784
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.mjs CHANGED
@@ -8,8 +8,8 @@ export { DATA_MIGRATION_STATE_TABLE, readMigrationStatus, runDataMigration } fro
8
8
  export { SCAN_DEP, createDependencyTracker, depKey } from './packem_shared/SCAN_DEP-DLJF8dsj.mjs';
9
9
  export { renderSql } from './packem_shared/renderSql-D6eUcn2N.mjs';
10
10
  export { diffExternalSource } from './packem_shared/diffExternalSource-CovHfdyo.mjs';
11
- export { materializeExternalRows, readExternalSourceBaseline, runExternalSourceTick } from './packem_shared/materializeExternalRows-CoGmFmsY.mjs';
12
- export { isSourceDue, liftSourceId, pullExternalSourceTick } from './packem_shared/isSourceDue-Bj7I3v1b.mjs';
11
+ export { materializeExternalRows, materializeExternalRowsIncremental, readExternalSourceBaseline, runExternalSourceTick } from './packem_shared/materializeExternalRows-FyA5Rwn4.mjs';
12
+ export { isSoftDeleted, isSourceDue, liftSourceId, pullExternalSourceIncrementalTick, pullExternalSourceTick } from './packem_shared/isSoftDeleted-i5kKh6Up.mjs';
13
13
  export { FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, ensureFunctionMetricsTables, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, recordFunctionMetric } from './packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs';
14
14
  export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, FLAGS_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, facetColumn, listTables, readTablePage, selectMatchingIds } from './packem_shared/ADMIN_FUNCTIONS-CAHLZMj8.mjs';
15
15
  export { LogBuffer } from './packem_shared/LogBuffer-B_Ezju_N.mjs';
@@ -0,0 +1,183 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { sql } from 'drizzle-orm';
3
+ import { r as runDrizzle } from './do-exec-5eQy5cEi.mjs';
4
+ import { runExternalSourceTick, materializeExternalRowsIncremental } from './materializeExternalRows-FyA5Rwn4.mjs';
5
+
6
+ const SOURCE_CURSOR_TABLE = "__lunora_source_cursor";
7
+ const serializeCursor = (value) => {
8
+ if (value instanceof Date) {
9
+ return `d:${value.toISOString()}`;
10
+ }
11
+ if (typeof value === "bigint") {
12
+ return `b:${value.toString()}`;
13
+ }
14
+ if (typeof value === "number") {
15
+ return `n:${value.toString()}`;
16
+ }
17
+ return `s:${value}`;
18
+ };
19
+ const deserializeCursor = (text) => {
20
+ const rest = text.slice(2);
21
+ switch (text[0]) {
22
+ case "b": {
23
+ return BigInt(rest);
24
+ }
25
+ case "d": {
26
+ return new Date(rest);
27
+ }
28
+ case "n": {
29
+ return Number(rest);
30
+ }
31
+ default: {
32
+ return rest;
33
+ }
34
+ }
35
+ };
36
+ const INTEGER_STRING = /^-?\d+$/;
37
+ const DECIMAL_STRING = /^-?\d+(?:\.\d+)?$/;
38
+ const cursorAfter = (a, b) => {
39
+ if (a instanceof Date && b instanceof Date) {
40
+ return a.getTime() > b.getTime();
41
+ }
42
+ if (typeof a === "bigint" && typeof b === "bigint") {
43
+ return a > b;
44
+ }
45
+ if (typeof a === "number" && typeof b === "number") {
46
+ return a > b;
47
+ }
48
+ if (typeof a === "string" && typeof b === "string" && DECIMAL_STRING.test(a) && DECIMAL_STRING.test(b)) {
49
+ if (INTEGER_STRING.test(a) && INTEGER_STRING.test(b)) {
50
+ return BigInt(a) > BigInt(b);
51
+ }
52
+ return Number(a) > Number(b);
53
+ }
54
+ return String(a) > String(b);
55
+ };
56
+ const maxCursorValue = (rows, column, current) => {
57
+ let best = current === null ? void 0 : deserializeCursor(current);
58
+ for (const row of rows) {
59
+ const raw = row[column];
60
+ if (raw === null || raw === void 0) {
61
+ continue;
62
+ }
63
+ const value = raw;
64
+ if (best === void 0 || cursorAfter(value, best)) {
65
+ best = value;
66
+ }
67
+ }
68
+ return best === void 0 ? null : serializeCursor(best);
69
+ };
70
+ const migrateSourceCursor = (sql$1) => {
71
+ runDrizzle(
72
+ sql$1,
73
+ sql`CREATE TABLE IF NOT EXISTS ${sql.identifier(SOURCE_CURSOR_TABLE)} (
74
+ table_name TEXT NOT NULL,
75
+ shard_key TEXT NOT NULL,
76
+ watermark TEXT,
77
+ last_reconcile_ms INTEGER,
78
+ PRIMARY KEY (table_name, shard_key)
79
+ )`
80
+ );
81
+ };
82
+ const readSourceCursor = (sql$1, table, shardKey) => {
83
+ const rows = runDrizzle(
84
+ sql$1,
85
+ sql`SELECT watermark, last_reconcile_ms FROM ${sql.identifier(SOURCE_CURSOR_TABLE)} WHERE table_name = ${table} AND shard_key = ${shardKey} LIMIT 1`
86
+ ).toArray();
87
+ const row = rows[0];
88
+ return { lastReconcileMs: row?.last_reconcile_ms ?? null, watermark: row?.watermark ?? null };
89
+ };
90
+ const writeSourceCursor = (sql$1, table, shardKey, state) => {
91
+ runDrizzle(
92
+ sql$1,
93
+ sql`INSERT INTO ${sql.identifier(SOURCE_CURSOR_TABLE)} (table_name, shard_key, watermark, last_reconcile_ms)
94
+ VALUES (${table}, ${shardKey}, ${state.watermark}, ${state.lastReconcileMs})
95
+ ON CONFLICT(table_name, shard_key) DO UPDATE SET watermark = excluded.watermark, last_reconcile_ms = excluded.last_reconcile_ms`
96
+ );
97
+ };
98
+
99
+ const liftSourceId = (row, options = {}) => {
100
+ const { idColumn = "id", map } = options;
101
+ const idValue = row[idColumn];
102
+ if (idValue === void 0 || idValue === null) {
103
+ throw new LunoraError("INTERNAL", `external-source: row is missing id column "${idColumn}"`);
104
+ }
105
+ if (typeof idValue !== "string" && typeof idValue !== "number" && typeof idValue !== "bigint") {
106
+ throw new TypeError(`external-source: id column "${idColumn}" must be a string or number`);
107
+ }
108
+ const id = String(idValue);
109
+ if (map) {
110
+ return { ...map(row), _id: id };
111
+ }
112
+ const body = {};
113
+ for (const [key, value] of Object.entries(row)) {
114
+ if (key !== idColumn) {
115
+ body[key] = value;
116
+ }
117
+ }
118
+ return { ...body, _id: id };
119
+ };
120
+ const isSourceDue = (refresh, lastPolledMs, nowMs) => {
121
+ if (refresh === "manual") {
122
+ return false;
123
+ }
124
+ if (refresh === void 0 || lastPolledMs === void 0) {
125
+ return true;
126
+ }
127
+ return nowMs - lastPolledMs >= refresh.everyMs;
128
+ };
129
+ const pullAndLift = async (client, query, parameters, source) => {
130
+ const rows = await client.query(query, parameters);
131
+ const documents = rows.map((row) => liftSourceId(row, { idColumn: source.idColumn, map: source.map }));
132
+ return { documents, rows };
133
+ };
134
+ const pullExternalSourceTick = async (sql, writer, client, table, source, shardKey) => {
135
+ const parameters = source.tenantBy ? source.tenantBy(shardKey) : [];
136
+ const { documents } = await pullAndLift(client, source.query, parameters, source);
137
+ return runExternalSourceTick(sql, writer, documents, { columns: source.columns, table });
138
+ };
139
+ const isSoftDeleted = (row, column) => {
140
+ const value = row[column];
141
+ return value !== null && value !== void 0 && value !== false && value !== 0;
142
+ };
143
+ const pullExternalSourceIncrementalTick = async (sql, writer, client, table, source, shardKey, nowMs) => {
144
+ const { cursor } = source;
145
+ if (!cursor) {
146
+ throw new LunoraError(
147
+ "INTERNAL",
148
+ `external-source: table "${table}" is mode "incremental" but has no \`cursor\` — this should have been rejected at defineSchema`
149
+ );
150
+ }
151
+ migrateSourceCursor(sql);
152
+ const state = readSourceCursor(sql, table, shardKey);
153
+ const tenantParameters = source.tenantBy ? source.tenantBy(shardKey) : [];
154
+ const reconcileDue = source.reconcileEveryMs !== void 0 && (state.lastReconcileMs === null || nowMs - state.lastReconcileMs >= source.reconcileEveryMs);
155
+ const fullPull = state.watermark === null || reconcileDue;
156
+ let slice;
157
+ let applied;
158
+ if (state.watermark === null || reconcileDue) {
159
+ slice = await pullAndLift(client, source.query, tenantParameters, source);
160
+ ({ applied } = await runExternalSourceTick(sql, writer, slice.documents, { columns: source.columns, table }));
161
+ } else {
162
+ slice = await pullAndLift(client, cursor.query, [...tenantParameters, deserializeCursor(state.watermark)], source);
163
+ const { softDeleteColumn } = source;
164
+ const deletedIds = softDeleteColumn ? new Set(
165
+ slice.documents.flatMap((document, index) => {
166
+ const row = slice.rows[index];
167
+ return row && isSoftDeleted(row, softDeleteColumn) ? [String(document._id)] : [];
168
+ })
169
+ ) : void 0;
170
+ ({ applied } = await materializeExternalRowsIncremental(writer, slice.documents, { columns: source.columns, deletedIds, table }));
171
+ }
172
+ const watermark = maxCursorValue(slice.rows, cursor.column, state.watermark);
173
+ if (fullPull && watermark === null && slice.rows.length > 0) {
174
+ throw new LunoraError(
175
+ "INTERNAL",
176
+ `external-source: table "${table}" (mode "incremental") pulled ${String(slice.rows.length)} rows but none carry the cursor column "${cursor.column}" — the seed \`query\` must project it (matching \`cursor.query\`'s alias), or the watermark can never advance.`
177
+ );
178
+ }
179
+ writeSourceCursor(sql, table, shardKey, { lastReconcileMs: fullPull ? nowMs : state.lastReconcileMs, watermark });
180
+ return { applied };
181
+ };
182
+
183
+ export { isSoftDeleted, isSourceDue, liftSourceId, pullExternalSourceIncrementalTick, pullExternalSourceTick };
@@ -8,6 +8,25 @@ const materializeExternalRows = async (writer, pulled, baseline, options) => {
8
8
  await applyCdcChanges(writer, changes);
9
9
  return { applied: changes.length, nextBaseline };
10
10
  };
11
+ const materializeExternalRowsIncremental = async (writer, pulled, options) => {
12
+ const { columns, deletedIds, table } = options;
13
+ const changes = [];
14
+ for (const source of pulled) {
15
+ const value = projectExternalSourceRow(source, columns);
16
+ const id = String(value._id);
17
+ if (deletedIds?.has(id)) {
18
+ changes.push({ id, op: "delete", seq: 0, table, ts: 0 });
19
+ continue;
20
+ }
21
+ const stored = await writer.get(id, table);
22
+ if (stored && stableStringify(projectExternalSourceRow({ ...stored, _id: id }, columns)) === stableStringify(value)) {
23
+ continue;
24
+ }
25
+ changes.push({ doc: value, id, op: "insert", seq: 0, table, ts: 0 });
26
+ }
27
+ await applyCdcChanges(writer, changes);
28
+ return { applied: changes.length };
29
+ };
11
30
  const readExternalSourceBaseline = (sql, table, columns) => {
12
31
  const baseline = /* @__PURE__ */ new Map();
13
32
  for (const { doc, id } of selectShapeRows(sql, table, void 0)) {
@@ -20,4 +39,4 @@ const runExternalSourceTick = async (sql, writer, pulled, options) => {
20
39
  return materializeExternalRows(writer, pulled, baseline, options);
21
40
  };
22
41
 
23
- export { materializeExternalRows, readExternalSourceBaseline, runExternalSourceTick };
42
+ export { materializeExternalRows, materializeExternalRowsIncremental, readExternalSourceBaseline, runExternalSourceTick };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.31",
3
+ "version": "1.0.0-alpha.32",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,41 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
- import { runExternalSourceTick } from './materializeExternalRows-CoGmFmsY.mjs';
3
-
4
- const liftSourceId = (row, options = {}) => {
5
- const { idColumn = "id", map } = options;
6
- const idValue = row[idColumn];
7
- if (idValue === void 0 || idValue === null) {
8
- throw new LunoraError("INTERNAL", `external-source: row is missing id column "${idColumn}"`);
9
- }
10
- if (typeof idValue !== "string" && typeof idValue !== "number" && typeof idValue !== "bigint") {
11
- throw new TypeError(`external-source: id column "${idColumn}" must be a string or number`);
12
- }
13
- const id = String(idValue);
14
- if (map) {
15
- return { ...map(row), _id: id };
16
- }
17
- const body = {};
18
- for (const [key, value] of Object.entries(row)) {
19
- if (key !== idColumn) {
20
- body[key] = value;
21
- }
22
- }
23
- return { ...body, _id: id };
24
- };
25
- const isSourceDue = (refresh, lastPolledMs, nowMs) => {
26
- if (refresh === "manual") {
27
- return false;
28
- }
29
- if (refresh === void 0 || lastPolledMs === void 0) {
30
- return true;
31
- }
32
- return nowMs - lastPolledMs >= refresh.everyMs;
33
- };
34
- const pullExternalSourceTick = async (sql, writer, client, table, source, shardKey) => {
35
- const parameters = source.tenantBy ? source.tenantBy(shardKey) : [];
36
- const rows = await client.query(source.query, parameters);
37
- const documents = rows.map((row) => liftSourceId(row, { idColumn: source.idColumn, map: source.map }));
38
- return runExternalSourceTick(sql, writer, documents, { columns: source.columns, table });
39
- };
40
-
41
- export { isSourceDue, liftSourceId, pullExternalSourceTick };