monorise 1.6.3 → 1.7.0-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.
@@ -1,6 +1,13 @@
1
1
  import type { Entity } from '../../base/index';
2
2
  export declare const convertToMap: <T extends Record<string, any>>(data: T[], mapKey: string) => Map<any, any>;
3
3
  export declare const getMutualStateKey: (byEntity: Entity, byEntityId: string | null, entity: Entity, entityId?: string, chainEntityQuery?: string) => string;
4
+ export declare const parseMutualStateKey: (stateKey: string) => {
5
+ byEntity: Entity;
6
+ byEntityId: string;
7
+ entity: Entity;
8
+ entityId: string;
9
+ chainEntityQuery: string | undefined;
10
+ };
4
11
  export declare const getTagStateKey: (entityType: Entity, tagName: string, params?: Record<string, string>) => string;
5
12
  export declare const getUniqueFieldStateKey: (fieldName: string, fieldValue: string) => string;
6
13
  export declare const getEntityRequestKey: (mode: "create" | "upsert" | "edit" | "adjust" | "delete" | "get" | "list" | "search", entityType: Entity, entityId?: string) => string;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../lib/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE7C,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACxD,MAAM,CAAC,EAAE,EACT,QAAQ,MAAM,kBASf,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAC5B,UAAU,MAAM,EAChB,YAAY,MAAM,GAAG,IAAI,EACzB,QAAQ,MAAM,EACd,WAAW,MAAM,EACjB,mBAAmB,MAAM,WAG1B,CAAC;AAEF,eAAO,MAAM,cAAc,GACzB,YAAY,MAAM,EAClB,SAAS,MAAM,EACf,SAAQ,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,WASpC,CAAC;AAEF,eAAO,MAAM,sBAAsB,GACjC,WAAW,MAAM,EACjB,YAAY,MAAM,WAGn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,MAAM,CAAM,WASpC,CAAC;AAEF,eAAO,MAAM,sBAAsB,GACjC,WAAW,MAAM,EACjB,YAAY,MAAM,WAGnB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAC9B,MAAM,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,EACpF,YAAY,MAAM,EAClB,WAAW,MAAM,WAGlB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAC9B,MAAM,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,KAAK,GAAG,MAAM,EACrD,cAAc,MAAM,EACpB,YAAY,MAAM,EAClB,YAAY,MAAM,GAAG,IAAI,EACzB,WAAW,MAAM,EACjB,mBAAmB,MAAM,WAG1B,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAC3B,MAAM,MAAM,EACZ,YAAY,MAAM,EAClB,SAAS,MAAM,EACf,SAAQ,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,WAGpC,CAAC;AAEF,eAAO,MAAM,wBAAwB,GACnC,YAAY,MAAM,EAClB,WAAW,MAAM,EACjB,OAAO,MAAM,WAGd,CAAC"}
@@ -0,0 +1,72 @@
1
+ export type SuppliedAnalyticsResources = {
2
+ bucket?: {
3
+ arn: $util.Input<string>;
4
+ name: $util.Input<string>;
5
+ /** Set only when this bucket has no existing notifications and Monorise may manage them. */
6
+ notificationsManaged?: boolean;
7
+ };
8
+ glueDatabase?: {
9
+ name: $util.Input<string>;
10
+ };
11
+ workgroup?: {
12
+ name: $util.Input<string>;
13
+ };
14
+ };
15
+ export type AnalyticsArgs = {
16
+ /** Omit or set false to leave analytics disabled. */
17
+ enabled?: boolean;
18
+ resources?: SuppliedAnalyticsResources;
19
+ fields?: {
20
+ omit?: string[];
21
+ };
22
+ partitions?: Record<string, 'day' | 'hour'>;
23
+ /** Required when `fromTableName` is used because DynamoDB does not expose PITR through table metadata. */
24
+ importedTable?: {
25
+ pointInTimeRecoveryEnabled: true;
26
+ };
27
+ /** Server-to-server API for executing only these named Athena queries. */
28
+ queryApi?: {
29
+ enabled?: boolean;
30
+ queries: Record<string, {
31
+ sql: string;
32
+ parameters?: Record<string, {
33
+ type: 'string' | 'number' | 'boolean' | 'date' | 'timestamp';
34
+ }>;
35
+ /** Reuse an identical Athena result for this many minutes. Athena does not detect source-data changes. */
36
+ resultReuse?: {
37
+ maxAgeMinutes: number;
38
+ };
39
+ }>;
40
+ };
41
+ /** Deployment-managed reusable Athena views. */
42
+ views?: Record<string, {
43
+ sql: string;
44
+ }>;
45
+ /** Scheduled Iceberg tables refreshed over a trailing time window. */
46
+ models?: Record<string, {
47
+ sql: string;
48
+ schedule: string;
49
+ partitionColumn: string;
50
+ lookbackDays?: number;
51
+ }>;
52
+ };
53
+ export declare class Analytics {
54
+ readonly bucket: {
55
+ arn: $util.Input<string>;
56
+ name: $util.Input<string>;
57
+ };
58
+ readonly glueDatabase: {
59
+ name: $util.Input<string>;
60
+ };
61
+ readonly workgroup: {
62
+ name: $util.Input<string>;
63
+ };
64
+ readonly deliveryStream: aws.kinesis.FirehoseDeliveryStream;
65
+ readonly dlq: sst.aws.Queue;
66
+ readonly schedule: sst.aws.CronV2;
67
+ readonly queryApi?: sst.aws.ApiGatewayV2;
68
+ readonly processorFunctionName: string;
69
+ readonly backfillFunctionName: string;
70
+ constructor(id: string, args: AnalyticsArgs, table: sst.aws.Dynamo, alarmTopic: sst.aws.SnsTopic, configRoot?: string, logging?: sst.aws.FunctionArgs['logging']);
71
+ }
72
+ //# sourceMappingURL=analytics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../components/analytics.ts"],"names":[],"mappings":"AA6BA,MAAM,MAAM,0BAA0B,GAAG;IACvC,MAAM,CAAC,EAAE;QACP,GAAG,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACzB,IAAI,EAAE,KAAK,CAAC,KAAK,CAA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Retention = NonNullable<Extract<sst.aws.FunctionArgs['logging'], {
3
4
  retention?: unknown;
