@anthusai/papyrus 5.110.0 → 5.112.0-next.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.
Files changed (92) hide show
  1. package/amplify/auth/resource.js +3 -0
  2. package/amplify/auth/resource.ts +3 -0
  3. package/amplify/auth/tenant-session-claims.js +27 -0
  4. package/amplify/auth/tenant-session-claims.ts +31 -0
  5. package/amplify/cost-attribution.js +12 -0
  6. package/amplify/cost-attribution.ts +12 -0
  7. package/amplify/data/resource.js +79 -0
  8. package/amplify/data/resource.ts +82 -0
  9. package/amplify/data/schema.js +82 -1
  10. package/amplify/data/schema.ts +85 -1
  11. package/amplify/functions/assignment-action/handler.ts +14 -9
  12. package/amplify/functions/automation-view/wire.js +2 -1
  13. package/amplify/functions/automation-view/wire.ts +2 -1
  14. package/amplify/functions/category-action/handler.ts +24 -18
  15. package/amplify/functions/category-action/message-hashtags.js +2 -1
  16. package/amplify/functions/category-action/message-hashtags.ts +2 -1
  17. package/amplify/functions/category-action/reference-links.js +3 -2
  18. package/amplify/functions/category-action/reference-links.ts +3 -2
  19. package/amplify/functions/console-chat-responder/resource.js +2 -1
  20. package/amplify/functions/console-chat-responder/resource.ts +2 -1
  21. package/amplify/functions/content-actions/handler.py +54 -22
  22. package/amplify/functions/content-actions/resource.js +4 -0
  23. package/amplify/functions/content-actions/resource.ts +5 -0
  24. package/amplify/functions/editorial-checks/handler.py +5 -1
  25. package/amplify/functions/editorial-checks/schema.js +10 -2
  26. package/amplify/functions/editorial-checks/schema.ts +10 -2
  27. package/amplify/functions/editorial-checks/wire.js +2 -1
  28. package/amplify/functions/editorial-checks/wire.ts +2 -1
  29. package/amplify/functions/image-service/wire.js +2 -1
  30. package/amplify/functions/image-service/wire.ts +2 -1
  31. package/amplify/functions/monitoring-view/wire.js +2 -1
  32. package/amplify/functions/monitoring-view/wire.ts +2 -1
  33. package/amplify/functions/newsroom-summary/handler.ts +16 -12
  34. package/amplify/functions/shared/tenant-context.js +98 -0
  35. package/amplify/functions/shared/tenant-context.ts +33 -0
  36. package/amplify/functions/shared/tenant-scoped-client.ts +80 -0
  37. package/amplify/functions/tenant-claims/claims.ts +90 -0
  38. package/amplify/functions/tenant-claims/environment.js +7 -0
  39. package/amplify/functions/tenant-claims/environment.ts +7 -0
  40. package/amplify/functions/tenant-claims/handler.ts +56 -0
  41. package/amplify/functions/tenant-claims/resource.js +12 -0
  42. package/amplify/functions/tenant-claims/resource.ts +13 -0
  43. package/amplify/plugins/newsletter/sending.js +2 -1
  44. package/amplify/plugins/newsletter/sending.ts +2 -1
  45. package/amplify/plugins/notifications/papyrus.plugin.js +2 -1
  46. package/amplify/plugins/notifications/papyrus.plugin.ts +2 -1
  47. package/amplify/plugins/reader-steering/schema.js +15 -3
  48. package/amplify/plugins/reader-steering/schema.ts +15 -3
  49. package/amplify/plugins/signup/papyrus.plugin.js +2 -1
  50. package/amplify/plugins/signup/papyrus.plugin.ts +2 -1
  51. package/amplify/plugins/signup/schema.js +1 -0
  52. package/amplify/plugins/signup/schema.ts +1 -0
  53. package/amplify/shared-stack/alarms.js +53 -0
  54. package/amplify/shared-stack/alarms.ts +109 -0
  55. package/amplify/shared-stack/define.js +15 -0
  56. package/amplify/shared-stack/define.ts +17 -0
  57. package/amplify/shared-stack/deny.js +27 -0
  58. package/amplify/shared-stack/deny.ts +28 -0
  59. package/amplify/shared-stack/inline-policy.js +53 -0
  60. package/amplify/shared-stack/inline-policy.ts +65 -0
  61. package/amplify/shared-stack/isolation.js +161 -0
  62. package/amplify/shared-stack/isolation.ts +204 -0
  63. package/amplify/shared-stack/names.js +95 -0
  64. package/amplify/shared-stack/names.ts +133 -0
  65. package/amplify/shared-stack/settings.js +70 -0
  66. package/amplify/shared-stack/settings.ts +95 -0
  67. package/amplify/site-api-access.js +13 -0
  68. package/amplify/site-api-access.ts +14 -0
  69. package/amplify/site-backend-config.js +7 -1
  70. package/amplify/site-backend-config.ts +8 -2
  71. package/amplify/site-backend.js +65 -13
  72. package/amplify/site-backend.ts +75 -19
  73. package/components/news-desk-taxonomy-client.ts +5 -0
  74. package/components/newsroom-article-editor.tsx +7 -3
  75. package/components/newsroom-board-view.tsx +4 -2
  76. package/components/newsroom-organizer.css +2 -2
  77. package/components/use-newsroom-desk-sections.ts +31 -0
  78. package/infra/amplify-app-shell.js +4 -1
  79. package/infra/amplify-app-shell.ts +4 -1
  80. package/infra/build-specs.js +4 -1
  81. package/infra/build-specs.ts +5 -1
  82. package/infra/cost-tags.test.js +1 -1
  83. package/infra/cost-tags.test.ts +1 -1
  84. package/infra/shared-stack-deny.js +80 -0
  85. package/infra/shared-stack-deny.test.js +56 -0
  86. package/infra/shared-stack-deny.test.ts +66 -0
  87. package/infra/shared-stack-deny.ts +86 -0
  88. package/lib/newsroom-sections.ts +14 -0
  89. package/lib/tenant-keys.js +16 -0
  90. package/lib/tenant-keys.ts +19 -0
  91. package/package.json +2 -1
  92. package/routes.manifest.json +1 -1
