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