4
5
  }>['retention']>;
5
- type MonoriseCoreArgs = {
6
+ export type MonoriseCoreArgs = {
6
7
  fromTableName?: $util.Input<string>;
7
8
  slackWebhook?: string;
8
9
  allowHeaders?: string[];
@@ -12,6 +13,8 @@ type MonoriseCoreArgs = {
12
13
  cloudwatchDashboard?: {
13
14
  enabled?: boolean;
14
15
  };
16
+ /** Disabled by default. Requires `.monorise/analytics-manifest.json`. */
17
+ analytics?: AnalyticsArgs;
15
18
  };
16
19
  export declare class MonoriseCore {
17
20
  readonly id: string;
@@ -19,6 +22,7 @@ export declare class MonoriseCore {
19
22
  readonly bus: sst.aws.Bus;
20
23
  readonly table: SingleTable;
21
24
  readonly alarmTopic: sst.aws.SnsTopic;
25
+ readonly analytics?: Analytics;
22
26
  constructor(id: string, args?: MonoriseCoreArgs);
23
27
  }
24
28
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"monorise-core.d.ts","sourceRoot":"","sources":["../../components/monorise-core.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,KAAK,sBAAsB,GAAG,WAAW,CACvC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAAC,WAAW,CAAC,CAC/E,CAAC;AAEF,KAAK,gBAAgB,GAAG;IACtB,aAAa,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACpC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,sBAAsB,CAAC,EAAE,sBAAsB,CAAC;IAChD,mBAAmB,CAAC,EAAE;QACpB,OAAO,C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vB,SAAgB,EAAE,EAAE,MAAM,CAAC;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC;IAC1C,SAAgB,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC;IACjC,SAAgB,KAAK,EAAE,WAAW,CAAC;IACnC,SAAgB,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC;IAC7C,SAAgB,SAAS,CAAC,EAAE,SAAS,CAAC;gBAE1B,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,gBAAgB;CAmOhD"}
@@ -6,7 +6,9 @@ type SingleTableArgs = {
6
6
  * Name of an existing DynamoDB table to use instead of creating a new one.
7
7
  * The table must already have DynamoDB Streams enabled with NEW_AND_OLD_IMAGES,
8
8
  * the GSIs (R1, R2) expected by monorise, and TTL enabled on the `expiresAt`
9
- * attribute (monorise always uses `expiresAt` as the TTL attribute name).
9
+ * attribute (monorise always uses `expiresAt` as the TTL attribute name). When
10
+ * analytics is enabled it must also have point-in-time recovery enabled; AWS does
11
+ * not expose that setting through DescribeTable, so SST cannot validate it here.
10
12
  */
11
13
  fromTableName?: $util.Input<string>;
12
14
  };
@@ -1 +1 @@
1
- {"version":3,"file":"single-table.d.ts","sourceRoot":"","sources":["../../components/single-table.ts"],"names":[],"mappings":"AAMA,KAAK,eAAe,GAAG;IACrB,OAAO,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1C,OAAO,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;CACrC,CAAC;AAEF,qBAAa,WAAW;IACtB,SAAgB,EAAE,EAAE,MAAM,CAAC;IAC3B,SAAgB,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC;IACtC,SAAgB,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC;IACnC,SAAgB,sBAAsB,EAAE,MAAM,CAAC;gBAEnC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe;CAiF/C"}
1
+ {"version":3,"file":"single-table.d.ts","sourceRoot":"","sources":["../../components/single-table.ts"],"names":[],"mappings":"AAMA,KAAK,eAAe,GAAG;IACrB,OAAO,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1C,OAAO,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;CACrC,CAAC;AAEF,qBAAa,WAAW;IACtB,SAAgB,EAAE,EAAE,MAAM,CAAC;IAC3B,SAAgB,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC;IACtC,SAAgB,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC;IACnC,SAAgB,sBAAsB,EAAE,MAAM,CAAC;gBAEnC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe;CAoF/C"}
package/dist/sst/index.js CHANGED
@@ -31,7 +31,7 @@ var __objRest = (source, exclude) => {
31
31
  };
32
32
 
33
33
  // components/monorise-core.ts
34
- import path2 from "path";
34
+ import path3 from "path";
35
35
 
36
36
  // constants/event.ts
37
37
  var SOURCE = {
@@ -269,6 +269,426 @@ function createFunctionWidgets(title, functionName, y, region, dlqName) {
269
269
  return widgets;
270
270
  }
271
271
 
272
+ // components/analytics.ts
273
+ import fs from "fs";
274
+ import path from "path";
275
+ import { createHash } from "crypto";
276
+ function validateQueries(queries) {
277
+ var _a, _b;
278
+ for (const [name, query] of Object.entries(queries)) {
279
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
280
+ throw new Error(`Invalid analytics query name: ${name}. Names must be lower-kebab-case.`);
281
+ }
282
+ if (!query.sql.trim() || !/^(select|with)\b/i.test(query.sql.trim()) || /;\s*\S/.test(query.sql)) {
283
+ throw new Error(`Analytics query ${name} must contain one read-only SELECT or WITH statement.`);
284
+ }
285
+ if (((_a = query.sql.match(/\?/g)) != null ? _a : []).length !== Object.keys((_b = query.parameters) != null ? _b : {}).length) {
286
+ throw new Error(`Analytics query ${name} must have one ? placeholder for each declared parameter.`);
287
+ }
288
+ if (query.resultReuse && (!Number.isInteger(query.resultReuse.maxAgeMinutes) || query.resultReuse.maxAgeMinutes < 1 || query.resultReuse.maxAgeMinutes > 10080)) {
289
+ throw new Error(`Analytics query ${name} resultReuse.maxAgeMinutes must be between 1 and 10080.`);
290
+ }
291
+ }
292
+ }
293
+ function validateDefinitions(definitions, kind) {
294
+ for (const [name, definition] of Object.entries(definitions)) {
295
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error(`Invalid analytics ${kind} name: ${name}. Names must be lower-kebab-case.`);
296
+ if (!definition || typeof definition !== "object" || !("sql" in definition) || typeof definition.sql !== "string" || !definition.sql.trim()) {
297
+ throw new Error(`Analytics ${kind} ${name} requires SQL.`);
298
+ }
299
+ }
300
+ }
301
+ function loadManifest(configRoot) {
302
+ const manifestPath = path.join(
303
+ configRoot != null ? configRoot : "",
304
+ ".monorise",
305
+ "analytics-manifest.json"
306
+ );
307
+ if (!fs.existsSync(manifestPath)) {
308
+ throw new Error(
309
+ `Analytics requires ${manifestPath}. Run the Monorise generator before deploying.`
310
+ );
311
+ }
312
+ let manifest;
313
+ try {
314
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
315
+ } catch (e) {
316
+ throw new Error(
317
+ `Analytics manifest at ${manifestPath} is invalid. Run the Monorise generator before deploying.`
318
+ );
319
+ }
320
+ if (manifest.version !== 2 || !Array.isArray(manifest.datasets) || !Array.isArray(manifest.unnamedMutuals) || typeof manifest.schemaFingerprint !== "string") {
321
+ throw new Error(
322
+ `Analytics manifest at ${manifestPath} is invalid. Run the Monorise generator before deploying.`
323
+ );
324
+ }
325
+ const fingerprint = createHash("sha256").update(JSON.stringify(manifest.datasets)).digest("hex");
326
+ if (fingerprint !== manifest.schemaFingerprint) {
327
+ throw new Error(
328
+ `Analytics manifest at ${manifestPath} is stale or has been modified. Run the Monorise generator before deploying.`
329
+ );
330
+ }
331
+ const identifiers = /* @__PURE__ */ new Set();
332
+ for (const dataset of manifest.datasets) {
333
+ if (!dataset.name || !dataset.identifier || !dataset.idColumn || !Array.isArray(dataset.columns) || !Array.isArray(dataset.endpoints) || identifiers.has(dataset.identifier)) {
334
+ throw new Error(
335
+ `Analytics manifest at ${manifestPath} contains invalid or colliding datasets. Run the Monorise generator before deploying.`
336
+ );
337
+ }
338
+ identifiers.add(dataset.identifier);
339
+ }
340
+ if (manifest.unnamedMutuals.length > 0) {
341
+ throw new Error(
342
+ `Analytics requires named mutual configs. Add names for: ${manifest.unnamedMutuals.join(", ")}.`
343
+ );
344
+ }
345
+ return manifest;
346
+ }
347
+ var Analytics = class {
348
+ constructor(id, args, table, alarmTopic, configRoot, logging) {
349
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
350
+ const manifest = loadManifest(configRoot);
351
+ const datasets = manifest.datasets.map((dataset) => {
352
+ var _a2, _b2;
353
+ return __spreadProps(__spreadValues({}, dataset), {
354
+ partition: {
355
+ granularity: (_b2 = (_a2 = args.partitions) == null ? void 0 : _a2[dataset.name]) != null ? _b2 : dataset.partition.granularity
356
+ }
357
+ });
358
+ });
359
+ this.processorFunctionName = `${$app.stage}-${$app.name}-${id}-analytics-processor`;
360
+ this.backfillFunctionName = `${$app.stage}-${$app.name}-${id}-analytics-backfill`;
361
+ const managedBucket = ((_a = args.resources) == null ? void 0 : _a.bucket) ? void 0 : new aws.s3.Bucket(`${id}-analytics-bucket`, {
362
+ forceDestroy: false,
363
+ serverSideEncryptionConfiguration: {
364
+ rule: {
365
+ applyServerSideEncryptionByDefault: {
366
+ sseAlgorithm: "AES256"
367
+ }
368
+ }
369
+ }
370
+ }, { retainOnDelete: true });
371
+ if (managedBucket) {
372
+ new aws.s3.BucketPublicAccessBlock(`${id}-analytics-bucket-public-access`, {
373
+ bucket: managedBucket.id,
374
+ blockPublicAcls: true,
375
+ blockPublicPolicy: true,
376
+ ignorePublicAcls: true,
377
+ restrictPublicBuckets: true
378
+ });
379
+ }
380
+ const managedDatabase = ((_b = args.resources) == null ? void 0 : _b.glueDatabase) ? void 0 : new aws.glue.CatalogDatabase(`${id}-analytics-database`, {}, { retainOnDelete: true });
381
+ const managedWorkgroup = ((_c = args.resources) == null ? void 0 : _c.workgroup) ? void 0 : new aws.athena.Workgroup(`${id}-analytics-workgroup`, {
382
+ configuration: {
383
+ enforceWorkgroupConfiguration: true,
384
+ publishCloudwatchMetricsEnabled: true,
385
+ resultConfiguration: {
386
+ outputLocation: $interpolate`s3://${managedBucket.bucket}/athena-results/`,
387
+ encryptionConfiguration: { encryptionOption: "SSE_S3" }
388
+ }
389
+ }
390
+ }, { retainOnDelete: true });
391
+ this.bucket = (_e = (_d = args.resources) == null ? void 0 : _d.bucket) != null ? _e : { arn: managedBucket.arn, name: managedBucket.bucket };
392
+ this.glueDatabase = (_g = (_f = args.resources) == null ? void 0 : _f.glueDatabase) != null ? _g : { name: managedDatabase.name };
393
+ this.workgroup = (_i = (_h = args.resources) == null ? void 0 : _h.workgroup) != null ? _i : { name: managedWorkgroup.name };
394
+ if (((_j = args.queryApi) == null ? void 0 : _j.enabled) !== false && args.queryApi) {
395
+ validateQueries(args.queryApi.queries);
396
+ const queryKeys = new sst.Secret("ANALYTICS_API_KEYS", '["analytics-secret-1", "analytics-secret-2"]');
397
+ const executions = new sst.aws.Dynamo(`${id}-analytics-executions`, {
398
+ fields: { id: "string" },
399
+ primaryIndex: { hashKey: "id" },
400
+ ttl: "expiresAt"
401
+ });
402
+ this.queryApi = new sst.aws.ApiGatewayV2(`${id}-analytics-api`);
403
+ this.queryApi.route("ANY /analytics/{proxy+}", {
404
+ name: `${$app.stage}-${$app.name}-${id}-analytics-query-api`,
405
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsQueryHandler"),
406
+ runtime: "nodejs22.x",
407
+ timeout: "30 seconds",
408
+ memory: "512 MB",
409
+ logging,
410
+ link: [executions, queryKeys],
411
+ environment: {
412
+ ANALYTICS_API_KEYS: queryKeys.value,
413
+ ANALYTICS_EXECUTIONS_TABLE: executions.name,
414
+ ANALYTICS_QUERIES: JSON.stringify(args.queryApi.queries),
415
+ ANALYTICS_DATABASE: this.glueDatabase.name,
416
+ ANALYTICS_WORKGROUP: this.workgroup.name,
417
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
418
+ },
419
+ permissions: [
420
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults", "athena:StopQueryExecution"], resources: ["*"] },
421
+ { actions: ["glue:GetDatabase", "glue:GetTable"], resources: ["*"] },
422
+ { actions: ["s3:GetObject", "s3:ListBucket", "s3:PutObject"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
423
+ ]
424
+ });
425
+ }
426
+ const athenaPermissions = [
427
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution"], resources: ["*"] },
428
+ { actions: ["glue:GetDatabase", "glue:GetTable", "glue:CreateTable", "glue:UpdateTable"], resources: ["*"] },
429
+ { actions: ["s3:GetObject", "s3:ListBucket", "s3:PutObject", "s3:DeleteObject"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
430
+ ];
431
+ if (args.views) {
432
+ validateDefinitions(args.views, "view");
433
+ for (const [name, view] of Object.entries(args.views)) {
434
+ const viewFunction = new sst.aws.Function(`${id}-${name}-analytics-view`, {
435
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsViewHandler"),
436
+ runtime: "nodejs22.x",
437
+ timeout: "15 minutes",
438
+ memory: "512 MB",
439
+ logging,
440
+ environment: {
441
+ ANALYTICS_VIEW: JSON.stringify({ name, sql: view.sql }),
442
+ ANALYTICS_DATABASE: this.glueDatabase.name,
443
+ ANALYTICS_WORKGROUP: this.workgroup.name,
444
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
445
+ },
446
+ permissions: athenaPermissions
447
+ });
448
+ new aws.lambda.Invocation(`${id}-${name}-analytics-view-apply`, {
449
+ // Changing the definition changes the invocation input and reapplies the view.
450
+ functionName: viewFunction.name,
451
+ input: JSON.stringify({ sql: view.sql })
452
+ });
453
+ }
454
+ }
455
+ if (args.models) {
456
+ validateDefinitions(args.models, "model");
457
+ for (const [name, model] of Object.entries(args.models)) {
458
+ if (!model.partitionColumn || !/^[a-z][a-z0-9_]*$/.test(model.partitionColumn)) throw new Error(`Analytics model ${name} requires a snake_case partitionColumn.`);
459
+ if (model.lookbackDays !== void 0 && (!Number.isInteger(model.lookbackDays) || model.lookbackDays < 1)) throw new Error(`Analytics model ${name} lookbackDays must be a positive integer.`);
460
+ new sst.aws.CronV2(`${id}-${name}-analytics-model`, {
461
+ schedule: model.schedule,
462
+ function: {
463
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsModelHandler"),
464
+ runtime: "nodejs22.x",
465
+ timeout: "15 minutes",
466
+ memory: "1024 MB",
467
+ logging,
468
+ environment: {
469
+ ANALYTICS_MODEL: JSON.stringify({ name, sql: model.sql, partitionColumn: model.partitionColumn, lookbackDays: (_k = model.lookbackDays) != null ? _k : 3 }),
470
+ ANALYTICS_DATABASE: this.glueDatabase.name,
471
+ ANALYTICS_BUCKET: this.bucket.name,
472
+ ANALYTICS_WORKGROUP: this.workgroup.name,
473
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
474
+ },
475
+ permissions: athenaPermissions
476
+ }
477
+ });
478
+ }
479
+ }
480
+ const firehoseRole = new aws.iam.Role(`${id}-analytics-firehose-role`, {
481
+ assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({ Service: "firehose.amazonaws.com" })
482
+ });
483
+ new aws.iam.RolePolicy(`${id}-analytics-firehose-policy`, {
484
+ role: firehoseRole.id,
485
+ policy: $resolve([this.bucket.arn]).apply(([bucketArn]) => JSON.stringify({
486
+ Version: "2012-10-17",
487
+ Statement: [{ Effect: "Allow", Action: ["s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:PutObject"], Resource: [bucketArn, `${bucketArn}/*`] }]
488
+ }))
489
+ });
490
+ this.deliveryStream = new aws.kinesis.FirehoseDeliveryStream(`${id}-analytics-delivery`, {
491
+ destination: "extended_s3",
492
+ extendedS3Configuration: {
493
+ roleArn: firehoseRole.arn,
494
+ bucketArn: this.bucket.arn,
495
+ bufferingInterval: 300,
496
+ bufferingSize: 5,
497
+ compressionFormat: "GZIP",
498
+ prefix: "history/!{partitionKeyFromQuery:path}/",
499
+ errorOutputPrefix: "errors/!{firehose:error-output-type}/",
500
+ dynamicPartitioningConfiguration: { enabled: true },
501
+ processingConfiguration: {
502
+ enabled: true,
503
+ processors: [{ type: "MetadataExtraction", parameters: [{ parameterName: "MetadataExtractionQuery", parameterValue: "{path:.path}" }, { parameterName: "JsonParsingEngine", parameterValue: "JQ-1.6" }] }]
504
+ }
505
+ }
506
+ });
507
+ this.dlq = new sst.aws.Queue(`${id}-analytics-dlq`);
508
+ table.subscribe(`${id}-analytics`, {
509
+ name: this.processorFunctionName,
510
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsHandler"),
511
+ runtime: "nodejs22.x",
512
+ timeout: "60 seconds",
513
+ memory: "512 MB",
514
+ logging,
515
+ link: [table, this.dlq],
516
+ environment: {
517
+ ANALYTICS_DELIVERY_STREAM: this.deliveryStream.name,
518
+ ANALYTICS_MANIFEST: JSON.stringify(__spreadProps(__spreadValues({}, manifest), { datasets })),
519
+ ANALYTICS_OMIT_FIELDS: JSON.stringify((_m = (_l = args.fields) == null ? void 0 : _l.omit) != null ? _m : [])
520
+ },
521
+ permissions: [{ actions: ["firehose:PutRecordBatch"], resources: [this.deliveryStream.arn] }]
522
+ }, {
523
+ transform: { eventSourceMapping: { startingPosition: "LATEST", bisectBatchOnFunctionError: true, maximumRetryAttempts: 1, destinationConfig: { onFailure: { destinationArn: this.dlq.arn } } } }
524
+ });
525
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-dlq-alarm`, {
526
+ name: `${id}-analytics-dlq`,
527
+ namespace: "AWS/SQS",
528
+ metricName: "ApproximateNumberOfMessagesVisible",
529
+ statistic: "Maximum",
530
+ period: 300,
531
+ evaluationPeriods: 1,
532
+ threshold: 1,
533
+ comparisonOperator: "GreaterThanOrEqualToThreshold",
534
+ alarmActions: [alarmTopic.arn],
535
+ dimensions: { QueueName: this.dlq.nodes.queue.name }
536
+ });
537
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-iterator-age`, {
538
+ name: `${id}-analytics-iterator-age`,
539
+ namespace: "AWS/Lambda",
540
+ metricName: "IteratorAge",
541
+ statistic: "Maximum",
542
+ period: 300,
543
+ evaluationPeriods: 1,
544
+ threshold: 3e5,
545
+ comparisonOperator: "GreaterThanThreshold",
546
+ alarmActions: [alarmTopic.arn],
547
+ dimensions: { FunctionName: this.processorFunctionName }
548
+ });
549
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-firehose-failures`, {
550
+ name: `${id}-analytics-firehose-failures`,
551
+ namespace: "AWS/Firehose",
552
+ metricName: "DeliveryToS3.DataFreshness",
553
+ statistic: "Maximum",
554
+ period: 300,
555
+ evaluationPeriods: 1,
556
+ threshold: 900,
557
+ comparisonOperator: "GreaterThanThreshold",
558
+ alarmActions: [alarmTopic.arn],
559
+ dimensions: { DeliveryStreamName: this.deliveryStream.name }
560
+ });
561
+ if (((_n = args.resources) == null ? void 0 : _n.bucket) && !args.resources.bucket.notificationsManaged) {
562
+ throw new Error(
563
+ "Analytics backfill requires exclusive management of S3 bucket notifications. S3 only permits one notification configuration; ensure the supplied bucket has no existing notifications, then set analytics.resources.bucket.notificationsManaged to true."
564
+ );
565
+ }
566
+ const backfillPrefix = "backfill";
567
+ const backfillFunction = new sst.aws.Function(`${id}-analytics-backfill`, {
568
+ name: this.backfillFunctionName,
569
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsBackfillHandler"),
570
+ runtime: "nodejs22.x",
571
+ timeout: "15 minutes",
572
+ memory: "1024 MB",
573
+ logging,
574
+ environment: {
575
+ ANALYTICS_TABLE_ARN: table.arn,
576
+ ANALYTICS_BACKFILL_MARKER_TABLE: table.name,
577
+ ANALYTICS_BACKFILL_BUCKET: this.bucket.name,
578
+ ANALYTICS_BACKFILL_PREFIX: backfillPrefix,
579
+ ANALYTICS_DELIVERY_STREAM: this.deliveryStream.name,
580
+ ANALYTICS_MANIFEST: JSON.stringify(__spreadProps(__spreadValues({}, manifest), { datasets })),
581
+ ANALYTICS_OMIT_FIELDS: JSON.stringify((_p = (_o = args.fields) == null ? void 0 : _o.omit) != null ? _p : [])
582
+ },
583
+ permissions: [
584
+ { actions: ["dynamodb:ExportTableToPointInTime", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem"], resources: [table.arn] },
585
+ { actions: ["s3:GetObject"], resources: [$interpolate`${this.bucket.arn}/${backfillPrefix}/*`] },
586
+ { actions: ["firehose:PutRecordBatch"], resources: [this.deliveryStream.arn] }
587
+ ]
588
+ });
589
+ const backfillPermission = new aws.lambda.Permission(`${id}-analytics-backfill-s3-permission`, {
590
+ action: "lambda:InvokeFunction",
591
+ function: backfillFunction.name,
592
+ principal: "s3.amazonaws.com",
593
+ sourceArn: this.bucket.arn
594
+ });
595
+ const backfillNotification = new aws.s3.BucketNotification(`${id}-analytics-backfill-notification`, {
596
+ bucket: this.bucket.name,
597
+ lambdaFunctions: [{ lambdaFunctionArn: backfillFunction.arn, events: ["s3:ObjectCreated:*"], filterPrefix: `${backfillPrefix}/AWSDynamoDB/` }]
598
+ }, { dependsOn: [backfillPermission] });
599
+ new aws.lambda.Invocation(`${id}-analytics-backfill-launch`, {
600
+ functionName: backfillFunction.name,
601
+ // This resource is recreated after analytics is disabled, so reconcile
602
+ // current state when delivery is enabled again.
603
+ input: JSON.stringify({ action: "reconcile" })
604
+ }, { dependsOn: [backfillNotification] });
605
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-backfill-errors`, {
606
+ name: `${id}-analytics-backfill-errors`,
607
+ namespace: "AWS/Lambda",
608
+ metricName: "Errors",
609
+ statistic: "Sum",
610
+ period: 300,
611
+ evaluationPeriods: 1,
612
+ threshold: 1,
613
+ comparisonOperator: "GreaterThanOrEqualToThreshold",
614
+ alarmActions: [alarmTopic.arn],
615
+ dimensions: { FunctionName: this.backfillFunctionName }
616
+ });
617
+ for (const dataset of datasets) {
618
+ const rawTable = `${dataset.historyTable}_raw`;
619
+ const rawLocation = $resolve([this.bucket.name]).apply(
620
+ ([bucketName]) => `s3://${bucketName}/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`
621
+ );
622
+ const projection = dataset.partition.granularity === "hour" ? {
623
+ "projection.event_hour.type": "integer",
624
+ "projection.event_hour.range": "0,23",
625
+ "projection.event_hour.digits": "2",
626
+ "storage.location.template": rawLocation.apply(
627
+ (location) => `${location}event_date=\${event_date}/event_hour=\${event_hour}/`
628
+ )
629
+ } : {
630
+ "storage.location.template": rawLocation.apply(
631
+ (location) => `${location}event_date=\${event_date}/`
632
+ )
633
+ };
634
+ new aws.glue.CatalogTable(`${id}-${dataset.identifier}-raw`, {
635
+ databaseName: this.glueDatabase.name,
636
+ name: rawTable,
637
+ tableType: "EXTERNAL_TABLE",
638
+ parameters: __spreadValues({
639
+ EXTERNAL: "TRUE",
640
+ "projection.enabled": "true",
641
+ "projection.event_date.type": "date",
642
+ "projection.event_date.range": "2020-01-01,NOW",
643
+ "projection.event_date.format": "yyyy-MM-dd"
644
+ }, projection),
645
+ storageDescriptor: {
646
+ location: rawLocation,
647
+ inputFormat: "org.apache.hadoop.mapred.TextInputFormat",
648
+ outputFormat: "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
649
+ serDeInfo: { serializationLibrary: "org.openx.data.jsonserde.JsonSerDe" },
650
+ columns: [
651
+ { name: "event_id", type: "string" },
652
+ { name: "idempotency_key", type: "string" },
653
+ { name: "ordering_key", type: "string" },
654
+ { name: "sequence_number", type: "string" },
655
+ { name: "operation", type: "string" },
656
+ { name: "occurred_at", type: "string" },
657
+ { name: "dataset", type: "string" },
658
+ { name: "kind", type: "string" },
659
+ { name: "path", type: "string" },
660
+ { name: "before", type: "string" },
661
+ { name: "after", type: "string" }
662
+ ]
663
+ },
664
+ partitionKeys: [{ name: "event_date", type: "string" }, ...dataset.partition.granularity === "hour" ? [{ name: "event_hour", type: "string" }] : []]
665
+ });
666
+ }
667
+ this.schedule = new sst.aws.CronV2(`${id}-analytics-daily`, {
668
+ schedule: "cron(0 0 * * ? *)",
669
+ function: {
670
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsMaterializationHandler"),
671
+ runtime: "nodejs22.x",
672
+ timeout: "15 minutes",
673
+ memory: "1024 MB",
674
+ logging,
675
+ environment: {
676
+ ANALYTICS_MANIFEST: JSON.stringify(__spreadProps(__spreadValues({}, manifest), { datasets })),
677
+ ANALYTICS_DATABASE: this.glueDatabase.name,
678
+ ANALYTICS_BUCKET: this.bucket.name,
679
+ ANALYTICS_WORKGROUP: this.workgroup.name,
680
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
681
+ },
682
+ permissions: [
683
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults"], resources: ["*"] },
684
+ { actions: ["glue:GetDatabase", "glue:GetTable", "glue:CreateTable", "glue:UpdateTable"], resources: ["*"] },
685
+ { actions: ["s3:GetObject", "s3:PutObject", "s3:ListBucket"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
686
+ ]
687
+ }
688
+ });
689
+ }
690
+ };
691
+
272
692
  // components/q-function.ts
273
693
  var QFunction = class {
274
694
  constructor(id, args) {
@@ -328,7 +748,7 @@ var QFunction = class {
328
748
  };
329
749
 
330
750
  // components/single-table.ts
331
- import path from "path";
751
+ import path2 from "path";
332
752
 
333
753
  // constants/table.ts
334
754
  var ENTITY_REPLICATION_INDEX = "ENTITY_REPLICATION_INDEX";
@@ -378,7 +798,10 @@ var SingleTable = class {
378
798
  }
379
799
  },
380
800
  stream: "new-and-old-images",
381
- ttl: "expiresAt"
801
+ ttl: "expiresAt",
802
+ transform: {
803
+ table: { pointInTimeRecovery: { enabled: true } }
804
+ }
382
805
  });
383
806
  const environment = {
384
807
  CORE_TABLE: this.table.name
@@ -387,7 +810,7 @@ var SingleTable = class {
387
810
  `${id}-core-replicator`,
388
811
  {
389
812
  name: this.replicatorFunctionName,
390
- handler: path.join(
813
+ handler: path2.join(
391
814
  (_a = args == null ? void 0 : args.configRoot) != null ? _a : "",
392
815
  ".monorise/handle.replicationHandler"
393
816
  ),
@@ -419,10 +842,10 @@ var SingleTable = class {
419
842
  // components/monorise-core.ts
420
843
  var MonoriseCore = class {
421
844
  constructor(id, args) {
422
- var _a, _b;
845
+ var _a, _b, _c, _d;
423
846
  const runtime = "nodejs22.x";
424
847
  const configRootCommand = (args == null ? void 0 : args.configRoot) ? `--config-root ${args.configRoot}` : "";
425
- const dotMonorisePath = path2.join((_a = args == null ? void 0 : args.configRoot) != null ? _a : "", ".monorise");
848
+ const dotMonorisePath = path3.join((_a = args == null ? void 0 : args.configRoot) != null ? _a : "", ".monorise");
426
849
  const logging = (args == null ? void 0 : args.cloudwatchLogRetention) ? { retention: args.cloudwatchLogRetention } : void 0;
427
850
  new sst.x.DevCommand("Monorise", {
428
851
  dev: {
@@ -464,6 +887,21 @@ var MonoriseCore = class {
464
887
  logging
465
888
  });
466
889
  this.alarmTopic = new sst.aws.SnsTopic(`${id}-monorise-dlq-alarm-topic`);
890
+ if (((_b = args == null ? void 0 : args.analytics) == null ? void 0 : _b.enabled) !== false && (args == null ? void 0 : args.analytics)) {
891
+ if (args.fromTableName && ((_c = args.analytics.importedTable) == null ? void 0 : _c.pointInTimeRecoveryEnabled) !== true) {
892
+ throw new Error(
893
+ "Analytics backfill requires point-in-time recovery on fromTableName. Enable it on the imported table and set analytics.importedTable.pointInTimeRecoveryEnabled to true."
894
+ );
895
+ }
896
+ this.analytics = new Analytics(
897
+ id,
898
+ args.analytics,
899
+ this.table.table,
900
+ this.alarmTopic,
901
+ args.configRoot,
902
+ logging
903
+ );
904
+ }
467
905
  const environment = {
468
906
  CORE_TABLE: this.table.table.name,
469
907
  CORE_EVENT_BUS: this.bus.name
@@ -534,7 +972,7 @@ var MonoriseCore = class {
534
972
  ]
535
973
  }
536
974
  });
537
- if (((_b = args == null ? void 0 : args.cloudwatchDashboard) == null ? void 0 : _b.enabled) !== false) {
975
+ if (((_d = args == null ? void 0 : args.cloudwatchDashboard) == null ? void 0 : _d.enabled) !== false) {
538
976
  new aws.cloudwatch.Dashboard(`${id}-monorise-dashboard`, {
539
977
  dashboardName: `${$app.stage}-${$app.name}-${id}-monorise`,
540
978
  dashboardBody: $resolve([