@gscdump/engine 0.9.2 → 0.10.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/README.md CHANGED
@@ -33,7 +33,7 @@ Optional peers (install only what your runtime needs):
33
33
  | `@gscdump/engine/sql-fragments` | Reusable SQL fragments shared across analyzers. |
34
34
  | `@gscdump/engine/rollups` | Pre-aggregated rollup contracts + helpers. |
35
35
  | `@gscdump/engine/entities` | Entity helpers (sites, tenants, scope keys). |
36
- | `@gscdump/engine/resolver` | Dialect-neutral SQL composition: `ResolverAdapter`, `pgResolverAdapter`, `compilePg`/`compileSqlite`, `resolveToSQL`. |
36
+ | `@gscdump/engine/resolver` | Dialect-neutral SQL composition: `ResolverAdapter`, `pgResolverAdapter`, `resolveToSQL`. |
37
37
  | `@gscdump/engine/scope` | Multi-tenant scope predicates. |
38
38
  | `@gscdump/engine/arrow` | Apache Arrow utilities for engine result conversion. |
39
39
  | `@gscdump/engine/node` | Node-only DuckDB handle. |
@@ -6,26 +6,21 @@ var AnalyzerCapabilityError = class extends Error {
6
6
  this.name = "AnalyzerCapabilityError";
7
7
  }
8
8
  };
