@classytic/facts 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -0
- package/LICENSE +75 -0
- package/README.md +153 -0
- package/dist/index.d.mts +944 -0
- package/dist/index.mjs +2361 -0
- package/package.json +68 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,944 @@
|
|
|
1
|
+
import { ModelBlueprint, Repository } from "@classytic/mongokit";
|
|
2
|
+
import mongoose, { Connection, IndexOptions, Model, Schema, SchemaDefinitionProperty, Types } from "mongoose";
|
|
3
|
+
import { CleanupStep } from "@classytic/repo-core/cleanup";
|
|
4
|
+
import { RepoCapabilities } from "@classytic/repo-core/repository";
|
|
5
|
+
import { HttpError } from "@classytic/repo-core/errors";
|
|
6
|
+
//#region src/civil/civil.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Instant → business-zone civil labels. Bound by the host over its business
|
|
9
|
+
* timezone (e.g. be-prod's `business-date` helpers for Asia/Dhaka).
|
|
10
|
+
*
|
|
11
|
+
* CONSISTENCY CONTRACT (rebuild equivalence depends on it):
|
|
12
|
+
* - `weekOf(d)` MUST equal `isoWeekOfCivilDate(dateOf(d))`
|
|
13
|
+
* - `monthOf(d)` MUST equal `dateOf(d).slice(0, 7)`
|
|
14
|
+
*
|
|
15
|
+
* i.e. week/month are pure functions of the civil DATE. The rollup rebuild
|
|
16
|
+
* re-derives `civilWeek`/`civilMonth` from `civilDate` with exactly those two
|
|
17
|
+
* formulas, so a port that disagrees would make rebuilt rows diverge from
|
|
18
|
+
* live rows.
|
|
19
|
+
*/
|
|
20
|
+
interface CivilCalendarPort {
|
|
21
|
+
/** Business-zone civil date (YYYY-MM-DD) of a UTC instant. */
|
|
22
|
+
dateOf(instant: Date): string;
|
|
23
|
+
/** ISO-8601 week label (YYYY-Www) of the instant's business civil date. */
|
|
24
|
+
weekOf(instant: Date): string;
|
|
25
|
+
/** Month label (YYYY-MM) of the instant's business civil date. */
|
|
26
|
+
monthOf(instant: Date): string;
|
|
27
|
+
}
|
|
28
|
+
/** The next day after a civil-date string. "2024-01-15" → "2024-01-16". */
|
|
29
|
+
declare function nextCivilDate(dateStr: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* ISO-8601 week label (`'YYYY-Www'`) for a CIVIL date string, computed purely
|
|
32
|
+
* from the calendar PARTS — never by parsing `'YYYY-MM-DD'` through a Date
|
|
33
|
+
* zone. The `YYYY` here is the ISO **week-numbering year** (the calendar year
|
|
34
|
+
* of the week's Thursday), not the civil date's calendar year: Dec 29–31 can
|
|
35
|
+
* belong to next year's W01, and Jan 1–3 to the previous year's W52/W53.
|
|
36
|
+
*/
|
|
37
|
+
declare function isoWeekOfCivilDate(dateStr: string): string;
|
|
38
|
+
/** The system time-field block of one fact row, derived via the port. */
|
|
39
|
+
interface CivilFields {
|
|
40
|
+
occurredAt: Date;
|
|
41
|
+
civilDate: string;
|
|
42
|
+
civilWeek: string;
|
|
43
|
+
civilMonth: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Convenience for domain mappers: instant → the four system time fields of a
|
|
47
|
+
* fact row through the injected port.
|
|
48
|
+
*/
|
|
49
|
+
declare function civilFieldsOf(civil: CivilCalendarPort, occurredAt: Date): CivilFields;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/models/manifest.model.d.ts
|
|
52
|
+
type ProjectionManifestState = 'active' | 'rebuilding' | 'catching_up' | 'verified';
|
|
53
|
+
/** The three in-flight rebuild states — dual-write is on in ALL of them. */
|
|
54
|
+
declare const REBUILD_STATES: readonly ProjectionManifestState[];
|
|
55
|
+
/** Reconciliation evidence stamped by `markVerified`. */
|
|
56
|
+
interface RebuildVerification {
|
|
57
|
+
/** Civil-date window the clean reconcile covered. */
|
|
58
|
+
window: {
|
|
59
|
+
from: string;
|
|
60
|
+
to: string;
|
|
61
|
+
};
|
|
62
|
+
/** Drift count from the reconcile — must be 0 (markVerified refuses otherwise). */
|
|
63
|
+
driftCount: number;
|
|
64
|
+
/** Optional integrity token over the verified fact set (operator-supplied). */
|
|
65
|
+
factChecksum?: string;
|
|
66
|
+
}
|
|
67
|
+
interface ProjectionManifestData {
|
|
68
|
+
_id: string;
|
|
69
|
+
activeGeneration: number;
|
|
70
|
+
state: ProjectionManifestState;
|
|
71
|
+
rebuildGeneration?: number;
|
|
72
|
+
/** When the current rebuild flipped state to 'rebuilding' (cutover time-guard input). */
|
|
73
|
+
rebuildStartedAt?: Date;
|
|
74
|
+
/** When markBackfillComplete flipped 'rebuilding' → 'catching_up'. */
|
|
75
|
+
backfillCompletedAt?: Date;
|
|
76
|
+
/** Per-source checkpoint summary recorded at backfill completion. */
|
|
77
|
+
backfillCheckpointSummary?: unknown;
|
|
78
|
+
/** When markVerified flipped 'catching_up' → 'verified'. */
|
|
79
|
+
verifiedAt?: Date;
|
|
80
|
+
/** The clean-reconcile evidence this rebuild's verification rests on. */
|
|
81
|
+
verification?: RebuildVerification;
|
|
82
|
+
updatedAt: Date;
|
|
83
|
+
}
|
|
84
|
+
type ProjectionManifestDocument = ProjectionManifestData & mongoose.Document<string>;
|
|
85
|
+
interface BeginRebuildResult {
|
|
86
|
+
activeGeneration: number;
|
|
87
|
+
rebuildGeneration: number;
|
|
88
|
+
/** True when an in-flight rebuild was resumed instead of allocating a new generation. */
|
|
89
|
+
resumed: boolean;
|
|
90
|
+
}
|
|
91
|
+
interface MarkBackfillCompleteOptions {
|
|
92
|
+
/** Per-source checkpoint summary from the completed backfill (evidence). */
|
|
93
|
+
checkpointSummary: unknown;
|
|
94
|
+
/**
|
|
95
|
+
* Aggregate mapper-failure count from the backfill (`BackfillResult.failed`).
|
|
96
|
+
* When provided and non-zero, `markBackfillComplete` REFUSES — the generation
|
|
97
|
+
* is missing the failed docs' facts and must not advance toward cutover.
|
|
98
|
+
* Omit (legacy callers) to skip the check; pass `allowFailed` to override
|
|
99
|
+
* with intent. Mirrors `markVerified`'s non-zero-drift refusal.
|
|
100
|
+
*/
|
|
101
|
+
failed?: number | undefined;
|
|
102
|
+
/** Explicit override: proceed even though `failed > 0` (records the count). */
|
|
103
|
+
allowFailed?: boolean | undefined;
|
|
104
|
+
}
|
|
105
|
+
interface MarkVerifiedOptions {
|
|
106
|
+
/** Civil-date window the clean reconcile covered. */
|
|
107
|
+
window: {
|
|
108
|
+
from: string;
|
|
109
|
+
to: string;
|
|
110
|
+
};
|
|
111
|
+
/** Drift count reported by the reconcile — MUST be 0. */
|
|
112
|
+
driftCount: number;
|
|
113
|
+
/** Optional integrity token over the verified fact set. */
|
|
114
|
+
factChecksum?: string | undefined;
|
|
115
|
+
}
|
|
116
|
+
interface CutoverOptions {
|
|
117
|
+
/**
|
|
118
|
+
* Injectable clock for the time-guard (tests simulate elapsed visibility
|
|
119
|
+
* instead of sleeping 3 × TTL). Defaults to the real current time.
|
|
120
|
+
*/
|
|
121
|
+
now?: Date | undefined;
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/engine/spec-schema.d.ts
|
|
125
|
+
/**
|
|
126
|
+
* System field names owned by the engine — a domain dimension, measure or
|
|
127
|
+
* marker may never shadow one.
|
|
128
|
+
*/
|
|
129
|
+
declare const RESERVED_FACT_FIELDS: readonly string[];
|
|
130
|
+
/** A measure normalized to its object form. */
|
|
131
|
+
interface ResolvedMeasure {
|
|
132
|
+
name: string;
|
|
133
|
+
nonNegative: boolean;
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/models/fact.model.d.ts
|
|
137
|
+
type FactDocument = BaseFactRow & mongoose.Document;
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/models/rollup.model.d.ts
|
|
140
|
+
/** The system portion of one rollup row (grain dims + measures are dynamic). */
|
|
141
|
+
interface BaseRollupRow {
|
|
142
|
+
generation: number;
|
|
143
|
+
civilDate: string;
|
|
144
|
+
civilWeek?: string | undefined;
|
|
145
|
+
civilMonth?: string | undefined;
|
|
146
|
+
schemaVersion: number;
|
|
147
|
+
/** Number of facts rolled into this row (plain integer — bounded per grain-day). */
|
|
148
|
+
factCount: number;
|
|
149
|
+
updatedAt: Date;
|
|
150
|
+
/** Grain dimensions (sentinel-normalized String) + Decimal128 measures. */
|
|
151
|
+
[key: string]: unknown;
|
|
152
|
+
}
|
|
153
|
+
type RollupDocument = BaseRollupRow & mongoose.Document;
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region src/models/checkpoint.model.d.ts
|
|
156
|
+
interface ProjectionCheckpoint {
|
|
157
|
+
checkpointId: string;
|
|
158
|
+
source: string;
|
|
159
|
+
generation: number;
|
|
160
|
+
lastId?: mongoose.Types.ObjectId;
|
|
161
|
+
processed: number;
|
|
162
|
+
inserted: number;
|
|
163
|
+
duplicates: number;
|
|
164
|
+
failed: number;
|
|
165
|
+
done: boolean;
|
|
166
|
+
startedAt: Date;
|
|
167
|
+
updatedAt: Date;
|
|
168
|
+
}
|
|
169
|
+
type CheckpointDocument = ProjectionCheckpoint & mongoose.Document;
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/backfill/backfill.d.ts
|
|
172
|
+
/**
|
|
173
|
+
* Compose the next keyset query: base filter + `_id > lastId` when resuming.
|
|
174
|
+
* Pure — the "resume from checkpoint" logic in one testable place.
|
|
175
|
+
*/
|
|
176
|
+
declare function buildKeysetQuery(baseFilter: Record<string, unknown>, lastId?: Types.ObjectId | null): Record<string, unknown>;
|
|
177
|
+
/**
|
|
178
|
+
* Classify an `insertMany({ordered:false})` outcome into inserted/duplicates
|
|
179
|
+
* counts. Call ONLY after `isDuplicateKeyOnly(err)` returned true — every
|
|
180
|
+
* write error is then a duplicate-key no-op. Pure.
|
|
181
|
+
*/
|
|
182
|
+
declare function countDuplicateWrites(err: unknown, totalFacts: number): number;
|
|
183
|
+
interface BackfillMapFailure {
|
|
184
|
+
id: string;
|
|
185
|
+
reason: string;
|
|
186
|
+
}
|
|
187
|
+
interface BackfillMapResult<TFact extends BaseFactRow = BaseFactRow> {
|
|
188
|
+
facts: TFact[];
|
|
189
|
+
failures: BackfillMapFailure[];
|
|
190
|
+
}
|
|
191
|
+
interface BackfillMapContext {
|
|
192
|
+
/** Target generation (active or a shadow rebuild generation). */
|
|
193
|
+
generation: number;
|
|
194
|
+
/** Batch projector stamp for `recordedAt`. */
|
|
195
|
+
recordedAt: Date;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* One keyset-iterable backfill source. The ENGINE owns iteration order,
|
|
199
|
+
* checkpoints, insert-dedupe and counting; the source owns the two
|
|
200
|
+
* domain-bound pieces:
|
|
201
|
+
*
|
|
202
|
+
* - `read(query, limit)` — return the next page of raw docs matching
|
|
203
|
+
* `query`, sorted `_id` ASCENDING, at most `limit`. Bind it over a driver
|
|
204
|
+
* collection (`c.find(q).sort({_id:1}).limit(n).toArray()`) or a mongoose
|
|
205
|
+
* model (`M.find(q).sort({_id:1}).limit(n).lean()`).
|
|
206
|
+
* - `mapBatch(docs, ctx)` — map raw docs to fact rows + per-doc failures
|
|
207
|
+
* (async so batch enrichment loads — e.g. parent-doc snapshots — can
|
|
208
|
+
* happen inside).
|
|
209
|
+
*
|
|
210
|
+
* Docs MUST have ObjectId `_id`s (the checkpoint cursor type).
|
|
211
|
+
*/
|
|
212
|
+
interface DocumentSource<TFact extends BaseFactRow = BaseFactRow> {
|
|
213
|
+
name: string;
|
|
214
|
+
/** Base filter of the scan (soft-delete-aware, matching what the live stream covered). */
|
|
215
|
+
filter: Record<string, unknown>;
|
|
216
|
+
read(query: Record<string, unknown>, limit: number): Promise<Array<Record<string, unknown>>>;
|
|
217
|
+
/** Optional total estimate for progress logging (e.g. `countDocuments(filter)`). */
|
|
218
|
+
estimateTotal?: ((filter: Record<string, unknown>) => Promise<number>) | undefined;
|
|
219
|
+
mapBatch(docs: Array<Record<string, unknown>>, ctx: BackfillMapContext): Promise<BackfillMapResult<TFact>> | BackfillMapResult<TFact>;
|
|
220
|
+
}
|
|
221
|
+
type BackfillLogger = (message: string) => void;
|
|
222
|
+
interface BackfillOptions<TFact extends BaseFactRow = BaseFactRow> {
|
|
223
|
+
/** Host-bound document sources — run in array order (parents-first matters). */
|
|
224
|
+
sources: readonly DocumentSource<TFact>[];
|
|
225
|
+
/** Target generation (active or a shadow rebuild generation). */
|
|
226
|
+
generation: number;
|
|
227
|
+
/** Checkpoint namespace — re-running this id for the same generation resumes. */
|
|
228
|
+
checkpointId: string;
|
|
229
|
+
batchSize?: number | undefined;
|
|
230
|
+
/** Total source-doc budget for THIS invocation (across sources). */
|
|
231
|
+
maxDocs?: number | undefined;
|
|
232
|
+
/** Pause between batches (rate limiting). */
|
|
233
|
+
sleepMs?: number | undefined;
|
|
234
|
+
/** Clear the (checkpointId, sources) checkpoints and start over. */
|
|
235
|
+
restart?: boolean | undefined;
|
|
236
|
+
log?: BackfillLogger | undefined;
|
|
237
|
+
}
|
|
238
|
+
interface SourceBackfillResult {
|
|
239
|
+
source: string;
|
|
240
|
+
processed: number;
|
|
241
|
+
inserted: number;
|
|
242
|
+
duplicates: number;
|
|
243
|
+
failed: number;
|
|
244
|
+
done: boolean;
|
|
245
|
+
}
|
|
246
|
+
interface BackfillResult {
|
|
247
|
+
generation: number;
|
|
248
|
+
checkpointId: string;
|
|
249
|
+
sources: SourceBackfillResult[];
|
|
250
|
+
/** True when every requested source ran to completion. */
|
|
251
|
+
complete: boolean;
|
|
252
|
+
/**
|
|
253
|
+
* Aggregate mapper-failure count across all sources. A source can finish
|
|
254
|
+
* `done: true` with `failed > 0` (mapper failures are logged, not aborted),
|
|
255
|
+
* so `complete` alone does NOT prove the generation is whole.
|
|
256
|
+
*/
|
|
257
|
+
failed: number;
|
|
258
|
+
/**
|
|
259
|
+
* True only when the generation is safe to cut over to: every source ran to
|
|
260
|
+
* completion AND zero docs failed to map. Gate `markBackfillComplete` /
|
|
261
|
+
* cutover on THIS, never on `complete` — a `complete && !clean` generation is
|
|
262
|
+
* MISSING the failed docs' facts.
|
|
263
|
+
*/
|
|
264
|
+
clean: boolean;
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/reconcile/reconcile.d.ts
|
|
268
|
+
interface ReconcileWindow {
|
|
269
|
+
/** Civil-date window, inclusive (YYYY-MM-DD, business zone). */
|
|
270
|
+
from: string;
|
|
271
|
+
to: string;
|
|
272
|
+
}
|
|
273
|
+
/** One source-side total cell: a civil day × cell-dimension values. */
|
|
274
|
+
interface ReconcileSourceRow {
|
|
275
|
+
civilDate: string;
|
|
276
|
+
/** Values for the reconcile cell dimensions (omit when `dimensions` is empty). */
|
|
277
|
+
dimensions?: Record<string, string> | undefined;
|
|
278
|
+
/** measure → total, for (a subset of) the source's declared measures. */
|
|
279
|
+
totals: Record<string, number>;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* A named source-side aggregation: independently recompute per-cell totals
|
|
283
|
+
* for the fact measures it is authoritative for, straight from the durable
|
|
284
|
+
* source documents.
|
|
285
|
+
*/
|
|
286
|
+
interface ReconcileSource {
|
|
287
|
+
name: string;
|
|
288
|
+
/** The fact measures this source contributes (each must be a declared fact measure). */
|
|
289
|
+
measures: readonly string[];
|
|
290
|
+
aggregate(window: ReconcileWindow): Promise<ReconcileSourceRow[]>;
|
|
291
|
+
}
|
|
292
|
+
interface DriftRow {
|
|
293
|
+
civilDate: string;
|
|
294
|
+
/** Cell dimension values (empty object when reconciling per-day only). */
|
|
295
|
+
dimensions: Record<string, string>;
|
|
296
|
+
measure: string;
|
|
297
|
+
factTotal: number;
|
|
298
|
+
sourceTotal: number;
|
|
299
|
+
drift: number;
|
|
300
|
+
}
|
|
301
|
+
interface ReconcileSummary {
|
|
302
|
+
generation: number;
|
|
303
|
+
from: string;
|
|
304
|
+
to: string;
|
|
305
|
+
cellsCompared: number;
|
|
306
|
+
driftCount: number;
|
|
307
|
+
clean: boolean;
|
|
308
|
+
}
|
|
309
|
+
interface ReconcileReport {
|
|
310
|
+
drifts: DriftRow[];
|
|
311
|
+
summary: ReconcileSummary;
|
|
312
|
+
}
|
|
313
|
+
interface ReconcileOptions {
|
|
314
|
+
generation: number;
|
|
315
|
+
/** Civil-date window, inclusive (YYYY-MM-DD, business zone). */
|
|
316
|
+
from: string;
|
|
317
|
+
to: string;
|
|
318
|
+
/**
|
|
319
|
+
* Fact dimensions that define a reconcile CELL alongside `civilDate`
|
|
320
|
+
* (e.g. `['organizationId']`). Default: per-day totals only.
|
|
321
|
+
*/
|
|
322
|
+
dimensions?: readonly string[] | undefined;
|
|
323
|
+
sources: readonly ReconcileSource[];
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/manifest/manifest.d.ts
|
|
327
|
+
/** Default manifest read-cache TTL when the spec does not override it. */
|
|
328
|
+
declare const DEFAULT_GENERATION_CACHE_TTL_MS = 5000;
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/freshness/freshness.d.ts
|
|
331
|
+
/** Diagnostic reads over the projection's DEDICATED outbox store (P10 port). */
|
|
332
|
+
interface FreshnessSource {
|
|
333
|
+
/** Age in ms of the oldest pending row; null (or 0) when the queue is drained. */
|
|
334
|
+
oldestPendingAgeMs(): Promise<number | null>;
|
|
335
|
+
/** Business instant (`meta.timestamp`) of the newest DELIVERED row; null when none. */
|
|
336
|
+
newestDeliveredInstant?: (() => Promise<Date | null>) | undefined;
|
|
337
|
+
}
|
|
338
|
+
interface ProjectionFreshness {
|
|
339
|
+
projectedThrough: Date | null;
|
|
340
|
+
lagMs: number;
|
|
341
|
+
status: 'fresh' | 'delayed' | 'rebuilding';
|
|
342
|
+
}
|
|
343
|
+
interface GetFreshnessOptions {
|
|
344
|
+
/** Lag threshold for `delayed` (default 60 000 ms). */
|
|
345
|
+
maxLagMs?: number | undefined;
|
|
346
|
+
}
|
|
347
|
+
declare const DEFAULT_MAX_LAG_MS = 60000;
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region src/rollup/increments.d.ts
|
|
350
|
+
/**
|
|
351
|
+
* Null-normalization sentinel for absent grain dimensions. Stable — changing
|
|
352
|
+
* it strands existing rows under the old sentinel.
|
|
353
|
+
*/
|
|
354
|
+
declare const ROLLUP_DIM_NONE = "(none)";
|
|
355
|
+
declare function normalizeDim(value: unknown): string;
|
|
356
|
+
/** The unique grain of one rollup row: generation + civilDate + grain dims. */
|
|
357
|
+
interface RollupGrain {
|
|
358
|
+
generation: number;
|
|
359
|
+
civilDate: string;
|
|
360
|
+
/** Sentinel-normalized grain dimension values. */
|
|
361
|
+
[dim: string]: string | number;
|
|
362
|
+
}
|
|
363
|
+
/** The rollup grain a fact rolls into — sentinel-normalized (see header). */
|
|
364
|
+
declare function grainFromFact(rollup: RollupSpec, fact: BaseFactRow): RollupGrain;
|
|
365
|
+
interface RollupIncrement {
|
|
366
|
+
grain: RollupGrain;
|
|
367
|
+
/**
|
|
368
|
+
* Grain-adjacent calendar labels for the `$setOnInsert` arm of the upsert
|
|
369
|
+
* — taken from the facts (which carry both, derived from the same
|
|
370
|
+
* civilDate), NOT part of the match filter.
|
|
371
|
+
*/
|
|
372
|
+
civilWeek: string;
|
|
373
|
+
civilMonth: string;
|
|
374
|
+
/** Per-measure integer deltas plus factCount. */
|
|
375
|
+
inc: Record<string, number>;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Group facts into per-grain `$inc` deltas — the pure core of the §4.3
|
|
379
|
+
* projection transaction. Deterministic order (sorted by grain key) so
|
|
380
|
+
* concurrent transactions touch rollup rows in a stable order.
|
|
381
|
+
*/
|
|
382
|
+
declare function incrementsFromFacts(rollup: RollupSpec, facts: readonly BaseFactRow[]): RollupIncrement[];
|
|
383
|
+
/**
|
|
384
|
+
* Serialize a Decimal128 (or driver-numeric) measure to a JS number at a
|
|
385
|
+
* read boundary. THROWS on non-integer or unsafe magnitude — a lossy
|
|
386
|
+
* conversion must never be silent (the exactness contract).
|
|
387
|
+
*/
|
|
388
|
+
declare function rollupMeasureToNumber(value: unknown, context: string): number;
|
|
389
|
+
//#endregion
|
|
390
|
+
//#region src/rollup/rebuild.d.ts
|
|
391
|
+
interface RebuildRollupOptions {
|
|
392
|
+
generation: number;
|
|
393
|
+
/** Civil-date window, inclusive. Defaults to the generation's fact min/max. */
|
|
394
|
+
from?: string | undefined;
|
|
395
|
+
to?: string | undefined;
|
|
396
|
+
/** Days per aggregate/write batch (default 7). */
|
|
397
|
+
batchDays?: number | undefined;
|
|
398
|
+
log?: ((message: string) => void) | undefined;
|
|
399
|
+
}
|
|
400
|
+
interface RebuildRollupResult {
|
|
401
|
+
generation: number;
|
|
402
|
+
/** Window actually rebuilt (null when the generation has no facts). */
|
|
403
|
+
from: string | null;
|
|
404
|
+
to: string | null;
|
|
405
|
+
days: number;
|
|
406
|
+
/** Rollup grain rows written. */
|
|
407
|
+
rows: number;
|
|
408
|
+
/** Pre-existing rollup rows deleted before rewrite. */
|
|
409
|
+
deleted: number;
|
|
410
|
+
}
|
|
411
|
+
interface MergedRow {
|
|
412
|
+
grain: RollupGrain;
|
|
413
|
+
totals: Record<string, number>;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Merge raw per-(rawGrain) aggregate rows into sentinel-normalized rollup
|
|
417
|
+
* rows, summing measures. Pure (exported for unit tests). Rows missing
|
|
418
|
+
* `civilDate` are skipped defensively (it is a required fact field).
|
|
419
|
+
*/
|
|
420
|
+
declare function mergeFactRowsByNormalizedGrain(rollup: RollupSpec, generation: number, rows: readonly Record<string, unknown>[]): MergedRow[];
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/purge/purge.d.ts
|
|
423
|
+
interface PurgeGenerationOptions {
|
|
424
|
+
/** Rows per purge batch (native chunking). Default kit-specific (~1000). */
|
|
425
|
+
batchSize?: number | undefined;
|
|
426
|
+
}
|
|
427
|
+
interface PurgeGenerationResult {
|
|
428
|
+
/** Fact rows hard-deleted. */
|
|
429
|
+
facts: number;
|
|
430
|
+
/** Rollup rows hard-deleted. */
|
|
431
|
+
rollup: number;
|
|
432
|
+
/** Checkpoint bookkeeping rows removed. */
|
|
433
|
+
checkpoints: number;
|
|
434
|
+
/** Evidence scaffolding for the host: `generation:<gen>`. */
|
|
435
|
+
scope: string;
|
|
436
|
+
/** Evidence scaffolding: the strategy that ran (always `hard` here). */
|
|
437
|
+
strategy: 'hard';
|
|
438
|
+
/** Evidence scaffolding: measures were NOT retained (rows removed). */
|
|
439
|
+
measuresRetained: false;
|
|
440
|
+
}
|
|
441
|
+
interface PurgeOccurrenceOptions {
|
|
442
|
+
/**
|
|
443
|
+
* After deleting the fact rows, re-derive the affected civilDate rollup
|
|
444
|
+
* window(s) so the aggregate reflects the erasure. When omitted the rollup
|
|
445
|
+
* keeps the stale `$inc` contribution until the next rebuild.
|
|
446
|
+
*/
|
|
447
|
+
rebuild?: boolean | undefined;
|
|
448
|
+
/**
|
|
449
|
+
* Explicit civilDate window override for the rebuild (defaults to the
|
|
450
|
+
* deleted facts' own civilDate extent, per affected generation).
|
|
451
|
+
*/
|
|
452
|
+
from?: string | undefined;
|
|
453
|
+
to?: string | undefined;
|
|
454
|
+
}
|
|
455
|
+
interface PurgeOccurrenceResult {
|
|
456
|
+
/** Fact rows hard-deleted for this dedupeKey. */
|
|
457
|
+
facts: number;
|
|
458
|
+
/** True when the affected civilDate rollup window(s) were rebuilt. */
|
|
459
|
+
rebuilt?: boolean | undefined;
|
|
460
|
+
/** Evidence scaffolding: `occurrence:<dedupeKey>`. */
|
|
461
|
+
scope: string;
|
|
462
|
+
/** Evidence scaffolding: strategy (always `hard`). */
|
|
463
|
+
strategy: 'hard';
|
|
464
|
+
/** Evidence scaffolding: measures were NOT retained (rows removed). */
|
|
465
|
+
measuresRetained: false;
|
|
466
|
+
}
|
|
467
|
+
interface AnonymizeFactWindowOptions {
|
|
468
|
+
generation: number;
|
|
469
|
+
/** Inclusive civilDate window start (YYYY-MM-DD). */
|
|
470
|
+
from: string;
|
|
471
|
+
/** Inclusive civilDate window end (YYYY-MM-DD). */
|
|
472
|
+
to: string;
|
|
473
|
+
/**
|
|
474
|
+
* The PII-redaction `$set` patch — declared fields overwritten on every
|
|
475
|
+
* matching row (e.g. `{ customerId: null }`). Measures are NEVER listed
|
|
476
|
+
* here; they are retained by design.
|
|
477
|
+
*/
|
|
478
|
+
fields: Record<string, unknown>;
|
|
479
|
+
/** Optional extra dimension equality clauses ANDed into the window filter. */
|
|
480
|
+
dimensions?: Record<string, unknown> | undefined;
|
|
481
|
+
/**
|
|
482
|
+
* Opt-in escape hatch for redacting a field that IS part of `rollup.grain`.
|
|
483
|
+
* Absent (the default), a `fields` key intersecting the grain is REJECTED —
|
|
484
|
+
* redacting a grain dimension shifts fact rows to the `'(none)'` sentinel
|
|
485
|
+
* while the rollup grain rows keep the old value, a silent facts↔rollup
|
|
486
|
+
* divergence. With `rebuild: true` the affected civilDate window's rollup is
|
|
487
|
+
* re-derived from the (now-redacted) facts afterwards — the same rebuild
|
|
488
|
+
* machinery `purgeOccurrence` uses — so the aggregate reconverges.
|
|
489
|
+
*/
|
|
490
|
+
rebuild?: boolean | undefined;
|
|
491
|
+
/** Rows per purge batch (native chunking). */
|
|
492
|
+
batchSize?: number | undefined;
|
|
493
|
+
}
|
|
494
|
+
interface AnonymizeFactWindowResult {
|
|
495
|
+
/** Fact rows redacted. */
|
|
496
|
+
processed: number;
|
|
497
|
+
/** Evidence scaffolding: measures were RETAINED (only dimensions redacted). */
|
|
498
|
+
measuresRetained: true;
|
|
499
|
+
/** Evidence scaffolding: strategy (always `anonymize`). */
|
|
500
|
+
strategy: 'anonymize';
|
|
501
|
+
/** Evidence scaffolding: `generation:<gen>`. */
|
|
502
|
+
scope: string;
|
|
503
|
+
/**
|
|
504
|
+
* True when a grain-dimension redaction triggered a rollup rebuild of the
|
|
505
|
+
* affected civilDate window. Omitted when no grain dimension was redacted
|
|
506
|
+
* (rollup grain untouched — no rebuild needed).
|
|
507
|
+
*/
|
|
508
|
+
rebuilt?: boolean | undefined;
|
|
509
|
+
}
|
|
510
|
+
//#endregion
|
|
511
|
+
//#region src/engine/engine-types.d.ts
|
|
512
|
+
/** Structural logger (pino-compatible object-first) — P10 optional in the spec. */
|
|
513
|
+
interface FactProjectionLogger {
|
|
514
|
+
info(obj: unknown, msg?: string): void;
|
|
515
|
+
warn(obj: unknown, msg?: string): void;
|
|
516
|
+
error(obj: unknown, msg?: string): void;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* The SYSTEM field families every fact row carries (the domain adds its
|
|
520
|
+
* dimensions, measures and markers on top via the index signature):
|
|
521
|
+
*
|
|
522
|
+
* - identity/provenance: `generation`, `dedupeKey` (deterministic BUSINESS
|
|
523
|
+
* occurrence key — the idempotency contract), `eventId`/`eventType`
|
|
524
|
+
* (provenance ONLY, never uniqueness), `schemaVersion`;
|
|
525
|
+
* - time: `occurredAt` (business instant), `recordedAt` (projector stamp),
|
|
526
|
+
* `civilDate`/`civilWeek`/`civilMonth` (business-zone categorical labels).
|
|
527
|
+
*
|
|
528
|
+
* Uniqueness is per `(generation, dedupeKey)` — at-least-once redelivery and
|
|
529
|
+
* transition-vs-completed double surfaces converge to one row.
|
|
530
|
+
*/
|
|
531
|
+
interface BaseFactRow {
|
|
532
|
+
generation: number;
|
|
533
|
+
dedupeKey: string;
|
|
534
|
+
eventId?: string | undefined;
|
|
535
|
+
eventType?: string | undefined;
|
|
536
|
+
schemaVersion?: number | undefined;
|
|
537
|
+
occurredAt: Date;
|
|
538
|
+
recordedAt: Date;
|
|
539
|
+
civilDate: string;
|
|
540
|
+
civilWeek: string;
|
|
541
|
+
civilMonth: string;
|
|
542
|
+
/** Domain dimensions, measures and quality markers (declared in the spec). */
|
|
543
|
+
[key: string]: unknown;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* One integer fact measure. Plain string = safe-integer validated (money in
|
|
547
|
+
* minor units). `nonNegative: true` additionally rejects negatives (whole
|
|
548
|
+
* quantities). Schema validators are the BACKSTOP — mappers should throw
|
|
549
|
+
* first via `assertValidQty` / `safeMulMinor`.
|
|
550
|
+
*/
|
|
551
|
+
type FactMeasureSpec<TMeasure extends string = string> = TMeasure | {
|
|
552
|
+
name: TMeasure;
|
|
553
|
+
nonNegative?: boolean | undefined;
|
|
554
|
+
};
|
|
555
|
+
/** Quality-marker vocabulary: an enum String field with an optional default. */
|
|
556
|
+
interface FactMarkerSpec {
|
|
557
|
+
values: readonly string[];
|
|
558
|
+
default?: string | undefined;
|
|
559
|
+
}
|
|
560
|
+
/** A domain secondary index. Rule 34: `comment` NAMES the query it serves. */
|
|
561
|
+
interface FactIndexSpec {
|
|
562
|
+
fields: Record<string, 1 | -1>;
|
|
563
|
+
/** The query pattern this index supports (rule 34 — no orphan indexes). */
|
|
564
|
+
comment: string;
|
|
565
|
+
options?: IndexOptions | undefined;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Fact-side declaration: dimensions (verbatim mongoose fields), measures,
|
|
569
|
+
* markers. Generic over the declared dimension + measure NAME unions (FIX 6)
|
|
570
|
+
* so `RollupSpec.grain ⊆ dimensions` and `RollupSpec.measures ⊆ measures` are
|
|
571
|
+
* COMPILER-checked (both default to `string` — an un-annotated / cast spec
|
|
572
|
+
* behaves exactly as before, with runtime `validateSpec` as the backstop).
|
|
573
|
+
*/
|
|
574
|
+
interface FactSpec<TDim extends string = string, TMeasure extends string = string> {
|
|
575
|
+
/**
|
|
576
|
+
* Domain dimension/provenance fields, verbatim mongoose definitions
|
|
577
|
+
* (e.g. `{ organizationId: { type: String, required: true }, skuRef: { type: String } }`).
|
|
578
|
+
* System field names are reserved and rejected at construction. The key
|
|
579
|
+
* union is captured as `TDim` so the rollup grain is checked against it.
|
|
580
|
+
*/
|
|
581
|
+
dimensions: Record<TDim, SchemaDefinitionProperty>;
|
|
582
|
+
/** Integer `Number` measures (see {@link FactMeasureSpec}). */
|
|
583
|
+
measures: readonly FactMeasureSpec<TMeasure>[];
|
|
584
|
+
/** Quality markers (plan §5.2 — reconstructed history must be marked). */
|
|
585
|
+
markers?: Record<string, FactMarkerSpec> | undefined;
|
|
586
|
+
/** Domain secondaries beyond the system unique `{generation, dedupeKey}`. */
|
|
587
|
+
extraIndexes?: readonly FactIndexSpec[] | undefined;
|
|
588
|
+
/** Fact-row schema version stamped as the field default (default 1). */
|
|
589
|
+
schemaVersion?: number | undefined;
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Rollup-side declaration: grain dimensions + Decimal128 measures. Generic
|
|
593
|
+
* over the fact's dimension + measure name unions (FIX 6) so `grain` and
|
|
594
|
+
* `measures` are constrained to declared fact fields at compile time.
|
|
595
|
+
*/
|
|
596
|
+
interface RollupSpec<TDim extends string = string, TMeasure extends string = string> {
|
|
597
|
+
/**
|
|
598
|
+
* Grain dimension names (each must be a declared fact dimension). The full
|
|
599
|
+
* unique grain is `generation × civilDate × ...grain` — absent values are
|
|
600
|
+
* null-normalized to the `'(none)'` sentinel.
|
|
601
|
+
*
|
|
602
|
+
* `NoInfer` makes this a CHECK-only position (FIX 6): the dimension union
|
|
603
|
+
* `TDim` is inferred solely from `fact.dimensions`, and grain entries are
|
|
604
|
+
* verified ⊆ that union — never the other way around (which would wrongly
|
|
605
|
+
* constrain the fact dimensions to the grain).
|
|
606
|
+
*/
|
|
607
|
+
grain: readonly NoInfer<TDim>[];
|
|
608
|
+
/** Measures accumulated as Decimal128 (each must be a declared fact measure). */
|
|
609
|
+
measures: readonly NoInfer<TMeasure>[];
|
|
610
|
+
/**
|
|
611
|
+
* Grain-adjacent calendar labels copied on first insert (1:1 with
|
|
612
|
+
* civilDate). Both default ON — the standard week/month grouping columns.
|
|
613
|
+
*/
|
|
614
|
+
derived?: {
|
|
615
|
+
civilWeek?: boolean | undefined;
|
|
616
|
+
civilMonth?: boolean | undefined;
|
|
617
|
+
} | undefined;
|
|
618
|
+
/** Domain secondaries beyond the unique grain index. */
|
|
619
|
+
extraIndexes?: readonly FactIndexSpec[] | undefined;
|
|
620
|
+
/** Rollup-row schema version stamped on insert (default 1). */
|
|
621
|
+
schemaVersion?: number | undefined;
|
|
622
|
+
}
|
|
623
|
+
/** Explicit physical collection names (rule 20.1 — never Mongoose pluralization). */
|
|
624
|
+
interface FactProjectionCollections {
|
|
625
|
+
facts: string;
|
|
626
|
+
rollup: string;
|
|
627
|
+
manifest: string;
|
|
628
|
+
checkpoints: string;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* DESCRIBE-time SHAPE (STANDARDIZATION-PLAN §6.2) — everything that determines
|
|
632
|
+
* the persistence SHAPE and the projection's identity, needing no connection or
|
|
633
|
+
* I/O to inspect. Nothing here opens a socket, reads a secret or computes a
|
|
634
|
+
* civil label. `defineFactProjection(shape)` validates this and freezes the
|
|
635
|
+
* model NAMES; the runtime collaborators arrive at `.bind()`.
|
|
636
|
+
*/
|
|
637
|
+
interface FactProjectionShape<TDim extends string = string, TMeasure extends string = string> {
|
|
638
|
+
/**
|
|
639
|
+
* Projection name — the manifest doc id, the model-name namespace and the
|
|
640
|
+
* label in every operator-facing message. Lowercase slug (e.g. `'sales'`).
|
|
641
|
+
*/
|
|
642
|
+
name: string;
|
|
643
|
+
collections: FactProjectionCollections;
|
|
644
|
+
fact: FactSpec<TDim, TMeasure>;
|
|
645
|
+
rollup: RollupSpec<TDim, TMeasure>;
|
|
646
|
+
/**
|
|
647
|
+
* Manifest read-cache TTL (default 5000ms). The cutover time-guard is
|
|
648
|
+
* 3 × this value — see the manifest module docblock.
|
|
649
|
+
*/
|
|
650
|
+
cacheTtlMs?: number | undefined;
|
|
651
|
+
/** Rule 35 — `false` in production; run `engine.syncIndexes()` at deploy. */
|
|
652
|
+
autoIndex?: boolean | undefined;
|
|
653
|
+
/**
|
|
654
|
+
* On a model-name collision: default throws (mongokit `ModelCollisionError`);
|
|
655
|
+
* `true` deletes + re-registers (hot-reload / test fixtures only, refused
|
|
656
|
+
* under `NODE_ENV=production`). Maps to mongokit's `replace` policy.
|
|
657
|
+
*/
|
|
658
|
+
forceRecreate?: boolean | undefined;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* BIND-time runtime collaborators — the live connection is the first `bind`
|
|
662
|
+
* arg; these are the rest. A source PORT (the civil calendar), a logger or a
|
|
663
|
+
* transactional-fallback policy belongs here, not in the shape (§6.2).
|
|
664
|
+
*/
|
|
665
|
+
interface FactProjectionRuntime {
|
|
666
|
+
/** Business-zone instant → civil label port (see the port's consistency contract). */
|
|
667
|
+
civil: CivilCalendarPort;
|
|
668
|
+
/**
|
|
669
|
+
* Standalone-Mongo fallback for the §4.3 projection transaction (the
|
|
670
|
+
* codebase-wide `allowFallback` convention): dev/tests only — production
|
|
671
|
+
* hosts leave this false so a non-transactional deployment fails closed.
|
|
672
|
+
*/
|
|
673
|
+
allowNonTransactional?: boolean | undefined;
|
|
674
|
+
logger?: FactProjectionLogger | undefined;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* The DESCRIBE/BIND blueprint for a fact projection (§6.1). `defineFactProjection(shape)`
|
|
678
|
+
* returns this: pure — validates the shape and freezes the model names, registering
|
|
679
|
+
* nothing until `.bind(connection, runtime)` compiles the schemas on the supplied
|
|
680
|
+
* connection and returns the live {@link FactProjection}. This is the SOLE construction
|
|
681
|
+
* API — there is no `createFactProjection` wrapper.
|
|
682
|
+
*/
|
|
683
|
+
interface FactProjectionBlueprint<TFact extends BaseFactRow = BaseFactRow> {
|
|
684
|
+
/** The projection identity — the shape's `name`. */
|
|
685
|
+
readonly id: string;
|
|
686
|
+
/** The four model names this blueprint registers — known without a connection. */
|
|
687
|
+
readonly modelNames: readonly string[];
|
|
688
|
+
/**
|
|
689
|
+
* Compile + register the four models on `connection`, wire repositories/manifest,
|
|
690
|
+
* and return the frozen engine. Synchronous — facts' construction performs no async
|
|
691
|
+
* work (`ensureReady()` does the boot I/O).
|
|
692
|
+
*/
|
|
693
|
+
bind(connection: Connection, runtime: FactProjectionRuntime): FactProjection<TFact>;
|
|
694
|
+
}
|
|
695
|
+
interface FactProjectionModels {
|
|
696
|
+
Fact: Model<FactDocument>;
|
|
697
|
+
Rollup: Model<RollupDocument>;
|
|
698
|
+
Manifest: Model<ProjectionManifestDocument>;
|
|
699
|
+
Checkpoint: Model<CheckpointDocument>;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* mongokit repositories over the projections — the read surface for ports
|
|
703
|
+
* and the rebuild/reconcile aggregate paths. NO tenant/soft-delete plugins
|
|
704
|
+
* BY DESIGN: these are analytical projections where `organizationId` (when
|
|
705
|
+
* the domain declares it) is a queryable DIMENSION, not a scope; scope
|
|
706
|
+
* enforcement lives at the query surface (lens/resource layer). Attaching a
|
|
707
|
+
* tenant plugin would break the projector (system writes carry no request
|
|
708
|
+
* scope) and HQ rollup reads.
|
|
709
|
+
*/
|
|
710
|
+
interface FactProjectionRepositories {
|
|
711
|
+
facts: Repository<FactDocument>;
|
|
712
|
+
rollup: Repository<RollupDocument>;
|
|
713
|
+
}
|
|
714
|
+
/** The generation-manifest verb surface (§9 verified-cutover protocol). */
|
|
715
|
+
interface FactProjectionManifest {
|
|
716
|
+
/** The manifest read-cache TTL in effect. */
|
|
717
|
+
readonly cacheTtlMs: number;
|
|
718
|
+
/** Cutover time-guard: minimum rebuild visibility (3 × cacheTtlMs). */
|
|
719
|
+
readonly cutoverMinRebuildVisibleMs: number;
|
|
720
|
+
beginRebuild(): Promise<BeginRebuildResult>;
|
|
721
|
+
markBackfillComplete(options: MarkBackfillCompleteOptions): Promise<ProjectionManifestData>;
|
|
722
|
+
markVerified(options: MarkVerifiedOptions): Promise<ProjectionManifestData>;
|
|
723
|
+
cutover(options?: CutoverOptions): Promise<ProjectionManifestData>;
|
|
724
|
+
abortRebuild(): Promise<void>;
|
|
725
|
+
/** The generation READERS resolve through (cached; default 1 when absent). */
|
|
726
|
+
getActiveGeneration(): Promise<number>;
|
|
727
|
+
/**
|
|
728
|
+
* The generation set the live PROJECTOR writes through: `[active]`
|
|
729
|
+
* normally, `[active, rebuildGeneration]` while a rebuild is in ANY
|
|
730
|
+
* rebuild state (dual-write through the whole protocol).
|
|
731
|
+
*/
|
|
732
|
+
getGenerationTargets(): Promise<number[]>;
|
|
733
|
+
/** Current manifest snapshot (null when the doc was never created). */
|
|
734
|
+
getManifest(): Promise<ProjectionManifestData | null>;
|
|
735
|
+
/** Drop the per-engine caches — called by every mutation (and tests). */
|
|
736
|
+
invalidateCache(): void;
|
|
737
|
+
}
|
|
738
|
+
interface ProjectFactsOptions {
|
|
739
|
+
/**
|
|
740
|
+
* Explicit target generations (each row is restamped per target). Defaults
|
|
741
|
+
* to the manifest's cached `getGenerationTargets()` — dual-write during
|
|
742
|
+
* rebuilds. Backfills pass their single explicit shadow generation instead.
|
|
743
|
+
*/
|
|
744
|
+
generations?: readonly number[] | undefined;
|
|
745
|
+
}
|
|
746
|
+
interface FactProjection<TFact extends BaseFactRow = BaseFactRow> {
|
|
747
|
+
/** The resolved projection name. */
|
|
748
|
+
readonly name: string;
|
|
749
|
+
readonly models: FactProjectionModels;
|
|
750
|
+
readonly repositories: FactProjectionRepositories;
|
|
751
|
+
readonly manifest: FactProjectionManifest;
|
|
752
|
+
/** Instant → the four system time fields, through the injected civil port. */
|
|
753
|
+
civilFields(occurredAt: Date): CivilFields;
|
|
754
|
+
/**
|
|
755
|
+
* The §4.3 small projection transaction for rows ALREADY MAPPED by the
|
|
756
|
+
* domain: per target generation — dedupe pre-read (redelivery drives
|
|
757
|
+
* nothing) → ONE transaction: insert only-new facts + apply their per-grain
|
|
758
|
+
* rollup `$inc` upserts. Every failure THROWS (relay retry/DLQ contract).
|
|
759
|
+
*/
|
|
760
|
+
projectFacts(facts: readonly TFact[], options?: ProjectFactsOptions): Promise<void>;
|
|
761
|
+
/** Deterministic rollup re-aggregation from facts (bounded civil-date chunks). */
|
|
762
|
+
rebuildRollup(options: RebuildRollupOptions): Promise<RebuildRollupResult>;
|
|
763
|
+
/**
|
|
764
|
+
* Hard-purge a RETIRED generation's facts + rollup + checkpoints (native
|
|
765
|
+
* `purgeByField`). REFUSES the live active / in-flight rebuild generation.
|
|
766
|
+
* Closes the retired-generation cleanup leak left by `cutover()`.
|
|
767
|
+
*/
|
|
768
|
+
purgeGeneration(gen: number, options?: PurgeGenerationOptions): Promise<PurgeGenerationResult>;
|
|
769
|
+
/**
|
|
770
|
+
* Hard-delete one business occurrence's fact rows (native `purgeByField` on
|
|
771
|
+
* `dedupeKey`); with `{ rebuild: true }` re-derives the affected civilDate
|
|
772
|
+
* rollup window(s). The per-occurrence erasure companion.
|
|
773
|
+
*/
|
|
774
|
+
purgeOccurrence(dedupeKey: string, options?: PurgeOccurrenceOptions): Promise<PurgeOccurrenceResult>;
|
|
775
|
+
/**
|
|
776
|
+
* Redact PII dimensions across a civilDate RANGE while RETAINING measures
|
|
777
|
+
* (native `purgeByFilter` + `anonymize` strategy over a repo-core Filter IR
|
|
778
|
+
* window). The GDPR / retention path — measures untouched.
|
|
779
|
+
*/
|
|
780
|
+
anonymizeFactWindow(options: AnonymizeFactWindowOptions): Promise<AnonymizeFactWindowResult>;
|
|
781
|
+
/** Resumable keyset document backfill over host-supplied sources. */
|
|
782
|
+
runBackfill(options: BackfillOptions<TFact>): Promise<BackfillResult>;
|
|
783
|
+
/** Facts-vs-source drift report over a civil-date window (read-only). */
|
|
784
|
+
reconcile(options: ReconcileOptions): Promise<ReconcileReport>;
|
|
785
|
+
/** Outbox + manifest → `{projectedThrough, lagMs, status}` (§4.4 freshness). */
|
|
786
|
+
getFreshness(source: FreshnessSource, options?: GetFreshnessOptions): Promise<ProjectionFreshness>;
|
|
787
|
+
/**
|
|
788
|
+
* Boot gate: asserts backend capabilities (transactions unless
|
|
789
|
+
* `allowNonTransactional`, upsert) and materialises the four collections
|
|
790
|
+
* (MongoDB refuses DDL inside transactions). `skipIndexes: true` for
|
|
791
|
+
* production boots (rule 35).
|
|
792
|
+
*/
|
|
793
|
+
ensureReady(options?: {
|
|
794
|
+
skipIndexes?: boolean | undefined;
|
|
795
|
+
}): Promise<void>;
|
|
796
|
+
/** Deploy-time index sync across every managed model (rule 35). */
|
|
797
|
+
syncIndexes(): Promise<void>;
|
|
798
|
+
/**
|
|
799
|
+
* Release engine-held state (the manifest read-cache). Models stay registered
|
|
800
|
+
* on the connection. The SOLE teardown name (§6.4) — no `destroy`/`dispose`.
|
|
801
|
+
* Facts owns no event transport, so there is nothing external to unsubscribe.
|
|
802
|
+
*/
|
|
803
|
+
close(): Promise<void>;
|
|
804
|
+
}
|
|
805
|
+
//#endregion
|
|
806
|
+
//#region src/engine/define-fact-projection.d.ts
|
|
807
|
+
/**
|
|
808
|
+
* Describe a fact projection. Pure — validates the shape, freezes the four
|
|
809
|
+
* model names, registers nothing and performs no I/O.
|
|
810
|
+
*/
|
|
811
|
+
declare function defineFactProjection<TFact extends BaseFactRow = BaseFactRow, TDim extends string = string, TMeasure extends string = string>(shape: FactProjectionShape<TDim, TMeasure>): FactProjectionBlueprint<TFact>;
|
|
812
|
+
//#endregion
|
|
813
|
+
//#region src/models/create-models.d.ts
|
|
814
|
+
interface DefineFactProjectionModelsConfig {
|
|
815
|
+
name: string;
|
|
816
|
+
/**
|
|
817
|
+
* Explicit physical collection names from the shape (rule 20.1) — every model
|
|
818
|
+
* pins its collection so Mongoose never falls back to its pluralizer. Changing
|
|
819
|
+
* a deployed name is a breaking change (renames the physical collection); ship
|
|
820
|
+
* a rename migration, never in a patch.
|
|
821
|
+
*/
|
|
822
|
+
collections: FactProjectionCollections;
|
|
823
|
+
fact: FactSpec;
|
|
824
|
+
measures: readonly ResolvedMeasure[];
|
|
825
|
+
rollup: RollupSpec;
|
|
826
|
+
/** On a name collision: `false` (default) throws; `true` re-registers (test/dev fixtures). */
|
|
827
|
+
forceRecreate?: boolean | undefined;
|
|
828
|
+
/** Rule 35 — `false` for production boots; sync indexes at deploy time. Default `true`. */
|
|
829
|
+
autoIndex?: boolean | undefined;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Describe the four projection models as a connection-free blueprint. Pure —
|
|
833
|
+
* builds no schema and registers nothing until `.bind(connection)`. Each schema
|
|
834
|
+
* factory runs at most once, only when its model is actually registered.
|
|
835
|
+
*/
|
|
836
|
+
declare function defineFactProjectionModels(config: DefineFactProjectionModelsConfig): ModelBlueprint<FactProjectionModels>;
|
|
837
|
+
//#endregion
|
|
838
|
+
//#region src/projector/guards.d.ts
|
|
839
|
+
/**
|
|
840
|
+
* Assert a quantity is a whole, non-negative, safe integer. THROWS otherwise
|
|
841
|
+
* (relay retry/DLQ path for live events; loud abort for the backfill) — a
|
|
842
|
+
* negative or fractional quantity is corrupt input that must never be
|
|
843
|
+
* silently projected.
|
|
844
|
+
*/
|
|
845
|
+
declare function assertValidQty(value: number, context: string): number;
|
|
846
|
+
/**
|
|
847
|
+
* Multiply a per-unit minor-unit amount by a quantity, THROWING when the
|
|
848
|
+
* product leaves the safe-integer range. Writing an unsafe float would
|
|
849
|
+
* silently corrupt money aggregates — the error must ride the retry/DLQ (or
|
|
850
|
+
* backfill-abort) path instead.
|
|
851
|
+
*/
|
|
852
|
+
declare function safeMulMinor(unitMinor: number, quantity: number, context: string): number;
|
|
853
|
+
/**
|
|
854
|
+
* True when an `insertMany` failure is ONLY duplicate-key (code 11000) —
|
|
855
|
+
* i.e. every failed write hit the unique `{generation, dedupeKey}` index.
|
|
856
|
+
* Any other error class (validation, network, mixed batches) returns false
|
|
857
|
+
* and MUST be rethrown by the caller. Scalar classification delegates to
|
|
858
|
+
* mongokit's `isDuplicateKeyError` (the authoritative 11000 classifier).
|
|
859
|
+
*/
|
|
860
|
+
declare function isDuplicateKeyOnly(err: unknown): boolean;
|
|
861
|
+
/**
|
|
862
|
+
* Given a duplicate-key-only `insertMany({ordered:false})` failure, return
|
|
863
|
+
* the facts that DID insert (writeErrors carry the failed batch indexes).
|
|
864
|
+
* Pure; used only on the non-transactional fallback path.
|
|
865
|
+
*/
|
|
866
|
+
declare function subtractFailedInserts<TFact extends BaseFactRow>(facts: readonly TFact[], err: unknown): TFact[];
|
|
867
|
+
//#endregion
|
|
868
|
+
//#region src/cleanup/steps.d.ts
|
|
869
|
+
/** The projection surface the steps drive — everything `defineFactProjection().bind()` returns. */
|
|
870
|
+
type ProjectionCleanupSource = Pick<FactProjection, 'name' | 'repositories' | 'manifest' | 'rebuildRollup' | 'purgeGeneration'>;
|
|
871
|
+
interface ProjectionCleanupSteps {
|
|
872
|
+
/** §4.3 `cleanup.rebuild-projections` provider — non-destructive. */
|
|
873
|
+
rebuildRollup: CleanupStep;
|
|
874
|
+
/** Retired-generation hygiene provider — destructive (facts+rollup+checkpoints). */
|
|
875
|
+
purgeRetiredGenerations: CleanupStep;
|
|
876
|
+
}
|
|
877
|
+
declare function createProjectionCleanupSteps(projection: ProjectionCleanupSource): ProjectionCleanupSteps;
|
|
878
|
+
//#endregion
|
|
879
|
+
//#region src/ensure-ready.d.ts
|
|
880
|
+
/**
|
|
881
|
+
* ## This gate could not fire until 2026-08-05
|
|
882
|
+
*
|
|
883
|
+
* `capabilities` resolved to mongokit's STATIC `MONGOKIT_CAPABILITIES`, whose
|
|
884
|
+
* `transactions` was hard-coded `true`, so the `transactions` half of this
|
|
885
|
+
* check was a tautology for every mongoose-backed repository and
|
|
886
|
+
* `allowNonTransactional` waived nothing (AGENTS.md FAIL LOUD rule 4).
|
|
887
|
+
* mongokit now OBSERVES the live SDAM topology per connection.
|
|
888
|
+
*
|
|
889
|
+
* Three answers, not two: an OBSERVED "no" (a standalone — fix the deployment)
|
|
890
|
+
* is distinguished from "could not determine" (bound before the connection
|
|
891
|
+
* opened, an unreadable driver). Both refuse, because an unobserved outcome is
|
|
892
|
+
* not a positive one (rule 3) — but the operator's fix differs, so the message
|
|
893
|
+
* does too. Only `transactions` is ever waivable; a backend without `upsert` /
|
|
894
|
+
* `purgeByField` / `purgeByFilter` is broken, not a deployment choice.
|
|
895
|
+
*/
|
|
896
|
+
declare function assertFactsCapabilities(capabilities: RepoCapabilities | undefined, allowNonTransactional: boolean): void;
|
|
897
|
+
interface EnsureFactsReadyOptions {
|
|
898
|
+
skipIndexes?: boolean | undefined;
|
|
899
|
+
}
|
|
900
|
+
declare function ensureFactsReady(engine: Pick<FactProjection, 'models' | 'syncIndexes'>, options?: EnsureFactsReadyOptions): Promise<void>;
|
|
901
|
+
//#endregion
|
|
902
|
+
//#region src/errors.d.ts
|
|
903
|
+
/**
|
|
904
|
+
* Base domain error for the facts kernel. Implements repo-core's `HttpError`
|
|
905
|
+
* shape so an arc host serializes every facts error to a proper
|
|
906
|
+
* `ErrorContract` with a status code — hosts switch on `code`, never on
|
|
907
|
+
* `message`.
|
|
908
|
+
*
|
|
909
|
+
* Codes are hierarchical: `facts.<area>.<problem>`.
|
|
910
|
+
*/
|
|
911
|
+
declare class FactsError extends Error implements HttpError {
|
|
912
|
+
readonly status: number;
|
|
913
|
+
readonly code: string;
|
|
914
|
+
readonly meta?: Record<string, unknown>;
|
|
915
|
+
constructor(input: {
|
|
916
|
+
status: number;
|
|
917
|
+
code: string;
|
|
918
|
+
message: string;
|
|
919
|
+
meta?: Record<string, unknown> | undefined;
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* The projection shape failed Zod validation at describe time, or the civil
|
|
924
|
+
* source port was malformed at bind (fail-fast). A model-name collision is NOT
|
|
925
|
+
* one of these — that surfaces as mongokit's typed `ModelCollisionError`.
|
|
926
|
+
*/
|
|
927
|
+
declare class FactsSpecError extends FactsError {
|
|
928
|
+
constructor(message: string, meta?: Record<string, unknown>);
|
|
929
|
+
}
|
|
930
|
+
/** The wired backend is missing runtime capabilities the projection requires. */
|
|
931
|
+
declare class FactsCapabilityError extends FactsError {
|
|
932
|
+
/**
|
|
933
|
+
* `true` when the backend never ANSWERED (bound before the connection
|
|
934
|
+
* opened, a driver exposing no topology) rather than answering "no". Both
|
|
935
|
+
* refuse — an unobserved outcome is never a positive one (AGENTS.md FAIL
|
|
936
|
+
* LOUD rule 3) — but the operator's fix differs, so the message must.
|
|
937
|
+
*/
|
|
938
|
+
readonly indeterminate: boolean;
|
|
939
|
+
constructor(missing: readonly string[], opts?: {
|
|
940
|
+
indeterminate?: boolean;
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
//#endregion
|
|
944
|
+
export { type AnonymizeFactWindowOptions, type AnonymizeFactWindowResult, type BackfillLogger, type BackfillMapContext, type BackfillMapFailure, type BackfillMapResult, type BackfillOptions, type BackfillResult, type BaseFactRow, type BaseRollupRow, type BeginRebuildResult, type CivilCalendarPort, type CivilFields, type CutoverOptions, DEFAULT_GENERATION_CACHE_TTL_MS, DEFAULT_MAX_LAG_MS, type DefineFactProjectionModelsConfig, type DocumentSource, type DriftRow, type FactDocument, type FactIndexSpec, type FactMarkerSpec, type FactMeasureSpec, type FactProjection, type FactProjectionBlueprint, type FactProjectionCollections, type FactProjectionLogger, type FactProjectionManifest, type FactProjectionModels, type FactProjectionRepositories, type FactProjectionRuntime, type FactProjectionShape, type FactSpec, FactsCapabilityError, FactsError, FactsSpecError, type FreshnessSource, type GetFreshnessOptions, type MarkBackfillCompleteOptions, type MarkVerifiedOptions, type ProjectFactsOptions, type ProjectionCheckpoint, type ProjectionCleanupSource, type ProjectionCleanupSteps, type ProjectionFreshness, type ProjectionManifestData, type ProjectionManifestState, type PurgeGenerationOptions, type PurgeGenerationResult, type PurgeOccurrenceOptions, type PurgeOccurrenceResult, REBUILD_STATES, RESERVED_FACT_FIELDS, ROLLUP_DIM_NONE, type RebuildRollupOptions, type RebuildRollupResult, type RebuildVerification, type ReconcileOptions, type ReconcileReport, type ReconcileSource, type ReconcileSourceRow, type ReconcileSummary, type ReconcileWindow, type RollupDocument, type RollupGrain, type RollupIncrement, type RollupSpec, type SourceBackfillResult, assertFactsCapabilities, assertValidQty, buildKeysetQuery, civilFieldsOf, countDuplicateWrites, createProjectionCleanupSteps, defineFactProjection, defineFactProjectionModels, ensureFactsReady, grainFromFact, incrementsFromFacts, isDuplicateKeyOnly, isoWeekOfCivilDate, mergeFactRowsByNormalizedGrain, nextCivilDate, normalizeDim, rollupMeasureToNumber, safeMulMinor, subtractFailedInserts };
|