@@ -4,6 +4,7 @@ import { Architecture, Function as LambdaFunction, Runtime } from "aws-cdk-lib/a
4
4
  import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
5
5
  import { CfnSchedule } from "aws-cdk-lib/aws-scheduler";
6
6
  import { Queue, QueueEncryption } from "aws-cdk-lib/aws-sqs";
7
+ import { connectToSiteApi } from "../../site-api-access.js";
7
8
  export const NEWSLETTER_WORKER_HANDLER = "papyrus_content.newsletter.worker.handler";
8
9
  /** The worker mails up to 50 subscribers per message at the SES send rate; the visibility timeout is six times this. */
9
10
  export const WORKER_TIMEOUT_SECONDS = 180;
@@ -62,7 +63,7 @@ export function wireSending(inputs) {
62
63
  lambda.addEnvironment("SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
63
64
  lambda.addEnvironment("QUEUE_URL", queue.queueUrl);
64
65
  lambda.addEnvironment("CONTENT_ACTIONS_FUNCTION", contentActions.functionName);
65
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
66
+ connectToSiteApi(lambda, context.graphqlEndpoint);
66
67
  queue.grantSendMessages(lambda);
67
68
  contentActions.grantInvoke(lambda);
68
69
  lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["ssm:GetParameter"], resources: postalAddressParameterArns(stack, config.siteId) }));
@@ -7,6 +7,7 @@ import { CfnSchedule } from "aws-cdk-lib/aws-scheduler";
7
7
  import { Queue, QueueEncryption } from "aws-cdk-lib/aws-sqs";
8
8
  import type { PluginWiringContext } from "../types";
9
9
  import type { NewsletterConfig, RoundupList } from "./config";
10
+ import { connectToSiteApi } from "../../site-api-access";
10
11
 
11
12
  export const NEWSLETTER_WORKER_HANDLER = "papyrus_content.newsletter.worker.handler";
12
13
  /** The worker mails up to 50 subscribers per message at the SES send rate; the visibility timeout is six times this. */
