monorise 1.7.0-dev.9 → 1.7.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/cli/cli.js +143 -131
- package/dist/cli/cli.js.map +1 -1
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +141 -51
- package/dist/core/index.js.map +1 -1
- package/dist/sst/components/analytics.d.ts.map +1 -1
- package/dist/sst/components/monorise-core.d.ts.map +1 -1
- package/dist/sst/components/single-table.d.ts +1 -0
- package/dist/sst/components/single-table.d.ts.map +1 -1
- package/dist/sst/index.js +37 -35
- package/dist/sst/index.js.map +1 -1
- package/package.json +1 -1
package/dist/core/index.js
CHANGED
|
@@ -2324,6 +2324,7 @@ import {
|
|
|
2324
2324
|
StopQueryExecutionCommand
|
|
2325
2325
|
} from "@aws-sdk/client-athena";
|
|
2326
2326
|
import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
|
|
2327
|
+
import { createHash } from "crypto";
|
|
2327
2328
|
import { handle as handle2 } from "hono/aws-lambda";
|
|
2328
2329
|
import { Hono as Hono3 } from "hono";
|
|
2329
2330
|
import httpStatus4 from "http-status";
|
|
@@ -2345,17 +2346,27 @@ function validParameter(value, type) {
|
|
|
2345
2346
|
if (type === "timestamp" && typeof value === "string" && !Number.isNaN(Date.parse(value))) return value;
|
|
2346
2347
|
return void 0;
|
|
2347
2348
|
}
|
|
2349
|
+
function executionParameter(value, type) {
|
|
2350
|
+
if (type === "string") return `'${value.replaceAll("'", "''")}'`;
|
|
2351
|
+
if (type === "date") return `DATE '${value}'`;
|
|
2352
|
+
if (type === "timestamp") return `TIMESTAMP '${value.replaceAll("'", "''")}'`;
|
|
2353
|
+
return value;
|
|
2354
|
+
}
|
|
2348
2355
|
function apiKeys() {
|
|
2349
2356
|
return process.env.ANALYTICS_API_KEYS ? JSON.parse(process.env.ANALYTICS_API_KEYS) : [];
|
|
2350
2357
|
}
|
|
2351
|
-
function
|
|
2358
|
+
function keyFingerprint(key) {
|
|
2359
|
+
return createHash("sha256").update(key).digest("hex");
|
|
2360
|
+
}
|
|
2361
|
+
function ownedExecution(id, key) {
|
|
2352
2362
|
return __async(this, null, function* () {
|
|
2363
|
+
var _a, _b;
|
|
2353
2364
|
const item = yield dynamo.send(new GetItemCommand({
|
|
2354
2365
|
TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
|
|
2355
2366
|
Key: { id: { S: id } },
|
|
2356
2367
|
ConsistentRead: true
|
|
2357
2368
|
}));
|
|
2358
|
-
return
|
|
2369
|
+
return ((_b = (_a = item.Item) == null ? void 0 : _a.ownerKeyHash) == null ? void 0 : _b.S) === keyFingerprint(key);
|
|
2359
2370
|
});
|
|
2360
2371
|
}
|
|
2361
2372
|
var analyticsQueryHandler = () => {
|
|
@@ -2374,7 +2385,7 @@ var analyticsQueryHandler = () => {
|
|
|
2374
2385
|
})
|
|
2375
2386
|
}));
|
|
2376
2387
|
app.post("/queries/:name/executions", (c) => __async(null, null, function* () {
|
|
2377
|
-
var _a;
|
|
2388
|
+
var _a, _b;
|
|
2378
2389
|
const query = queries()[c.req.param("name")];
|
|
2379
2390
|
if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus4.NOT_FOUND);
|
|
2380
2391
|
const body = yield c.req.json().catch(() => ({}));
|
|
@@ -2382,12 +2393,12 @@ var analyticsQueryHandler = () => {
|
|
|
2382
2393
|
if (Object.keys(body).some((name) => !(name in declared))) {
|
|
2383
2394
|
return c.json({ message: "Unexpected query parameter." }, httpStatus4.BAD_REQUEST);
|
|
2384
2395
|
}
|
|
2385
|
-
const parameters = Object.entries(declared).map(([name, definition]) => {
|
|
2386
|
-
const value = validParameter(body[name], definition.type);
|
|
2387
|
-
if (value === void 0) throw new Error(`Invalid or missing parameter: ${name}.`);
|
|
2388
|
-
return value;
|
|
2389
|
-
});
|
|
2390
2396
|
try {
|
|
2397
|
+
const parameters = Object.entries(declared).map(([name, definition]) => {
|
|
2398
|
+
const value = validParameter(body[name], definition.type);
|
|
2399
|
+
if (value === void 0) throw new Error(`Invalid or missing parameter: ${name}.`);
|
|
2400
|
+
return executionParameter(value, definition.type);
|
|
2401
|
+
});
|
|
2391
2402
|
const started = yield athena.send(new StartQueryExecutionCommand({
|
|
2392
2403
|
QueryString: query.sql,
|
|
2393
2404
|
ExecutionParameters: parameters,
|
|
@@ -2402,6 +2413,7 @@ var analyticsQueryHandler = () => {
|
|
|
2402
2413
|
Item: {
|
|
2403
2414
|
id: { S: started.QueryExecutionId },
|
|
2404
2415
|
queryName: { S: c.req.param("name") },
|
|
2416
|
+
ownerKeyHash: { S: keyFingerprint((_b = c.req.header("x-api-key")) != null ? _b : "") },
|
|
2405
2417
|
expiresAt: { N: String(Math.floor(Date.now() / 1e3) + 86400) }
|
|
2406
2418
|
}
|
|
2407
2419
|
}));
|
|
@@ -2414,24 +2426,24 @@ var analyticsQueryHandler = () => {
|
|
|
2414
2426
|
}
|
|
2415
2427
|
}));
|
|
2416
2428
|
app.get("/executions/:id", (c) => __async(null, null, function* () {
|
|
2417
|
-
var _a, _b, _c, _d, _e;
|
|
2429
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2418
2430
|
const id = c.req.param("id");
|
|
2419
|
-
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2431
|
+
if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2420
2432
|
const execution = yield athena.send(new GetQueryExecutionCommand({ QueryExecutionId: id }));
|
|
2421
|
-
const status = (
|
|
2433
|
+
const status = (_b = execution.QueryExecution) == null ? void 0 : _b.Status;
|
|
2422
2434
|
return c.json({
|
|
2423
2435
|
queryExecutionId: id,
|
|
2424
2436
|
state: status == null ? void 0 : status.State,
|
|
2425
2437
|
reason: status == null ? void 0 : status.StateChangeReason,
|
|
2426
|
-
statistics: (
|
|
2427
|
-
reusedPreviousResult: (
|
|
2438
|
+
statistics: (_c = execution.QueryExecution) == null ? void 0 : _c.Statistics,
|
|
2439
|
+
reusedPreviousResult: (_f = (_e = (_d = execution.QueryExecution) == null ? void 0 : _d.Statistics) == null ? void 0 : _e.ResultReuseInformation) == null ? void 0 : _f.ReusedPreviousResult
|
|
2428
2440
|
});
|
|
2429
2441
|
}));
|
|
2430
2442
|
app.get("/executions/:id/results", (c) => __async(null, null, function* () {
|
|
2431
|
-
var _a, _b, _c, _d, _e, _f;
|
|
2443
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
2432
2444
|
const id = c.req.param("id");
|
|
2433
|
-
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2434
|
-
const requested = Number((
|
|
2445
|
+
if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2446
|
+
const requested = Number((_b = c.req.query("maxResults")) != null ? _b : 100);
|
|
2435
2447
|
const maxResults = Number.isFinite(requested) ? Math.min(Math.max(requested, 1), 1e3) : 100;
|
|
2436
2448
|
const nextToken = c.req.query("nextToken");
|
|
2437
2449
|
const results = yield athena.send(new GetQueryResultsCommand({
|
|
@@ -2439,8 +2451,8 @@ var analyticsQueryHandler = () => {
|
|
|
2439
2451
|
NextToken: nextToken,
|
|
2440
2452
|
MaxResults: maxResults
|
|
2441
2453
|
}));
|
|
2442
|
-
const rows = (
|
|
2443
|
-
const columns = ((
|
|
2454
|
+
const rows = (_d = (_c = results.ResultSet) == null ? void 0 : _c.Rows) != null ? _d : [];
|
|
2455
|
+
const columns = ((_g = (_f = (_e = results.ResultSet) == null ? void 0 : _e.ResultSetMetadata) == null ? void 0 : _f.ColumnInfo) != null ? _g : []).map((column) => column.Name);
|
|
2444
2456
|
return c.json({
|
|
2445
2457
|
columns,
|
|
2446
2458
|
rows: rows.slice(nextToken ? 0 : 1).map((row) => {
|
|
@@ -2454,8 +2466,9 @@ var analyticsQueryHandler = () => {
|
|
|
2454
2466
|
});
|
|
2455
2467
|
}));
|
|
2456
2468
|
app.post("/executions/:id/cancel", (c) => __async(null, null, function* () {
|
|
2469
|
+
var _a;
|
|
2457
2470
|
const id = c.req.param("id");
|
|
2458
|
-
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2471
|
+
if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2459
2472
|
yield athena.send(new StopQueryExecutionCommand({ QueryExecutionId: id }));
|
|
2460
2473
|
return c.body(null, httpStatus4.NO_CONTENT);
|
|
2461
2474
|
}));
|
|
@@ -2504,6 +2517,8 @@ import {
|
|
|
2504
2517
|
PutRecordBatchCommand
|
|
2505
2518
|
} from "@aws-sdk/client-firehose";
|
|
2506
2519
|
import { unmarshall as unmarshall4 } from "@aws-sdk/util-dynamodb";
|
|
2520
|
+
var maxFirehoseBatchBytes = 4 * 1024 * 1024;
|
|
2521
|
+
var maxFirehoseRecordBytes = 1e3 * 1024;
|
|
2507
2522
|
var firehose = new FirehoseClient();
|
|
2508
2523
|
function encodeAnalyticsEvent(event) {
|
|
2509
2524
|
return {
|
|
@@ -2520,6 +2535,28 @@ function encodeAnalyticsEvent(event) {
|
|
|
2520
2535
|
after: event.after ? JSON.stringify(event.after) : void 0
|
|
2521
2536
|
};
|
|
2522
2537
|
}
|
|
2538
|
+
function batchAnalyticsRecords(values, serialize) {
|
|
2539
|
+
const batches = [];
|
|
2540
|
+
const oversized = [];
|
|
2541
|
+
let batch = [];
|
|
2542
|
+
let batchBytes = 0;
|
|
2543
|
+
for (const value of values) {
|
|
2544
|
+
const bytes = Buffer.byteLength(serialize(value));
|
|
2545
|
+
if (bytes > maxFirehoseRecordBytes) {
|
|
2546
|
+
oversized.push(value);
|
|
2547
|
+
continue;
|
|
2548
|
+
}
|
|
2549
|
+
if (batch.length === 500 || batchBytes + bytes > maxFirehoseBatchBytes) {
|
|
2550
|
+
batches.push(batch);
|
|
2551
|
+
batch = [];
|
|
2552
|
+
batchBytes = 0;
|
|
2553
|
+
}
|
|
2554
|
+
batch.push(value);
|
|
2555
|
+
batchBytes += bytes;
|
|
2556
|
+
}
|
|
2557
|
+
if (batch.length) batches.push(batch);
|
|
2558
|
+
return { batches, oversized };
|
|
2559
|
+
}
|
|
2523
2560
|
function omitTopLevelFields(value, fields) {
|
|
2524
2561
|
if (!value) return value;
|
|
2525
2562
|
return Object.fromEntries(
|
|
@@ -2580,7 +2617,7 @@ function datasetForRecord(record, manifest2, config) {
|
|
|
2580
2617
|
}
|
|
2581
2618
|
}
|
|
2582
2619
|
var handler2 = (config) => (event) => __async(null, null, function* () {
|
|
2583
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
2620
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
|
|
2584
2621
|
const streamName = process.env.ANALYTICS_DELIVERY_STREAM;
|
|
2585
2622
|
if (!streamName) throw new Error("ANALYTICS_DELIVERY_STREAM is required.");
|
|
2586
2623
|
const manifest2 = parseAnalyticsManifest();
|
|
@@ -2628,8 +2665,15 @@ var handler2 = (config) => (event) => __async(null, null, function* () {
|
|
|
2628
2665
|
failures.push({ itemIdentifier: (_j = (_i = record.dynamodb) == null ? void 0 : _i.SequenceNumber) != null ? _j : "" });
|
|
2629
2666
|
}
|
|
2630
2667
|
}
|
|
2631
|
-
|
|
2632
|
-
|
|
2668
|
+
const { batches, oversized } = batchAnalyticsRecords(
|
|
2669
|
+
events,
|
|
2670
|
+
({ event: value }) => `${JSON.stringify(encodeAnalyticsEvent(value))}
|
|
2671
|
+
`
|
|
2672
|
+
);
|
|
2673
|
+
for (const { record } of oversized) {
|
|
2674
|
+
failures.push({ itemIdentifier: (_l = (_k = record.dynamodb) == null ? void 0 : _k.SequenceNumber) != null ? _l : "" });
|
|
2675
|
+
}
|
|
2676
|
+
for (const batch of batches) {
|
|
2633
2677
|
const result = yield firehose.send(
|
|
2634
2678
|
new PutRecordBatchCommand({
|
|
2635
2679
|
DeliveryStreamName: streamName,
|
|
@@ -2639,7 +2683,7 @@ var handler2 = (config) => (event) => __async(null, null, function* () {
|
|
|
2639
2683
|
}))
|
|
2640
2684
|
})
|
|
2641
2685
|
);
|
|
2642
|
-
(
|
|
2686
|
+
(_m = result.RequestResponses) == null ? void 0 : _m.forEach((response, responseIndex) => {
|
|
2643
2687
|
var _a2, _b2, _c2;
|
|
2644
2688
|
if (!response.ErrorCode) return;
|
|
2645
2689
|
failures.push({
|
|
@@ -2660,11 +2704,14 @@ import {
|
|
|
2660
2704
|
UpdateItemCommand
|
|
2661
2705
|
} from "@aws-sdk/client-dynamodb";
|
|
2662
2706
|
import { FirehoseClient as FirehoseClient2, PutRecordBatchCommand as PutRecordBatchCommand2 } from "@aws-sdk/client-firehose";
|
|
2707
|
+
import { InvokeCommand, LambdaClient } from "@aws-sdk/client-lambda";
|
|
2663
2708
|
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2664
2709
|
import { marshall as marshall5, unmarshall as unmarshall5 } from "@aws-sdk/util-dynamodb";
|
|
2710
|
+
import { setTimeout as setTimeout2 } from "timers/promises";
|
|
2665
2711
|
import { gunzipSync } from "zlib";
|
|
2666
2712
|
var dynamodb = new DynamoDBClient2();
|
|
2667
2713
|
var firehose2 = new FirehoseClient2();
|
|
2714
|
+
var lambda = new LambdaClient();
|
|
2668
2715
|
var s3 = new S3Client();
|
|
2669
2716
|
var backfillMarker = { PK: "#ANALYTICS#", SK: "#BACKFILL#" };
|
|
2670
2717
|
function required2(name) {
|
|
@@ -2779,9 +2826,9 @@ function streamToBuffer(stream) {
|
|
|
2779
2826
|
return Buffer.concat(chunks);
|
|
2780
2827
|
}))();
|
|
2781
2828
|
}
|
|
2782
|
-
function snapshotEvent(item, config, occurredAt, omittedFields) {
|
|
2829
|
+
function snapshotEvent(item, config, manifest2, occurredAt, omittedFields) {
|
|
2783
2830
|
const attributes = marshall5(item, { removeUndefinedValues: true });
|
|
2784
|
-
const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } },
|
|
2831
|
+
const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, manifest2, config);
|
|
2785
2832
|
if (!dataset) return void 0;
|
|
2786
2833
|
const after = sanitizeItem(item, omittedFields);
|
|
2787
2834
|
const key = `${String(item.PK)}:${String(item.SK)}`;
|
|
@@ -2806,27 +2853,48 @@ var handler3 = (config) => (event) => __async(null, null, function* () {
|
|
|
2806
2853
|
throw new Error("Unsupported analytics backfill event.");
|
|
2807
2854
|
}
|
|
2808
2855
|
const timestamp = yield backfillTimestamp();
|
|
2856
|
+
const manifest2 = parseAnalyticsManifest();
|
|
2809
2857
|
const omittedFields = new Set(JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]"));
|
|
2810
2858
|
const deliveryStream = required2("ANALYTICS_DELIVERY_STREAM");
|
|
2859
|
+
let exportComplete = false;
|
|
2811
2860
|
let delivered = 0;
|
|
2812
2861
|
for (const record of event.Records) {
|
|
2813
2862
|
const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
|
|
2863
|
+
if (key.endsWith("manifest-summary.json")) {
|
|
2864
|
+
exportComplete = true;
|
|
2865
|
+
continue;
|
|
2866
|
+
}
|
|
2814
2867
|
if (!key.endsWith(".json.gz")) continue;
|
|
2815
2868
|
const response = yield s3.send(new GetObjectCommand({ Bucket: record.s3.bucket.name, Key: key }));
|
|
2816
2869
|
if (!response.Body) throw new Error(`Backfill export object ${key} has no body.`);
|
|
2817
2870
|
const content = gunzipSync(yield streamToBuffer(response.Body)).toString("utf8");
|
|
2818
2871
|
const events = content.split("\n").filter(Boolean).flatMap((line) => {
|
|
2819
2872
|
const attributes = JSON.parse(line).Item;
|
|
2820
|
-
return attributes ? [snapshotEvent(unmarshall5(attributes), config, timestamp, omittedFields)].filter(Boolean) : [];
|
|
2873
|
+
return attributes ? [snapshotEvent(unmarshall5(attributes), config, manifest2, timestamp, omittedFields)].filter(Boolean) : [];
|
|
2821
2874
|
});
|
|
2822
|
-
|
|
2823
|
-
|
|
2875
|
+
const { batches, oversized } = batchAnalyticsRecords(
|
|
2876
|
+
events,
|
|
2877
|
+
(value) => `${JSON.stringify(encodeAnalyticsEvent(value))}
|
|
2878
|
+
`
|
|
2879
|
+
);
|
|
2880
|
+
if (oversized.length) {
|
|
2881
|
+
throw new Error(`Cannot deliver ${oversized.length} backfill records exceeding Firehose's 1000 KiB record limit.`);
|
|
2882
|
+
}
|
|
2883
|
+
for (const batch of batches) {
|
|
2824
2884
|
const result = yield firehose2.send(new PutRecordBatchCommand2({ DeliveryStreamName: deliveryStream, Records: batch.map((value) => ({ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
|
|
2825
2885
|
`) })) }));
|
|
2826
2886
|
if (result.FailedPutCount) throw new Error(`Failed to deliver ${result.FailedPutCount} backfill records; retry this export object.`);
|
|
2827
2887
|
delivered += batch.length;
|
|
2828
2888
|
}
|
|
2829
2889
|
}
|
|
2890
|
+
if (exportComplete && process.env.ANALYTICS_MATERIALIZATION_FUNCTION) {
|
|
2891
|
+
yield setTimeout2(31e4);
|
|
2892
|
+
yield lambda.send(new InvokeCommand({
|
|
2893
|
+
FunctionName: process.env.ANALYTICS_MATERIALIZATION_FUNCTION,
|
|
2894
|
+
InvocationType: "Event",
|
|
2895
|
+
Payload: Buffer.from("{}")
|
|
2896
|
+
}));
|
|
2897
|
+
}
|
|
2830
2898
|
return { delivered, exportTime: timestamp.toISOString() };
|
|
2831
2899
|
});
|
|
2832
2900
|
|
|
@@ -2846,6 +2914,11 @@ function required3(name) {
|
|
|
2846
2914
|
function quoteIdentifier(identifier) {
|
|
2847
2915
|
return `"${identifier.replaceAll('"', '""')}"`;
|
|
2848
2916
|
}
|
|
2917
|
+
function quoteDdlIdentifier(identifier) {
|
|
2918
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier))
|
|
2919
|
+
throw new Error(`Invalid Athena DDL identifier: ${identifier}`);
|
|
2920
|
+
return identifier;
|
|
2921
|
+
}
|
|
2849
2922
|
function quoteLiteral(value) {
|
|
2850
2923
|
return `'${value.replaceAll("'", "''")}'`;
|
|
2851
2924
|
}
|
|
@@ -2855,7 +2928,7 @@ function manifest() {
|
|
|
2855
2928
|
function valueExpression(column, kind) {
|
|
2856
2929
|
const payload = "coalesce(after, before)";
|
|
2857
2930
|
const path = `$.${kind === "mutual" ? "mutualData" : "data"}.${column.sourceName.replaceAll('"', '\\"')}`;
|
|
2858
|
-
const scalar = `json_extract_scalar(payload, ${quoteLiteral(path)})`;
|
|
2931
|
+
const scalar = `json_extract_scalar(${payload}, ${quoteLiteral(path)})`;
|
|
2859
2932
|
switch (column.type) {
|
|
2860
2933
|
case "boolean":
|
|
2861
2934
|
return `try_cast(${scalar} AS boolean)`;
|
|
@@ -2864,7 +2937,7 @@ function valueExpression(column, kind) {
|
|
|
2864
2937
|
case "timestamp":
|
|
2865
2938
|
return `try_cast(from_iso8601_timestamp(${scalar}) AS timestamp)`;
|
|
2866
2939
|
case "json":
|
|
2867
|
-
return `json_format(json_extract(payload, ${quoteLiteral(path)}))`;
|
|
2940
|
+
return `json_format(json_extract(${payload}, ${quoteLiteral(path)}))`;
|
|
2868
2941
|
default:
|
|
2869
2942
|
return scalar;
|
|
2870
2943
|
}
|
|
@@ -2884,19 +2957,25 @@ function datasetSql(dataset, database, bucket) {
|
|
|
2884
2957
|
var _a;
|
|
2885
2958
|
const history = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.historyTable)}`;
|
|
2886
2959
|
const current = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.currentTable)}`;
|
|
2960
|
+
const historyDdl = dataset.historyTable;
|
|
2961
|
+
const currentDdl = dataset.currentTable;
|
|
2887
2962
|
const raw = `${quoteIdentifier(database)}.${quoteIdentifier((_a = dataset.rawTable) != null ? _a : `${dataset.historyTable}_raw`)}`;
|
|
2888
2963
|
const typedColumns = dataset.columns.map(
|
|
2889
|
-
(column) => `${
|
|
2964
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
2890
2965
|
);
|
|
2891
2966
|
const names = dataset.columns.map((column) => quoteIdentifier(column.name));
|
|
2892
2967
|
const endpointNames = dataset.endpoints.map(
|
|
2893
2968
|
(endpoint) => quoteIdentifier(endpoint.column)
|
|
2894
2969
|
);
|
|
2970
|
+
const endpointDdlNames = dataset.endpoints.map(
|
|
2971
|
+
(endpoint) => quoteDdlIdentifier(endpoint.column)
|
|
2972
|
+
);
|
|
2895
2973
|
const values = dataset.columns.map(
|
|
2896
2974
|
(column) => valueExpression(column, dataset.kind)
|
|
2897
2975
|
);
|
|
2898
2976
|
const payload = "coalesce(after, before)";
|
|
2899
2977
|
const idPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
|
|
2978
|
+
const recentRaw = `${raw} WHERE event_date >= date_format(date_add('day', -3, current_date), '%Y-%m-%d')`;
|
|
2900
2979
|
const selected = [
|
|
2901
2980
|
"event_id",
|
|
2902
2981
|
"idempotency_key",
|
|
@@ -2913,16 +2992,16 @@ function datasetSql(dataset, database, bucket) {
|
|
|
2913
2992
|
...values.map((value, index) => `${value} AS ${names[index]}`)
|
|
2914
2993
|
];
|
|
2915
2994
|
const allColumns = [
|
|
2916
|
-
"event_id
|
|
2917
|
-
"idempotency_key
|
|
2918
|
-
"ordering_key
|
|
2919
|
-
"sequence_number
|
|
2920
|
-
"operation
|
|
2995
|
+
"event_id string",
|
|
2996
|
+
"idempotency_key string",
|
|
2997
|
+
"ordering_key string",
|
|
2998
|
+
"sequence_number string",
|
|
2999
|
+
"operation string",
|
|
2921
3000
|
"occurred_at timestamp",
|
|
2922
|
-
`${
|
|
2923
|
-
"before_json
|
|
2924
|
-
"after_json
|
|
2925
|
-
...
|
|
3001
|
+
`${quoteDdlIdentifier(dataset.idColumn)} string`,
|
|
3002
|
+
"before_json string",
|
|
3003
|
+
"after_json string",
|
|
3004
|
+
...endpointDdlNames.map((name) => `${name} string`),
|
|
2926
3005
|
...typedColumns
|
|
2927
3006
|
];
|
|
2928
3007
|
const historyNames = [
|
|
@@ -2952,10 +3031,10 @@ function datasetSql(dataset, database, bucket) {
|
|
|
2952
3031
|
...names.map((name) => `s.${name}`)
|
|
2953
3032
|
].join(", ");
|
|
2954
3033
|
return [
|
|
2955
|
-
`CREATE TABLE
|
|
2956
|
-
`MERGE INTO ${history} h USING (SELECT * FROM (SELECT ${selected.join(", ")}, row_number() OVER (PARTITION BY event_id ORDER BY ordering_key DESC) AS row_number FROM ${
|
|
2957
|
-
`CREATE TABLE
|
|
2958
|
-
`MERGE INTO ${current} c USING (SELECT * FROM (SELECT h.*, row_number() OVER (PARTITION BY ${quoteIdentifier(dataset.idColumn)} ORDER BY occurred_at DESC, ordering_key DESC) AS row_number FROM ${history} h) WHERE row_number = 1) s ON c.${quoteIdentifier(dataset.idColumn)} = s.${quoteIdentifier(dataset.idColumn)} WHEN MATCHED AND s.operation = 'REMOVE' THEN DELETE WHEN MATCHED THEN UPDATE SET operation = s.operation, occurred_at = s.occurred_at, ordering_key = s.ordering_key${endpointNames.map((name) => `, ${name} = s.${name}`).join("")}${names.map((name) => `, ${name} = s.${name}`).join("")} WHEN NOT MATCHED AND s.operation <> 'REMOVE' THEN INSERT (operation, occurred_at, ordering_key, ${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.join(", ")}` : ""}${names.length ? `, ${names.join(", ")}` : ""}) VALUES (s.operation, s.occurred_at, s.ordering_key, s.${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.map((name) => `s.${name}`).join(", ")}` : ""}${names.length ? `, ${names.map((name) => `s.${name}`).join(", ")}` : ""})`
|
|
3034
|
+
`CREATE TABLE ${historyDdl} (${allColumns.join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/curated/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`)} TBLPROPERTIES ('table_type' = 'ICEBERG')`,
|
|
3035
|
+
`MERGE INTO ${history} h USING (SELECT * FROM (SELECT ${selected.join(", ")}, row_number() OVER (PARTITION BY event_id ORDER BY ordering_key DESC) AS row_number FROM ${recentRaw}) WHERE row_number = 1) s ON h.event_id = s.event_id WHEN NOT MATCHED THEN INSERT (${historyNames}) VALUES (${insertValues})`,
|
|
3036
|
+
`CREATE TABLE ${currentDdl} (${allColumns.filter((column) => !column.startsWith("event_id ") && !column.startsWith("idempotency_key ") && !column.startsWith("sequence_number ") && !column.startsWith("before_json ") && !column.startsWith("after_json ")).join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/current/${dataset.name}/`)} TBLPROPERTIES ('table_type' = 'ICEBERG')`,
|
|
3037
|
+
`MERGE INTO ${current} c USING (SELECT * FROM (SELECT h.*, row_number() OVER (PARTITION BY ${quoteIdentifier(dataset.idColumn)} ORDER BY occurred_at DESC, ordering_key DESC) AS row_number FROM ${history} h WHERE h.${quoteIdentifier(dataset.idColumn)} IN (SELECT DISTINCT json_extract_scalar(${payload}, ${quoteLiteral(idPath)}) FROM ${recentRaw})) WHERE row_number = 1) s ON c.${quoteIdentifier(dataset.idColumn)} = s.${quoteIdentifier(dataset.idColumn)} WHEN MATCHED AND s.operation = 'REMOVE' THEN DELETE WHEN MATCHED THEN UPDATE SET operation = s.operation, occurred_at = s.occurred_at, ordering_key = s.ordering_key${endpointNames.map((name) => `, ${name} = s.${name}`).join("")}${names.map((name) => `, ${name} = s.${name}`).join("")} WHEN NOT MATCHED AND s.operation <> 'REMOVE' THEN INSERT (operation, occurred_at, ordering_key, ${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.join(", ")}` : ""}${names.length ? `, ${names.join(", ")}` : ""}) VALUES (s.operation, s.occurred_at, s.ordering_key, s.${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.map((name) => `s.${name}`).join(", ")}` : ""}${names.length ? `, ${names.map((name) => `s.${name}`).join(", ")}` : ""})`
|
|
2959
3038
|
];
|
|
2960
3039
|
}
|
|
2961
3040
|
function execute(statement) {
|
|
@@ -2989,6 +3068,16 @@ function execute(statement) {
|
|
|
2989
3068
|
}
|
|
2990
3069
|
});
|
|
2991
3070
|
}
|
|
3071
|
+
function createTable(statement) {
|
|
3072
|
+
return __async(this, null, function* () {
|
|
3073
|
+
try {
|
|
3074
|
+
yield execute(statement);
|
|
3075
|
+
} catch (error) {
|
|
3076
|
+
if (/already exists/i.test(error instanceof Error ? error.message : String(error))) return;
|
|
3077
|
+
throw error;
|
|
3078
|
+
}
|
|
3079
|
+
});
|
|
3080
|
+
}
|
|
2992
3081
|
function tableColumns(database, table) {
|
|
2993
3082
|
return __async(this, null, function* () {
|
|
2994
3083
|
var _a, _b;
|
|
@@ -3013,7 +3102,7 @@ function addMissingColumns(database, table, columns) {
|
|
|
3013
3102
|
(column) => {
|
|
3014
3103
|
var _a, _b;
|
|
3015
3104
|
return !existing.has(
|
|
3016
|
-
(_b = (_a = column.match(/^
|
|
3105
|
+
(_b = (_a = column.match(/^([A-Za-z_][A-Za-z0-9_]*)/)) == null ? void 0 : _a[1]) != null ? _b : ""
|
|
3017
3106
|
);
|
|
3018
3107
|
}
|
|
3019
3108
|
);
|
|
@@ -3025,9 +3114,9 @@ function addMissingColumns(database, table, columns) {
|
|
|
3025
3114
|
}
|
|
3026
3115
|
function generatedColumns(dataset) {
|
|
3027
3116
|
return [
|
|
3028
|
-
`${
|
|
3117
|
+
`${quoteDdlIdentifier(dataset.idColumn)} string`,
|
|
3029
3118
|
...dataset.endpoints.map(
|
|
3030
|
-
(endpoint) => `${
|
|
3119
|
+
(endpoint) => `${quoteDdlIdentifier(endpoint.column)} string`
|
|
3031
3120
|
)
|
|
3032
3121
|
];
|
|
3033
3122
|
}
|
|
@@ -3036,20 +3125,20 @@ var handler4 = (configuredManifest) => () => __async(null, null, function* () {
|
|
|
3036
3125
|
const bucket = required3("ANALYTICS_BUCKET");
|
|
3037
3126
|
for (const dataset of (configuredManifest != null ? configuredManifest : manifest()).datasets) {
|
|
3038
3127
|
const statements = datasetSql(dataset, database, bucket);
|
|
3039
|
-
yield
|
|
3128
|
+
yield createTable(statements[0]);
|
|
3040
3129
|
yield addMissingColumns(
|
|
3041
3130
|
database,
|
|
3042
3131
|
dataset.historyTable,
|
|
3043
3132
|
[...generatedColumns(dataset), ...dataset.columns.map(
|
|
3044
|
-
(column) => `${
|
|
3133
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
3045
3134
|
)]
|
|
3046
3135
|
);
|
|
3047
|
-
yield
|
|
3136
|
+
yield createTable(statements[2]);
|
|
3048
3137
|
yield addMissingColumns(
|
|
3049
3138
|
database,
|
|
3050
3139
|
dataset.currentTable,
|
|
3051
3140
|
[...generatedColumns(dataset), ...dataset.columns.map(
|
|
3052
|
-
(column) => `${
|
|
3141
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
3053
3142
|
)]
|
|
3054
3143
|
);
|
|
3055
3144
|
for (const statement of [statements[1], statements[3]]) {
|
|
@@ -3091,6 +3180,7 @@ function modelStatements(model, database, bucket, now = /* @__PURE__ */ new Date
|
|
|
3091
3180
|
const table = model.name.replaceAll("-", "_");
|
|
3092
3181
|
const end = now;
|
|
3093
3182
|
const start = new Date(end.getTime() - model.lookbackDays * 864e5);
|
|
3183
|
+
start.setUTCHours(0, 0, 0, 0);
|
|
3094
3184
|
const source = model.sql.replaceAll("{{windowStart}}", `'${start.toISOString().replaceAll("'", "''")}'`).replaceAll("{{windowEnd}}", `'${end.toISOString().replaceAll("'", "''")}'`);
|
|
3095
3185
|
const target = `${quote(database)}.${quote(table)}`;
|
|
3096
3186
|
const location = `s3://${bucket}/models/${table}/`;
|