monorise 1.6.3 → 1.6.5-dev.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/base/index.d.ts +5 -0
- package/dist/base/index.js.map +1 -1
- package/dist/cli/cli.js +237 -1
- package/dist/cli/cli.js.map +1 -1
- package/dist/core/index.d.ts +97 -8
- package/dist/core/index.js +893 -68
- package/dist/core/index.js.map +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/react/actions/core.action.d.ts.map +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +19 -26
- package/dist/react/index.js.map +1 -1
- package/dist/react/lib/utils.d.ts +7 -0
- package/dist/react/lib/utils.d.ts.map +1 -1
- package/dist/sst/components/analytics.d.ts +72 -0
- package/dist/sst/components/analytics.d.ts.map +1 -0
- package/dist/sst/components/monorise-core.d.ts +5 -1
- package/dist/sst/components/monorise-core.d.ts.map +1 -1
- package/dist/sst/components/single-table.d.ts +3 -1
- package/dist/sst/components/single-table.d.ts.map +1 -1
- package/dist/sst/index.js +448 -7
- package/dist/sst/index.js.map +1 -1
- package/package.json +4 -1
package/dist/core/index.js
CHANGED
|
@@ -4,6 +4,7 @@ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
|
4
4
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
6
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
|
|
7
8
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
9
|
var __spreadValues = (a, b) => {
|
|
9
10
|
for (var prop in b || (b = {}))
|
|
@@ -53,6 +54,7 @@ var __async = (__this, __arguments, generator) => {
|
|
|
53
54
|
step((generator = generator.apply(__this, __arguments)).next());
|
|
54
55
|
});
|
|
55
56
|
};
|
|
57
|
+
var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
|
|
56
58
|
|
|
57
59
|
// controllers/setupRoutes.ts
|
|
58
60
|
import { Hono } from "hono";
|
|
@@ -2313,6 +2315,159 @@ var appHandler = (container) => ({ routes }) => {
|
|
|
2313
2315
|
return handle(app);
|
|
2314
2316
|
};
|
|
2315
2317
|
|
|
2318
|
+
// handles/analytics-query.ts
|
|
2319
|
+
import {
|
|
2320
|
+
AthenaClient,
|
|
2321
|
+
GetQueryExecutionCommand,
|
|
2322
|
+
GetQueryResultsCommand,
|
|
2323
|
+
StartQueryExecutionCommand,
|
|
2324
|
+
StopQueryExecutionCommand
|
|
2325
|
+
} from "@aws-sdk/client-athena";
|
|
2326
|
+
import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
|
|
2327
|
+
import { handle as handle2 } from "hono/aws-lambda";
|
|
2328
|
+
import { Hono as Hono3 } from "hono";
|
|
2329
|
+
import httpStatus4 from "http-status";
|
|
2330
|
+
var athena = new AthenaClient();
|
|
2331
|
+
var dynamo = new DynamoDBClient();
|
|
2332
|
+
function required(name) {
|
|
2333
|
+
const value = process.env[name];
|
|
2334
|
+
if (!value) throw new Error(`${name} is required.`);
|
|
2335
|
+
return value;
|
|
2336
|
+
}
|
|
2337
|
+
function queries() {
|
|
2338
|
+
return JSON.parse(required("ANALYTICS_QUERIES"));
|
|
2339
|
+
}
|
|
2340
|
+
function validParameter(value, type) {
|
|
2341
|
+
if (type === "string" && typeof value === "string") return value;
|
|
2342
|
+
if (type === "number" && typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
2343
|
+
if (type === "boolean" && typeof value === "boolean") return String(value);
|
|
2344
|
+
if (type === "date" && typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
|
|
2345
|
+
if (type === "timestamp" && typeof value === "string" && !Number.isNaN(Date.parse(value))) return value;
|
|
2346
|
+
return void 0;
|
|
2347
|
+
}
|
|
2348
|
+
function executionParameter(value, type) {
|
|
2349
|
+
if (type === "string") return `'${value.replaceAll("'", "''")}'`;
|
|
2350
|
+
if (type === "date") return `DATE '${value}'`;
|
|
2351
|
+
if (type === "timestamp") return `TIMESTAMP '${value.replaceAll("'", "''")}'`;
|
|
2352
|
+
return value;
|
|
2353
|
+
}
|
|
2354
|
+
function apiKeys() {
|
|
2355
|
+
return process.env.ANALYTICS_API_KEYS ? JSON.parse(process.env.ANALYTICS_API_KEYS) : [];
|
|
2356
|
+
}
|
|
2357
|
+
function ownedExecution(id) {
|
|
2358
|
+
return __async(this, null, function* () {
|
|
2359
|
+
const item = yield dynamo.send(new GetItemCommand({
|
|
2360
|
+
TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
|
|
2361
|
+
Key: { id: { S: id } },
|
|
2362
|
+
ConsistentRead: true
|
|
2363
|
+
}));
|
|
2364
|
+
return Boolean(item.Item);
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
var analyticsQueryHandler = () => {
|
|
2368
|
+
const app = new Hono3().basePath("/analytics");
|
|
2369
|
+
app.use("*", (c, next) => __async(null, null, function* () {
|
|
2370
|
+
const key = c.req.header("x-api-key");
|
|
2371
|
+
if (!key || !apiKeys().includes(key)) {
|
|
2372
|
+
return c.json({ status: httpStatus4.UNAUTHORIZED, message: httpStatus4["401_MESSAGE"] }, httpStatus4.UNAUTHORIZED);
|
|
2373
|
+
}
|
|
2374
|
+
return next();
|
|
2375
|
+
}));
|
|
2376
|
+
app.get("/queries", (c) => c.json({
|
|
2377
|
+
queries: Object.entries(queries()).map(([name, query]) => {
|
|
2378
|
+
var _a;
|
|
2379
|
+
return { name, parameters: (_a = query.parameters) != null ? _a : {} };
|
|
2380
|
+
})
|
|
2381
|
+
}));
|
|
2382
|
+
app.post("/queries/:name/executions", (c) => __async(null, null, function* () {
|
|
2383
|
+
var _a;
|
|
2384
|
+
const query = queries()[c.req.param("name")];
|
|
2385
|
+
if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus4.NOT_FOUND);
|
|
2386
|
+
const body = yield c.req.json().catch(() => ({}));
|
|
2387
|
+
const declared = (_a = query.parameters) != null ? _a : {};
|
|
2388
|
+
if (Object.keys(body).some((name) => !(name in declared))) {
|
|
2389
|
+
return c.json({ message: "Unexpected query parameter." }, httpStatus4.BAD_REQUEST);
|
|
2390
|
+
}
|
|
2391
|
+
const parameters = Object.entries(declared).map(([name, definition]) => {
|
|
2392
|
+
const value = validParameter(body[name], definition.type);
|
|
2393
|
+
if (value === void 0) throw new Error(`Invalid or missing parameter: ${name}.`);
|
|
2394
|
+
return executionParameter(value, definition.type);
|
|
2395
|
+
});
|
|
2396
|
+
try {
|
|
2397
|
+
const started = yield athena.send(new StartQueryExecutionCommand({
|
|
2398
|
+
QueryString: query.sql,
|
|
2399
|
+
ExecutionParameters: parameters,
|
|
2400
|
+
WorkGroup: required("ANALYTICS_WORKGROUP"),
|
|
2401
|
+
QueryExecutionContext: { Database: required("ANALYTICS_DATABASE") },
|
|
2402
|
+
ResultConfiguration: { OutputLocation: required("ANALYTICS_ATHENA_OUTPUT") },
|
|
2403
|
+
ResultReuseConfiguration: query.resultReuse ? { ResultReuseByAgeConfiguration: { Enabled: true, MaxAgeInMinutes: query.resultReuse.maxAgeMinutes } } : void 0
|
|
2404
|
+
}));
|
|
2405
|
+
if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
|
|
2406
|
+
yield dynamo.send(new PutItemCommand({
|
|
2407
|
+
TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
|
|
2408
|
+
Item: {
|
|
2409
|
+
id: { S: started.QueryExecutionId },
|
|
2410
|
+
queryName: { S: c.req.param("name") },
|
|
2411
|
+
expiresAt: { N: String(Math.floor(Date.now() / 1e3) + 86400) }
|
|
2412
|
+
}
|
|
2413
|
+
}));
|
|
2414
|
+
return c.json({ queryExecutionId: started.QueryExecutionId, state: "QUEUED" }, httpStatus4.ACCEPTED);
|
|
2415
|
+
} catch (error) {
|
|
2416
|
+
if (error instanceof Error && error.message.startsWith("Invalid or missing parameter:")) {
|
|
2417
|
+
return c.json({ message: error.message }, httpStatus4.BAD_REQUEST);
|
|
2418
|
+
}
|
|
2419
|
+
throw error;
|
|
2420
|
+
}
|
|
2421
|
+
}));
|
|
2422
|
+
app.get("/executions/:id", (c) => __async(null, null, function* () {
|
|
2423
|
+
var _a, _b, _c, _d, _e;
|
|
2424
|
+
const id = c.req.param("id");
|
|
2425
|
+
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2426
|
+
const execution = yield athena.send(new GetQueryExecutionCommand({ QueryExecutionId: id }));
|
|
2427
|
+
const status = (_a = execution.QueryExecution) == null ? void 0 : _a.Status;
|
|
2428
|
+
return c.json({
|
|
2429
|
+
queryExecutionId: id,
|
|
2430
|
+
state: status == null ? void 0 : status.State,
|
|
2431
|
+
reason: status == null ? void 0 : status.StateChangeReason,
|
|
2432
|
+
statistics: (_b = execution.QueryExecution) == null ? void 0 : _b.Statistics,
|
|
2433
|
+
reusedPreviousResult: (_e = (_d = (_c = execution.QueryExecution) == null ? void 0 : _c.Statistics) == null ? void 0 : _d.ResultReuseInformation) == null ? void 0 : _e.ReusedPreviousResult
|
|
2434
|
+
});
|
|
2435
|
+
}));
|
|
2436
|
+
app.get("/executions/:id/results", (c) => __async(null, null, function* () {
|
|
2437
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2438
|
+
const id = c.req.param("id");
|
|
2439
|
+
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2440
|
+
const requested = Number((_a = c.req.query("maxResults")) != null ? _a : 100);
|
|
2441
|
+
const maxResults = Number.isFinite(requested) ? Math.min(Math.max(requested, 1), 1e3) : 100;
|
|
2442
|
+
const nextToken = c.req.query("nextToken");
|
|
2443
|
+
const results = yield athena.send(new GetQueryResultsCommand({
|
|
2444
|
+
QueryExecutionId: id,
|
|
2445
|
+
NextToken: nextToken,
|
|
2446
|
+
MaxResults: maxResults
|
|
2447
|
+
}));
|
|
2448
|
+
const rows = (_c = (_b = results.ResultSet) == null ? void 0 : _b.Rows) != null ? _c : [];
|
|
2449
|
+
const columns = ((_f = (_e = (_d = results.ResultSet) == null ? void 0 : _d.ResultSetMetadata) == null ? void 0 : _e.ColumnInfo) != null ? _f : []).map((column) => column.Name);
|
|
2450
|
+
return c.json({
|
|
2451
|
+
columns,
|
|
2452
|
+
rows: rows.slice(nextToken ? 0 : 1).map((row) => {
|
|
2453
|
+
var _a2;
|
|
2454
|
+
return ((_a2 = row.Data) != null ? _a2 : []).map((value) => {
|
|
2455
|
+
var _a3;
|
|
2456
|
+
return (_a3 = value.VarCharValue) != null ? _a3 : null;
|
|
2457
|
+
});
|
|
2458
|
+
}),
|
|
2459
|
+
nextToken: results.NextToken
|
|
2460
|
+
});
|
|
2461
|
+
}));
|
|
2462
|
+
app.post("/executions/:id/cancel", (c) => __async(null, null, function* () {
|
|
2463
|
+
const id = c.req.param("id");
|
|
2464
|
+
if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
|
|
2465
|
+
yield athena.send(new StopQueryExecutionCommand({ QueryExecutionId: id }));
|
|
2466
|
+
return c.body(null, httpStatus4.NO_CONTENT);
|
|
2467
|
+
}));
|
|
2468
|
+
return handle2(app);
|
|
2469
|
+
};
|
|
2470
|
+
|
|
2316
2471
|
// processors/create-entity-processor.ts
|
|
2317
2472
|
var handler = (container) => (ev) => __async(null, null, function* () {
|
|
2318
2473
|
const { entityService } = container;
|
|
@@ -2349,12 +2504,673 @@ var handler = (container) => (ev) => __async(null, null, function* () {
|
|
|
2349
2504
|
return { batchItemFailures };
|
|
2350
2505
|
});
|
|
2351
2506
|
|
|
2507
|
+
// processors/analytics-processor.ts
|
|
2508
|
+
import {
|
|
2509
|
+
FirehoseClient,
|
|
2510
|
+
PutRecordBatchCommand
|
|
2511
|
+
} from "@aws-sdk/client-firehose";
|
|
2512
|
+
import { unmarshall as unmarshall4 } from "@aws-sdk/util-dynamodb";
|
|
2513
|
+
var firehose = new FirehoseClient();
|
|
2514
|
+
function encodeAnalyticsEvent(event) {
|
|
2515
|
+
return {
|
|
2516
|
+
event_id: event.eventId,
|
|
2517
|
+
idempotency_key: event.idempotencyKey,
|
|
2518
|
+
ordering_key: event.orderingKey,
|
|
2519
|
+
sequence_number: event.sequenceNumber,
|
|
2520
|
+
operation: event.operation,
|
|
2521
|
+
occurred_at: event.occurredAt,
|
|
2522
|
+
dataset: event.dataset,
|
|
2523
|
+
kind: event.kind,
|
|
2524
|
+
path: event.path,
|
|
2525
|
+
before: event.before ? JSON.stringify(event.before) : void 0,
|
|
2526
|
+
after: event.after ? JSON.stringify(event.after) : void 0
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
function omitTopLevelFields(value, fields) {
|
|
2530
|
+
if (!value) return value;
|
|
2531
|
+
return Object.fromEntries(
|
|
2532
|
+
Object.entries(value).filter(([key]) => !fields.has(key))
|
|
2533
|
+
);
|
|
2534
|
+
}
|
|
2535
|
+
function sanitizeItem(item, omittedFields) {
|
|
2536
|
+
if (!item) return item;
|
|
2537
|
+
return __spreadProps(__spreadValues({}, item), {
|
|
2538
|
+
data: omitTopLevelFields(
|
|
2539
|
+
item.data,
|
|
2540
|
+
omittedFields
|
|
2541
|
+
),
|
|
2542
|
+
mutualData: omitTopLevelFields(
|
|
2543
|
+
item.mutualData,
|
|
2544
|
+
omittedFields
|
|
2545
|
+
)
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
function parseAnalyticsManifest() {
|
|
2549
|
+
const raw = process.env.ANALYTICS_MANIFEST;
|
|
2550
|
+
if (!raw) throw new Error("ANALYTICS_MANIFEST is required.");
|
|
2551
|
+
return JSON.parse(raw);
|
|
2552
|
+
}
|
|
2553
|
+
function datasetForRecord(record, manifest2, config) {
|
|
2554
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
2555
|
+
const image = (_c = (_a = record.dynamodb) == null ? void 0 : _a.NewImage) != null ? _c : (_b = record.dynamodb) == null ? void 0 : _b.OldImage;
|
|
2556
|
+
if (!((_d = image == null ? void 0 : image.PK) == null ? void 0 : _d.S) || ((_e = image.SK) == null ? void 0 : _e.S) !== "#METADATA#") return void 0;
|
|
2557
|
+
if (!image.PK.S.startsWith("MUTUAL#")) {
|
|
2558
|
+
const entityType = (_f = image.entityType) == null ? void 0 : _f.S;
|
|
2559
|
+
const dataset = manifest2.datasets.find(
|
|
2560
|
+
(candidate) => candidate.kind === "entity" && candidate.name === entityType
|
|
2561
|
+
);
|
|
2562
|
+
return dataset && {
|
|
2563
|
+
name: dataset.name,
|
|
2564
|
+
kind: dataset.kind,
|
|
2565
|
+
granularity: dataset.partition.granularity
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
const item = unmarshall4(image);
|
|
2569
|
+
const pair = [item.byEntityType, item.entityType].sort().join("::");
|
|
2570
|
+
for (const entityConfig of Object.values(config)) {
|
|
2571
|
+
for (const field of Object.values(
|
|
2572
|
+
(_h = (_g = entityConfig.mutual) == null ? void 0 : _g.mutualFields) != null ? _h : {}
|
|
2573
|
+
)) {
|
|
2574
|
+
const mutual = field.mutual;
|
|
2575
|
+
if (!(mutual == null ? void 0 : mutual.name)) continue;
|
|
2576
|
+
if ([entityConfig.name, field.entityType].sort().join("::") !== pair) continue;
|
|
2577
|
+
const dataset = manifest2.datasets.find(
|
|
2578
|
+
(candidate) => candidate.kind === "mutual" && candidate.name === mutual.name
|
|
2579
|
+
);
|
|
2580
|
+
return dataset && {
|
|
2581
|
+
name: dataset.name,
|
|
2582
|
+
kind: dataset.kind,
|
|
2583
|
+
granularity: dataset.partition.granularity
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
var handler2 = (config) => (event) => __async(null, null, function* () {
|
|
2589
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
2590
|
+
const streamName = process.env.ANALYTICS_DELIVERY_STREAM;
|
|
2591
|
+
if (!streamName) throw new Error("ANALYTICS_DELIVERY_STREAM is required.");
|
|
2592
|
+
const manifest2 = parseAnalyticsManifest();
|
|
2593
|
+
const omittedFields = new Set(
|
|
2594
|
+
JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]")
|
|
2595
|
+
);
|
|
2596
|
+
const failures = [];
|
|
2597
|
+
const events = [];
|
|
2598
|
+
for (const record of event.Records) {
|
|
2599
|
+
try {
|
|
2600
|
+
const dataset = datasetForRecord(record, manifest2, config);
|
|
2601
|
+
if (!dataset || !record.eventName || !record.eventID) continue;
|
|
2602
|
+
const occurredAt = new Date(
|
|
2603
|
+
Number(
|
|
2604
|
+
(_c = (_b = record.dynamodb) == null ? void 0 : _b.ApproximateCreationDateTime) != null ? _c : Date.now() / 1e3
|
|
2605
|
+
) * 1e3
|
|
2606
|
+
);
|
|
2607
|
+
const eventDate = occurredAt.toISOString().slice(0, 10);
|
|
2608
|
+
const eventHour = occurredAt.toISOString().slice(11, 13);
|
|
2609
|
+
const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${eventDate}${dataset.granularity === "hour" ? `/event_hour=${eventHour}` : ""}`;
|
|
2610
|
+
events.push({
|
|
2611
|
+
record,
|
|
2612
|
+
event: {
|
|
2613
|
+
eventId: record.eventID,
|
|
2614
|
+
idempotencyKey: record.eventID,
|
|
2615
|
+
orderingKey: (_e = (_d = record.dynamodb) == null ? void 0 : _d.SequenceNumber) != null ? _e : record.eventID,
|
|
2616
|
+
sequenceNumber: (_f = record.dynamodb) == null ? void 0 : _f.SequenceNumber,
|
|
2617
|
+
operation: record.eventName,
|
|
2618
|
+
occurredAt: occurredAt.toISOString(),
|
|
2619
|
+
dataset: dataset.name,
|
|
2620
|
+
kind: dataset.kind,
|
|
2621
|
+
path,
|
|
2622
|
+
before: sanitizeItem(
|
|
2623
|
+
((_g = record.dynamodb) == null ? void 0 : _g.OldImage) ? unmarshall4(record.dynamodb.OldImage) : void 0,
|
|
2624
|
+
omittedFields
|
|
2625
|
+
),
|
|
2626
|
+
after: sanitizeItem(
|
|
2627
|
+
((_h = record.dynamodb) == null ? void 0 : _h.NewImage) ? unmarshall4(record.dynamodb.NewImage) : void 0,
|
|
2628
|
+
omittedFields
|
|
2629
|
+
)
|
|
2630
|
+
}
|
|
2631
|
+
});
|
|
2632
|
+
} catch (error) {
|
|
2633
|
+
console.error("Unable to normalize analytics stream record", error);
|
|
2634
|
+
failures.push({ itemIdentifier: (_j = (_i = record.dynamodb) == null ? void 0 : _i.SequenceNumber) != null ? _j : "" });
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
for (let index = 0; index < events.length; index += 500) {
|
|
2638
|
+
const batch = events.slice(index, index + 500);
|
|
2639
|
+
const result = yield firehose.send(
|
|
2640
|
+
new PutRecordBatchCommand({
|
|
2641
|
+
DeliveryStreamName: streamName,
|
|
2642
|
+
Records: batch.map(({ event: value }) => ({
|
|
2643
|
+
Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
|
|
2644
|
+
`)
|
|
2645
|
+
}))
|
|
2646
|
+
})
|
|
2647
|
+
);
|
|
2648
|
+
(_k = result.RequestResponses) == null ? void 0 : _k.forEach((response, responseIndex) => {
|
|
2649
|
+
var _a2, _b2, _c2;
|
|
2650
|
+
if (!response.ErrorCode) return;
|
|
2651
|
+
failures.push({
|
|
2652
|
+
itemIdentifier: (_c2 = (_b2 = (_a2 = batch[responseIndex]) == null ? void 0 : _a2.record.dynamodb) == null ? void 0 : _b2.SequenceNumber) != null ? _c2 : ""
|
|
2653
|
+
});
|
|
2654
|
+
});
|
|
2655
|
+
}
|
|
2656
|
+
return { batchItemFailures: failures };
|
|
2657
|
+
});
|
|
2658
|
+
|
|
2659
|
+
// processors/analytics-backfill-processor.ts
|
|
2660
|
+
import {
|
|
2661
|
+
DeleteItemCommand,
|
|
2662
|
+
DynamoDBClient as DynamoDBClient2,
|
|
2663
|
+
ExportTableToPointInTimeCommand,
|
|
2664
|
+
GetItemCommand as GetItemCommand2,
|
|
2665
|
+
PutItemCommand as PutItemCommand2,
|
|
2666
|
+
UpdateItemCommand
|
|
2667
|
+
} from "@aws-sdk/client-dynamodb";
|
|
2668
|
+
import { FirehoseClient as FirehoseClient2, PutRecordBatchCommand as PutRecordBatchCommand2 } from "@aws-sdk/client-firehose";
|
|
2669
|
+
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2670
|
+
import { marshall as marshall5, unmarshall as unmarshall5 } from "@aws-sdk/util-dynamodb";
|
|
2671
|
+
import { gunzipSync } from "zlib";
|
|
2672
|
+
var dynamodb = new DynamoDBClient2();
|
|
2673
|
+
var firehose2 = new FirehoseClient2();
|
|
2674
|
+
var s3 = new S3Client();
|
|
2675
|
+
var backfillMarker = { PK: "#ANALYTICS#", SK: "#BACKFILL#" };
|
|
2676
|
+
function required2(name) {
|
|
2677
|
+
const value = process.env[name];
|
|
2678
|
+
if (!value) throw new Error(`${name} is required.`);
|
|
2679
|
+
return value;
|
|
2680
|
+
}
|
|
2681
|
+
function exportTimestamp() {
|
|
2682
|
+
const value = process.env.ANALYTICS_EXPORT_TIME;
|
|
2683
|
+
const timestamp = value ? new Date(value) : /* @__PURE__ */ new Date();
|
|
2684
|
+
if (Number.isNaN(timestamp.getTime())) {
|
|
2685
|
+
throw new Error("ANALYTICS_EXPORT_TIME must be an ISO-8601 timestamp.");
|
|
2686
|
+
}
|
|
2687
|
+
return timestamp;
|
|
2688
|
+
}
|
|
2689
|
+
function startBackfill(reconcile = false) {
|
|
2690
|
+
return __async(this, null, function* () {
|
|
2691
|
+
var _a, _b, _c;
|
|
2692
|
+
const timestamp = exportTimestamp();
|
|
2693
|
+
const tableName = required2("ANALYTICS_BACKFILL_MARKER_TABLE");
|
|
2694
|
+
const marker = marshall5(__spreadProps(__spreadValues({}, backfillMarker), { exportTime: timestamp.toISOString(), state: "starting" }));
|
|
2695
|
+
let createdMarker = false;
|
|
2696
|
+
try {
|
|
2697
|
+
yield dynamodb.send(new PutItemCommand2({ TableName: tableName, Item: marker, ConditionExpression: "attribute_not_exists(PK)" }));
|
|
2698
|
+
createdMarker = true;
|
|
2699
|
+
} catch (error) {
|
|
2700
|
+
if (error.name !== "ConditionalCheckFailedException") throw error;
|
|
2701
|
+
if (reconcile) {
|
|
2702
|
+
yield dynamodb.send(new UpdateItemCommand({
|
|
2703
|
+
TableName: tableName,
|
|
2704
|
+
Key: marshall5(backfillMarker),
|
|
2705
|
+
UpdateExpression: "SET exportTime = :exportTime, #state = :state REMOVE exportArn",
|
|
2706
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
2707
|
+
ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString(), ":state": "starting" })
|
|
2708
|
+
}));
|
|
2709
|
+
} else {
|
|
2710
|
+
const existing = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
|
|
2711
|
+
const value = existing.Item ? unmarshall5(existing.Item) : {};
|
|
2712
|
+
return { exportArn: value.exportArn, exportTime: value.exportTime, started: false };
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
let result;
|
|
2716
|
+
try {
|
|
2717
|
+
result = yield dynamodb.send(new ExportTableToPointInTimeCommand({
|
|
2718
|
+
TableArn: required2("ANALYTICS_TABLE_ARN"),
|
|
2719
|
+
S3Bucket: required2("ANALYTICS_BACKFILL_BUCKET"),
|
|
2720
|
+
S3Prefix: (_a = process.env.ANALYTICS_BACKFILL_PREFIX) != null ? _a : "backfill",
|
|
2721
|
+
ExportTime: timestamp,
|
|
2722
|
+
ExportFormat: "DYNAMODB_JSON"
|
|
2723
|
+
}));
|
|
2724
|
+
} catch (error) {
|
|
2725
|
+
if (createdMarker) {
|
|
2726
|
+
yield dynamodb.send(new DeleteItemCommand({
|
|
2727
|
+
TableName: tableName,
|
|
2728
|
+
Key: marshall5(backfillMarker),
|
|
2729
|
+
ConditionExpression: "exportTime = :exportTime",
|
|
2730
|
+
ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString() })
|
|
2731
|
+
}));
|
|
2732
|
+
} else {
|
|
2733
|
+
yield dynamodb.send(new UpdateItemCommand({
|
|
2734
|
+
TableName: tableName,
|
|
2735
|
+
Key: marshall5(backfillMarker),
|
|
2736
|
+
UpdateExpression: "SET #state = :state",
|
|
2737
|
+
ConditionExpression: "exportTime = :exportTime",
|
|
2738
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
2739
|
+
ExpressionAttributeValues: marshall5({ ":state": "failed", ":exportTime": timestamp.toISOString() })
|
|
2740
|
+
}));
|
|
2741
|
+
}
|
|
2742
|
+
throw error;
|
|
2743
|
+
}
|
|
2744
|
+
yield dynamodb.send(new UpdateItemCommand({
|
|
2745
|
+
TableName: tableName,
|
|
2746
|
+
Key: marshall5(backfillMarker),
|
|
2747
|
+
UpdateExpression: "SET #state = :state, exportArn = :exportArn",
|
|
2748
|
+
ConditionExpression: "exportTime = :exportTime",
|
|
2749
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
2750
|
+
ExpressionAttributeValues: marshall5({ ":state": "started", ":exportArn": (_b = result.ExportDescription) == null ? void 0 : _b.ExportArn, ":exportTime": timestamp.toISOString() }, { removeUndefinedValues: true })
|
|
2751
|
+
}));
|
|
2752
|
+
return { exportArn: (_c = result.ExportDescription) == null ? void 0 : _c.ExportArn, exportTime: timestamp.toISOString(), started: true };
|
|
2753
|
+
});
|
|
2754
|
+
}
|
|
2755
|
+
function backfillTimestamp() {
|
|
2756
|
+
return __async(this, null, function* () {
|
|
2757
|
+
const tableName = process.env.ANALYTICS_BACKFILL_MARKER_TABLE;
|
|
2758
|
+
if (!tableName) return exportTimestamp();
|
|
2759
|
+
const result = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
|
|
2760
|
+
const value = result.Item ? unmarshall5(result.Item).exportTime : void 0;
|
|
2761
|
+
if (typeof value !== "string") throw new Error("Analytics backfill marker is missing its export timestamp.");
|
|
2762
|
+
const timestamp = new Date(value);
|
|
2763
|
+
if (Number.isNaN(timestamp.getTime())) throw new Error("Analytics backfill marker has an invalid export timestamp.");
|
|
2764
|
+
return timestamp;
|
|
2765
|
+
});
|
|
2766
|
+
}
|
|
2767
|
+
function streamToBuffer(stream) {
|
|
2768
|
+
return (() => __async(null, null, function* () {
|
|
2769
|
+
const chunks = [];
|
|
2770
|
+
try {
|
|
2771
|
+
for (var iter = __forAwait(stream), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
|
|
2772
|
+
const chunk = temp.value;
|
|
2773
|
+
chunks.push(chunk);
|
|
2774
|
+
}
|
|
2775
|
+
} catch (temp) {
|
|
2776
|
+
error = [temp];
|
|
2777
|
+
} finally {
|
|
2778
|
+
try {
|
|
2779
|
+
more && (temp = iter.return) && (yield temp.call(iter));
|
|
2780
|
+
} finally {
|
|
2781
|
+
if (error)
|
|
2782
|
+
throw error[0];
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
return Buffer.concat(chunks);
|
|
2786
|
+
}))();
|
|
2787
|
+
}
|
|
2788
|
+
function snapshotEvent(item, config, occurredAt, omittedFields) {
|
|
2789
|
+
const attributes = marshall5(item, { removeUndefinedValues: true });
|
|
2790
|
+
const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, parseAnalyticsManifest(), config);
|
|
2791
|
+
if (!dataset) return void 0;
|
|
2792
|
+
const after = sanitizeItem(item, omittedFields);
|
|
2793
|
+
const key = `${String(item.PK)}:${String(item.SK)}`;
|
|
2794
|
+
const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${occurredAt.toISOString().slice(0, 10)}${dataset.granularity === "hour" ? `/event_hour=${occurredAt.toISOString().slice(11, 13)}` : ""}`;
|
|
2795
|
+
return {
|
|
2796
|
+
eventId: `snapshot:${key}:${occurredAt.toISOString()}`,
|
|
2797
|
+
idempotencyKey: `snapshot:${key}:${occurredAt.toISOString()}`,
|
|
2798
|
+
orderingKey: occurredAt.toISOString(),
|
|
2799
|
+
operation: "SNAPSHOT",
|
|
2800
|
+
occurredAt: occurredAt.toISOString(),
|
|
2801
|
+
dataset: dataset.name,
|
|
2802
|
+
kind: dataset.kind,
|
|
2803
|
+
path,
|
|
2804
|
+
after
|
|
2805
|
+
};
|
|
2806
|
+
}
|
|
2807
|
+
var handler3 = (config) => (event) => __async(null, null, function* () {
|
|
2808
|
+
var _a;
|
|
2809
|
+
if (!("Records" in event)) {
|
|
2810
|
+
if (event.action === "start") return startBackfill();
|
|
2811
|
+
if (event.action === "reconcile") return startBackfill(true);
|
|
2812
|
+
throw new Error("Unsupported analytics backfill event.");
|
|
2813
|
+
}
|
|
2814
|
+
const timestamp = yield backfillTimestamp();
|
|
2815
|
+
const omittedFields = new Set(JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]"));
|
|
2816
|
+
const deliveryStream = required2("ANALYTICS_DELIVERY_STREAM");
|
|
2817
|
+
let delivered = 0;
|
|
2818
|
+
for (const record of event.Records) {
|
|
2819
|
+
const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
|
|
2820
|
+
if (!key.endsWith(".json.gz")) continue;
|
|
2821
|
+
const response = yield s3.send(new GetObjectCommand({ Bucket: record.s3.bucket.name, Key: key }));
|
|
2822
|
+
if (!response.Body) throw new Error(`Backfill export object ${key} has no body.`);
|
|
2823
|
+
const content = gunzipSync(yield streamToBuffer(response.Body)).toString("utf8");
|
|
2824
|
+
const events = content.split("\n").filter(Boolean).flatMap((line) => {
|
|
2825
|
+
const attributes = JSON.parse(line).Item;
|
|
2826
|
+
return attributes ? [snapshotEvent(unmarshall5(attributes), config, timestamp, omittedFields)].filter(Boolean) : [];
|
|
2827
|
+
});
|
|
2828
|
+
for (let index = 0; index < events.length; index += 500) {
|
|
2829
|
+
const batch = events.slice(index, index + 500);
|
|
2830
|
+
const result = yield firehose2.send(new PutRecordBatchCommand2({ DeliveryStreamName: deliveryStream, Records: batch.map((value) => ({ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
|
|
2831
|
+
`) })) }));
|
|
2832
|
+
if (result.FailedPutCount) throw new Error(`Failed to deliver ${result.FailedPutCount} backfill records; retry this export object.`);
|
|
2833
|
+
delivered += batch.length;
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
return { delivered, exportTime: timestamp.toISOString() };
|
|
2837
|
+
});
|
|
2838
|
+
|
|
2839
|
+
// processors/analytics-materialization-processor.ts
|
|
2840
|
+
import {
|
|
2841
|
+
AthenaClient as AthenaClient2,
|
|
2842
|
+
GetQueryExecutionCommand as GetQueryExecutionCommand2,
|
|
2843
|
+
GetQueryResultsCommand as GetQueryResultsCommand2,
|
|
2844
|
+
StartQueryExecutionCommand as StartQueryExecutionCommand2
|
|
2845
|
+
} from "@aws-sdk/client-athena";
|
|
2846
|
+
var athena2 = new AthenaClient2();
|
|
2847
|
+
function required3(name) {
|
|
2848
|
+
const value = process.env[name];
|
|
2849
|
+
if (!value) throw new Error(`${name} is required.`);
|
|
2850
|
+
return value;
|
|
2851
|
+
}
|
|
2852
|
+
function quoteIdentifier(identifier) {
|
|
2853
|
+
return `"${identifier.replaceAll('"', '""')}"`;
|
|
2854
|
+
}
|
|
2855
|
+
function quoteDdlIdentifier(identifier) {
|
|
2856
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier))
|
|
2857
|
+
throw new Error(`Invalid Athena DDL identifier: ${identifier}`);
|
|
2858
|
+
return identifier;
|
|
2859
|
+
}
|
|
2860
|
+
function quoteLiteral(value) {
|
|
2861
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
2862
|
+
}
|
|
2863
|
+
function manifest() {
|
|
2864
|
+
return JSON.parse(required3("ANALYTICS_MANIFEST"));
|
|
2865
|
+
}
|
|
2866
|
+
function valueExpression(column, kind) {
|
|
2867
|
+
const payload = "coalesce(after, before)";
|
|
2868
|
+
const path = `$.${kind === "mutual" ? "mutualData" : "data"}.${column.sourceName.replaceAll('"', '\\"')}`;
|
|
2869
|
+
const scalar = `json_extract_scalar(${payload}, ${quoteLiteral(path)})`;
|
|
2870
|
+
switch (column.type) {
|
|
2871
|
+
case "boolean":
|
|
2872
|
+
return `try_cast(${scalar} AS boolean)`;
|
|
2873
|
+
case "double":
|
|
2874
|
+
return `try_cast(${scalar} AS double)`;
|
|
2875
|
+
case "timestamp":
|
|
2876
|
+
return `try_cast(from_iso8601_timestamp(${scalar}) AS timestamp)`;
|
|
2877
|
+
case "json":
|
|
2878
|
+
return `json_format(json_extract(${payload}, ${quoteLiteral(path)}))`;
|
|
2879
|
+
default:
|
|
2880
|
+
return scalar;
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
function endpointExpression(endpoint) {
|
|
2884
|
+
const payload = "coalesce(after, before)";
|
|
2885
|
+
if (endpoint.role === "source") {
|
|
2886
|
+
return `json_extract_scalar(${payload}, '$.byEntityId')`;
|
|
2887
|
+
}
|
|
2888
|
+
if (endpoint.role === "target") {
|
|
2889
|
+
return `json_extract_scalar(${payload}, '$.entityId')`;
|
|
2890
|
+
}
|
|
2891
|
+
const entityName = quoteLiteral(endpoint.entityName);
|
|
2892
|
+
return `CASE WHEN json_extract_scalar(${payload}, '$.byEntityType') = ${entityName} THEN json_extract_scalar(${payload}, '$.byEntityId') WHEN json_extract_scalar(${payload}, '$.entityType') = ${entityName} THEN json_extract_scalar(${payload}, '$.entityId') END`;
|
|
2893
|
+
}
|
|
2894
|
+
function datasetSql(dataset, database, bucket) {
|
|
2895
|
+
var _a;
|
|
2896
|
+
const history = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.historyTable)}`;
|
|
2897
|
+
const current = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.currentTable)}`;
|
|
2898
|
+
const historyDdl = dataset.historyTable;
|
|
2899
|
+
const currentDdl = dataset.currentTable;
|
|
2900
|
+
const raw = `${quoteIdentifier(database)}.${quoteIdentifier((_a = dataset.rawTable) != null ? _a : `${dataset.historyTable}_raw`)}`;
|
|
2901
|
+
const typedColumns = dataset.columns.map(
|
|
2902
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
2903
|
+
);
|
|
2904
|
+
const names = dataset.columns.map((column) => quoteIdentifier(column.name));
|
|
2905
|
+
const endpointNames = dataset.endpoints.map(
|
|
2906
|
+
(endpoint) => quoteIdentifier(endpoint.column)
|
|
2907
|
+
);
|
|
2908
|
+
const endpointDdlNames = dataset.endpoints.map(
|
|
2909
|
+
(endpoint) => quoteDdlIdentifier(endpoint.column)
|
|
2910
|
+
);
|
|
2911
|
+
const values = dataset.columns.map(
|
|
2912
|
+
(column) => valueExpression(column, dataset.kind)
|
|
2913
|
+
);
|
|
2914
|
+
const payload = "coalesce(after, before)";
|
|
2915
|
+
const idPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
|
|
2916
|
+
const selected = [
|
|
2917
|
+
"event_id",
|
|
2918
|
+
"idempotency_key",
|
|
2919
|
+
"ordering_key",
|
|
2920
|
+
"sequence_number",
|
|
2921
|
+
"operation",
|
|
2922
|
+
"try_cast(from_iso8601_timestamp(occurred_at) AS timestamp) AS occurred_at",
|
|
2923
|
+
`json_extract_scalar(${payload}, ${quoteLiteral(idPath)}) AS ${quoteIdentifier(dataset.idColumn)}`,
|
|
2924
|
+
"before AS before_json",
|
|
2925
|
+
"after AS after_json",
|
|
2926
|
+
...dataset.endpoints.map(
|
|
2927
|
+
(endpoint) => `${endpointExpression(endpoint)} AS ${quoteIdentifier(endpoint.column)}`
|
|
2928
|
+
),
|
|
2929
|
+
...values.map((value, index) => `${value} AS ${names[index]}`)
|
|
2930
|
+
];
|
|
2931
|
+
const allColumns = [
|
|
2932
|
+
"event_id string",
|
|
2933
|
+
"idempotency_key string",
|
|
2934
|
+
"ordering_key string",
|
|
2935
|
+
"sequence_number string",
|
|
2936
|
+
"operation string",
|
|
2937
|
+
"occurred_at timestamp",
|
|
2938
|
+
`${quoteDdlIdentifier(dataset.idColumn)} string`,
|
|
2939
|
+
"before_json string",
|
|
2940
|
+
"after_json string",
|
|
2941
|
+
...endpointDdlNames.map((name) => `${name} string`),
|
|
2942
|
+
...typedColumns
|
|
2943
|
+
];
|
|
2944
|
+
const historyNames = [
|
|
2945
|
+
"event_id",
|
|
2946
|
+
"idempotency_key",
|
|
2947
|
+
"ordering_key",
|
|
2948
|
+
"sequence_number",
|
|
2949
|
+
"operation",
|
|
2950
|
+
"occurred_at",
|
|
2951
|
+
dataset.idColumn,
|
|
2952
|
+
"before_json",
|
|
2953
|
+
"after_json",
|
|
2954
|
+
...dataset.endpoints.map((endpoint) => endpoint.column),
|
|
2955
|
+
...dataset.columns.map((column) => column.name)
|
|
2956
|
+
].map(quoteIdentifier).join(", ");
|
|
2957
|
+
const insertValues = [
|
|
2958
|
+
"s.event_id",
|
|
2959
|
+
"s.idempotency_key",
|
|
2960
|
+
"s.ordering_key",
|
|
2961
|
+
"s.sequence_number",
|
|
2962
|
+
"s.operation",
|
|
2963
|
+
"s.occurred_at",
|
|
2964
|
+
`s.${quoteIdentifier(dataset.idColumn)}`,
|
|
2965
|
+
"s.before_json",
|
|
2966
|
+
"s.after_json",
|
|
2967
|
+
...endpointNames.map((name) => `s.${name}`),
|
|
2968
|
+
...names.map((name) => `s.${name}`)
|
|
2969
|
+
].join(", ");
|
|
2970
|
+
return [
|
|
2971
|
+
`CREATE TABLE ${historyDdl} (${allColumns.join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/curated/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`)} TBLPROPERTIES ('table_type' = 'ICEBERG')`,
|
|
2972
|
+
`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 ${raw}) WHERE row_number = 1) s ON h.event_id = s.event_id WHEN NOT MATCHED THEN INSERT (${historyNames}) VALUES (${insertValues})`,
|
|
2973
|
+
`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')`,
|
|
2974
|
+
`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(", ")}` : ""})`
|
|
2975
|
+
];
|
|
2976
|
+
}
|
|
2977
|
+
function execute(statement) {
|
|
2978
|
+
return __async(this, null, function* () {
|
|
2979
|
+
var _a, _b;
|
|
2980
|
+
const started = yield athena2.send(
|
|
2981
|
+
new StartQueryExecutionCommand2({
|
|
2982
|
+
QueryString: statement,
|
|
2983
|
+
WorkGroup: required3("ANALYTICS_WORKGROUP"),
|
|
2984
|
+
QueryExecutionContext: { Database: required3("ANALYTICS_DATABASE") },
|
|
2985
|
+
ResultConfiguration: {
|
|
2986
|
+
OutputLocation: required3("ANALYTICS_ATHENA_OUTPUT")
|
|
2987
|
+
}
|
|
2988
|
+
})
|
|
2989
|
+
);
|
|
2990
|
+
if (!started.QueryExecutionId)
|
|
2991
|
+
throw new Error("Athena did not return a query execution id.");
|
|
2992
|
+
for (; ; ) {
|
|
2993
|
+
const status = (_a = (yield athena2.send(
|
|
2994
|
+
new GetQueryExecutionCommand2({
|
|
2995
|
+
QueryExecutionId: started.QueryExecutionId
|
|
2996
|
+
})
|
|
2997
|
+
)).QueryExecution) == null ? void 0 : _a.Status;
|
|
2998
|
+
if ((status == null ? void 0 : status.State) === "SUCCEEDED") return started.QueryExecutionId;
|
|
2999
|
+
if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
|
|
3000
|
+
throw new Error(
|
|
3001
|
+
`Athena materialization query ${started.QueryExecutionId} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`
|
|
3002
|
+
);
|
|
3003
|
+
}
|
|
3004
|
+
yield new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
3005
|
+
}
|
|
3006
|
+
});
|
|
3007
|
+
}
|
|
3008
|
+
function createTable(statement) {
|
|
3009
|
+
return __async(this, null, function* () {
|
|
3010
|
+
try {
|
|
3011
|
+
yield execute(statement);
|
|
3012
|
+
} catch (error) {
|
|
3013
|
+
if (/already exists/i.test(error instanceof Error ? error.message : String(error))) return;
|
|
3014
|
+
throw error;
|
|
3015
|
+
}
|
|
3016
|
+
});
|
|
3017
|
+
}
|
|
3018
|
+
function tableColumns(database, table) {
|
|
3019
|
+
return __async(this, null, function* () {
|
|
3020
|
+
var _a, _b;
|
|
3021
|
+
const queryExecutionId = yield execute(
|
|
3022
|
+
`SELECT column_name FROM information_schema.columns WHERE table_schema = ${quoteLiteral(database)} AND table_name = ${quoteLiteral(table)}`
|
|
3023
|
+
);
|
|
3024
|
+
const result = yield athena2.send(
|
|
3025
|
+
new GetQueryResultsCommand2({ QueryExecutionId: queryExecutionId })
|
|
3026
|
+
);
|
|
3027
|
+
return new Set(
|
|
3028
|
+
((_b = (_a = result.ResultSet) == null ? void 0 : _a.Rows) != null ? _b : []).slice(1).map((row) => {
|
|
3029
|
+
var _a2, _b2;
|
|
3030
|
+
return (_b2 = (_a2 = row.Data) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.VarCharValue;
|
|
3031
|
+
}).filter((name) => Boolean(name))
|
|
3032
|
+
);
|
|
3033
|
+
});
|
|
3034
|
+
}
|
|
3035
|
+
function addMissingColumns(database, table, columns) {
|
|
3036
|
+
return __async(this, null, function* () {
|
|
3037
|
+
const existing = yield tableColumns(database, table);
|
|
3038
|
+
const missing = columns.filter(
|
|
3039
|
+
(column) => {
|
|
3040
|
+
var _a, _b;
|
|
3041
|
+
return !existing.has(
|
|
3042
|
+
(_b = (_a = column.match(/^([A-Za-z_][A-Za-z0-9_]*)/)) == null ? void 0 : _a[1]) != null ? _b : ""
|
|
3043
|
+
);
|
|
3044
|
+
}
|
|
3045
|
+
);
|
|
3046
|
+
if (missing.length)
|
|
3047
|
+
yield execute(
|
|
3048
|
+
`ALTER TABLE ${quoteIdentifier(database)}.${quoteIdentifier(table)} ADD COLUMNS (${missing.join(", ")})`
|
|
3049
|
+
);
|
|
3050
|
+
});
|
|
3051
|
+
}
|
|
3052
|
+
function generatedColumns(dataset) {
|
|
3053
|
+
return [
|
|
3054
|
+
`${quoteDdlIdentifier(dataset.idColumn)} string`,
|
|
3055
|
+
...dataset.endpoints.map(
|
|
3056
|
+
(endpoint) => `${quoteDdlIdentifier(endpoint.column)} string`
|
|
3057
|
+
)
|
|
3058
|
+
];
|
|
3059
|
+
}
|
|
3060
|
+
var handler4 = (configuredManifest) => () => __async(null, null, function* () {
|
|
3061
|
+
const database = required3("ANALYTICS_DATABASE");
|
|
3062
|
+
const bucket = required3("ANALYTICS_BUCKET");
|
|
3063
|
+
for (const dataset of (configuredManifest != null ? configuredManifest : manifest()).datasets) {
|
|
3064
|
+
const statements = datasetSql(dataset, database, bucket);
|
|
3065
|
+
yield createTable(statements[0]);
|
|
3066
|
+
yield addMissingColumns(
|
|
3067
|
+
database,
|
|
3068
|
+
dataset.historyTable,
|
|
3069
|
+
[...generatedColumns(dataset), ...dataset.columns.map(
|
|
3070
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
3071
|
+
)]
|
|
3072
|
+
);
|
|
3073
|
+
yield createTable(statements[2]);
|
|
3074
|
+
yield addMissingColumns(
|
|
3075
|
+
database,
|
|
3076
|
+
dataset.currentTable,
|
|
3077
|
+
[...generatedColumns(dataset), ...dataset.columns.map(
|
|
3078
|
+
(column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
|
|
3079
|
+
)]
|
|
3080
|
+
);
|
|
3081
|
+
for (const statement of [statements[1], statements[3]]) {
|
|
3082
|
+
yield execute(statement);
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
});
|
|
3086
|
+
|
|
3087
|
+
// processors/analytics-model-processor.ts
|
|
3088
|
+
import { AthenaClient as AthenaClient3, GetQueryExecutionCommand as GetQueryExecutionCommand3, StartQueryExecutionCommand as StartQueryExecutionCommand3 } from "@aws-sdk/client-athena";
|
|
3089
|
+
var athena3 = new AthenaClient3();
|
|
3090
|
+
function required4(name) {
|
|
3091
|
+
const value = process.env[name];
|
|
3092
|
+
if (!value) throw new Error(`${name} is required.`);
|
|
3093
|
+
return value;
|
|
3094
|
+
}
|
|
3095
|
+
function quote(identifier) {
|
|
3096
|
+
return `"${identifier.replaceAll('"', '""')}"`;
|
|
3097
|
+
}
|
|
3098
|
+
function execute2(statement) {
|
|
3099
|
+
return __async(this, null, function* () {
|
|
3100
|
+
var _a, _b;
|
|
3101
|
+
const started = yield athena3.send(new StartQueryExecutionCommand3({
|
|
3102
|
+
QueryString: statement,
|
|
3103
|
+
WorkGroup: required4("ANALYTICS_WORKGROUP"),
|
|
3104
|
+
QueryExecutionContext: { Database: required4("ANALYTICS_DATABASE") },
|
|
3105
|
+
ResultConfiguration: { OutputLocation: required4("ANALYTICS_ATHENA_OUTPUT") }
|
|
3106
|
+
}));
|
|
3107
|
+
if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
|
|
3108
|
+
for (; ; ) {
|
|
3109
|
+
const status = (_a = (yield athena3.send(new GetQueryExecutionCommand3({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
|
|
3110
|
+
if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
|
|
3111
|
+
if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") throw new Error(`Analytics model ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`);
|
|
3112
|
+
yield new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
3113
|
+
}
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
function modelStatements(model, database, bucket, now = /* @__PURE__ */ new Date()) {
|
|
3117
|
+
const table = model.name.replaceAll("-", "_");
|
|
3118
|
+
const end = now;
|
|
3119
|
+
const start = new Date(end.getTime() - model.lookbackDays * 864e5);
|
|
3120
|
+
const source = model.sql.replaceAll("{{windowStart}}", `'${start.toISOString().replaceAll("'", "''")}'`).replaceAll("{{windowEnd}}", `'${end.toISOString().replaceAll("'", "''")}'`);
|
|
3121
|
+
const target = `${quote(database)}.${quote(table)}`;
|
|
3122
|
+
const location = `s3://${bucket}/models/${table}/`;
|
|
3123
|
+
const partitionStart = start.toISOString().slice(0, 10);
|
|
3124
|
+
return [
|
|
3125
|
+
`CREATE TABLE IF NOT EXISTS ${target} WITH (table_type = 'ICEBERG', location = '${location}', partitioning = ARRAY['${model.partitionColumn}']) AS ${source}`,
|
|
3126
|
+
`DELETE FROM ${target} WHERE ${quote(model.partitionColumn)} >= DATE '${partitionStart}'`,
|
|
3127
|
+
`INSERT INTO ${target} ${source}`
|
|
3128
|
+
];
|
|
3129
|
+
}
|
|
3130
|
+
var handler5 = () => __async(null, null, function* () {
|
|
3131
|
+
const model = JSON.parse(required4("ANALYTICS_MODEL"));
|
|
3132
|
+
for (const statement of modelStatements(model, required4("ANALYTICS_DATABASE"), required4("ANALYTICS_BUCKET"))) {
|
|
3133
|
+
yield execute2(statement);
|
|
3134
|
+
}
|
|
3135
|
+
});
|
|
3136
|
+
|
|
3137
|
+
// processors/analytics-view-processor.ts
|
|
3138
|
+
import { AthenaClient as AthenaClient4, GetQueryExecutionCommand as GetQueryExecutionCommand4, StartQueryExecutionCommand as StartQueryExecutionCommand4 } from "@aws-sdk/client-athena";
|
|
3139
|
+
var athena4 = new AthenaClient4();
|
|
3140
|
+
function required5(name) {
|
|
3141
|
+
const value = process.env[name];
|
|
3142
|
+
if (!value) throw new Error(`${name} is required.`);
|
|
3143
|
+
return value;
|
|
3144
|
+
}
|
|
3145
|
+
function quote2(identifier) {
|
|
3146
|
+
return `"${identifier.replaceAll('"', '""')}"`;
|
|
3147
|
+
}
|
|
3148
|
+
var handler6 = () => __async(null, null, function* () {
|
|
3149
|
+
var _a, _b;
|
|
3150
|
+
const view = JSON.parse(required5("ANALYTICS_VIEW"));
|
|
3151
|
+
const started = yield athena4.send(new StartQueryExecutionCommand4({
|
|
3152
|
+
QueryString: `CREATE OR REPLACE VIEW ${quote2(required5("ANALYTICS_DATABASE"))}.${quote2(view.name.replaceAll("-", "_"))} AS ${view.sql}`,
|
|
3153
|
+
WorkGroup: required5("ANALYTICS_WORKGROUP"),
|
|
3154
|
+
QueryExecutionContext: { Database: required5("ANALYTICS_DATABASE") },
|
|
3155
|
+
ResultConfiguration: { OutputLocation: required5("ANALYTICS_ATHENA_OUTPUT") }
|
|
3156
|
+
}));
|
|
3157
|
+
if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
|
|
3158
|
+
for (; ; ) {
|
|
3159
|
+
const status = (_a = (yield athena4.send(new GetQueryExecutionCommand4({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
|
|
3160
|
+
if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
|
|
3161
|
+
if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
|
|
3162
|
+
throw new Error(`Analytics view ${view.name} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`);
|
|
3163
|
+
}
|
|
3164
|
+
yield new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
3165
|
+
}
|
|
3166
|
+
});
|
|
3167
|
+
|
|
2352
3168
|
// processors/mutual-processor.ts
|
|
2353
3169
|
import { TransactionCanceledException as TransactionCanceledException3 } from "@aws-sdk/client-dynamodb";
|
|
2354
3170
|
var processEntities = (entityIds, action) => __async(null, null, function* () {
|
|
2355
3171
|
return Promise.allSettled(entityIds.map(action));
|
|
2356
3172
|
});
|
|
2357
|
-
var
|
|
3173
|
+
var handler7 = (container) => (ev) => __async(null, null, function* () {
|
|
2358
3174
|
const batchItemFailures = [];
|
|
2359
3175
|
const { entityRepository, mutualRepository, publishEvent: publishEvent2 } = container;
|
|
2360
3176
|
yield Promise.allSettled(
|
|
@@ -2695,7 +3511,7 @@ function publishToSubscribers(_0) {
|
|
|
2695
3511
|
);
|
|
2696
3512
|
});
|
|
2697
3513
|
}
|
|
2698
|
-
var
|
|
3514
|
+
var handler8 = (container) => (ev) => __async(null, null, function* () {
|
|
2699
3515
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
2700
3516
|
const batchItemFailures = [];
|
|
2701
3517
|
const { mutualRepository, publishEvent: publishEvent2 } = container;
|
|
@@ -2748,7 +3564,7 @@ var handler3 = (container) => (ev) => __async(null, null, function* () {
|
|
|
2748
3564
|
|
|
2749
3565
|
// processors/replication-processor.ts
|
|
2750
3566
|
import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
|
|
2751
|
-
var
|
|
3567
|
+
var handler9 = (container) => (event) => __async(null, null, function* () {
|
|
2752
3568
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
2753
3569
|
const TableName = process.env.DDB_TABLE || container.coreTable;
|
|
2754
3570
|
const batchItemFailures = [];
|
|
@@ -3012,7 +3828,7 @@ function batchUpdateTags(_0) {
|
|
|
3012
3828
|
yield Promise.all(addPromises);
|
|
3013
3829
|
});
|
|
3014
3830
|
}
|
|
3015
|
-
var
|
|
3831
|
+
var handler10 = (container) => (ev) => __async(null, null, function* () {
|
|
3016
3832
|
var _a;
|
|
3017
3833
|
const batchItemFailures = [];
|
|
3018
3834
|
for (const record of ev.Records) {
|
|
@@ -3154,7 +3970,7 @@ var EventUtils = class {
|
|
|
3154
3970
|
|
|
3155
3971
|
// controllers/entity/create-entity.controller.ts
|
|
3156
3972
|
import { createMiddleware as createMiddleware3 } from "hono/factory";
|
|
3157
|
-
import
|
|
3973
|
+
import httpStatus5 from "http-status";
|
|
3158
3974
|
var CreateEntityController = class {
|
|
3159
3975
|
constructor(entityService) {
|
|
3160
3976
|
this.entityService = entityService;
|
|
@@ -3173,11 +3989,11 @@ var CreateEntityController = class {
|
|
|
3173
3989
|
createAndUpdateDatetime: body.createdAt
|
|
3174
3990
|
}
|
|
3175
3991
|
});
|
|
3176
|
-
c.status(
|
|
3992
|
+
c.status(httpStatus5.OK);
|
|
3177
3993
|
return c.json(entity);
|
|
3178
3994
|
} catch (err) {
|
|
3179
3995
|
if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
|
|
3180
|
-
c.status(
|
|
3996
|
+
c.status(httpStatus5.BAD_REQUEST);
|
|
3181
3997
|
return c.json({
|
|
3182
3998
|
code: "API_VALIDATION_ERROR",
|
|
3183
3999
|
message: "API validation failed",
|
|
@@ -3185,11 +4001,11 @@ var CreateEntityController = class {
|
|
|
3185
4001
|
});
|
|
3186
4002
|
}
|
|
3187
4003
|
if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
|
|
3188
|
-
c.status(
|
|
4004
|
+
c.status(httpStatus5.BAD_REQUEST);
|
|
3189
4005
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
3190
4006
|
}
|
|
3191
4007
|
if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
|
|
3192
|
-
c.status(
|
|
4008
|
+
c.status(httpStatus5.BAD_REQUEST);
|
|
3193
4009
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
3194
4010
|
}
|
|
3195
4011
|
console.log("===create-entity error:", {
|
|
@@ -3207,7 +4023,7 @@ var CreateEntityController = class {
|
|
|
3207
4023
|
|
|
3208
4024
|
// controllers/entity/delete-entity.controller.ts
|
|
3209
4025
|
import { createMiddleware as createMiddleware4 } from "hono/factory";
|
|
3210
|
-
import
|
|
4026
|
+
import httpStatus6 from "http-status";
|
|
3211
4027
|
var DeleteEntityController = class {
|
|
3212
4028
|
constructor(entityService) {
|
|
3213
4029
|
this.entityService = entityService;
|
|
@@ -3223,7 +4039,7 @@ var DeleteEntityController = class {
|
|
|
3223
4039
|
return c.json({ message: "entity deleted" });
|
|
3224
4040
|
} catch (err) {
|
|
3225
4041
|
if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_NOT_FOUND) {
|
|
3226
|
-
c.status(
|
|
4042
|
+
c.status(httpStatus6.NOT_FOUND);
|
|
3227
4043
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
3228
4044
|
}
|
|
3229
4045
|
throw err;
|
|
@@ -3234,7 +4050,7 @@ var DeleteEntityController = class {
|
|
|
3234
4050
|
|
|
3235
4051
|
// controllers/entity/get-entity-by-unique-field-value.controller.ts
|
|
3236
4052
|
import { createMiddleware as createMiddleware5 } from "hono/factory";
|
|
3237
|
-
import
|
|
4053
|
+
import httpStatus7 from "http-status";
|
|
3238
4054
|
var GetEntityByUniqueFieldValueController = class {
|
|
3239
4055
|
constructor(entityRepository) {
|
|
3240
4056
|
this.entityRepository = entityRepository;
|
|
@@ -3249,7 +4065,7 @@ var GetEntityByUniqueFieldValueController = class {
|
|
|
3249
4065
|
return c.json(entity);
|
|
3250
4066
|
} catch (err) {
|
|
3251
4067
|
if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
|
|
3252
|
-
c.status(
|
|
4068
|
+
c.status(httpStatus7.NOT_FOUND);
|
|
3253
4069
|
return c.json({
|
|
3254
4070
|
code: "ENTITY_NOT_FOUND",
|
|
3255
4071
|
message: "Entity not found"
|
|
@@ -3263,7 +4079,7 @@ var GetEntityByUniqueFieldValueController = class {
|
|
|
3263
4079
|
|
|
3264
4080
|
// controllers/entity/get-entity.controller.ts
|
|
3265
4081
|
import { createMiddleware as createMiddleware6 } from "hono/factory";
|
|
3266
|
-
import
|
|
4082
|
+
import httpStatus8 from "http-status";
|
|
3267
4083
|
var GetEntityController = class {
|
|
3268
4084
|
constructor(entityRepository) {
|
|
3269
4085
|
this.entityRepository = entityRepository;
|
|
@@ -3274,11 +4090,11 @@ var GetEntityController = class {
|
|
|
3274
4090
|
entityType,
|
|
3275
4091
|
entityId
|
|
3276
4092
|
);
|
|
3277
|
-
c.status(
|
|
4093
|
+
c.status(httpStatus8.OK);
|
|
3278
4094
|
return c.json(entity);
|
|
3279
4095
|
} catch (err) {
|
|
3280
4096
|
if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
|
|
3281
|
-
c.status(
|
|
4097
|
+
c.status(httpStatus8.NOT_FOUND);
|
|
3282
4098
|
return c.json({
|
|
3283
4099
|
code: "ENTITY_NOT_FOUND",
|
|
3284
4100
|
message: "Entity not found"
|
|
@@ -7258,12 +8074,12 @@ var ListEntitiesController = class {
|
|
|
7258
8074
|
throw new Error("multiple account-id detected");
|
|
7259
8075
|
}
|
|
7260
8076
|
const params = c.req.param();
|
|
7261
|
-
const
|
|
8077
|
+
const queries2 = c.req.query();
|
|
7262
8078
|
errorContext.accountId = accountId;
|
|
7263
8079
|
errorContext.params = params;
|
|
7264
|
-
errorContext.query =
|
|
8080
|
+
errorContext.query = queries2;
|
|
7265
8081
|
const { entityType } = params;
|
|
7266
|
-
const { lastKey, query, limit, start, end } = querySchema.parse(
|
|
8082
|
+
const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
|
|
7267
8083
|
if (query) {
|
|
7268
8084
|
const results2 = yield this.entityRepository.queryEntities(
|
|
7269
8085
|
entityType,
|
|
@@ -7299,7 +8115,7 @@ var ListEntitiesController = class {
|
|
|
7299
8115
|
|
|
7300
8116
|
// controllers/entity/update-entity.controller.ts
|
|
7301
8117
|
import { createMiddleware as createMiddleware8 } from "hono/factory";
|
|
7302
|
-
import
|
|
8118
|
+
import httpStatus9 from "http-status";
|
|
7303
8119
|
var UpdateEntityController = class {
|
|
7304
8120
|
constructor(entityService) {
|
|
7305
8121
|
this.entityService = entityService;
|
|
@@ -7311,7 +8127,7 @@ var UpdateEntityController = class {
|
|
|
7311
8127
|
const _a = body, { $condition: condition, $where: where } = _a, entityPayload = __objRest(_a, ["$condition", "$where"]);
|
|
7312
8128
|
if (condition !== void 0) {
|
|
7313
8129
|
if (typeof condition !== "string" || condition.trim().length === 0) {
|
|
7314
|
-
c.status(
|
|
8130
|
+
c.status(httpStatus9.BAD_REQUEST);
|
|
7315
8131
|
return c.json({
|
|
7316
8132
|
code: "API_VALIDATION_ERROR",
|
|
7317
8133
|
message: "$condition must be a non-empty string"
|
|
@@ -7333,11 +8149,11 @@ var UpdateEntityController = class {
|
|
|
7333
8149
|
where
|
|
7334
8150
|
});
|
|
7335
8151
|
errorContext.entity = entity;
|
|
7336
|
-
c.status(
|
|
8152
|
+
c.status(httpStatus9.OK);
|
|
7337
8153
|
return c.json(entity);
|
|
7338
8154
|
} catch (err) {
|
|
7339
8155
|
if (((_b = err.constructor) == null ? void 0 : _b.name) === "ZodError") {
|
|
7340
|
-
c.status(
|
|
8156
|
+
c.status(httpStatus9.BAD_REQUEST);
|
|
7341
8157
|
return c.json({
|
|
7342
8158
|
code: "API_VALIDATION_ERROR",
|
|
7343
8159
|
message: "API validation failed",
|
|
@@ -7345,19 +8161,19 @@ var UpdateEntityController = class {
|
|
|
7345
8161
|
});
|
|
7346
8162
|
}
|
|
7347
8163
|
if (err instanceof StandardError && (err.code === StandardErrorCode.ENTITY_NOT_FOUND || err.code === StandardErrorCode.ENTITY_IS_UNDEFINED)) {
|
|
7348
|
-
c.status(
|
|
8164
|
+
c.status(httpStatus9.NOT_FOUND);
|
|
7349
8165
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7350
8166
|
}
|
|
7351
8167
|
if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
|
|
7352
|
-
c.status(
|
|
8168
|
+
c.status(httpStatus9.BAD_REQUEST);
|
|
7353
8169
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7354
8170
|
}
|
|
7355
8171
|
if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
|
|
7356
|
-
c.status(
|
|
8172
|
+
c.status(httpStatus9.BAD_REQUEST);
|
|
7357
8173
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7358
8174
|
}
|
|
7359
8175
|
if (err instanceof StandardError && err.code === StandardErrorCode.CONDITIONAL_CHECK_FAILED) {
|
|
7360
|
-
c.status(
|
|
8176
|
+
c.status(httpStatus9.CONFLICT);
|
|
7361
8177
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7362
8178
|
}
|
|
7363
8179
|
console.log(
|
|
@@ -7373,7 +8189,7 @@ var UpdateEntityController = class {
|
|
|
7373
8189
|
|
|
7374
8190
|
// controllers/entity/adjust-entity.controller.ts
|
|
7375
8191
|
import { createMiddleware as createMiddleware9 } from "hono/factory";
|
|
7376
|
-
import
|
|
8192
|
+
import httpStatus10 from "http-status";
|
|
7377
8193
|
var AdjustEntityController = class {
|
|
7378
8194
|
constructor(entityService) {
|
|
7379
8195
|
this.entityService = entityService;
|
|
@@ -7385,7 +8201,7 @@ var AdjustEntityController = class {
|
|
|
7385
8201
|
const _a = body, { $condition: condition } = _a, adjustments = __objRest(_a, ["$condition"]);
|
|
7386
8202
|
if (condition !== void 0) {
|
|
7387
8203
|
if (typeof condition !== "string" || condition.trim().length === 0) {
|
|
7388
|
-
c.status(
|
|
8204
|
+
c.status(httpStatus10.BAD_REQUEST);
|
|
7389
8205
|
return c.json({
|
|
7390
8206
|
code: "API_VALIDATION_ERROR",
|
|
7391
8207
|
message: "$condition must be a non-empty string"
|
|
@@ -7394,7 +8210,7 @@ var AdjustEntityController = class {
|
|
|
7394
8210
|
}
|
|
7395
8211
|
for (const [key, value] of Object.entries(adjustments)) {
|
|
7396
8212
|
if (typeof value !== "number") {
|
|
7397
|
-
c.status(
|
|
8213
|
+
c.status(httpStatus10.BAD_REQUEST);
|
|
7398
8214
|
return c.json({
|
|
7399
8215
|
code: "API_VALIDATION_ERROR",
|
|
7400
8216
|
message: `Field "${key}" must be a number, got ${typeof value}`
|
|
@@ -7409,19 +8225,19 @@ var AdjustEntityController = class {
|
|
|
7409
8225
|
accountId,
|
|
7410
8226
|
condition
|
|
7411
8227
|
});
|
|
7412
|
-
c.status(
|
|
8228
|
+
c.status(httpStatus10.OK);
|
|
7413
8229
|
return c.json(entity.toJSON());
|
|
7414
8230
|
} catch (err) {
|
|
7415
8231
|
if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
|
|
7416
|
-
c.status(
|
|
8232
|
+
c.status(httpStatus10.NOT_FOUND);
|
|
7417
8233
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7418
8234
|
}
|
|
7419
8235
|
if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
|
|
7420
|
-
c.status(
|
|
8236
|
+
c.status(httpStatus10.BAD_REQUEST);
|
|
7421
8237
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7422
8238
|
}
|
|
7423
8239
|
if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_b = err == null ? void 0 : err.__type) == null ? void 0 : _b.includes("ConditionalCheckFailed"))) {
|
|
7424
|
-
c.status(
|
|
8240
|
+
c.status(httpStatus10.CONFLICT);
|
|
7425
8241
|
return c.json({
|
|
7426
8242
|
code: "ADJUSTMENT_CONSTRAINT_VIOLATED",
|
|
7427
8243
|
message: "Adjustment would violate entity constraints"
|
|
@@ -7436,7 +8252,7 @@ var AdjustEntityController = class {
|
|
|
7436
8252
|
|
|
7437
8253
|
// controllers/entity/upsert-entity.controller.ts
|
|
7438
8254
|
import { createMiddleware as createMiddleware10 } from "hono/factory";
|
|
7439
|
-
import
|
|
8255
|
+
import httpStatus11 from "http-status";
|
|
7440
8256
|
var UpsertEntityController = class {
|
|
7441
8257
|
constructor(EntityConfig, entityRepository, publishEvent2) {
|
|
7442
8258
|
this.EntityConfig = EntityConfig;
|
|
@@ -7498,7 +8314,7 @@ var UpsertEntityController = class {
|
|
|
7498
8314
|
return c.json(entity);
|
|
7499
8315
|
} catch (err) {
|
|
7500
8316
|
if (err instanceof ZodError) {
|
|
7501
|
-
c.status(
|
|
8317
|
+
c.status(httpStatus11.BAD_REQUEST);
|
|
7502
8318
|
return c.json({
|
|
7503
8319
|
code: "API_VALIDATION_ERROR",
|
|
7504
8320
|
message: "API validation failed",
|
|
@@ -7506,7 +8322,7 @@ var UpsertEntityController = class {
|
|
|
7506
8322
|
});
|
|
7507
8323
|
}
|
|
7508
8324
|
if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
|
|
7509
|
-
c.status(
|
|
8325
|
+
c.status(httpStatus11.BAD_REQUEST);
|
|
7510
8326
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7511
8327
|
}
|
|
7512
8328
|
throw err;
|
|
@@ -7517,7 +8333,7 @@ var UpsertEntityController = class {
|
|
|
7517
8333
|
|
|
7518
8334
|
// controllers/mutual/create-mutual.controller.ts
|
|
7519
8335
|
import { createMiddleware as createMiddleware11 } from "hono/factory";
|
|
7520
|
-
import
|
|
8336
|
+
import httpStatus12 from "http-status";
|
|
7521
8337
|
var CreateMutualController = class {
|
|
7522
8338
|
constructor(mutualService) {
|
|
7523
8339
|
this.mutualService = mutualService;
|
|
@@ -7541,7 +8357,7 @@ var CreateMutualController = class {
|
|
|
7541
8357
|
return c.json(mutual);
|
|
7542
8358
|
} catch (err) {
|
|
7543
8359
|
if (err instanceof ZodError) {
|
|
7544
|
-
c.status(
|
|
8360
|
+
c.status(httpStatus12.BAD_REQUEST);
|
|
7545
8361
|
return c.json({
|
|
7546
8362
|
code: "API_VALIDATION_ERROR",
|
|
7547
8363
|
message: "API validation failed",
|
|
@@ -7549,11 +8365,11 @@ var CreateMutualController = class {
|
|
|
7549
8365
|
});
|
|
7550
8366
|
}
|
|
7551
8367
|
if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_EXISTS) {
|
|
7552
|
-
c.status(
|
|
8368
|
+
c.status(httpStatus12.BAD_REQUEST);
|
|
7553
8369
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7554
8370
|
}
|
|
7555
8371
|
if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
|
|
7556
|
-
c.status(
|
|
8372
|
+
c.status(httpStatus12.BAD_REQUEST);
|
|
7557
8373
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7558
8374
|
}
|
|
7559
8375
|
throw err;
|
|
@@ -7564,7 +8380,7 @@ var CreateMutualController = class {
|
|
|
7564
8380
|
|
|
7565
8381
|
// controllers/mutual/delete-mutual.controller.ts
|
|
7566
8382
|
import { createMiddleware as createMiddleware12 } from "hono/factory";
|
|
7567
|
-
import
|
|
8383
|
+
import httpStatus13 from "http-status";
|
|
7568
8384
|
var DeleteMutualController = class {
|
|
7569
8385
|
constructor(mutualService) {
|
|
7570
8386
|
this.mutualService = mutualService;
|
|
@@ -7582,7 +8398,7 @@ var DeleteMutualController = class {
|
|
|
7582
8398
|
return c.json(mutual);
|
|
7583
8399
|
} catch (err) {
|
|
7584
8400
|
if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
|
|
7585
|
-
c.status(
|
|
8401
|
+
c.status(httpStatus13.BAD_REQUEST);
|
|
7586
8402
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7587
8403
|
}
|
|
7588
8404
|
throw err;
|
|
@@ -7593,7 +8409,7 @@ var DeleteMutualController = class {
|
|
|
7593
8409
|
|
|
7594
8410
|
// controllers/mutual/get-mutual.controller.ts
|
|
7595
8411
|
import { createMiddleware as createMiddleware13 } from "hono/factory";
|
|
7596
|
-
import
|
|
8412
|
+
import httpStatus14 from "http-status";
|
|
7597
8413
|
var GetMutualController = class {
|
|
7598
8414
|
constructor(associateRepository) {
|
|
7599
8415
|
this.associateRepository = associateRepository;
|
|
@@ -7609,7 +8425,7 @@ var GetMutualController = class {
|
|
|
7609
8425
|
return c.json(associate);
|
|
7610
8426
|
} catch (err) {
|
|
7611
8427
|
if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
|
|
7612
|
-
c.status(
|
|
8428
|
+
c.status(httpStatus14.NOT_FOUND);
|
|
7613
8429
|
return c.json({
|
|
7614
8430
|
code: "MUTUAL_NOT_FOUND",
|
|
7615
8431
|
message: "Mutual not found"
|
|
@@ -7685,7 +8501,7 @@ var ListEntitiesByEntityController = class {
|
|
|
7685
8501
|
|
|
7686
8502
|
// controllers/mutual/update-mutual.controller.ts
|
|
7687
8503
|
import { createMiddleware as createMiddleware15 } from "hono/factory";
|
|
7688
|
-
import
|
|
8504
|
+
import httpStatus15 from "http-status";
|
|
7689
8505
|
var UpdateMutualController = class {
|
|
7690
8506
|
constructor(mutualService) {
|
|
7691
8507
|
this.mutualService = mutualService;
|
|
@@ -7708,7 +8524,7 @@ var UpdateMutualController = class {
|
|
|
7708
8524
|
return c.json(mutual);
|
|
7709
8525
|
} catch (err) {
|
|
7710
8526
|
if (err instanceof ZodError) {
|
|
7711
|
-
c.status(
|
|
8527
|
+
c.status(httpStatus15.BAD_REQUEST);
|
|
7712
8528
|
return c.json({
|
|
7713
8529
|
code: "API_VALIDATION_ERROR",
|
|
7714
8530
|
message: "API validation failed",
|
|
@@ -7716,7 +8532,7 @@ var UpdateMutualController = class {
|
|
|
7716
8532
|
});
|
|
7717
8533
|
}
|
|
7718
8534
|
if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
|
|
7719
|
-
c.status(
|
|
8535
|
+
c.status(httpStatus15.BAD_REQUEST);
|
|
7720
8536
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
7721
8537
|
}
|
|
7722
8538
|
throw err;
|
|
@@ -7726,10 +8542,10 @@ var UpdateMutualController = class {
|
|
|
7726
8542
|
};
|
|
7727
8543
|
|
|
7728
8544
|
// services/entity.service.ts
|
|
7729
|
-
import { marshall as
|
|
8545
|
+
import { marshall as marshall7 } from "@aws-sdk/util-dynamodb";
|
|
7730
8546
|
|
|
7731
8547
|
// data/utils/build-condition-expression.ts
|
|
7732
|
-
import { marshall as
|
|
8548
|
+
import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
|
|
7733
8549
|
function buildConditionExpression(where) {
|
|
7734
8550
|
const conditions = ["attribute_exists(PK)"];
|
|
7735
8551
|
const expressionAttributeNames = { "#data": "data" };
|
|
@@ -7785,7 +8601,7 @@ function buildConditionExpression(where) {
|
|
|
7785
8601
|
return {
|
|
7786
8602
|
ConditionExpression: conditions.join(" AND "),
|
|
7787
8603
|
ExpressionAttributeNames: expressionAttributeNames,
|
|
7788
|
-
ExpressionAttributeValues:
|
|
8604
|
+
ExpressionAttributeValues: marshall6(expressionAttributeValues)
|
|
7789
8605
|
};
|
|
7790
8606
|
}
|
|
7791
8607
|
|
|
@@ -8118,7 +8934,7 @@ var EntityService = class {
|
|
|
8118
8934
|
return {
|
|
8119
8935
|
ConditionExpression: conditionParts.join(" AND "),
|
|
8120
8936
|
ExpressionAttributeNames: names,
|
|
8121
|
-
ExpressionAttributeValues:
|
|
8937
|
+
ExpressionAttributeValues: marshall7(values)
|
|
8122
8938
|
};
|
|
8123
8939
|
}
|
|
8124
8940
|
};
|
|
@@ -8424,7 +9240,7 @@ var ListTagsController = class {
|
|
|
8424
9240
|
|
|
8425
9241
|
// controllers/transaction/execute-transaction.controller.ts
|
|
8426
9242
|
import { createMiddleware as createMiddleware17 } from "hono/factory";
|
|
8427
|
-
import
|
|
9243
|
+
import httpStatus16 from "http-status";
|
|
8428
9244
|
var ExecuteTransactionController = class {
|
|
8429
9245
|
constructor(transactionService) {
|
|
8430
9246
|
this.transactionService = transactionService;
|
|
@@ -8435,7 +9251,7 @@ var ExecuteTransactionController = class {
|
|
|
8435
9251
|
try {
|
|
8436
9252
|
const body = yield c.req.json();
|
|
8437
9253
|
if (!body.operations || !Array.isArray(body.operations)) {
|
|
8438
|
-
c.status(
|
|
9254
|
+
c.status(httpStatus16.BAD_REQUEST);
|
|
8439
9255
|
return c.json({
|
|
8440
9256
|
code: "API_VALIDATION_ERROR",
|
|
8441
9257
|
message: 'Request body must contain an "operations" array'
|
|
@@ -8445,11 +9261,11 @@ var ExecuteTransactionController = class {
|
|
|
8445
9261
|
body.operations,
|
|
8446
9262
|
accountId
|
|
8447
9263
|
);
|
|
8448
|
-
c.status(
|
|
9264
|
+
c.status(httpStatus16.OK);
|
|
8449
9265
|
return c.json(result);
|
|
8450
9266
|
} catch (err) {
|
|
8451
9267
|
if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
|
|
8452
|
-
c.status(
|
|
9268
|
+
c.status(httpStatus16.BAD_REQUEST);
|
|
8453
9269
|
return c.json({
|
|
8454
9270
|
code: "API_VALIDATION_ERROR",
|
|
8455
9271
|
message: "Validation failed",
|
|
@@ -8457,7 +9273,7 @@ var ExecuteTransactionController = class {
|
|
|
8457
9273
|
});
|
|
8458
9274
|
}
|
|
8459
9275
|
if (err instanceof SyntaxError) {
|
|
8460
|
-
c.status(
|
|
9276
|
+
c.status(httpStatus16.BAD_REQUEST);
|
|
8461
9277
|
return c.json({
|
|
8462
9278
|
code: "API_VALIDATION_ERROR",
|
|
8463
9279
|
message: "Request body must be valid JSON"
|
|
@@ -8466,15 +9282,15 @@ var ExecuteTransactionController = class {
|
|
|
8466
9282
|
if (err instanceof StandardError) {
|
|
8467
9283
|
const code = err.code;
|
|
8468
9284
|
if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
|
|
8469
|
-
c.status(
|
|
9285
|
+
c.status(httpStatus16.NOT_FOUND);
|
|
8470
9286
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
8471
9287
|
}
|
|
8472
9288
|
if (code === StandardErrorCode.TRANSACTION_EMPTY || code === StandardErrorCode.TRANSACTION_ITEM_LIMIT_EXCEEDED || code === StandardErrorCode.TRANSACTION_UNIQUE_FIELD_UPDATE || code === StandardErrorCode.TRANSACTION_INVALID_OPERATION || code === StandardErrorCode.TRANSACTION_VALIDATION_ERROR || code === StandardErrorCode.INVALID_ENTITY_TYPE || code === StandardErrorCode.INVALID_CONDITION || code === StandardErrorCode.INVALID_UNIQUE_VALUE_TYPE) {
|
|
8473
|
-
c.status(
|
|
9289
|
+
c.status(httpStatus16.BAD_REQUEST);
|
|
8474
9290
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
8475
9291
|
}
|
|
8476
9292
|
if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
|
|
8477
|
-
c.status(
|
|
9293
|
+
c.status(httpStatus16.CONFLICT);
|
|
8478
9294
|
return c.json(__spreadValues({}, err.toJSON()));
|
|
8479
9295
|
}
|
|
8480
9296
|
}
|
|
@@ -9210,11 +10026,13 @@ var CoreFactory = class {
|
|
|
9210
10026
|
const dependencyContainer = new DependencyContainer(this.config);
|
|
9211
10027
|
this.dependencyContainer = dependencyContainer;
|
|
9212
10028
|
this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
|
|
9213
|
-
this.mutualProcessor =
|
|
9214
|
-
this.replicationProcessor =
|
|
10029
|
+
this.mutualProcessor = handler7(dependencyContainer);
|
|
10030
|
+
this.replicationProcessor = handler9(dependencyContainer);
|
|
9215
10031
|
this.createEntityProcessor = handler(dependencyContainer);
|
|
9216
|
-
this.
|
|
9217
|
-
this.
|
|
10032
|
+
this.analyticsProcessor = handler2(this.config.EntityConfig);
|
|
10033
|
+
this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
|
|
10034
|
+
this.prejoinProcessor = handler8(dependencyContainer);
|
|
10035
|
+
this.tagProcessor = handler10(dependencyContainer);
|
|
9218
10036
|
this.appHandler = appHandler(dependencyContainer);
|
|
9219
10037
|
}
|
|
9220
10038
|
};
|
|
@@ -9232,14 +10050,21 @@ export {
|
|
|
9232
10050
|
StandardErrorCode,
|
|
9233
10051
|
TagRepository,
|
|
9234
10052
|
TransactionService,
|
|
10053
|
+
handler3 as analyticsBackfillProcessor,
|
|
10054
|
+
handler4 as analyticsMaterializationProcessor,
|
|
10055
|
+
handler5 as analyticsModelProcessor,
|
|
10056
|
+
handler2 as analyticsProcessor,
|
|
10057
|
+
analyticsQueryHandler,
|
|
10058
|
+
handler6 as analyticsViewProcessor,
|
|
9235
10059
|
appHandler,
|
|
9236
10060
|
handler as createEntityProcessor,
|
|
9237
10061
|
index_default as default,
|
|
9238
|
-
|
|
9239
|
-
|
|
9240
|
-
|
|
10062
|
+
handler7 as mutualProcessor,
|
|
10063
|
+
handler8 as prejoinProcessor,
|
|
10064
|
+
handler9 as replicationProcessor,
|
|
9241
10065
|
setupCommonRoutes,
|
|
9242
|
-
|
|
10066
|
+
startBackfill as startAnalyticsBackfill,
|
|
10067
|
+
handler10 as tagProcessor,
|
|
9243
10068
|
transactional
|
|
9244
10069
|
};
|
|
9245
10070
|
//# sourceMappingURL=index.js.map
|