@@ -90,7 +91,7 @@ export function wireSending(inputs: SendingInputs): { queue: Queue; deadLetterQu
90
91
  lambda.addEnvironment("SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
91
92
  lambda.addEnvironment("QUEUE_URL", queue.queueUrl);
92
93
  lambda.addEnvironment("CONTENT_ACTIONS_FUNCTION", contentActions.functionName);
93
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
94
+ connectToSiteApi(lambda, context.graphqlEndpoint);
94
95
 
95
96
  queue.grantSendMessages(lambda);
96
97
  contentActions.grantInvoke(lambda);
@@ -16,6 +16,7 @@ import { SecureStringParameter } from "../newsletter/secure-string-parameter.js"
16
16
  import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD } from "../newsletter/papyrus.plugin.js";
17
17
  import { functionArn, postalAddressParameterArns } from "../newsletter/sending.js";
18
18
  import { resolveNotificationsConfig } from "./config.js";
19
+ import { siteApiEnvironment } from "../../site-api-access.js";
19
20
  export { resolveNotificationsConfig };
20
21
  export const NOTIFICATIONS_OUTPUT_KEY = "notifications";
21
22
  /** Set on the site's content-actions function: it invokes the router function (`story-published`) after a real publish. Unset: no notices. */
@@ -189,7 +190,7 @@ export const notificationsPlugin = {
189
190
  const environment = {
190
191
  ...notificationsEnvironment(config, { table: table.tableName, operators: operatorsParameter, key: keyParameter.parameterName }),
191
192
  EMAIL_QUEUE_URL: emailQueue.queueUrl,
192
- PAPYRUS_GRAPHQL_ENDPOINT: context.graphqlEndpoint,
193
+ ...siteApiEnvironment(context.graphqlEndpoint),
193
194
  };
194
195
  const common = { runtime: Runtime.PYTHON_3_12, architecture: Architecture.ARM_64, code, environment };
195
196
  const router = new LambdaFunction(stack, "RouterFunction", {
@@ -17,6 +17,7 @@ import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD }
17
17
  import { functionArn, postalAddressParameterArns } from "../newsletter/sending";
18
18
  import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../types";
19
19
  import { resolveNotificationsConfig, type NotificationsConfig } from "./config";
20
+ import { siteApiEnvironment } from "../../site-api-access";
20
21
 
21
22
  export { resolveNotificationsConfig };
22
23
  export type { NotificationsConfig };
@@ -209,7 +210,7 @@ export const notificationsPlugin: PapyrusPlugin<NotificationsConfig, Record<stri
209
210
  const environment = {
210
211
  ...notificationsEnvironment(config, { table: table.tableName, operators: operatorsParameter, key: keyParameter.parameterName }),
211
212
  EMAIL_QUEUE_URL: emailQueue.queueUrl,
212
- PAPYRUS_GRAPHQL_ENDPOINT: context.graphqlEndpoint,
213
+ ...siteApiEnvironment(context.graphqlEndpoint),
213
214
  };
214
215
  const common = { runtime: Runtime.PYTHON_3_12, architecture: Architecture.ARM_64, code, environment };
215
216
  const router = new LambdaFunction(stack, "RouterFunction", {
@@ -21,7 +21,10 @@ export function readerSteeringSchemaDefinitions() {
21
21
  karma: a.integer(),
22
22
  })
23
23
  .disableOperations(["subscriptions"])
24
- .secondaryIndexes((index) => [index("readerId").name("profilesByReader").queryField("listReaderProfilesByReader")])
24
+ .secondaryIndexes((index) => [
25
+ index("readerId").name("profilesByReader").queryField("listReaderProfilesByReader"),
26
+ index("tenantId").sortKeys(["id"]).name("profilesByTenant").queryField("listReaderProfilesByTenant"),
27
+ ])
25
28
  .authorization(staffOnly),
26
29
  ReaderHandle: a
27
30
  .model({
@@ -30,6 +33,7 @@ export function readerSteeringSchemaDefinitions() {
30
33
  readerId: a.string().required(),
31
34
  })
32
35
  .disableOperations(["subscriptions"])
36
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("handlesByTenant").queryField("listReaderHandlesByTenant")])
33
37
  .authorization(staffOnly),
34
38
  ReaderVote: a
35
39
  .model({
@@ -43,6 +47,7 @@ export function readerSteeringSchemaDefinitions() {
43
47
  voterRole: a.string().required(),
44
48
  })
45
49
  .disableOperations(["subscriptions"])
50
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("votesByTenant").queryField("listReaderVotesByTenant")])
46
51
  .authorization(staffOnly),
47
52
  ReaderFlag: a
48
53
  .model({
@@ -59,6 +64,7 @@ export function readerSteeringSchemaDefinitions() {
59
64
  createdAt: a.datetime().required(),
60
65
  })
61
66
  .disableOperations(["subscriptions"])
67
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("flagsByTenant").queryField("listReaderFlagsByTenant")])
62
68
  .authorization(staffOnly),
63
69
  ReaderComment: a
64
70
  .model({
@@ -125,7 +131,10 @@ export function readerSteeringSchemaDefinitions() {
125
131
  createdAt: a.datetime().required(),
126
132
  })
127
133
  .disableOperations(["subscriptions"])
128
- .secondaryIndexes((index) => [index("target").sortKeys(["createdAt"]).name("reportsByTarget").queryField("listReaderReportsByTargetAndCreatedAt")])
134
+ .secondaryIndexes((index) => [
135
+ index("target").sortKeys(["createdAt"]).name("reportsByTarget").queryField("listReaderReportsByTargetAndCreatedAt"),
136
+ index("tenantId").sortKeys(["id"]).name("reportsByTenant").queryField("listReaderReportsByTenant"),
137
+ ])
129
138
  .authorization(staffOnly),
130
139
  ModerationAction: a
131
140
  .model({
@@ -146,7 +155,10 @@ export function readerSteeringSchemaDefinitions() {
146
155
  at: a.datetime().required(),
147
156
  })
148
157
  .disableOperations(["subscriptions"])
149
- .secondaryIndexes((index) => [index("target").sortKeys(["at"]).name("actionsByTarget").queryField("listModerationActionsByTargetAndAt")])
158
+ .secondaryIndexes((index) => [
159
+ index("target").sortKeys(["at"]).name("actionsByTarget").queryField("listModerationActionsByTargetAndAt"),
160
+ index("tenantId").sortKeys(["id"]).name("actionsByTenant").queryField("listModerationActionsByTenant"),
161
+ ])
150
162
  .authorization(staffOnly),
151
163
  ModerationReceipt: a.customType({
152
164
  status: a.string().required(),
@@ -23,7 +23,10 @@ export function readerSteeringSchemaDefinitions() {
23
23
  karma: a.integer(),
24
24
  })
25
25
  .disableOperations(["subscriptions"])
26
- .secondaryIndexes((index) => [index("readerId").name("profilesByReader").queryField("listReaderProfilesByReader")])
26
+ .secondaryIndexes((index) => [
27
+ index("readerId").name("profilesByReader").queryField("listReaderProfilesByReader"),
28
+ index("tenantId").sortKeys(["id"]).name("profilesByTenant").queryField("listReaderProfilesByTenant"),
29
+ ])
27
30
  .authorization(staffOnly),
28
31
  ReaderHandle: a
29
32
  .model({
@@ -32,6 +35,7 @@ export function readerSteeringSchemaDefinitions() {
32
35
  readerId: a.string().required(),
33
36
  })
34
37
  .disableOperations(["subscriptions"])
38
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("handlesByTenant").queryField("listReaderHandlesByTenant")])
35
39
  .authorization(staffOnly),
36
40
  ReaderVote: a
37
41
  .model({
@@ -45,6 +49,7 @@ export function readerSteeringSchemaDefinitions() {
45
49
  voterRole: a.string().required(),
46
50
  })
47
51
  .disableOperations(["subscriptions"])
52
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("votesByTenant").queryField("listReaderVotesByTenant")])
48
53
  .authorization(staffOnly),
49
54
  ReaderFlag: a
50
55
  .model({
@@ -61,6 +66,7 @@ export function readerSteeringSchemaDefinitions() {
61
66
  createdAt: a.datetime().required(),
62
67
  })
63
68
  .disableOperations(["subscriptions"])
69
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).name("flagsByTenant").queryField("listReaderFlagsByTenant")])
64
70
  .authorization(staffOnly),
65
71
  ReaderComment: a
