@friggframework/devtools 2.0.0-next.128 → 2.0.0-next.129

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.
@@ -32,6 +32,7 @@ const {
32
32
  const {
33
33
  nestedNodeModulesExcludes,
34
34
  } = require('../shared/utilities/nested-node-modules');
35
+ const { queueArnFromUrl } = require('../shared/utilities/sqs-queue-arn');
35
36
  const { bundledPrismaEngineExcludes } = require('../shared/lambda-architectures');
36
37
  const {
37
38
  INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
@@ -622,6 +623,20 @@ class IntegrationBuilder extends InfrastructureBuilder {
622
623
  appDefinition
623
624
  );
624
625
 
626
+ // The base role grants these only on the queues the stack names, and
627
+ // the queue worker sends, looks up and defers rate-limited messages
628
+ // on this queue too (ADR-049).
629
+ result.iamStatements.push({
630
+ Effect: 'Allow',
631
+ Action: [
632
+ 'sqs:SendMessage',
633
+ 'sqs:GetQueueUrl',
634
+ 'sqs:GetQueueAttributes',
635
+ 'sqs:ChangeMessageVisibility',
636
+ ],
637
+ Resource: [queueArnFromUrl(decision.physicalId)],
638
+ });
639
+
625
640
  console.log(` ✓ Using external queue: ${decision.physicalId}`);
626
641
  }
627
642
 
@@ -11,6 +11,8 @@ const {
11
11
  const { IntegrationBuilder } = require('./integration-builder');
12
12
  const { ValidationResult } = require('../shared/base-builder');
13
13
  const { itBundlesOnlyTheTargetPrismaEngine } = require('../../__tests__/helpers/bundled-prisma-engine-excludes');
14
+ const { BuilderOrchestrator } = require('../shared/builder-orchestrator');
15
+ const { SchedulerBuilder } = require('../scheduler/scheduler-builder');
14
16
 
15
17
  describe('IntegrationBuilder', () => {
16
18
  let integrationBuilder;
@@ -260,6 +262,81 @@ describe('IntegrationBuilder', () => {
260
262
  ).toBeUndefined();
261
263
  });
262
264
 
265
+ it('lets the functions send to, look up and defer messages on an external queue', async () => {
266
+ const result = await integrationBuilder.build(
267
+ {
268
+ integrations: [
269
+ {
270
+ Definition: { name: 'test' },
271
+ ownership: { queue: 'external' },
272
+ queue: {
273
+ url: 'https://sqs.us-east-1.amazonaws.com/123456789012/test-queue',
274
+ },
275
+ },
276
+ ],
277
+ },
278
+ {}
279
+ );
280
+
281
+ expect(result.iamStatements).toEqual([
282
+ {
283
+ Effect: 'Allow',
284
+ Action: [
285
+ 'sqs:SendMessage',
286
+ 'sqs:GetQueueUrl',
287
+ 'sqs:GetQueueAttributes',
288
+ 'sqs:ChangeMessageVisibility',
289
+ ],
290
+ Resource: [
291
+ {
292
+ 'Fn::Sub':
293
+ 'arn:${AWS::Partition}:sqs:us-east-1:123456789012:test-queue',
294
+ },
295
+ ],
296
+ },
297
+ ]);
298
+ });
299
+
300
+ it('adds no queue statement for a queue the stack creates, because the base role covers it', async () => {
301
+ const result = await integrationBuilder.build(
302
+ { integrations: [{ Definition: { name: 'test' } }] },
303
+ {}
304
+ );
305
+
306
+ expect(result.iamStatements).toEqual([]);
307
+ });
308
+
309
+ it('adds no resource, function or env var when no module declares rateLimit', async () => {
310
+ class Api {}
311
+ const { merged } = await new BuilderOrchestrator([
312
+ new IntegrationBuilder(),
313
+ new SchedulerBuilder(),
314
+ ]).buildAll({
315
+ integrations: [
316
+ {
317
+ Definition: {
318
+ name: 'test',
319
+ modules: { crm: { definition: { API: Api } } },
320
+ },
321
+ },
322
+ ],
323
+ });
324
+ const before = await integrationBuilder.build(
325
+ { integrations: [{ Definition: { name: 'test' } }] },
326
+ {}
327
+ );
328
+
329
+ expect(Object.keys(merged.resources)).toEqual(
330
+ Object.keys(before.resources)
331
+ );
332
+ expect(Object.keys(merged.functions)).toEqual(
333
+ Object.keys(before.functions)
334
+ );
335
+ expect(Object.keys(merged.environment)).toEqual(
336
+ Object.keys(before.environment)
337
+ );
338
+ });
339
+
263
340
  it('should create queue worker function', async () => {
264
341
  const appDefinition = {
265
342
  integrations: [
@@ -13,11 +13,18 @@
13
13
  */
14
14
 
15
15
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
16
+ const { ResourceOwnership } = require('../shared/types/resource-ownership');
16
17
  const {
17
18
  isScopedEnvironmentActive,
18
19
  getIntegrationFunctionNames,
19
20
  getAdminFunctionNames,
20
21
  } = require('../shared/function-environments');
22
+ const { queueArnFromUrl } = require('../shared/utilities/sqs-queue-arn');
23
+
24
+ const declaresRateLimit = (integration) =>
25
+ Object.values(integration?.Definition?.modules ?? {}).some((module) =>
26
+ Boolean(module?.definition?.API?.rateLimit)
27
+ );
21
28
 
22
29
  class SchedulerBuilder extends InfrastructureBuilder {
23
30
  constructor() {
@@ -37,7 +44,8 @@ class SchedulerBuilder extends InfrastructureBuilder {
37
44
  return appDefinition.integrations.some(
38
45
  (integration) =>
39
46
  integration?.Definition?.webhooks?.enabled === true ||
40
- integration?.Definition?.webhooks === true
47
+ integration?.Definition?.webhooks === true ||
48
+ declaresRateLimit(integration)
41
49
  );
42
50
  }
43
51
 
@@ -107,7 +115,11 @@ class SchedulerBuilder extends InfrastructureBuilder {
107
115
  if (Array.isArray(appDefinition.integrations)) {
108
116
  appDefinition.integrations.forEach((integration) => {
109
117
  const integrationName = integration?.Definition?.name;
110
- if (integrationName) {
118
+ if (
119
+ integration.ownership?.queue === ResourceOwnership.EXTERNAL
120
+ ) {
121
+ queueArns.push(queueArnFromUrl(integration.queue.url));
122
+ } else if (integrationName) {
111
123
  const capitalizedName =
112
124
  integrationName.charAt(0).toUpperCase() +
113
125
  integrationName.slice(1);
@@ -38,6 +38,61 @@ describe('SchedulerBuilder', () => {
38
38
  ).toBe(true);
39
39
  });
40
40
 
41
+ it('runs when any module declares a rate limit', () => {
42
+ class Api {
43
+ static rateLimit = { minRetryAfterMs: 1_000 };
44
+ }
45
+ expect(
46
+ schedulerBuilder.shouldExecute({
47
+ integrations: [
48
+ { Definition: { name: 'a' } },
49
+ {
50
+ Definition: {
51
+ name: 'b',
52
+ modules: { crm: { definition: { API: Api } } },
53
+ },
54
+ },
55
+ ],
56
+ })
57
+ ).toBe(true);
58
+ });
59
+
60
+ it('skips a module whose API declares no rate limit', () => {
61
+ class Api {}
62
+ expect(
63
+ schedulerBuilder.shouldExecute({
64
+ integrations: [
65
+ {
66
+ Definition: {
67
+ name: 'a',
68
+ modules: { crm: { definition: { API: Api } } },
69
+ },
70
+ },
71
+ ],
72
+ })
73
+ ).toBe(false);
74
+ });
75
+
76
+ it.each([
77
+ ['no modules', { name: 'a' }],
78
+ ['an empty modules object', { name: 'a', modules: {} }],
79
+ [
80
+ 'a module with no definition',
81
+ { name: 'a', modules: { crm: {} } },
82
+ ],
83
+ ['a null module', { name: 'a', modules: { crm: null } }],
84
+ [
85
+ 'a definition with no API',
86
+ { name: 'a', modules: { crm: { definition: {} } } },
87
+ ],
88
+ ])('skips an integration with %s', (_label, Definition) => {
89
+ expect(
90
+ schedulerBuilder.shouldExecute({
91
+ integrations: [{ Definition }],
92
+ })
93
+ ).toBe(false);
94
+ });
95
+
41
96
  it('skips otherwise', () => {
42
97
  expect(
43
98
  schedulerBuilder.shouldExecute({
@@ -115,4 +170,51 @@ describe('SchedulerBuilder', () => {
115
170
  expect(result.functionEnvironments).toBeUndefined();
116
171
  });
117
172
  });
173
+
174
+ describe('build() execution role', () => {
175
+ const sendableQueues = (result) =>
176
+ result.resources.SchedulerExecutionRole.Properties.Policies[0]
177
+ .PolicyDocument.Statement[0].Resource;
178
+
179
+ it('allows sending to a queue the stack creates', async () => {
180
+ const result = await schedulerBuilder.build(
181
+ {
182
+ scheduler: { enable: true },
183
+ integrations: [{ Definition: { name: 'hubspot' } }],
184
+ },
185
+ {}
186
+ );
187
+
188
+ expect(sendableQueues(result)).toEqual([
189
+ { 'Fn::GetAtt': ['HubspotQueue', 'Arn'] },
190
+ ]);
191
+ });
192
+
193
+ it('allows sending to an external queue by its ARN, not a resource the stack lacks', async () => {
194
+ const result = await schedulerBuilder.build(
195
+ {
196
+ scheduler: { enable: true },
197
+ integrations: [
198
+ { Definition: { name: 'hubspot' } },
199
+ {
200
+ Definition: { name: 'salesforce' },
201
+ ownership: { queue: 'external' },
202
+ queue: {
203
+ url: 'https://sqs.us-east-1.amazonaws.com/123456789012/acme-salesforce',
204
+ },
205
+ },
206
+ ],
207
+ },
208
+ {}
209
+ );
210
+
211
+ expect(sendableQueues(result)).toEqual([
212
+ { 'Fn::GetAtt': ['HubspotQueue', 'Arn'] },
213
+ {
214
+ 'Fn::Sub':
215
+ 'arn:${AWS::Partition}:sqs:us-east-1:123456789012:acme-salesforce',
216
+ },
217
+ ]);
218
+ });
219
+ });
118
220
  });
@@ -204,6 +204,7 @@ function createBaseDefinition(
204
204
  'sqs:SendMessageBatch',
205
205
  'sqs:GetQueueUrl',
206
206
  'sqs:GetQueueAttributes',
207
+ 'sqs:ChangeMessageVisibility',
207
208
  ],
208
209
  Resource: [
209
210
  { 'Fn::GetAtt': ['InternalErrorQueue', 'Arn'] },
@@ -169,6 +169,18 @@ describe('Base Definition Factory', () => {
169
169
  expect(sqsPermission).toBeDefined();
170
170
  });
171
171
 
172
+ it('should let a function extend the visibility timeout of a message on an integration queue', () => {
173
+ const result = createBaseDefinition({}, {}, {});
174
+
175
+ const sqsPermission = result.provider.iamRoleStatements.find(
176
+ (stmt) => stmt.Action.includes('sqs:SendMessage')
177
+ );
178
+ expect(sqsPermission.Action).toContain(
179
+ 'sqs:ChangeMessageVisibility'
180
+ );
181
+ expect(JSON.stringify(sqsPermission.Resource)).toContain('*Queue');
182
+ });
183
+
172
184
  it('should include required plugins', () => {
173
185
  const result = createBaseDefinition({}, {}, {});
174
186
 
@@ -0,0 +1,59 @@
1
+ const LEGACY_US_EAST_1_HOST = 'queue.amazonaws.com';
2
+ const AWS_DOMAIN = /\.amazonaws\.com(\.cn)?$/;
3
+
4
+ function regionOfQueueHost(hostname) {
5
+ if (hostname === LEGACY_US_EAST_1_HOST) return 'us-east-1';
6
+ if (!AWS_DOMAIN.test(hostname)) return '${AWS::Region}';
7
+ const labels = hostname.split('.');
8
+ const sqsAt = labels.indexOf('sqs');
9
+ if (sqsAt !== -1 && labels[sqsAt + 1]) return labels[sqsAt + 1];
10
+ if (labels[1] === 'queue') return labels[0];
11
+ return '${AWS::Region}';
12
+ }
13
+
14
+ function parseQueueUrl(queueUrl) {
15
+ if (typeof queueUrl !== 'string') return null;
16
+ try {
17
+ const { hostname, pathname } = new URL(queueUrl);
18
+ const [accountId, queueName] = pathname.split('/').filter(Boolean);
19
+ return accountId && queueName
20
+ ? { hostname, accountId, queueName }
21
+ : null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * The ARN of the SQS queue at `queueUrl`, for an IAM policy. The partition is
29
+ * always the stack's. A value that is not a URL yet (a Serverless variable or
30
+ * a CloudFormation function) resolves after the build, so CloudFormation
31
+ * splits it, in the stack's region.
32
+ */
33
+ function queueArnFromUrl(queueUrl) {
34
+ const parsed = parseQueueUrl(queueUrl);
35
+ if (parsed) {
36
+ const region = regionOfQueueHost(parsed.hostname);
37
+ return {
38
+ 'Fn::Sub': `arn:\${AWS::Partition}:sqs:${region}:${parsed.accountId}:${parsed.queueName}`,
39
+ };
40
+ }
41
+ const part = (index) => ({
42
+ 'Fn::Select': [index, { 'Fn::Split': ['/', queueUrl] }],
43
+ });
44
+ return {
45
+ 'Fn::Join': [
46
+ ':',
47
+ [
48
+ 'arn',
49
+ { Ref: 'AWS::Partition' },
50
+ 'sqs',
51
+ { Ref: 'AWS::Region' },
52
+ part(3),
53
+ part(4),
54
+ ],
55
+ ],
56
+ };
57
+ }
58
+
59
+ module.exports = { queueArnFromUrl };
@@ -0,0 +1,70 @@
1
+ const { queueArnFromUrl } = require('./sqs-queue-arn');
2
+
3
+ const ACCOUNT = '123456789012';
4
+ const NAME = 'acme-salesforce';
5
+ const subArn = (region) => ({
6
+ 'Fn::Sub': `arn:\${AWS::Partition}:sqs:${region}:${ACCOUNT}:${NAME}`,
7
+ });
8
+
9
+ describe('queueArnFromUrl', () => {
10
+ it.each([
11
+ [
12
+ 'a regional endpoint',
13
+ `https://sqs.eu-west-1.amazonaws.com`,
14
+ 'eu-west-1',
15
+ ],
16
+ [
17
+ 'a China endpoint',
18
+ `https://sqs.cn-north-1.amazonaws.com.cn`,
19
+ 'cn-north-1',
20
+ ],
21
+ [
22
+ 'a legacy regional endpoint',
23
+ `https://eu-west-1.queue.amazonaws.com`,
24
+ 'eu-west-1',
25
+ ],
26
+ [
27
+ 'the legacy us-east-1 endpoint',
28
+ `https://queue.amazonaws.com`,
29
+ 'us-east-1',
30
+ ],
31
+ ])(
32
+ 'reads the region of %s and leaves the partition to the stack',
33
+ (_label, origin, region) => {
34
+ expect(queueArnFromUrl(`${origin}/${ACCOUNT}/${NAME}`)).toEqual(
35
+ subArn(region)
36
+ );
37
+ }
38
+ );
39
+
40
+ it('uses the stack region for a host it does not know', () => {
41
+ expect(
42
+ queueArnFromUrl(`https://sqs.internal.example/${ACCOUNT}/${NAME}`)
43
+ ).toEqual(subArn('${AWS::Region}'));
44
+ });
45
+
46
+ it.each([
47
+ ['a Serverless variable', '${ssm:/acme/queue-url}'],
48
+ ['a CloudFormation function', { 'Fn::ImportValue': 'AcmeQueueUrl' }],
49
+ ])(
50
+ 'splits %s in CloudFormation, because it resolves after the build',
51
+ (_label, queueUrl) => {
52
+ const part = (index) => ({
53
+ 'Fn::Select': [index, { 'Fn::Split': ['/', queueUrl] }],
54
+ });
55
+ expect(queueArnFromUrl(queueUrl)).toEqual({
56
+ 'Fn::Join': [
57
+ ':',
58
+ [
59
+ 'arn',
60
+ { Ref: 'AWS::Partition' },
61
+ 'sqs',
62
+ { Ref: 'AWS::Region' },
63
+ part(3),
64
+ part(4),
65
+ ],
66
+ ],
67
+ });
68
+ }
69
+ );
70
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0-next.128",
4
+ "version": "2.0.0-next.129",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
@@ -28,9 +28,9 @@
28
28
  "@babel/eslint-parser": "^7.18.9",
29
29
  "@babel/parser": "^7.25.3",
30
30
  "@babel/traverse": "^7.25.3",
31
- "@friggframework/core": "2.0.0-next.128",
32
- "@friggframework/schemas": "2.0.0-next.128",
33
- "@friggframework/test": "2.0.0-next.128",
31
+ "@friggframework/core": "2.0.0-next.129",
32
+ "@friggframework/schemas": "2.0.0-next.129",
33
+ "@friggframework/test": "2.0.0-next.129",
34
34
  "@hapi/boom": "^10.0.1",
35
35
  "@inquirer/prompts": "^5.3.8",
36
36
  "axios": "^1.18.0",
@@ -58,8 +58,8 @@
58
58
  "validate-npm-package-name": "^5.0.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@friggframework/eslint-config": "2.0.0-next.128",
62
- "@friggframework/prettier-config": "2.0.0-next.128",
61
+ "@friggframework/eslint-config": "2.0.0-next.129",
62
+ "@friggframework/prettier-config": "2.0.0-next.129",
63
63
  "aws-sdk-client-mock": "^4.1.0",
64
64
  "aws-sdk-client-mock-jest": "^4.1.0",
65
65
  "jest": "^30.1.3",
@@ -91,5 +91,5 @@
91
91
  "publishConfig": {
92
92
  "access": "public"
93
93
  },
94
- "gitHead": "c116a4803d205e5b54a59d56d8b163ab43d66205"
94
+ "gitHead": "4326b2498dcb1627e43fceada462b384b722da52"
95
95
  }