9
- function sourceCapabilities(source) {
10
- const caps = /* @__PURE__ */ new Set();
11
- if (source.executeSql) caps.add("executeSql");
12
- if (source.capabilities.fileSets) caps.add("partitionedParquet");
13
- if (source.capabilities.regex) caps.add("regex");
14
- if (source.capabilities.windowTotals) caps.add("windowTotals");
15
- if (source.capabilities.comparisonJoin) caps.add("comparisonJoin");
16
- if (source.capabilities.attachedTables) caps.add("attachedTables");
17
- return caps;
9
+ function sourceHas(source, cap) {
10
+ return source.capabilities[cap] === true;
18
11
  }
19
- function assertSatisfies(analyzer, caps) {
20
- const missing = analyzer.requires.filter((c) => !caps.has(c));
12
+ function assertSatisfies(analyzer, source) {
13
+ const missing = analyzer.requires.filter((c) => !sourceHas(source, c));
21
14
  if (missing.length > 0) throw new AnalyzerCapabilityError(analyzer.id, missing);
22
15
  }
23
16
  async function runAnalyzerFromSource(source, params, registry) {
24
- const caps = sourceCapabilities(source);
25
- const analyzer = registry.resolveAnalyzer(params.type, caps.has("executeSql") || caps.has("attachedTables"));
17
+ const analyzer = registry.resolveAnalyzer(params.type, sourceHas(source, "executeSql"));
26
18
  if (!analyzer) throw new AnalyzerCapabilityError(params.type, ["executeSql"]);
27
- assertSatisfies(analyzer, caps);
28
- const plan = analyzer.build(params);
19
+ assertSatisfies(analyzer, source);
20
+ const plan = analyzer.build(params, {
21
+ adapter: source.adapter,
22
+ siteId: source.siteId
23
+ });
29
24
  if (plan.kind === "rows") return runRowsPlanAgainstSource(source, analyzer, plan, params);
30
25
  return runSqlPlanAgainstSource(source, analyzer, plan, params);
31
26
  }
@@ -50,7 +45,6 @@ function fileSetsFor(plan) {
50
45
  }
51
46
  async function runSqlPlanAgainstSource(source, analyzer, plan, params) {
52
47
  if (!source.executeSql) throw new AnalyzerCapabilityError(analyzer.id, ["executeSql"]);
53
- if (plan.requiresAttachedTables && !source.capabilities.attachedTables) throw new AnalyzerCapabilityError(analyzer.id, ["attachedTables"]);
54
48
  const fileSets = source.capabilities.fileSets ? fileSetsFor(plan) : void 0;
55
49
  const rows = await source.executeSql(plan.sql, plan.params, fileSets ? { fileSets } : void 0);
56
50
  const extras = {};
@@ -62,7 +56,7 @@ async function runSqlPlanAgainstSource(source, analyzer, plan, params) {
62
56
  params,
63
57
  extras
64
58
  });
65
- const sourceMeta = source.capabilities.localSource ? { source: "local" } : source.capabilities.attachedTables ? { source: "browser" } : {};
59
+ const sourceMeta = source.kind ? { source: source.kind } : {};
66
60
  return {
67
61
  results,
68
62
  meta: {
@@ -0,0 +1,622 @@
1
+ import { r as currentSchemaVersion, t as SCHEMAS } from "./schema.mjs";
2
+ import { i as inferSearchType, n as dayPartition, s as objectKey, u as tenantPrefix } from "./storage.mjs";
3
+ import { a as compactTieredImpl, i as substituteNamedFiles, n as compileLogicalQueryPlan, o as enumeratePartitions } from "./compiler.mjs";
4
+ import { sqlEscape } from "../sql-bind.mjs";
5
+ import { d as buildExtrasQueries, f as buildTotalsSql, g as resolveToSQLOptimized, m as resolveComparisonSQL, t as createParquetResolverAdapter } from "./pg-adapter.mjs";
6
+ import { buildLogicalPlan } from "gscdump/query/plan";
7
+ import { normalizeUrl } from "gscdump/normalize";
8
+ async function encodeBytes(db, table, rows) {
9
+ const inName = db.makeTempPath("json");
10
+ const outName = db.makeTempPath("parquet");
11
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(rows));
12
+ const registered = [];
13
+ await db.registerFileBuffer(inName, jsonBytes);
14
+ registered.push(inName);
15
+ try {
16
+ const sql = rows.length === 0 ? `COPY (SELECT * FROM ${emptyTableSchema(table)} WHERE FALSE) TO '${sqlEscape(outName)}' (FORMAT PARQUET)` : `COPY (SELECT * FROM read_json_auto('${sqlEscape(inName)}', format='array', columns=${columnsJson(table)})) TO '${sqlEscape(outName)}' (FORMAT PARQUET)`;
17
+ await db.query(sql);
18
+ registered.push(outName);
19
+ return await db.copyFileToBuffer(outName);
20
+ } finally {
21
+ await db.dropFiles(registered);
22
+ }
23
+ }
24
+ async function decodeBytes(db, bytes, table) {
25
+ const name = db.makeTempPath("parquet");
26
+ await db.registerFileBuffer(name, bytes);
27
+ try {
28
+ return await db.query(`SELECT * ${dateReplaceClause(table)} FROM read_parquet('${sqlEscape(name)}')`);
29
+ } finally {
30
+ await db.dropFiles([name]);
31
+ }
32
+ }
33
+ function createDuckDBCodec(factory) {
34
+ return {
35
+ async writeRows(ctx, rows, key, dataSource) {
36
+ const bytes = await encodeBytes(await factory.getDuckDB(), ctx.table, rows);
37
+ await dataSource.write(key, bytes);
38
+ return {
39
+ bytes: bytes.byteLength,
40
+ rowCount: rows.length
41
+ };
42
+ },
43
+ async readRows(ctx, key, dataSource) {
44
+ return decodeBytes(await factory.getDuckDB(), await dataSource.read(key), ctx.table);
45
+ },
46
+ async compactRows(ctx, inputKeys, outputKey, dataSource) {
47
+ const db = await factory.getDuckDB();
48
+ if (inputKeys.length === 0) {
49
+ const bytes = await encodeBytes(db, ctx.table, []);
50
+ await dataSource.write(outputKey, bytes);
51
+ return {
52
+ bytes: bytes.byteLength,
53
+ rowCount: 0
54
+ };
55
+ }
56
+ const inputUris = inputKeys.map((k) => dataSource.uri?.(k));
57
+ if (inputUris.every((u) => u !== void 0)) {
58
+ const outName = db.makeTempPath("parquet");
59
+ const fileList = inputUris.map((u) => `'${sqlEscape(u)}'`).join(", ");
60
+ try {
61
+ await db.query(`COPY (SELECT * FROM read_parquet([${fileList}], union_by_name=true)) TO '${sqlEscape(outName)}' (FORMAT PARQUET)`);
62
+ const bytes = await db.copyFileToBuffer(outName);
63
+ const countRows = await db.query(`SELECT count(*)::BIGINT AS n FROM read_parquet('${sqlEscape(outName)}')`);
64
+ const rowCount = Number(countRows[0]?.n ?? 0);
65
+ await dataSource.write(outputKey, bytes);
66
+ return {
67
+ bytes: bytes.byteLength,
68
+ rowCount
69
+ };
70
+ } finally {
71
+ await db.dropFiles([outName]);
72
+ }
73
+ }
74
+ const inputs = await Promise.all(inputKeys.map((k) => dataSource.read(k)));
75
+ const inNames = [];
76
+ const outName = db.makeTempPath("parquet");
77
+ const registered = [];
78
+ for (let i = 0; i < inputs.length; i++) {
79
+ const name = db.makeTempPath("parquet");
80
+ await db.registerFileBuffer(name, inputs[i]);
81
+ inNames.push(name);
82
+ registered.push(name);
83
+ }
84
+ try {
85
+ const fileList = inNames.map((n) => `'${sqlEscape(n)}'`).join(", ");
86
+ await db.query(`COPY (SELECT * FROM read_parquet([${fileList}], union_by_name = true)) TO '${sqlEscape(outName)}' (FORMAT PARQUET)`);
87
+ registered.push(outName);
88
+ const bytes = await db.copyFileToBuffer(outName);
89
+ const countRows = await db.query(`SELECT count(*)::BIGINT AS n FROM read_parquet('${sqlEscape(outName)}')`);
90
+ const rowCount = Number(countRows[0]?.n ?? 0);
91
+ await dataSource.write(outputKey, bytes);
92
+ return {
93
+ bytes: bytes.byteLength,
94
+ rowCount
95
+ };
96
+ } finally {
97
+ await db.dropFiles(registered);
98
+ }
99
+ }
100
+ };
101
+ }
102
+ function rewriteEmptyFileSets(sql, placeholders, defaultTable, placeholderTables) {
103
+ let out = sql;
104
+ for (const [name, keys] of Object.entries(placeholders)) {
105
+ if (keys.length > 0) continue;
106
+ const emptyFallback = `(SELECT * FROM ${emptyTableSchema(placeholderTables?.[name] ?? defaultTable)} WHERE FALSE)`;
107
+ const pattern = new RegExp(`read_parquet\\(\\s*\\{\\{${name}\\}\\}\\s*(?:,\\s*union_by_name\\s*=\\s*true\\s*)?\\)`, "g");
108
+ out = out.replace(pattern, emptyFallback);
109
+ }
110
+ return out;
111
+ }
112
+ function createDuckDBExecutor(factory) {
113
+ return { async execute({ sql, params, fileKeys, placeholderTables, dataSource, table, signal }) {
114
+ signal?.throwIfAborted();
115
+ const db = await factory.getDuckDB();
116
+ const placeholders = {};
117
+ const registered = [];
118
+ for (const [name, keys] of Object.entries(fileKeys)) {
119
+ const resolved = [];
120
+ for (const key of keys) {
121
+ const uri = dataSource.uri?.(key);
122
+ if (uri !== void 0) resolved.push(uri);
123
+ else {
124
+ const bytes = await dataSource.read(key, void 0, signal);
125
+ await db.registerFileBuffer(key, bytes);
126
+ registered.push(key);
127
+ resolved.push(key);
128
+ }
129
+ }
130
+ placeholders[name] = resolved;
131
+ }
132
+ try {
133
+ signal?.throwIfAborted();
134
+ const finalSql = substituteNamedFiles(rewriteEmptyFileSets(sql, placeholders, table, placeholderTables), placeholders);
135
+ return {
136
+ rows: await db.query(finalSql, params),
137
+ sql: finalSql
138
+ };
139
+ } finally {
140
+ if (registered.length > 0) await db.dropFiles(registered);
141
+ }
142
+ } };
143
+ }
144
+ function emptyTableSchema(table) {
145
+ return `(FROM (VALUES ${placeholderValues(table)}) t(${columnList(table)}))`;
146
+ }
147
+ function canonicalEmptyParquetSchema(table) {
148
+ return emptyTableSchema(table);
149
+ }
150
+ function dateReplaceClause(table) {
151
+ if (!table) return "";
152
+ const dateCols = SCHEMAS[table].columns.filter((c) => c.type === "DATE").map((c) => c.name);
153
+ if (dateCols.length === 0) return "";
154
+ return `REPLACE (${dateCols.map((n) => `strftime(${n}, '%Y-%m-%d') AS ${n}`).join(", ")})`;
155
+ }
156
+ function columnList(table) {
157
+ return SCHEMAS[table].columns.map((c) => c.name).join(", ");
158
+ }
159
+ function placeholderValues(table) {
160
+ return `(${SCHEMAS[table].columns.map((c) => defaultForType(c.type)).join(", ")})`;
161
+ }
162
+ function defaultForType(t) {
163
+ if (t === "VARCHAR") return "''";
164
+ if (t === "DATE") return "DATE '1970-01-01'";
165
+ if (t === "INTEGER" || t === "BIGINT") return "0";
166
+ if (t === "DOUBLE") return "CAST(0 AS DOUBLE)";
167
+ return "NULL";
168
+ }
169
+ function columnsJson(table) {
170
+ return `{${SCHEMAS[table].columns.map((c) => `'${c.name}': '${c.type}'`).join(", ")}}`;
171
+ }
172
+ const VERSION_RE = /__v(\d+)\.parquet$/;
173
+ function parseLockScope(key) {
174
+ const match = VERSION_RE.exec(key);
175
+ if (!match) return void 0;
176
+ const parts = key.slice(0, match.index).split("/");
177
+ if (parts.length < 4) return void 0;
178
+ const userPart = parts[0];
179
+ if (!userPart.startsWith("u_")) return void 0;
180
+ const userId = userPart.slice(2);
181
+ const partition = parts.slice(-2).join("/");
182
+ const table = parts[parts.length - 3];
183
+ return {
184
+ userId,
185
+ siteId: parts.length >= 5 ? parts.slice(1, -3).join("/") : void 0,
186
+ table,
187
+ partition
188
+ };
189
+ }
190
+ async function gcOrphansImpl(deps, now, graceMs, opts = {}) {
191
+ const cutoff = now - graceMs;
192
+ const retired = await deps.manifestStore.listRetired(cutoff);
193
+ if (retired.length > 0) {
194
+ await deps.dataSource.delete(retired.map((e) => e.objectKey));
195
+ await deps.manifestStore.delete(retired);
196
+ }
197
+ let sweptOrphans = 0;
198
+ if (opts.userId) {
199
+ const prefix = tenantPrefix({
200
+ userId: opts.userId,
201
+ siteId: opts.siteId
202
+ });
203
+ const knownEntries = await deps.manifestStore.listAll({
204
+ userId: opts.userId,
205
+ siteId: opts.siteId
206
+ });
207
+ const knownSet = new Set(knownEntries.map((e) => e.objectKey));
208
+ const orphans = [];
209
+ const keyStream = deps.dataSource.streamList ? deps.dataSource.streamList(prefix) : async function* () {
210
+ const all = await deps.dataSource.list(prefix);
211
+ for (const k of all) yield k;
212
+ }();
213
+ for await (const key of keyStream) {
214
+ if (knownSet.has(key)) continue;
215
+ const match = VERSION_RE.exec(key);
216
+ if (!match) continue;
217
+ if (Number(match[1]) <= cutoff) orphans.push(key);
218
+ }
219
+ const byScope = /* @__PURE__ */ new Map();
220
+ for (const key of orphans) {
221
+ const scope = parseLockScope(key);
222
+ if (!scope) continue;
223
+ const sk = `${scope.userId}|${scope.siteId ?? ""}|${scope.table}|${scope.partition}`;
224
+ const bucket = byScope.get(sk) ?? {
225
+ scope,
226
+ keys: []
227
+ };
228
+ bucket.keys.push(key);
229
+ byScope.set(sk, bucket);
230
+ }
231
+ for (const { scope, keys } of byScope.values()) await deps.manifestStore.withLock(scope, async () => {
232
+ const known = await deps.manifestStore.listAll({
233
+ userId: scope.userId,
234
+ siteId: scope.siteId,
235
+ table: scope.table,
236
+ partitions: [scope.partition]
237
+ });
238
+ const knownInScope = new Set(known.map((e) => e.objectKey));
239
+ const stillOrphans = keys.filter((k) => !knownInScope.has(k));
240
+ if (stillOrphans.length > 0) {
241
+ await deps.dataSource.delete(stillOrphans);
242
+ sweptOrphans += stillOrphans.length;
243
+ }
244
+ });
245
+ }
246
+ return { deleted: retired.length + sweptOrphans };
247
+ }
248
+ const URL_PURGE_TABLES = ["pages", "page_keywords"];
249
+ const MAX_DAY_BYTES = 100 * 1024 * 1024;
250
+ const URL_COLUMNS = /* @__PURE__ */ new Set();
251
+ for (const t of Object.keys(SCHEMAS)) for (const col of SCHEMAS[t].columns) if (col.name === "url") URL_COLUMNS.add(`${t}:url`);
252
+ function normalizeRow(table, row) {
253
+ if (!URL_COLUMNS.has(`${table}:url`)) return row;
254
+ const url = row.url;
255
+ if (typeof url !== "string") return row;
256
+ const normalized = normalizeUrl(url);
257
+ if (normalized === url) return row;
258
+ return {
259
+ ...row,
260
+ url: normalized
261
+ };
262
+ }
263
+ function createStorageEngine(opts) {
264
+ const { dataSource, manifestStore, codec, executor } = opts;
265
+ const defaultNow = opts.now ?? (() => Date.now());
266
+ async function writeDay(ctx, rows) {
267
+ if (!ctx.date) throw new Error("writeDay requires ctx.date");
268
+ const date = ctx.date;
269
+ const now = (ctx.now ?? defaultNow)();
270
+ const partition = dayPartition(date);
271
+ const searchType = ctx.searchType;
272
+ return manifestStore.withLock({
273
+ userId: ctx.userId,
274
+ siteId: ctx.siteId,
275
+ table: ctx.table,
276
+ partition
277
+ }, async () => {
278
+ const superseding = (await manifestStore.listLive({
279
+ userId: ctx.userId,
280
+ siteId: ctx.siteId,
281
+ table: ctx.table,
282
+ partitions: [partition]
283
+ })).filter((e) => inferSearchType(e) === inferSearchType({ searchType }));
284
+ const normalizedRows = rows.map((r) => normalizeRow(ctx.table, r));
285
+ const key = objectKey(ctx, ctx.table, partition, now, searchType);
286
+ const { bytes: writtenBytes, rowCount } = await codec.writeRows({ table: ctx.table }, normalizedRows, key, dataSource);
287
+ let bytes = writtenBytes;
288
+ if (bytes === 0 && rowCount > 0 && dataSource.head) {
289
+ const probed = await dataSource.head(key);
290
+ if (probed) bytes = probed.bytes;
291
+ }
292
+ if (bytes > 104857600) {
293
+ await dataSource.delete([key]).catch(() => {});
294
+ throw new Error(`writeDay payload ${bytes} bytes exceeds ${MAX_DAY_BYTES} hard ceiling (table=${ctx.table}, key=${key})`);
295
+ }
296
+ const entry = {
297
+ userId: ctx.userId,
298
+ siteId: ctx.siteId,
299
+ table: ctx.table,
300
+ partition,
301
+ objectKey: key,
302
+ rowCount,
303
+ bytes,
304
+ createdAt: now,
305
+ schemaVersion: currentSchemaVersion(ctx.table),
306
+ tier: "raw",
307
+ ...searchType !== void 0 ? { searchType } : {}
308
+ };
309
+ await manifestStore.registerVersion(entry, superseding);
310
+ await manifestStore.bumpWatermark({
311
+ userId: ctx.userId,
312
+ siteId: ctx.siteId,
313
+ table: ctx.table
314
+ }, date, now);
315
+ });
316
+ }
317
+ async function runSQL(opts) {
318
+ opts.signal?.throwIfAborted();
319
+ const entries = Object.entries(opts.fileSets);
320
+ const perSet = await Promise.all(entries.map(async ([name, ref]) => {
321
+ return [name, (await manifestStore.listLive({
322
+ userId: opts.ctx.userId,
323
+ siteId: opts.ctx.siteId,
324
+ table: ref.table,
325
+ partitions: ref.partitions
326
+ })).map((e) => e.objectKey)];
327
+ }));
328
+ opts.signal?.throwIfAborted();
329
+ const fileKeys = {};
330
+ for (const [name, keys] of perSet) fileKeys[name] = keys;
331
+ const uniqueKeys = [...new Set(perSet.flatMap(([, keys]) => keys))];
332
+ let table = opts.table;
333
+ if (!table) {
334
+ if (new Set(entries.map(([, ref]) => ref.table)).size > 1) throw new Error("runSQL requires explicit ctx.table when fileSets reference multiple tables.");
335
+ table = entries[0]?.[1].table;
336
+ }
337
+ if (!table) throw new Error("runSQL requires at least one fileSet or an explicit table");
338
+ const placeholderTables = {};
339
+ for (const [name, ref] of entries) placeholderTables[name] = ref.table;
340
+ const result = await executor.execute({
341
+ sql: opts.sql,
342
+ params: opts.params ?? [],
343
+ fileKeys,
344
+ placeholderTables,
345
+ dataSource,
346
+ table,
347
+ signal: opts.signal
348
+ });
349
+ return {
350
+ rows: result.rows,
351
+ sql: result.sql,
352
+ objectKeys: uniqueKeys
353
+ };
354
+ }
355
+ async function query(ctx, state) {
356
+ const plan = buildLogicalPlan(state, { regex: true });
357
+ const table = ctx.table ?? plan.dataset;
358
+ const resolved = compileLogicalQueryPlan(plan, table);
359
+ return runSQL({
360
+ ctx: {
361
+ userId: ctx.userId,
362
+ siteId: ctx.siteId
363
+ },
364
+ table,
365
+ fileSets: { FILES: {
366
+ table,
367
+ partitions: resolved.partitions
368
+ } },
369
+ sql: resolved.sql,
370
+ params: resolved.params,
371
+ signal: ctx.signal
372
+ });
373
+ }
374
+ async function queryComparison(ctx, current, previous, filter) {
375
+ const adapter = createParquetResolverAdapter();
376
+ const currentPlan = buildLogicalPlan(current, adapter.capabilities);
377
+ const previousPlan = buildLogicalPlan(previous, adapter.capabilities);
378
+ if (currentPlan.dataset !== previousPlan.dataset) throw new Error(`queryComparison: current (${currentPlan.dataset}) and previous (${previousPlan.dataset}) must resolve to the same table`);
379
+ const table = ctx.table ?? currentPlan.dataset;
380
+ const comparison = resolveComparisonSQL(current, previous, {
381
+ adapter,
382
+ siteId: void 0
383
+ }, filter);
384
+ const totals = buildTotalsSql(current, {
385
+ adapter,
386
+ siteId: void 0
387
+ });
388
+ const fileSets = { FILES: {
389
+ table,
390
+ partitions: enumeratePartitions(currentPlan.dateRange.startDate < previousPlan.dateRange.startDate ? currentPlan.dateRange.startDate : previousPlan.dateRange.startDate, currentPlan.dateRange.endDate > previousPlan.dateRange.endDate ? currentPlan.dateRange.endDate : previousPlan.dateRange.endDate)
391
+ } };
392
+ const baseCtx = {
393
+ userId: ctx.userId,
394
+ siteId: ctx.siteId
395
+ };
396
+ const [main, count, totalsRow] = await Promise.all([
397
+ runSQL({
398
+ ctx: baseCtx,
399
+ table,
400
+ fileSets,
401
+ sql: comparison.sql,
402
+ params: comparison.params,
403
+ signal: ctx.signal
404
+ }),
405
+ runSQL({
406
+ ctx: baseCtx,
407
+ table,
408
+ fileSets,
409
+ sql: comparison.countSql,
410
+ params: comparison.countParams,
411
+ signal: ctx.signal
412
+ }),
413
+ runSQL({
414
+ ctx: baseCtx,
415
+ table,
416
+ fileSets,
417
+ sql: totals.sql,
418
+ params: totals.params,
419
+ signal: ctx.signal
420
+ })
421
+ ]);
422
+ return {
423
+ rows: main.rows,
424
+ totalCount: Number(count.rows[0]?.total ?? 0),
425
+ totals: totalsRow.rows[0] ?? {}
426
+ };
427
+ }
428
+ async function queryOptimized(ctx, state) {
429
+ const adapter = createParquetResolverAdapter();
430
+ const plan = buildLogicalPlan(state, adapter.capabilities);
431
+ const table = ctx.table ?? plan.dataset;
432
+ const partitions = enumeratePartitions(plan.dateRange.startDate, plan.dateRange.endDate);
433
+ const { sql, params } = resolveToSQLOptimized(state, {
434
+ adapter,
435
+ siteId: void 0
436
+ });
437
+ const result = await runSQL({
438
+ ctx: {
439
+ userId: ctx.userId,
440
+ siteId: ctx.siteId
441
+ },
442
+ table,
443
+ fileSets: { FILES: {
444
+ table,
445
+ partitions
446
+ } },
447
+ sql,
448
+ params,
449
+ signal: ctx.signal
450
+ });
451
+ const firstRow = result.rows[0];
452
+ const totalCount = Number(firstRow?.totalCount ?? 0);
453
+ const totals = {
454
+ clicks: Number(firstRow?.totalClicks ?? 0),
455
+ impressions: Number(firstRow?.totalImpressions ?? 0),
456
+ ctr: Number(firstRow?.totalCtr ?? 0),
457
+ position: Number(firstRow?.totalPosition ?? 0)
458
+ };
459
+ return {
460
+ rows: result.rows.map((r) => {
461
+ const { totalCount: _tc, totalClicks: _tcl, totalImpressions: _ti, totalCtr: _tr, totalPosition: _tp, ...rest } = r;
462
+ return rest;
463
+ }),
464
+ totalCount,
465
+ totals
466
+ };
467
+ }
468
+ async function queryExtras(ctx, state) {
469
+ const adapter = createParquetResolverAdapter();
470
+ const extras = buildExtrasQueries(state, {
471
+ adapter,
472
+ siteId: void 0
473
+ });
474
+ if (extras.length === 0) return [];
475
+ const plan = buildLogicalPlan(state, adapter.capabilities);
476
+ const table = ctx.table ?? plan.dataset;
477
+ const fileSets = { FILES: {
478
+ table,
479
+ partitions: enumeratePartitions(plan.dateRange.startDate, plan.dateRange.endDate)
480
+ } };
481
+ const baseCtx = {
482
+ userId: ctx.userId,
483
+ siteId: ctx.siteId
484
+ };
485
+ const results = await Promise.all(extras.map((e) => runSQL({
486
+ ctx: baseCtx,
487
+ table,
488
+ fileSets,
489
+ sql: e.sql,
490
+ params: e.params,
491
+ signal: ctx.signal
492
+ })));
493
+ return extras.map((e, i) => ({
494
+ key: e.key,
495
+ rows: results[i].rows
496
+ }));
497
+ }
498
+ async function compactTiered(ctx, thresholds) {
499
+ return compactTieredImpl({
500
+ dataSource,
501
+ manifestStore,
502
+ codec
503
+ }, ctx, (ctx.now ?? defaultNow)(), thresholds);
504
+ }
505
+ async function gcOrphans(ctx, graceMs) {
506
+ return gcOrphansImpl({
507
+ dataSource,
508
+ manifestStore
509
+ }, (ctx.now ?? defaultNow)(), graceMs, {
510
+ userId: ctx.userId,
511
+ siteId: ctx.siteId
512
+ });
513
+ }
514
+ async function purgeTenant(ctx) {
515
+ const prefix = tenantPrefix(ctx);
516
+ const keys = [];
517
+ const keyStream = dataSource.streamList ? dataSource.streamList(prefix) : async function* () {
518
+ for (const k of await dataSource.list(prefix)) yield k;
519
+ }();
520
+ for await (const key of keyStream) keys.push(key);
521
+ if (keys.length > 0) await dataSource.delete(keys);
522
+ const manifestResult = await manifestStore.purgeTenant({
523
+ userId: ctx.userId,
524
+ siteId: ctx.siteId
525
+ });
526
+ return {
527
+ userId: ctx.userId,
528
+ siteId: ctx.siteId,
529
+ prefix,
530
+ objectsDeleted: keys.length,
531
+ entriesRemoved: manifestResult.entriesRemoved,
532
+ watermarksRemoved: manifestResult.watermarksRemoved,
533
+ syncStatesRemoved: manifestResult.syncStatesRemoved,
534
+ at: defaultNow()
535
+ };
536
+ }
537
+ async function purgeUrls(ctx, urls) {
538
+ const now = defaultNow();
539
+ const urlSet = new Set(urls);
540
+ let entriesRewritten = 0;
541
+ let rowsRemoved = 0;
542
+ let bytesAfter = 0;
543
+ if (urlSet.size === 0) return {
544
+ userId: ctx.userId,
545
+ siteId: ctx.siteId,
546
+ urlsRequested: 0,
547
+ entriesRewritten: 0,
548
+ rowsRemoved: 0,
549
+ bytesAfter: 0,
550
+ at: now
551
+ };
552
+ for (const table of URL_PURGE_TABLES) {
553
+ const entries = await manifestStore.listLive({
554
+ userId: ctx.userId,
555
+ siteId: ctx.siteId,
556
+ table
557
+ });
558
+ for (const entry of entries) await manifestStore.withLock({
559
+ userId: entry.userId,
560
+ siteId: entry.siteId,
561
+ table,
562
+ partition: entry.partition
563
+ }, async () => {
564
+ const rows = await codec.readRows({ table }, entry.objectKey, dataSource);
565
+ const kept = rows.filter((r) => typeof r.url !== "string" || !urlSet.has(r.url));
566
+ const removed = rows.length - kept.length;
567
+ if (removed === 0) return;
568
+ const searchType = entry.searchType;
569
+ const newKey = objectKey({
570
+ userId: entry.userId,
571
+ siteId: entry.siteId
572
+ }, table, entry.partition, now, searchType);
573
+ const { bytes, rowCount } = await codec.writeRows({ table }, kept, newKey, dataSource);
574
+ const newEntry = {
575
+ userId: entry.userId,
576
+ siteId: entry.siteId,
577
+ table,
578
+ partition: entry.partition,
579
+ objectKey: newKey,
580
+ rowCount,
581
+ bytes,
582
+ createdAt: now,
583
+ schemaVersion: entry.schemaVersion ?? currentSchemaVersion(table),
584
+ ...entry.tier !== void 0 ? { tier: entry.tier } : {},
585
+ ...searchType !== void 0 ? { searchType } : {}
586
+ };
587
+ await manifestStore.registerVersion(newEntry, [entry]);
588
+ entriesRewritten++;
589
+ rowsRemoved += removed;
590
+ bytesAfter += bytes;
591
+ });
592
+ }
593
+ return {
594
+ userId: ctx.userId,
595
+ siteId: ctx.siteId,
596
+ urlsRequested: urlSet.size,
597
+ entriesRewritten,
598
+ rowsRemoved,
599
+ bytesAfter,
600
+ at: now
601
+ };
602
+ }
603
+ return {
604
+ writeDay,
605
+ query,
606
+ queryComparison,
607
+ queryExtras,
608
+ queryOptimized,
609
+ runSQL,
610
+ compactTiered,
611
+ gcOrphans,
612
+ purgeTenant,
613
+ purgeUrls,
614
+ listLive: (filter) => manifestStore.listLive(filter),
615
+ listAll: (filter) => manifestStore.listAll(filter),
616
+ getWatermarks: (filter) => manifestStore.getWatermarks(filter),
617
+ getSyncStates: (filter) => manifestStore.getSyncStates(filter),
618
+ setSyncState: (scope, state, detail) => manifestStore.setSyncState(scope, state, detail),
619
+ readObject: (key) => dataSource.read(key)
620
+ };
621
+ }
622
+ export { createDuckDBExecutor as a, createDuckDBCodec as i, createStorageEngine as n, canonicalEmptyParquetSchema as r, MAX_DAY_BYTES as t };