monorise 1.6.4 → 1.6.5-dev.1

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.
@@ -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: ConstructorParameters<typeof sst.aws.CronV2>[1]['schedule'];
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":"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"}
@@ -1,8 +1,9 @@
1
+ import { Analytics, type AnalyticsArgs } from './analytics';
1
2
  import { SingleTable } from './single-table';
2
3
  type CloudWatchLogRetention = 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,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,qBAAa,YAAY;IACvB,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;gBAEjC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,gBAAgB;CAgNhD"}
1
+ {"version":3,"file":"monorise-core.d.ts","sourceRoot":"","sources":["../../components/monorise-core.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5D,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,MAAM,MAAM,gBAAgB,GAAG;IAC7B,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,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;IACF,yEAAyE;IACzE,SAAS,CAAC,EAAE,aAAa,CAAC;CAC3B,CAAC;AAEF,qBAAa,YAAY;IACvB,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,429 @@ 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
+ return manifest;
341
+ }
342
+ var Analytics = class {
343
+ constructor(id, args, table, alarmTopic, configRoot, logging) {
344
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
345
+ const manifest = loadManifest(configRoot);
346
+ const datasets = manifest.datasets.map((dataset) => {
347
+ var _a2, _b2;
348
+ return __spreadProps(__spreadValues({}, dataset), {
349
+ partition: {
350
+ granularity: (_b2 = (_a2 = args.partitions) == null ? void 0 : _a2[dataset.name]) != null ? _b2 : dataset.partition.granularity
351
+ }
352
+ });
353
+ });
354
+ const serializedManifest = JSON.stringify({
355
+ datasets: datasets.map(({ kind, name, partition }) => ({ kind, name, partition }))
356
+ });
357
+ this.processorFunctionName = `${$app.stage}-${$app.name}-${id}-analytics-processor`;
358
+ this.backfillFunctionName = `${$app.stage}-${$app.name}-${id}-analytics-backfill`;
359
+ const managedBucket = ((_a = args.resources) == null ? void 0 : _a.bucket) ? void 0 : new aws.s3.Bucket(`${id}-analytics-bucket`, {
360
+ forceDestroy: false,
361
+ serverSideEncryptionConfiguration: {
362
+ rule: {
363
+ applyServerSideEncryptionByDefault: {
364
+ sseAlgorithm: "AES256"
365
+ }
366
+ }
367
+ }
368
+ }, { retainOnDelete: true });
369
+ if (managedBucket) {
370
+ new aws.s3.BucketPublicAccessBlock(`${id}-analytics-bucket-public-access`, {
371
+ bucket: managedBucket.id,
372
+ blockPublicAcls: true,
373
+ blockPublicPolicy: true,
374
+ ignorePublicAcls: true,
375
+ restrictPublicBuckets: true
376
+ });
377
+ }
378
+ const managedDatabase = ((_b = args.resources) == null ? void 0 : _b.glueDatabase) ? void 0 : new aws.glue.CatalogDatabase(`${id}-analytics-database`, {}, { retainOnDelete: true });
379
+ const managedWorkgroup = ((_c = args.resources) == null ? void 0 : _c.workgroup) ? void 0 : new aws.athena.Workgroup(`${id}-analytics-workgroup`, {
380
+ configuration: {
381
+ enforceWorkgroupConfiguration: true,
382
+ publishCloudwatchMetricsEnabled: true,
383
+ resultConfiguration: {
384
+ outputLocation: $interpolate`s3://${managedBucket.bucket}/athena-results/`,
385
+ encryptionConfiguration: { encryptionOption: "SSE_S3" }
386
+ }
387
+ }
388
+ }, { retainOnDelete: true });
389
+ this.bucket = (_e = (_d = args.resources) == null ? void 0 : _d.bucket) != null ? _e : { arn: managedBucket.arn, name: managedBucket.bucket };
390
+ this.glueDatabase = (_g = (_f = args.resources) == null ? void 0 : _f.glueDatabase) != null ? _g : { name: managedDatabase.name };
391
+ this.workgroup = (_i = (_h = args.resources) == null ? void 0 : _h.workgroup) != null ? _i : { name: managedWorkgroup.name };
392
+ if (((_j = args.queryApi) == null ? void 0 : _j.enabled) !== false && args.queryApi) {
393
+ validateQueries(args.queryApi.queries);
394
+ const queryKeys = new sst.Secret("ANALYTICS_API_KEYS", '["analytics-secret-1", "analytics-secret-2"]');
395
+ const executions = new sst.aws.Dynamo(`${id}-analytics-executions`, {
396
+ fields: { id: "string" },
397
+ primaryIndex: { hashKey: "id" },
398
+ ttl: "expiresAt"
399
+ });
400
+ this.queryApi = new sst.aws.ApiGatewayV2(`${id}-analytics-api`);
401
+ this.queryApi.route("ANY /analytics/{proxy+}", {
402
+ name: `${$app.stage}-${$app.name}-${id}-analytics-query-api`,
403
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsQueryHandler"),
404
+ runtime: "nodejs22.x",
405
+ timeout: "30 seconds",
406
+ memory: "512 MB",
407
+ logging,
408
+ link: [executions, queryKeys],
409
+ environment: {
410
+ ANALYTICS_API_KEYS: queryKeys.value,
411
+ ANALYTICS_EXECUTIONS_TABLE: executions.name,
412
+ ANALYTICS_QUERIES: JSON.stringify(args.queryApi.queries),
413
+ ANALYTICS_DATABASE: this.glueDatabase.name,
414
+ ANALYTICS_WORKGROUP: this.workgroup.name,
415
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
416
+ },
417
+ permissions: [
418
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults", "athena:StopQueryExecution"], resources: ["*"] },
419
+ { actions: ["glue:GetDatabase", "glue:GetDatabases", "glue:GetTable", "glue:GetTables"], resources: ["*"] },
420
+ { actions: ["s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:PutObject"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
421
+ ]
422
+ });
423
+ }
424
+ const athenaPermissions = [
425
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution"], resources: ["*"] },
426
+ { actions: ["glue:GetDatabase", "glue:GetDatabases", "glue:GetTable", "glue:GetTables", "glue:CreateTable", "glue:UpdateTable"], resources: ["*"] },
427
+ { actions: ["s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:PutObject", "s3:DeleteObject"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
428
+ ];
429
+ if (args.models) {
430
+ validateDefinitions(args.models, "model");
431
+ for (const [name, model] of Object.entries(args.models)) {
432
+ if (!model.partitionColumn || !/^[a-z][a-z0-9_]*$/.test(model.partitionColumn)) throw new Error(`Analytics model ${name} requires a snake_case partitionColumn.`);
433
+ if (model.lookbackDays !== void 0 && (!Number.isInteger(model.lookbackDays) || model.lookbackDays < 1)) throw new Error(`Analytics model ${name} lookbackDays must be a positive integer.`);
434
+ new sst.aws.CronV2(`${id}-${name}-analytics-model`, {
435
+ schedule: model.schedule,
436
+ function: {
437
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsModelHandler"),
438
+ runtime: "nodejs22.x",
439
+ timeout: "15 minutes",
440
+ memory: "1024 MB",
441
+ logging,
442
+ environment: {
443
+ ANALYTICS_MODEL: JSON.stringify({ name, sql: model.sql, partitionColumn: model.partitionColumn, lookbackDays: (_k = model.lookbackDays) != null ? _k : 3 }),
444
+ ANALYTICS_DATABASE: this.glueDatabase.name,
445
+ ANALYTICS_BUCKET: this.bucket.name,
446
+ ANALYTICS_WORKGROUP: this.workgroup.name,
447
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
448
+ },
449
+ permissions: athenaPermissions
450
+ }
451
+ });
452
+ }
453
+ }
454
+ const firehoseRole = new aws.iam.Role(`${id}-analytics-firehose-role`, {
455
+ assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({ Service: "firehose.amazonaws.com" })
456
+ });
457
+ new aws.iam.RolePolicy(`${id}-analytics-firehose-policy`, {
458
+ role: firehoseRole.id,
459
+ policy: $resolve([this.bucket.arn]).apply(([bucketArn]) => JSON.stringify({
460
+ Version: "2012-10-17",
461
+ Statement: [{ Effect: "Allow", Action: ["s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:PutObject"], Resource: [bucketArn, `${bucketArn}/*`] }]
462
+ }))
463
+ });
464
+ this.deliveryStream = new aws.kinesis.FirehoseDeliveryStream(`${id}-analytics-delivery`, {
465
+ destination: "extended_s3",
466
+ extendedS3Configuration: {
467
+ roleArn: firehoseRole.arn,
468
+ bucketArn: this.bucket.arn,
469
+ bufferingInterval: 300,
470
+ // Firehose requires at least 64 MiB when dynamic partitioning is enabled.
471
+ bufferingSize: 64,
472
+ compressionFormat: "GZIP",
473
+ prefix: "history/!{partitionKeyFromQuery:path}/",
474
+ errorOutputPrefix: "errors/!{firehose:error-output-type}/",
475
+ dynamicPartitioningConfiguration: { enabled: true },
476
+ processingConfiguration: {
477
+ enabled: true,
478
+ processors: [{ type: "MetadataExtraction", parameters: [{ parameterName: "MetadataExtractionQuery", parameterValue: "{path:.path}" }, { parameterName: "JsonParsingEngine", parameterValue: "JQ-1.6" }] }]
479
+ }
480
+ }
481
+ });
482
+ this.dlq = new sst.aws.Queue(`${id}-analytics-dlq`);
483
+ table.subscribe(`${id}-analytics`, {
484
+ name: this.processorFunctionName,
485
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsHandler"),
486
+ runtime: "nodejs22.x",
487
+ timeout: "60 seconds",
488
+ memory: "512 MB",
489
+ logging,
490
+ link: [table, this.dlq],
491
+ environment: {
492
+ ANALYTICS_DELIVERY_STREAM: this.deliveryStream.name,
493
+ ANALYTICS_MANIFEST: serializedManifest,
494
+ ANALYTICS_OMIT_FIELDS: JSON.stringify((_m = (_l = args.fields) == null ? void 0 : _l.omit) != null ? _m : [])
495
+ },
496
+ permissions: [{ actions: ["firehose:PutRecordBatch"], resources: [this.deliveryStream.arn] }]
497
+ }, {
498
+ transform: { eventSourceMapping: { startingPosition: "LATEST", bisectBatchOnFunctionError: true, maximumRetryAttempts: 1, destinationConfig: { onFailure: { destinationArn: this.dlq.arn } } } }
499
+ });
500
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-dlq-alarm`, {
501
+ name: `${id}-analytics-dlq`,
502
+ namespace: "AWS/SQS",
503
+ metricName: "ApproximateNumberOfMessagesVisible",
504
+ statistic: "Maximum",
505
+ period: 300,
506
+ evaluationPeriods: 1,
507
+ threshold: 1,
508
+ comparisonOperator: "GreaterThanOrEqualToThreshold",
509
+ alarmActions: [alarmTopic.arn],
510
+ dimensions: { QueueName: this.dlq.nodes.queue.name }
511
+ });
512
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-iterator-age`, {
513
+ name: `${id}-analytics-iterator-age`,
514
+ namespace: "AWS/Lambda",
515
+ metricName: "IteratorAge",
516
+ statistic: "Maximum",
517
+ period: 300,
518
+ evaluationPeriods: 1,
519
+ threshold: 3e5,
520
+ comparisonOperator: "GreaterThanThreshold",
521
+ alarmActions: [alarmTopic.arn],
522
+ dimensions: { FunctionName: this.processorFunctionName }
523
+ });
524
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-firehose-failures`, {
525
+ name: `${id}-analytics-firehose-failures`,
526
+ namespace: "AWS/Firehose",
527
+ metricName: "DeliveryToS3.DataFreshness",
528
+ statistic: "Maximum",
529
+ period: 300,
530
+ evaluationPeriods: 1,
531
+ threshold: 900,
532
+ comparisonOperator: "GreaterThanThreshold",
533
+ alarmActions: [alarmTopic.arn],
534
+ dimensions: { DeliveryStreamName: this.deliveryStream.name }
535
+ });
536
+ if (((_n = args.resources) == null ? void 0 : _n.bucket) && !args.resources.bucket.notificationsManaged) {
537
+ throw new Error(
538
+ "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."
539
+ );
540
+ }
541
+ const backfillPrefix = "backfill";
542
+ const backfillFunction = new sst.aws.Function(`${id}-analytics-backfill`, {
543
+ name: this.backfillFunctionName,
544
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsBackfillHandler"),
545
+ runtime: "nodejs22.x",
546
+ timeout: "15 minutes",
547
+ memory: "1024 MB",
548
+ logging,
549
+ environment: {
550
+ ANALYTICS_TABLE_ARN: table.arn,
551
+ ANALYTICS_BACKFILL_MARKER_TABLE: table.name,
552
+ ANALYTICS_BACKFILL_BUCKET: this.bucket.name,
553
+ ANALYTICS_BACKFILL_PREFIX: backfillPrefix,
554
+ ANALYTICS_DELIVERY_STREAM: this.deliveryStream.name,
555
+ ANALYTICS_MANIFEST: serializedManifest,
556
+ ANALYTICS_OMIT_FIELDS: JSON.stringify((_p = (_o = args.fields) == null ? void 0 : _o.omit) != null ? _p : [])
557
+ },
558
+ permissions: [
559
+ { actions: ["dynamodb:ExportTableToPointInTime", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem"], resources: [table.arn] },
560
+ { actions: ["s3:GetObject"], resources: [$interpolate`${this.bucket.arn}/${backfillPrefix}/*`] },
561
+ { actions: ["firehose:PutRecordBatch"], resources: [this.deliveryStream.arn] }
562
+ ]
563
+ });
564
+ const backfillPermission = new aws.lambda.Permission(`${id}-analytics-backfill-s3-permission`, {
565
+ action: "lambda:InvokeFunction",
566
+ function: backfillFunction.name,
567
+ principal: "s3.amazonaws.com",
568
+ sourceArn: this.bucket.arn
569
+ });
570
+ const backfillNotification = new aws.s3.BucketNotification(`${id}-analytics-backfill-notification`, {
571
+ bucket: this.bucket.name,
572
+ lambdaFunctions: [{ lambdaFunctionArn: backfillFunction.arn, events: ["s3:ObjectCreated:*"], filterPrefix: `${backfillPrefix}/AWSDynamoDB/` }]
573
+ }, { dependsOn: [backfillPermission] });
574
+ new aws.lambda.Invocation(`${id}-analytics-backfill-launch`, {
575
+ functionName: backfillFunction.name,
576
+ // This resource is recreated after analytics is disabled, so reconcile
577
+ // current state when delivery is enabled again.
578
+ input: JSON.stringify({ action: "reconcile" })
579
+ }, { dependsOn: [backfillNotification] });
580
+ new aws.cloudwatch.MetricAlarm(`${id}-analytics-backfill-errors`, {
581
+ name: `${id}-analytics-backfill-errors`,
582
+ namespace: "AWS/Lambda",
583
+ metricName: "Errors",
584
+ statistic: "Sum",
585
+ period: 300,
586
+ evaluationPeriods: 1,
587
+ threshold: 1,
588
+ comparisonOperator: "GreaterThanOrEqualToThreshold",
589
+ alarmActions: [alarmTopic.arn],
590
+ dimensions: { FunctionName: this.backfillFunctionName }
591
+ });
592
+ const rawTables = [];
593
+ for (const dataset of datasets) {
594
+ const rawTable = `${dataset.historyTable}_raw`;
595
+ const rawLocation = $resolve([this.bucket.name]).apply(
596
+ ([bucketName]) => `s3://${bucketName}/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`
597
+ );
598
+ const projection = dataset.partition.granularity === "hour" ? {
599
+ "projection.event_hour.type": "integer",
600
+ "projection.event_hour.range": "0,23",
601
+ "projection.event_hour.digits": "2",
602
+ "storage.location.template": rawLocation.apply(
603
+ (location) => `${location}event_date=\${event_date}/event_hour=\${event_hour}/`
604
+ )
605
+ } : {
606
+ "storage.location.template": rawLocation.apply(
607
+ (location) => `${location}event_date=\${event_date}/`
608
+ )
609
+ };
610
+ rawTables.push(new aws.glue.CatalogTable(`${id}-${dataset.identifier}-raw`, {
611
+ databaseName: this.glueDatabase.name,
612
+ name: rawTable,
613
+ tableType: "EXTERNAL_TABLE",
614
+ parameters: __spreadValues({
615
+ EXTERNAL: "TRUE",
616
+ "projection.enabled": "true",
617
+ "projection.event_date.type": "date",
618
+ "projection.event_date.range": "2020-01-01,NOW",
619
+ "projection.event_date.format": "yyyy-MM-dd"
620
+ }, projection),
621
+ storageDescriptor: {
622
+ location: rawLocation,
623
+ inputFormat: "org.apache.hadoop.mapred.TextInputFormat",
624
+ outputFormat: "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
625
+ serDeInfo: { serializationLibrary: "org.openx.data.jsonserde.JsonSerDe" },
626
+ columns: [
627
+ { name: "event_id", type: "string" },
628
+ { name: "idempotency_key", type: "string" },
629
+ { name: "ordering_key", type: "string" },
630
+ { name: "sequence_number", type: "string" },
631
+ { name: "operation", type: "string" },
632
+ { name: "occurred_at", type: "string" },
633
+ { name: "dataset", type: "string" },
634
+ { name: "kind", type: "string" },
635
+ { name: "path", type: "string" },
636
+ { name: "before", type: "string" },
637
+ { name: "after", type: "string" }
638
+ ]
639
+ },
640
+ partitionKeys: [{ name: "event_date", type: "string" }, ...dataset.partition.granularity === "hour" ? [{ name: "event_hour", type: "string" }] : []]
641
+ }));
642
+ }
643
+ this.schedule = new sst.aws.CronV2(`${id}-analytics-daily`, {
644
+ schedule: "cron(0 0 * * ? *)",
645
+ function: {
646
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsMaterializationHandler"),
647
+ runtime: "nodejs22.x",
648
+ timeout: "15 minutes",
649
+ memory: "1024 MB",
650
+ logging,
651
+ environment: {
652
+ ANALYTICS_DATABASE: this.glueDatabase.name,
653
+ ANALYTICS_BUCKET: this.bucket.name,
654
+ ANALYTICS_WORKGROUP: this.workgroup.name,
655
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
656
+ },
657
+ permissions: [
658
+ { actions: ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults"], resources: ["*"] },
659
+ { actions: ["glue:GetDatabase", "glue:GetDatabases", "glue:GetTable", "glue:GetTables", "glue:CreateTable", "glue:UpdateTable"], resources: ["*"] },
660
+ { actions: ["s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", "s3:ListBucket"], resources: [this.bucket.arn, $interpolate`${this.bucket.arn}/*`] }
661
+ ]
662
+ }
663
+ });
664
+ const initialMaterialization = new aws.lambda.Invocation(`${id}-analytics-materialization-initial`, {
665
+ functionName: this.schedule.nodes.function.name,
666
+ input: "{}"
667
+ }, { dependsOn: rawTables });
668
+ if (args.views) {
669
+ validateDefinitions(args.views, "view");
670
+ for (const [name, view] of Object.entries(args.views)) {
671
+ const viewFunction = new sst.aws.Function(`${id}-${name}-analytics-view`, {
672
+ handler: path.join(configRoot != null ? configRoot : "", ".monorise/handle.analyticsViewHandler"),
673
+ runtime: "nodejs22.x",
674
+ timeout: "15 minutes",
675
+ memory: "512 MB",
676
+ logging,
677
+ environment: {
678
+ ANALYTICS_VIEW: JSON.stringify({ name, sql: view.sql }),
679
+ ANALYTICS_DATABASE: this.glueDatabase.name,
680
+ ANALYTICS_WORKGROUP: this.workgroup.name,
681
+ ANALYTICS_ATHENA_OUTPUT: $interpolate`s3://${this.bucket.name}/athena-results/`
682
+ },
683
+ permissions: athenaPermissions
684
+ });
685
+ new aws.lambda.Invocation(`${id}-${name}-analytics-view-apply`, {
686
+ // Changing the definition changes the invocation input and reapplies the view.
687
+ functionName: viewFunction.name,
688
+ input: JSON.stringify({ sql: view.sql })
689
+ }, { dependsOn: [initialMaterialization] });
690
+ }
691
+ }
692
+ }
693
+ };
694
+
272
695
  // components/q-function.ts
273
696
  var QFunction = class {
274
697
  constructor(id, args) {
@@ -328,7 +751,7 @@ var QFunction = class {
328
751
  };
329
752
 
330
753
  // components/single-table.ts
331
- import path from "path";
754
+ import path2 from "path";
332
755
 
333
756
  // constants/table.ts
334
757
  var ENTITY_REPLICATION_INDEX = "ENTITY_REPLICATION_INDEX";
@@ -378,7 +801,10 @@ var SingleTable = class {
378
801
  }
379
802
  },
380
803
  stream: "new-and-old-images",
381
- ttl: "expiresAt"
804
+ ttl: "expiresAt",
805
+ transform: {
806
+ table: { pointInTimeRecovery: { enabled: true } }
807
+ }
382
808
  });
383
809
  const environment = {
384
810
  CORE_TABLE: this.table.name
@@ -387,7 +813,7 @@ var SingleTable = class {
387
813
  `${id}-core-replicator`,
388
814
  {
389
815
  name: this.replicatorFunctionName,
390
- handler: path.join(
816
+ handler: path2.join(
391
817
  (_a = args == null ? void 0 : args.configRoot) != null ? _a : "",
392
818
  ".monorise/handle.replicationHandler"
393
819
  ),
@@ -419,10 +845,10 @@ var SingleTable = class {
419
845
  // components/monorise-core.ts
420
846
  var MonoriseCore = class {
421
847
  constructor(id, args) {
422
- var _a, _b;
848
+ var _a, _b, _c, _d;
423
849
  const runtime = "nodejs22.x";
424
850
  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");
851
+ const dotMonorisePath = path3.join((_a = args == null ? void 0 : args.configRoot) != null ? _a : "", ".monorise");
426
852
  const logging = (args == null ? void 0 : args.cloudwatchLogRetention) ? { retention: args.cloudwatchLogRetention } : void 0;
427
853
  new sst.x.DevCommand("Monorise", {
428
854
  dev: {
@@ -464,6 +890,21 @@ var MonoriseCore = class {
464
890
  logging
465
891
  });
466
892
  this.alarmTopic = new sst.aws.SnsTopic(`${id}-monorise-dlq-alarm-topic`);
893
+ if (((_b = args == null ? void 0 : args.analytics) == null ? void 0 : _b.enabled) !== false && (args == null ? void 0 : args.analytics)) {
894
+ if (args.fromTableName && ((_c = args.analytics.importedTable) == null ? void 0 : _c.pointInTimeRecoveryEnabled) !== true) {
895
+ throw new Error(
896
+ "Analytics backfill requires point-in-time recovery on fromTableName. Enable it on the imported table and set analytics.importedTable.pointInTimeRecoveryEnabled to true."
897
+ );
898
+ }
899
+ this.analytics = new Analytics(
900
+ id,
901
+ args.analytics,
902
+ this.table.table,
903
+ this.alarmTopic,
904
+ args.configRoot,
905
+ logging
906
+ );
907
+ }
467
908
  const environment = {
468
909
  CORE_TABLE: this.table.table.name,
469
910
  CORE_EVENT_BUS: this.bus.name
@@ -534,7 +975,7 @@ var MonoriseCore = class {
534
975
  ]
535
976
  }
536
977
  });
537
- if (((_b = args == null ? void 0 : args.cloudwatchDashboard) == null ? void 0 : _b.enabled) !== false) {
978
+ if (((_d = args == null ? void 0 : args.cloudwatchDashboard) == null ? void 0 : _d.enabled) !== false) {
538
979
  new aws.cloudwatch.Dashboard(`${id}-monorise-dashboard`, {
539
980
  dashboardName: `${$app.stage}-${$app.name}-${id}-monorise`,
540
981
  dashboardBody: $resolve([