66
72
  .model({
@@ -127,7 +133,10 @@ export function readerSteeringSchemaDefinitions() {
127
133
  createdAt: a.datetime().required(),
128
134
  })
129
135
  .disableOperations(["subscriptions"])
130
- .secondaryIndexes((index) => [index("target").sortKeys(["createdAt"]).name("reportsByTarget").queryField("listReaderReportsByTargetAndCreatedAt")])
136
+ .secondaryIndexes((index) => [
137
+ index("target").sortKeys(["createdAt"]).name("reportsByTarget").queryField("listReaderReportsByTargetAndCreatedAt"),
138
+ index("tenantId").sortKeys(["id"]).name("reportsByTenant").queryField("listReaderReportsByTenant"),
139
+ ])
131
140
  .authorization(staffOnly),
132
141
  ModerationAction: a
133
142
  .model({
@@ -148,7 +157,10 @@ export function readerSteeringSchemaDefinitions() {
148
157
  at: a.datetime().required(),
149
158
  })
150
159
  .disableOperations(["subscriptions"])
151
- .secondaryIndexes((index) => [index("target").sortKeys(["at"]).name("actionsByTarget").queryField("listModerationActionsByTargetAndAt")])
160
+ .secondaryIndexes((index) => [
161
+ index("target").sortKeys(["at"]).name("actionsByTarget").queryField("listModerationActionsByTargetAndAt"),
162
+ index("tenantId").sortKeys(["id"]).name("actionsByTenant").queryField("listModerationActionsByTenant"),
163
+ ])
152
164
  .authorization(staffOnly),
153
165
  ModerationReceipt: a.customType({
154
166
  status: a.string().required(),
@@ -3,6 +3,7 @@ import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
3
  import { signupSubmit } from "./function/resource.js";
4
4
  import { signupSchemaDefinitions } from "./schema.js";
5
5
  import { SIGNUP_MUTATION_FIELD, WAF_MINIMUM_RATE_LIMIT, addSignupRateLimit } from "./waf.js";
6
+ import { connectToSiteApi } from "../../site-api-access.js";
6
7
  const FORM_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
7
8
  const KNOWN_KEYS = new Set(["name", "forms", "addressLimitPerMinute", "waf"]);
8
9
  export const signupManifest = {
@@ -41,7 +42,7 @@ export const signupPlugin = {
41
42
  wire(backend, config, context) {
42
43
  const lambda = backend.signupSubmit.resources.lambda;
43
44
  const stack = Stack.of(lambda);
44
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
45
+ connectToSiteApi(lambda, context.graphqlEndpoint);
45
46
  lambda.addEnvironment("PAPYRUS_SIGNUP_FORMS", config.forms.join(","));
46
47
  lambda.addEnvironment("PAPYRUS_SIGNUP_ADDRESS_LIMIT", String(config.addressLimitPerMinute));
47
48
  lambda.addToRolePolicy(new PolicyStatement({
@@ -5,6 +5,7 @@ import type { PapyrusPlugin, PluginManifest, PluginRequest, PluginWiringContext
5
5
  import { signupSubmit } from "./function/resource";
6
6
  import { signupSchemaDefinitions } from "./schema";
7
7
  import { SIGNUP_MUTATION_FIELD, WAF_MINIMUM_RATE_LIMIT, addSignupRateLimit } from "./waf";
8
+ import { connectToSiteApi } from "../../site-api-access";
8
9
 
9
10
  export type SignupPluginConfig = {
10
11
  /** Form names the site accepts. A submission naming any other form is rejected. */
@@ -54,7 +55,7 @@ export const signupPlugin: PapyrusPlugin<SignupPluginConfig, { signupSubmit: typ
54
55
  wire(backend, config, context: PluginWiringContext) {
55
56
  const lambda = backend.signupSubmit.resources.lambda as LambdaFunction;
56
57
  const stack = Stack.of(lambda);
57
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
58
+ connectToSiteApi(lambda, context.graphqlEndpoint);
58
59
  lambda.addEnvironment("PAPYRUS_SIGNUP_FORMS", config.forms.join(","));
59
60
  lambda.addEnvironment("PAPYRUS_SIGNUP_ADDRESS_LIMIT", String(config.addressLimitPerMinute));
60
61
  lambda.addToRolePolicy(
@@ -18,6 +18,7 @@ export function signupSchemaDefinitions() {
18
18
  .disableOperations(["subscriptions"])
19
19
  .secondaryIndexes((index) => [
20
20
  index("form").sortKeys(["submittedAt"]).queryField("listSignupEntriesByFormAndSubmittedAt"),
21
+ index("tenantId").sortKeys(["id"]).queryField("listSignupEntriesByTenant"),
21
22
  ])
22
23
  .authorization((allow) => [
23
24
  allow.group("editor").to(["read"]),
@@ -19,6 +19,7 @@ export function signupSchemaDefinitions() {
19
19
  .disableOperations(["subscriptions"])
20
20
  .secondaryIndexes((index) => [
21
21
  index("form").sortKeys(["submittedAt"]).queryField("listSignupEntriesByFormAndSubmittedAt"),
22
+ index("tenantId").sortKeys(["id"]).queryField("listSignupEntriesByTenant"),
22
23
  ])
23
24
  .authorization((allow) => [
24
25
  allow.group("editor").to(["read"]),
@@ -0,0 +1,53 @@
1
+ import { Duration } from "aws-cdk-lib";
2
+ import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
3
+ import { shortHash } from "./isolation.js";
4
+ export const DYNAMODB_TABLES_PER_ALARM = 5;
5
+ const minutes = (settings) => Duration.minutes(settings.alarms.periodMinutes);
6
+ function metricAlarm(scope, plan, kind, key, metric, threshold, description, operator = cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) {
7
+ return new cloudwatch.Alarm(scope, `${kind}${shortHash(key, 8)}`, {
8
+ alarmName: `${plan.stackPrefix}-${kind}-${key.replace(new RegExp(`^${plan.stackPrefix}-`), "").slice(0, 60)}`.slice(0, 255),
9
+ alarmDescription: description,
10
+ metric,
11
+ threshold,
12
+ evaluationPeriods: 1,
13
+ comparisonOperator: operator,
14
+ treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
15
+ });
16
+ }
17
+ export function addSharedStackAlarms(scope, plan, settings, inputs) {
18
+ const period = minutes(settings);
19
+ const alarms = [];
20
+ const where = `the ${plan.tier} shared stack`;
21
+ for (const target of inputs.functions) {
22
+ const dimensionsMap = { FunctionName: target.functionName };
23
+ const lambdaMetric = (metricName, statistic) => new cloudwatch.Metric({ namespace: "AWS/Lambda", metricName, dimensionsMap, statistic, period });
24
+ alarms.push(metricAlarm(scope, plan, "errors", target.functionName, lambdaMetric("Errors", "Sum"), settings.alarms.functionErrors, `${target.functionName} in ${where} returned errors.`), metricAlarm(scope, plan, "throttles", target.functionName, lambdaMetric("Throttles", "Sum"), settings.alarms.functionThrottles, `${target.functionName} in ${where} was throttled: it reached its reserved concurrency.`));
25
+ if (target.reserved !== undefined) {
26
+ // Concurrency against the reserved share: the reservation is also this function's ceiling, so a share of it is the early warning.
27
+ const threshold = Math.max(1, Math.ceil(target.reserved * settings.alarms.concurrencyShareOfReserved));
28
+ alarms.push(metricAlarm(scope, plan, "concurrency", target.functionName, lambdaMetric("ConcurrentExecutions", "Maximum"), threshold, `${target.functionName} in ${where} reached ${settings.alarms.concurrencyShareOfReserved * 100}% of its reserved concurrency of ${target.reserved}.`));
29
+ }
30
+ }
31
+ const appSync = (metricName) => new cloudwatch.Metric({ namespace: "AWS/AppSync", metricName, dimensionsMap: { GraphQLAPIId: inputs.appSyncApiId }, statistic: "Sum", period });
32
+ alarms.push(metricAlarm(scope, plan, "appsync-5xx", "api", appSync("5XXError"), settings.alarms.appSyncServerErrors, `The AppSync API of ${where} returned server errors.`),
33
+ // AppSync has no throttle metric: a throttled request is answered 429 and counted in 4XXError.
34
+ metricAlarm(scope, plan, "appsync-4xx", "api", appSync("4XXError"), settings.alarms.appSyncClientErrors, `The AppSync API of ${where} returned many client errors; throttled requests (429) are counted here.`));
35
+ for (let index = 0; index < inputs.tableNames.length; index += DYNAMODB_TABLES_PER_ALARM) {
36
+ const chunk = inputs.tableNames.slice(index, index + DYNAMODB_TABLES_PER_ALARM);
37
+ const usingMetrics = {};
38
+ chunk.forEach((tableName, position) => {
39
+ for (const metricName of ["ReadThrottleEvents", "WriteThrottleEvents"]) {
40
+ usingMetrics[`m${position}${metricName[0].toLowerCase()}`] = new cloudwatch.Metric({ namespace: "AWS/DynamoDB", metricName, dimensionsMap: { TableName: tableName }, statistic: "Sum", period });
41
+ }
42
+ });
43
+ const group = `group-${index / DYNAMODB_TABLES_PER_ALARM + 1}`;
44
+ alarms.push(metricAlarm(scope, plan, "dynamodb-throttles", group, new cloudwatch.MathExpression({ expression: "SUM(METRICS())", usingMetrics, period, label: "Throttled reads and writes" }), settings.alarms.dynamoDbThrottledRequests, `DynamoDB throttled reads or writes on ${chunk.length} tables of ${where}.`));
45
+ }
46
+ if (inputs.projectionDeadLetterQueueName !== undefined) {
47
+ alarms.push(metricAlarm(scope, plan, "projection-dlq", "queue", new cloudwatch.Metric({ namespace: "AWS/SQS", metricName: "ApproximateNumberOfMessagesVisible", dimensionsMap: { QueueName: inputs.projectionDeadLetterQueueName }, statistic: "Maximum", period }), settings.alarms.projectionDeadLetterMessages, `Failed projections are waiting in the dead-letter queue of ${where}.`));
48
+ }
49
+ if (inputs.distributionId !== undefined) {
50
+ alarms.push(metricAlarm(scope, plan, "purged-paths", inputs.distributionId, new cloudwatch.Metric({ namespace: "Papyrus/Edge", metricName: "InvalidatedPaths", dimensionsMap: { DistributionId: inputs.distributionId }, statistic: "Sum", period: Duration.days(7) }), settings.alarms.purgedPathsPerWeek, `The shared distribution of ${where} purged many paths in a week (billable past the free allowance).`));
51
+ }
52
+ return alarms;
53
+ }
@@ -0,0 +1,109 @@
1
+ import { Duration, type Stack } from "aws-cdk-lib";
2
+ import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
3
+ import { shortHash } from "./isolation";
4
+ import type { SharedTierPlan } from "./names";
5
+ import type { SharedStackSettings } from "./settings";
6
+
7
+ /**
8
+ * Layer 5 of the isolation: alarms that belong to one shared stack, separate from any dedicated site's. They carry no action:
9
+ * every CloudWatch alarm in the account reaches the operator through the default-bus listener (docs/operator-alerts.md), and
10
+ * the alarm names start with the stack's prefix so the operator sees which tier it is.
11
+ */
12
+
13
+ export type SharedFunctionAlarmTarget = {
14
+ /** The function's own name, which `applySharedStackIsolation` set, so no cross-stack reference is needed. */
15
+ functionName: string;
16
+ /** Reserved concurrency; undefined for a function with none (an infrastructure function), which gets no concurrency alarm. */
17
+ reserved?: number;
18
+ };
19
+
20
+ export type SharedAlarmInputs = {
21
+ functions: SharedFunctionAlarmTarget[];
22
+ appSyncApiId: string;
23
+ tableNames: string[];
24
+ /** The projection dead-letter queue's name, when the stack has a publication. */
25
+ projectionDeadLetterQueueName?: string;
26
+ /** The shared distribution's id, once one exists (PPY-3bbbf9); until then there is no purge to count. */
27
+ distributionId?: string;
28
+ };
29
+
30
+ export const DYNAMODB_TABLES_PER_ALARM = 5;
31
+
32
+ const minutes = (settings: SharedStackSettings) => Duration.minutes(settings.alarms.periodMinutes);
33
+
34
+ function metricAlarm(scope: Stack, plan: SharedTierPlan, kind: string, key: string, metric: cloudwatch.IMetric, threshold: number, description: string, operator = cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) {
35
+ return new cloudwatch.Alarm(scope, `${kind}${shortHash(key, 8)}`, {
36
+ alarmName: `${plan.stackPrefix}-${kind}-${key.replace(new RegExp(`^${plan.stackPrefix}-`), "").slice(0, 60)}`.slice(0, 255),
37
+ alarmDescription: description,
38
+ metric,
39
+ threshold,
40
+ evaluationPeriods: 1,
41
+ comparisonOperator: operator,
42
+ treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
43
+ });
44
+ }
45
+
46
+ export function addSharedStackAlarms(scope: Stack, plan: SharedTierPlan, settings: SharedStackSettings, inputs: SharedAlarmInputs): cloudwatch.Alarm[] {
47
+ const period = minutes(settings);
48
+ const alarms: cloudwatch.Alarm[] = [];
49
+ const where = `the ${plan.tier} shared stack`;
50
+
51
+ for (const target of inputs.functions) {
52
+ const dimensionsMap = { FunctionName: target.functionName };
53
+ const lambdaMetric = (metricName: string, statistic: string) => new cloudwatch.Metric({ namespace: "AWS/Lambda", metricName, dimensionsMap, statistic, period });
54
+ alarms.push(
55
+ metricAlarm(scope, plan, "errors", target.functionName, lambdaMetric("Errors", "Sum"), settings.alarms.functionErrors,
56
+ `${target.functionName} in ${where} returned errors.`),
57
+ metricAlarm(scope, plan, "throttles", target.functionName, lambdaMetric("Throttles", "Sum"), settings.alarms.functionThrottles,
58
+ `${target.functionName} in ${where} was throttled: it reached its reserved concurrency.`),
59
+ );
60
+ if (target.reserved !== undefined) {
61
+ // Concurrency against the reserved share: the reservation is also this function's ceiling, so a share of it is the early warning.
62
+ const threshold = Math.max(1, Math.ceil(target.reserved * settings.alarms.concurrencyShareOfReserved));
63
+ alarms.push(
64
+ metricAlarm(scope, plan, "concurrency", target.functionName, lambdaMetric("ConcurrentExecutions", "Maximum"), threshold,
65
+ `${target.functionName} in ${where} reached ${settings.alarms.concurrencyShareOfReserved * 100}% of its reserved concurrency of ${target.reserved}.`),
66
+ );
67
+ }
68
+ }
69
+
70
+ const appSync = (metricName: string) => new cloudwatch.Metric({ namespace: "AWS/AppSync", metricName, dimensionsMap: { GraphQLAPIId: inputs.appSyncApiId }, statistic: "Sum", period });
71
+ alarms.push(
72
+ metricAlarm(scope, plan, "appsync-5xx", "api", appSync("5XXError"), settings.alarms.appSyncServerErrors, `The AppSync API of ${where} returned server errors.`),
73
+ // AppSync has no throttle metric: a throttled request is answered 429 and counted in 4XXError.
74
+ metricAlarm(scope, plan, "appsync-4xx", "api", appSync("4XXError"), settings.alarms.appSyncClientErrors, `The AppSync API of ${where} returned many client errors; throttled requests (429) are counted here.`),
75
+ );
76
+
77
+ for (let index = 0; index < inputs.tableNames.length; index += DYNAMODB_TABLES_PER_ALARM) {
78
+ const chunk = inputs.tableNames.slice(index, index + DYNAMODB_TABLES_PER_ALARM);
79
+ const usingMetrics: Record<string, cloudwatch.IMetric> = {};
80
+ chunk.forEach((tableName, position) => {
81
+ for (const metricName of ["ReadThrottleEvents", "WriteThrottleEvents"]) {
82
+ usingMetrics[`m${position}${metricName[0].toLowerCase()}`] = new cloudwatch.Metric({ namespace: "AWS/DynamoDB", metricName, dimensionsMap: { TableName: tableName }, statistic: "Sum", period });
83
+ }
84
+ });
85
+ const group = `group-${index / DYNAMODB_TABLES_PER_ALARM + 1}`;
86
+ alarms.push(metricAlarm(
87
+ scope, plan, "dynamodb-throttles", group,
88
+ new cloudwatch.MathExpression({ expression: "SUM(METRICS())", usingMetrics, period, label: "Throttled reads and writes" }),
89
+ settings.alarms.dynamoDbThrottledRequests, `DynamoDB throttled reads or writes on ${chunk.length} tables of ${where}.`,
90
+ ));
91
+ }
92
+
93
+ if (inputs.projectionDeadLetterQueueName !== undefined) {
94
+ alarms.push(
95
+ metricAlarm(scope, plan, "projection-dlq", "queue",
96
+ new cloudwatch.Metric({ namespace: "AWS/SQS", metricName: "ApproximateNumberOfMessagesVisible", dimensionsMap: { QueueName: inputs.projectionDeadLetterQueueName }, statistic: "Maximum", period }),
97
+ settings.alarms.projectionDeadLetterMessages, `Failed projections are waiting in the dead-letter queue of ${where}.`),
98
+ );
99
+ }
100
+
101
+ if (inputs.distributionId !== undefined) {
102
+ alarms.push(
103
+ metricAlarm(scope, plan, "purged-paths", inputs.distributionId,
104
+ new cloudwatch.Metric({ namespace: "Papyrus/Edge", metricName: "InvalidatedPaths", dimensionsMap: { DistributionId: inputs.distributionId }, statistic: "Sum", period: Duration.days(7) }),
105
+ settings.alarms.purgedPathsPerWeek, `The shared distribution of ${where} purged many paths in a week (billable past the free allowance).`),
106
+ );
107
+ }
108
+ return alarms;
109
+ }
@@ -0,0 +1,15 @@
1
+ import { sharedTierPlan } from "./names.js";
2
+ /**
3
+ * The backend configuration of a shared stack: tenancy mode shared on the tier, a projection publication with no site's
4
+ * files, and none of the features that belong to one site's mailbox, chat workspace or backups. Nothing else is configured;
5
+ * a tenant's own settings live in the site store (PPY-ee1e02), never in this file.
6
+ */
7
+ export function sharedStackBackendConfig(tier) {
8
+ return {
9
+ brandId: sharedTierPlan(tier).stackPrefix,
10
+ productionAppId: "",
11
+ tenancy: { mode: "shared", tier },
12
+ publication: { kind: "s3-projection", reprojectOnDeploy: false },
13
+ features: { inboundEmail: false, slack: false, storageBackups: false, cliRemoteLogin: false, cliOnFederationClient: false },
14
+ };
15
+ }
@@ -0,0 +1,17 @@
1
+ import type { PapyrusSiteBackendConfig } from "../site-backend-config";
2
+ import { sharedTierPlan, type SharedTier } from "./names";
3
+
4
+ /**
5
+ * The backend configuration of a shared stack: tenancy mode shared on the tier, a projection publication with no site's
6
+ * files, and none of the features that belong to one site's mailbox, chat workspace or backups. Nothing else is configured;
7
+ * a tenant's own settings live in the site store (PPY-ee1e02), never in this file.
8
+ */
9
+ export function sharedStackBackendConfig(tier: SharedTier): PapyrusSiteBackendConfig {
10
+ return {
11
+ brandId: sharedTierPlan(tier).stackPrefix,
12
+ productionAppId: "",
13
+ tenancy: { mode: "shared", tier },
14
+ publication: { kind: "s3-projection", reprojectOnDeploy: false },
15
+ features: { inboundEmail: false, slack: false, storageBackups: false, cliRemoteLogin: false, cliOnFederationClient: false },
16
+ };
17
+ }
@@ -0,0 +1,27 @@
1
+ import { Stack } from "aws-cdk-lib";
2
+ import { CfnRole } from "aws-cdk-lib/aws-iam";
3
+ import { appendInlinePolicy, appendInlinePolicyToRawRole, findAllOfType, findResourcesOfCfnType } from "./inline-policy.js";
4
+ import { SHARED_DENY_POLICY_NAME, sharedStackDenyPolicyDocument } from "./names.js";
5
+ /**
6
+ * The deny that closes the reverse direction of the isolation (docs/plans/multi-tenant-architecture.md, layer 3): a dedicated
7
+ * site's roles may not touch anything of the shared tier. Added as an inline policy, so no template gains a resource.
8
+ *
9
+ * `skip` names the stacks left alone. A dedicated backend with many models would pass CloudFormation's 2,500-resource limit
10
+ * if one change touched every per-model nested stack (Papyrus 5.99.0 rolled back that way, amplify/cost-tag-waves.ts), and a
11
+ * per-model data stack's roles can reach only their own table. Returns the number of roles that got the deny.
12
+ */
13
+ export function addSharedStackDeny(scope, skip = () => false) {
14
+ const document = sharedStackDenyPolicyDocument();
15
+ const roles = findAllOfType(scope, CfnRole).filter((role) => !skip(Stack.of(role)));
16
+ for (const role of roles)
17
+ appendInlinePolicy(role, SHARED_DENY_POLICY_NAME, document);
18
+ // CDK writes the role of a custom resource provider as a raw resource, not a CfnRole.
19
+ const rawRoles = findResourcesOfCfnType(scope, "AWS::IAM::Role").filter((role) => !(role instanceof CfnRole) && !skip(Stack.of(role)));
20
+ for (const role of rawRoles)
21
+ appendInlinePolicyToRawRole(role, SHARED_DENY_POLICY_NAME, document);
22
+ return roles.length + rawRoles.length;
23
+ }
24
+ /** True for the nested stack of one data model (`data/PapyrusCmsApi/<Model>`), where the transformer puts the model's table role. */
25
+ export function isModelDataStack(stack, modelNames) {
26
+ return stack.node.scope?.node.id === "PapyrusCmsApi" && modelNames.has(stack.node.id);
27
+ }
@@ -0,0 +1,28 @@
1
+ import { Stack } from "aws-cdk-lib";
2
+ import { CfnRole } from "aws-cdk-lib/aws-iam";
3
+ import type { IConstruct } from "constructs";
4
+ import { appendInlinePolicy, appendInlinePolicyToRawRole, findAllOfType, findResourcesOfCfnType } from "./inline-policy";
5
+ import { SHARED_DENY_POLICY_NAME, sharedStackDenyPolicyDocument } from "./names";
6
+
7
+ /**
8
+ * The deny that closes the reverse direction of the isolation (docs/plans/multi-tenant-architecture.md, layer 3): a dedicated
9
+ * site's roles may not touch anything of the shared tier. Added as an inline policy, so no template gains a resource.
10
+ *
11
+ * `skip` names the stacks left alone. A dedicated backend with many models would pass CloudFormation's 2,500-resource limit
12
+ * if one change touched every per-model nested stack (Papyrus 5.99.0 rolled back that way, amplify/cost-tag-waves.ts), and a
13
+ * per-model data stack's roles can reach only their own table. Returns the number of roles that got the deny.
14
+ */
15
+ export function addSharedStackDeny(scope: IConstruct, skip: (stack: Stack) => boolean = () => false): number {
16
+ const document = sharedStackDenyPolicyDocument();
17
+ const roles = findAllOfType(scope, CfnRole).filter((role) => !skip(Stack.of(role)));
18
+ for (const role of roles) appendInlinePolicy(role, SHARED_DENY_POLICY_NAME, document);
19
+ // CDK writes the role of a custom resource provider as a raw resource, not a CfnRole.
20
+ const rawRoles = findResourcesOfCfnType(scope, "AWS::IAM::Role").filter((role) => !(role instanceof CfnRole) && !skip(Stack.of(role)));
21
+ for (const role of rawRoles) appendInlinePolicyToRawRole(role, SHARED_DENY_POLICY_NAME, document);
22
+ return roles.length + rawRoles.length;
23
+ }
24
+
25
+ /** True for the nested stack of one data model (`data/PapyrusCmsApi/<Model>`), where the transformer puts the model's table role. */
26
+ export function isModelDataStack(stack: Stack, modelNames: ReadonlySet<string>): boolean {
27
+ return stack.node.scope?.node.id === "PapyrusCmsApi" && modelNames.has(stack.node.id);
28
+ }
@@ -0,0 +1,53 @@
1
+ import { CfnResource, Lazy, Stack, Token } from "aws-cdk-lib";
2
+ /** Every L1 resource of a type under `scope`, in construct-tree order. */
3
+ export function findAllOfType(scope, type) {
4
+ return scope.node.findAll().filter((node) => node instanceof type);
5
+ }
6
+ /**
7
+ * Adds one inline policy to a role without adding a resource: `Policies` gains an entry, so the template holds exactly the
8
+ * resources it held before. Refuses a role whose `Policies` is not a plain list (a token cannot be extended safely).
9
+ */
10
+ export function appendInlinePolicy(role, policyName, policyDocument) {
11
+ const existing = role.policies;
12
+ if (existing !== undefined && (Token.isUnresolved(existing) || !Array.isArray(existing))) {
13
+ throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a plain list.`);
14
+ }
15
+ if (existing?.some((entry) => !Token.isUnresolved(entry) && entry.policyName === policyName)) {
16
+ throw new Error(`Role ${role.node.path} already has a ${policyName} policy.`);
17
+ }
18
+ role.policies = [...(existing ?? []), { policyName, policyDocument }];
19
+ }
20
+ /** Every resource of a CloudFormation type under `scope`, including the raw `CfnResource`s CDK writes for its own providers. */
21
+ export function findResourcesOfCfnType(scope, cfnType) {
22
+ return scope.node.findAll().filter((node) => CfnResource.isCfnResource(node) && node.cfnResourceType === cfnType);
23
+ }
24
+ /** Like `appendInlinePolicy`, for a raw `CfnResource` of type AWS::IAM::Role (a custom resource provider's role). */
25
+ export function appendInlinePolicyToRawRole(role, policyName, policyDocument) {
26
+ const previous = role.cfnProperties.Policies;
27
+ // A provider's own statements arrive lazily, so the list is read when the template is written.
28
+ role.addPropertyOverride("Policies", Lazy.any({
29
+ produce: () => {
30
+ const resolved = Stack.of(role).resolve(previous) ?? [];
31
+ if (!Array.isArray(resolved))
32
+ throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a list.`);
33
+ return [...resolved, { PolicyName: policyName, PolicyDocument: policyDocument }];
34
+ },
35
+ }));
36
+ }
37
+ /**
38
+ * The functions CDK and Amplify write for their own plumbing (custom resource providers, the branch linker, the secret fetcher, the
39
+ * table manager, log retention, bucket deployment). They run at deploy time only; every other function is a shared function that
40
+ * gets reserved concurrency.
41
+ */
42
+ export const INFRASTRUCTURE_FUNCTION_ID = /^(AWS[0-9a-f]{32}|framework-.*|LogRetention.*|Custom.*|BucketNotificationsHandler.*|Provider.*|Amplify(BranchLinker|SecretFetcher).*|TableManager.*)$/;
43
+ /** The construct id that names a function's owner: the L2 `Function`'s id, a provider's id for the raw function it writes, else the resource's own id. */
44
+ export function functionOwnerId(fn) {
45
+ return fn.node.id === "Resource" || fn.node.id === "Handler" ? (fn.node.scope?.node.id ?? fn.node.id) : fn.node.id;
46
+ }
47
+ export function isInfrastructureFunction(fn) {
48
+ return INFRASTRUCTURE_FUNCTION_ID.test(functionOwnerId(fn));
49
+ }
50
+ /** True for the construct id of a function CDK or Amplify writes for its own plumbing (see INFRASTRUCTURE_FUNCTION_ID). */
51
+ export function isInfrastructureConstructId(id) {
52
+ return INFRASTRUCTURE_FUNCTION_ID.test(id);
53
+ }
@@ -0,0 +1,65 @@
1
+ import { CfnResource, Lazy, Stack, Token } from "aws-cdk-lib";
2
+ import { CfnRole } from "aws-cdk-lib/aws-iam";
3
+ import type { IConstruct } from "constructs";
4
+
5
+ /** Every L1 resource of a type under `scope`, in construct-tree order. */
6
+ export function findAllOfType<T extends IConstruct>(scope: IConstruct, type: abstract new (...args: never[]) => T): T[] {
7
+ return scope.node.findAll().filter((node): node is T => node instanceof type);
8
+ }
9
+
10
+ /**
11
+ * Adds one inline policy to a role without adding a resource: `Policies` gains an entry, so the template holds exactly the
12
+ * resources it held before. Refuses a role whose `Policies` is not a plain list (a token cannot be extended safely).
13
+ */
14
+ export function appendInlinePolicy(role: CfnRole, policyName: string, policyDocument: object): void {
15
+ const existing = role.policies;
16
+ if (existing !== undefined && (Token.isUnresolved(existing) || !Array.isArray(existing))) {
17
+ throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a plain list.`);
18
+ }
19
+ if (existing?.some((entry) => !Token.isUnresolved(entry) && (entry as { policyName?: string }).policyName === policyName)) {
20
+ throw new Error(`Role ${role.node.path} already has a ${policyName} policy.`);
21
+ }
22
+ role.policies = [...(existing ?? []), { policyName, policyDocument }];
23
+ }
24
+
25
+ /** Every resource of a CloudFormation type under `scope`, including the raw `CfnResource`s CDK writes for its own providers. */
26
+ export function findResourcesOfCfnType(scope: IConstruct, cfnType: string): CfnResource[] {
27
+ return scope.node.findAll().filter((node): node is CfnResource => CfnResource.isCfnResource(node) && node.cfnResourceType === cfnType);
28
+ }
29
+
30
+ /** Like `appendInlinePolicy`, for a raw `CfnResource` of type AWS::IAM::Role (a custom resource provider's role). */
31
+ export function appendInlinePolicyToRawRole(role: CfnResource, policyName: string, policyDocument: object): void {
32
+ const previous = (role as unknown as { cfnProperties: Record<string, unknown> }).cfnProperties.Policies;
33
+ // A provider's own statements arrive lazily, so the list is read when the template is written.
34
+ role.addPropertyOverride(
35
+ "Policies",
36
+ Lazy.any({
37
+ produce: () => {
38
+ const resolved = Stack.of(role).resolve(previous) ?? [];
39
+ if (!Array.isArray(resolved)) throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a list.`);
40
+ return [...resolved, { PolicyName: policyName, PolicyDocument: policyDocument }];
41
+ },
42
+ }),
43
+ );
44
+ }
45
+
46
+ /**
47
+ * The functions CDK and Amplify write for their own plumbing (custom resource providers, the branch linker, the secret fetcher, the
48
+ * table manager, log retention, bucket deployment). They run at deploy time only; every other function is a shared function that
49
+ * gets reserved concurrency.
50
+ */
51
+ export const INFRASTRUCTURE_FUNCTION_ID = /^(AWS[0-9a-f]{32}|framework-.*|LogRetention.*|Custom.*|BucketNotificationsHandler.*|Provider.*|Amplify(BranchLinker|SecretFetcher).*|TableManager.*)$/;
52
+
53
+ /** The construct id that names a function's owner: the L2 `Function`'s id, a provider's id for the raw function it writes, else the resource's own id. */
54
+ export function functionOwnerId(fn: CfnResource): string {
55
+ return fn.node.id === "Resource" || fn.node.id === "Handler" ? (fn.node.scope?.node.id ?? fn.node.id) : fn.node.id;
56
+ }
57
+
58
+ export function isInfrastructureFunction(fn: CfnResource): boolean {
59
+ return INFRASTRUCTURE_FUNCTION_ID.test(functionOwnerId(fn));
60
+ }
61
+
62
+ /** True for the construct id of a function CDK or Amplify writes for its own plumbing (see INFRASTRUCTURE_FUNCTION_ID). */
63
+ export function isInfrastructureConstructId(id: string): boolean {
64
+ return INFRASTRUCTURE_FUNCTION_ID.test(id);
65
+ }