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

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 (32) hide show
  1. package/infrastructure/README.md +32 -5
  2. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +39 -0
  3. package/infrastructure/__tests__/management-api-gateway-routes.test.js +3 -0
  4. package/infrastructure/__tests__/postgres-config.test.js +3 -0
  5. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +3 -0
  6. package/infrastructure/__tests__/scoped-environment.test.js +3 -0
  7. package/infrastructure/__tests__/ssm-preload-node-options.test.js +3 -0
  8. package/infrastructure/__tests__/template-generation.test.js +3 -0
  9. package/infrastructure/app-definition-schema-contract.test.js +5 -0
  10. package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -0
  11. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +22 -6
  12. package/infrastructure/domains/database/migration-builder.js +21 -2
  13. package/infrastructure/domains/database/migration-builder.test.js +61 -6
  14. package/infrastructure/domains/database/migration-engines.js +93 -0
  15. package/infrastructure/domains/database/migration-engines.test.js +142 -0
  16. package/infrastructure/domains/integration/integration-builder.js +2 -0
  17. package/infrastructure/domains/integration/integration-builder.test.js +22 -6
  18. package/infrastructure/domains/shared/environment-builder.js +31 -5
  19. package/infrastructure/domains/shared/environment-builder.test.js +93 -7
  20. package/infrastructure/domains/shared/lambda-architectures.js +113 -0
  21. package/infrastructure/domains/shared/lambda-architectures.test.js +164 -0
  22. package/infrastructure/domains/shared/utilities/base-definition-factory.js +13 -1
  23. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +51 -4
  24. package/infrastructure/domains/shared/utilities/nested-node-modules.js +6 -5
  25. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +20 -26
  26. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
  27. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
  28. package/infrastructure/infrastructure-composer.js +12 -1
  29. package/infrastructure/infrastructure-composer.test.js +71 -0
  30. package/infrastructure/scripts/build-prisma-layer.js +136 -50
  31. package/infrastructure/scripts/build-prisma-layer.test.js +100 -0
  32. package/package.json +9 -9
@@ -0,0 +1,164 @@
1
+ const micromatch = require('micromatch');
2
+ const {
3
+ LAMBDA_ARCHITECTURES,
4
+ resolveLambdaArchitecture,
5
+ prismaEngineFileNames,
6
+ foreignPrismaEngineExcludes,
7
+ bundledPrismaEngineExcludes,
8
+ } = require('./lambda-architectures');
9
+
10
+ describe('resolveLambdaArchitecture()', () => {
11
+ it('resolves to x86_64 with the rhel engine when the key is unset', () => {
12
+ expect(resolveLambdaArchitecture({})).toEqual({
13
+ name: 'x86_64',
14
+ prismaBinaryTarget: 'rhel-openssl-3.0.x',
15
+ explicit: false,
16
+ });
17
+ });
18
+
19
+ it('resolves an explicit x86_64', () => {
20
+ expect(resolveLambdaArchitecture({ architecture: 'x86_64' })).toEqual({
21
+ name: 'x86_64',
22
+ prismaBinaryTarget: 'rhel-openssl-3.0.x',
23
+ explicit: true,
24
+ });
25
+ });
26
+
27
+ it('resolves arm64 to the linux-arm64 engine', () => {
28
+ expect(resolveLambdaArchitecture({ architecture: 'arm64' })).toEqual({
29
+ name: 'arm64',
30
+ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x',
31
+ explicit: true,
32
+ });
33
+ });
34
+
35
+ it('throws on an unknown architecture, naming the accepted ones', () => {
36
+ expect(() =>
37
+ resolveLambdaArchitecture({ architecture: 'aarch64' })
38
+ ).toThrow(/aarch64.*x86_64.*arm64/);
39
+ });
40
+
41
+ it('uses the AWS architecture names as registry keys', () => {
42
+ expect(Object.keys(LAMBDA_ARCHITECTURES)).toEqual(['x86_64', 'arm64']);
43
+ });
44
+ });
45
+
46
+ describe('prismaEngineFileNames()', () => {
47
+ it('names the schema engine and the query engine library the migrate CLI needs for a target', () => {
48
+ expect(prismaEngineFileNames('linux-arm64-openssl-3.0.x')).toEqual({
49
+ schemaEngine: 'schema-engine-linux-arm64-openssl-3.0.x',
50
+ queryEngineLibrary: 'libquery_engine-linux-arm64-openssl-3.0.x.so.node',
51
+ });
52
+ });
53
+ });
54
+
55
+ describe('foreignPrismaEngineExcludes()', () => {
56
+ const matches = (name, filePath) =>
57
+ micromatch([filePath], foreignPrismaEngineExcludes(name), {
58
+ dot: true,
59
+ }).length > 0;
60
+
61
+ const foreignEngineFiles = {
62
+ x86_64: [
63
+ 'node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node',
64
+ 'node_modules/@prisma/engines/schema-engine-darwin-arm64',
65
+ 'node_modules/.prisma/client/query_engine-windows.dll.node',
66
+ 'node_modules/@prisma/engines/query-engine-debian-openssl-3.0.x',
67
+ 'node_modules/.prisma/client/libquery_engine-debian-openssl-3.0.x.so.node',
68
+ 'node_modules/@prisma/engines/libquery_engine-linux-musl-openssl-3.0.x.so.node',
69
+ 'node_modules/@prisma/engines/schema-engine-linux-arm64-openssl-3.0.x',
70
+ 'node_modules/@prisma/engines/libquery_engine-linux-arm64-openssl-3.0.x.so.node',
71
+ ],
72
+ arm64: [
73
+ 'node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node',
74
+ 'node_modules/.prisma/client/query_engine-windows.dll.node',
75
+ 'node_modules/@prisma/engines/libquery_engine-linux-musl-openssl-3.0.x.so.node',
76
+ 'node_modules/@prisma/engines/schema-engine-rhel-openssl-3.0.x',
77
+ 'node_modules/@prisma/engines/libquery_engine-rhel-openssl-3.0.x.so.node',
78
+ ],
79
+ };
80
+
81
+ const targetEngineFiles = {
82
+ x86_64: [
83
+ 'node_modules/@prisma/engines/schema-engine-rhel-openssl-3.0.x',
84
+ 'node_modules/@prisma/engines/libquery_engine-rhel-openssl-3.0.x.so.node',
85
+ ],
86
+ arm64: [
87
+ 'node_modules/@prisma/engines/schema-engine-linux-arm64-openssl-3.0.x',
88
+ 'node_modules/@prisma/engines/libquery_engine-linux-arm64-openssl-3.0.x.so.node',
89
+ ],
90
+ };
91
+
92
+ const nonEngineFiles = [
93
+ 'node_modules/is-windows/index.js',
94
+ 'node_modules/is-windows/package.json',
95
+ 'node_modules/darwin-utils/lib/index.js',
96
+ 'node_modules/some-pkg/lib/debian-release.js',
97
+ 'node_modules/some-pkg/linux-musl-detect.js',
98
+ 'node_modules/@prisma/engines/query_engine_bg.wasm',
99
+ 'node_modules/.prisma/client/query_engine_bg.js',
100
+ 'node_modules/some-pkg/dist/linux-arm64-notes.js',
101
+ 'src/handlers/windows-handler.js',
102
+ ];
103
+
104
+ it.each(['x86_64', 'arm64'])(
105
+ 'matches every foreign engine file for %s',
106
+ (name) => {
107
+ foreignEngineFiles[name].forEach((file) =>
108
+ expect({ name, file, hit: matches(name, file) }).toEqual({
109
+ name,
110
+ file,
111
+ hit: true,
112
+ })
113
+ );
114
+ }
115
+ );
116
+
117
+ it.each(['x86_64', 'arm64'])(
118
+ 'keeps the engine files of the %s target',
119
+ (name) => {
120
+ targetEngineFiles[name].forEach((file) =>
121
+ expect({ file, hit: matches(name, file) }).toEqual({
122
+ file,
123
+ hit: false,
124
+ })
125
+ );
126
+ }
127
+ );
128
+
129
+ it.each(['x86_64', 'arm64'])(
130
+ 'keeps runtime files that only share a platform word with an engine for %s',
131
+ (name) => {
132
+ nonEngineFiles.forEach((file) =>
133
+ expect({ file, hit: matches(name, file) }).toEqual({
134
+ file,
135
+ hit: false,
136
+ })
137
+ );
138
+ }
139
+ );
140
+
141
+ it('never uses negation', () => {
142
+ ['x86_64', 'arm64'].forEach((name) =>
143
+ foreignPrismaEngineExcludes(name).forEach((pattern) =>
144
+ expect(pattern.startsWith('!')).toBe(false)
145
+ )
146
+ );
147
+ });
148
+ });
149
+
150
+ describe('bundledPrismaEngineExcludes()', () => {
151
+ it('adds nothing when the Prisma layer carries the engines', () => {
152
+ expect(bundledPrismaEngineExcludes({ architecture: 'arm64' }, true)).toEqual([]);
153
+ });
154
+
155
+ it.each([
156
+ [{}, 'x86_64'],
157
+ [{ architecture: 'x86_64' }, 'x86_64'],
158
+ [{ architecture: 'arm64' }, 'arm64'],
159
+ ])('with the layer off, excludes the engines %j does not load', (appDefinition, name) => {
160
+ expect(bundledPrismaEngineExcludes(appDefinition, false)).toEqual(
161
+ foreignPrismaEngineExcludes(name)
162
+ );
163
+ });
164
+ });
@@ -10,6 +10,10 @@
10
10
  const { buildEnvironment } = require('../environment-builder');
11
11
  const { nestedNodeModulesExcludes } = require('./nested-node-modules');
12
12
  const { buildLoggingProviderConfig } = require('./logging-config');
13
+ const {
14
+ resolveLambdaArchitecture,
15
+ bundledPrismaEngineExcludes,
16
+ } = require('../lambda-architectures');
13
17
 
14
18
  /**
15
19
  * Create base serverless definition with core functions and resources
@@ -35,6 +39,8 @@ function createBaseDefinition(
35
39
  ) {
36
40
  const region = process.env.AWS_REGION || 'us-east-1';
37
41
  const loggingConfig = buildLoggingProviderConfig(AppDefinition.logging);
42
+ const architecture = resolveLambdaArchitecture(AppDefinition);
43
+ const bundledEngineExcludes = bundledPrismaEngineExcludes(AppDefinition, usePrismaLayer);
38
44
 
39
45
  // Package config for handlers that skip esbuild (need node_modules dependencies)
40
46
  // Include backend src/ and index.js since handlers load the app definition
@@ -54,6 +60,7 @@ function createBaseDefinition(
54
60
  'node_modules/prisma/**',
55
61
  'node_modules/@friggframework/core/generated/**',
56
62
  ] : []),
63
+ ...bundledEngineExcludes,
57
64
 
58
65
  // Exclude AWS SDK (provided by Lambda runtime)
59
66
  'node_modules/aws-sdk/**',
@@ -127,6 +134,7 @@ function createBaseDefinition(
127
134
  'node_modules/prisma/**',
128
135
  'node_modules/@friggframework/core/generated/**',
129
136
  ] : []),
137
+ ...bundledEngineExcludes,
130
138
 
131
139
  // Exclude nested node_modules from symlinked frigg packages (for npm link development)
132
140
  'node_modules/@friggframework/core/node_modules/**',
@@ -178,6 +186,7 @@ function createBaseDefinition(
178
186
  name: AppDefinition.provider || 'aws',
179
187
  ...(process.env.AWS_PROFILE && { profile: process.env.AWS_PROFILE }),
180
188
  runtime: 'nodejs22.x', // Node.js 22.x (latest Lambda runtime with AWS SDK v3)
189
+ ...(architecture.explicit && { architecture: architecture.name }),
181
190
  timeout: 29, // Set to 29s to give buffer before API Gateway's 30s timeout
182
191
  region,
183
192
  stage: '${opt:stage}',
@@ -341,8 +350,11 @@ function createBaseDefinition(
341
350
  prisma: {
342
351
  path: 'layers/prisma',
343
352
  name: '${self:service}-prisma-${sls:stage}',
344
- description: 'Prisma runtime client only (NO CLI) with rhel-openssl-3.0.x binaries (~10-15MB). CLI packaged separately in dbMigrate function.',
353
+ description: 'Prisma runtime client only (NO CLI) with the query engine for the deployed Lambda architecture (~10-15MB). CLI packaged separately in dbMigrate function.',
345
354
  compatibleRuntimes: ['nodejs20.x', 'nodejs22.x'],
355
+ ...(architecture.explicit && {
356
+ compatibleArchitectures: [architecture.name],
357
+ }),
346
358
  retain: false,
347
359
  },
348
360
  } : {},
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  const { createBaseDefinition } = require('./base-definition-factory');
8
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../../__tests__/helpers/bundled-prisma-engine-excludes');
8
9
 
9
10
  describe('Base Definition Factory', () => {
10
11
  beforeEach(() => {
@@ -323,19 +324,65 @@ describe('Base Definition Factory', () => {
323
324
  });
324
325
 
325
326
 
326
- describe('nested node_modules (lambda.keepNestedNodeModules)', () => {
327
+ describe('Lambda architecture (architecture)', () => {
327
328
  const build = (appDefinition) => createBaseDefinition(appDefinition, {}, {}, true);
328
329
 
329
- it('excludes every nested node_modules from the core function packages by default', () => {
330
+ it('adds no architecture fields when the key is unset, so existing templates do not change', () => {
330
331
  const result = build({ name: 'test-app' });
331
332
 
333
+ expect(result.provider.architecture).toBeUndefined();
334
+ expect(result.layers.prisma.compatibleArchitectures).toBeUndefined();
335
+ });
336
+
337
+ it.each(['x86_64', 'arm64'])(
338
+ 'sets provider.architecture and the layer compatibleArchitectures to %s when set',
339
+ (architecture) => {
340
+ const result = build({ name: 'test-app', architecture });
341
+
342
+ expect(result.provider.architecture).toBe(architecture);
343
+ expect(result.layers.prisma.compatibleArchitectures).toEqual([architecture]);
344
+ }
345
+ );
346
+
347
+ it('describes the layer without naming an engine, since the engine follows the architecture', () => {
348
+ const result = build({ name: 'test-app' });
349
+
350
+ expect(result.layers.prisma.description).not.toContain('rhel');
351
+ });
352
+
353
+ it('rejects an architecture the registry does not know', () => {
354
+ expect(() => build({ name: 'test-app', architecture: 'aarch64' })).toThrow(
355
+ /aarch64/
356
+ );
357
+ });
358
+ });
359
+
360
+ describe('Lambda architecture with usePrismaLambdaLayer=false', () => {
361
+ const functionsOf = (usePrismaLayer, architecture) => {
362
+ const result = createBaseDefinition(
363
+ { name: 'test-app', ...(architecture && { architecture }) },
364
+ {},
365
+ {},
366
+ usePrismaLayer
367
+ );
368
+ return Object.values(result.functions);
369
+ };
370
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
371
+ });
372
+
373
+ describe('nested node_modules (lambda.keepNestedNodeModules)', () => {
374
+ const build = (appDefinition) => createBaseDefinition(appDefinition, {}, {}, true);
375
+
376
+ it('excludes every nested node_modules from the core function packages when the app opts out', () => {
377
+ const result = build({ name: 'test-app', lambda: { keepNestedNodeModules: false } });
378
+
332
379
  for (const fn of ['auth', 'user', 'health']) {
333
380
  expect(result.functions[fn].package.exclude).toContain('node_modules/**/node_modules/**');
334
381
  }
335
382
  });
336
383
 
337
- it('keeps nested node_modules when the app opts in, still excluding nested Frigg, AWS SDK and Prisma copies', () => {
338
- const result = build({ name: 'test-app', lambda: { keepNestedNodeModules: true } });
384
+ it('keeps nested node_modules by default, still excluding nested Frigg, AWS SDK and Prisma copies', () => {
385
+ const result = build({ name: 'test-app' });
339
386
 
340
387
  for (const fn of ['auth', 'user', 'health']) {
341
388
  const { exclude } = result.functions[fn].package;
@@ -6,10 +6,11 @@
6
6
  * npm nests a package only when the root copy cannot satisfy the dependant's
7
7
  * range. Excluding every nested node_modules from a Lambda package therefore
8
8
  * rewires module resolution to whatever is hoisted, and drops a package
9
- * outright when the root copy is dev-only. Apps opt in to shipping the tree
10
- * the way npm resolved it with `lambda.keepNestedNodeModules: true`. Nested
11
- * copies of Frigg packages, the AWS SDK and Prisma stay excluded because the
12
- * app's single core, the Lambda runtime and the Prisma layer provide them.
9
+ * outright when the root copy is dev-only. Function packages ship the tree the
10
+ * way npm resolved it unless an app opts out with
11
+ * `lambda.keepNestedNodeModules: false`. Nested copies of Frigg packages, the
12
+ * AWS SDK and Prisma stay excluded because the app's single core, the Lambda
13
+ * runtime and the Prisma layer provide them.
13
14
  */
14
15
 
15
16
  const ALL_NESTED_NODE_MODULES = 'node_modules/**/node_modules/**';
@@ -19,7 +20,7 @@ const ALL_NESTED_NODE_MODULES = 'node_modules/**/node_modules/**';
19
20
  * @returns {boolean}
20
21
  */
21
22
  function keepsNestedNodeModules(appDefinition = {}) {
22
- return appDefinition.lambda?.keepNestedNodeModules === true;
23
+ return appDefinition.lambda?.keepNestedNodeModules !== false;
23
24
  }
24
25
 
25
26
  /**
@@ -8,20 +8,13 @@ const {
8
8
  nestedNodeModulesExcludes,
9
9
  } = require('./nested-node-modules');
10
10
 
11
- describe('nestedNodeModulesExcludes', () => {
12
- it('excludes every nested node_modules by default', () => {
13
- expect(nestedNodeModulesExcludes({}, true)).toEqual([
14
- 'node_modules/**/node_modules/**',
15
- ]);
16
- expect(ALL_NESTED_NODE_MODULES).toBe('node_modules/**/node_modules/**');
17
- });
11
+ const OPT_OUT = { lambda: { keepNestedNodeModules: false } };
18
12
 
19
- it('keeps nested node_modules when the app opts in, except Frigg, AWS SDK and Prisma copies', () => {
20
- const appDefinition = { lambda: { keepNestedNodeModules: true } };
21
-
22
- const excludes = nestedNodeModulesExcludes(appDefinition, true);
13
+ describe('nestedNodeModulesExcludes', () => {
14
+ it('keeps nested node_modules by default, except Frigg, AWS SDK and Prisma copies', () => {
15
+ const excludes = nestedNodeModulesExcludes({}, true);
23
16
 
24
- expect(excludes).not.toContain('node_modules/**/node_modules/**');
17
+ expect(excludes).not.toContain(ALL_NESTED_NODE_MODULES);
25
18
  expect(excludes).toEqual([
26
19
  'node_modules/**/node_modules/@friggframework/**',
27
20
  'node_modules/**/node_modules/aws-sdk/**',
@@ -32,30 +25,31 @@ describe('nestedNodeModulesExcludes', () => {
32
25
  });
33
26
 
34
27
  it('keeps nested Prisma copies when the app bundles Prisma instead of using the layer', () => {
35
- const appDefinition = { lambda: { keepNestedNodeModules: true } };
36
-
37
- const excludes = nestedNodeModulesExcludes(appDefinition, false);
38
-
39
- expect(excludes).toEqual([
28
+ expect(nestedNodeModulesExcludes({}, false)).toEqual([
40
29
  'node_modules/**/node_modules/@friggframework/**',
41
30
  'node_modules/**/node_modules/aws-sdk/**',
42
31
  'node_modules/**/node_modules/@aws-sdk/**',
43
32
  ]);
44
33
  });
34
+
35
+ it('excludes every nested node_modules when the app opts out', () => {
36
+ expect(nestedNodeModulesExcludes(OPT_OUT, true)).toEqual([
37
+ 'node_modules/**/node_modules/**',
38
+ ]);
39
+ expect(ALL_NESTED_NODE_MODULES).toBe('node_modules/**/node_modules/**');
40
+ });
45
41
  });
46
42
 
47
43
  describe('keepsNestedNodeModules', () => {
48
- it('is only enabled by the boolean true', () => {
49
- expect(
50
- keepsNestedNodeModules({ lambda: { keepNestedNodeModules: true } })
51
- ).toBe(true);
44
+ it('is only disabled by the boolean false', () => {
45
+ expect(keepsNestedNodeModules(OPT_OUT)).toBe(false);
52
46
  expect(
53
47
  keepsNestedNodeModules({
54
- lambda: { keepNestedNodeModules: 'true' },
48
+ lambda: { keepNestedNodeModules: true },
55
49
  })
56
- ).toBe(false);
57
- expect(keepsNestedNodeModules({ lambda: {} })).toBe(false);
58
- expect(keepsNestedNodeModules({})).toBe(false);
59
- expect(keepsNestedNodeModules()).toBe(false);
50
+ ).toBe(true);
51
+ expect(keepsNestedNodeModules({ lambda: {} })).toBe(true);
52
+ expect(keepsNestedNodeModules({})).toBe(true);
53
+ expect(keepsNestedNodeModules()).toBe(true);
60
54
  });
61
55
  });
@@ -9,7 +9,11 @@
9
9
 
10
10
  const path = require('path');
11
11
  const fs = require('fs');
12
- const { buildPrismaLayer } = require('../../../scripts/build-prisma-layer');
12
+ const {
13
+ buildPrismaLayer,
14
+ layerBuildInputs,
15
+ } = require('../../../scripts/build-prisma-layer');
16
+ const { resolveLambdaArchitecture } = require('../lambda-architectures');
13
17
 
14
18
  /**
15
19
  * Check if a process is still running
@@ -26,6 +30,48 @@ function isProcessRunning(pid) {
26
30
  }
27
31
  }
28
32
 
33
+ const LEGACY_MARKER_TARGET = 'rhel-openssl-3.0.x';
34
+
35
+ /**
36
+ * The inputs a completion marker records. A marker written before the
37
+ * marker became JSON recorded nothing, and every layer then held the rhel
38
+ * engine; its versions are unknown, so it never matches and the layer is
39
+ * rebuilt once.
40
+ * @param {string} markerText
41
+ * @returns {{ prismaBinaryTarget: string, clientPackages: string[]|null, coreVersion: string|null, prismaClientVersion: string|null }}
42
+ */
43
+ function parseLayerMarker(markerText) {
44
+ try {
45
+ const marker = JSON.parse(markerText);
46
+ return {
47
+ prismaBinaryTarget: marker.prismaBinaryTarget,
48
+ clientPackages: marker.clientPackages,
49
+ coreVersion: marker.coreVersion,
50
+ prismaClientVersion: marker.prismaClientVersion,
51
+ };
52
+ } catch {
53
+ // A marker written before the JSON format is plain text: treat it as a legacy build
54
+ return {
55
+ prismaBinaryTarget: LEGACY_MARKER_TARGET,
56
+ clientPackages: null,
57
+ coreVersion: null,
58
+ prismaClientVersion: null,
59
+ };
60
+ }
61
+ }
62
+
63
+ function sameLayerInputs(a, b) {
64
+ return (
65
+ a.prismaBinaryTarget === b.prismaBinaryTarget &&
66
+ a.coreVersion === b.coreVersion &&
67
+ a.prismaClientVersion === b.prismaClientVersion &&
68
+ Array.isArray(a.clientPackages) &&
69
+ Array.isArray(b.clientPackages) &&
70
+ a.clientPackages.length === b.clientPackages.length &&
71
+ a.clientPackages.every((pkg, i) => pkg === b.clientPackages[i])
72
+ );
73
+ }
74
+
29
75
  /**
30
76
  * Ensure Prisma Lambda Layer exists
31
77
  *
@@ -34,23 +80,38 @@ function isProcessRunning(pid) {
34
80
  * Prisma CLI is bundled separately in the dbMigrate function.
35
81
  *
36
82
  * Domain Concept: Build Completion State & Process Locking
37
- * - Uses .build-complete marker file to track successful builds
83
+ * - Uses .build-complete marker file to track successful builds; it records
84
+ * the inputs the layer was built from, and a built layer is reused only
85
+ * when they match the requested ones
38
86
  * - Uses .build-lock PID file to prevent concurrent builds
39
87
  * - Waits for active builds to complete before starting new one
40
88
  * - Cleans stale locks and incomplete builds before retry
41
89
  *
42
- * @param {Object} databaseConfig - Database configuration from app definition
90
+ * @param {Object} options
91
+ * @param {Object} options.databaseConfig - Database configuration from app definition
92
+ * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
43
93
  * @returns {Promise<void>}
44
94
  * @throws {Error} If layer build fails
45
95
  */
46
- async function ensurePrismaLayerExists(databaseConfig = {}) {
96
+ async function ensurePrismaLayerExists({
97
+ databaseConfig = {},
98
+ prismaBinaryTarget = resolveLambdaArchitecture().prismaBinaryTarget,
99
+ } = {}) {
47
100
  const projectRoot = process.cwd();
48
101
  const layerPath = path.join(projectRoot, 'layers/prisma');
49
102
  const completionMarkerPath = path.join(layerPath, '.build-complete');
50
103
  const lockFilePath = path.join(layerPath, '.build-lock');
104
+ const inputs = layerBuildInputs({ databaseConfig, prismaBinaryTarget });
105
+
106
+ const builtLayerMatches = () =>
107
+ fs.existsSync(completionMarkerPath) &&
108
+ sameLayerInputs(
109
+ parseLayerMarker(fs.readFileSync(completionMarkerPath, 'utf-8')),
110
+ inputs
111
+ );
51
112
 
52
113
  // Check if build is complete (marker exists)
53
- if (fs.existsSync(completionMarkerPath)) {
114
+ if (builtLayerMatches()) {
54
115
  console.log('✓ Prisma Lambda Layer already exists at', layerPath);
55
116
  return;
56
117
  }
@@ -68,8 +129,13 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
68
129
 
69
130
  // Check if build completed
70
131
  if (fs.existsSync(completionMarkerPath)) {
71
- console.log('✓ Concurrent build completed successfully');
72
- return;
132
+ if (builtLayerMatches()) {
133
+ console.log('✓ Concurrent build completed successfully');
134
+ return;
135
+ }
136
+ console.log('⚠ Concurrent build completed for other inputs - rebuilding');
137
+ fs.rmSync(lockFilePath, { force: true });
138
+ break;
73
139
  }
74
140
 
75
141
  // Check if process died
@@ -81,14 +147,16 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
81
147
  }
82
148
 
83
149
  // Timeout - check one final time
84
- if (fs.existsSync(completionMarkerPath)) {
150
+ if (builtLayerMatches()) {
85
151
  console.log('✓ Concurrent build completed');
86
152
  return;
87
153
  }
88
154
 
89
155
  // Still locked after 60s - remove stale lock
90
- console.log('⚠ Build timeout - removing stale lock and rebuilding');
91
- fs.rmSync(lockFilePath, { force: true });
156
+ if (fs.existsSync(lockFilePath)) {
157
+ console.log('⚠ Build timeout - removing stale lock and rebuilding');
158
+ fs.rmSync(lockFilePath, { force: true });
159
+ }
92
160
  } else {
93
161
  // Stale lock file (process not running)
94
162
  console.log(`⚠ Stale lock file detected (PID ${lockPid} not running) - cleaning up`);
@@ -99,6 +167,8 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
99
167
  // Check if incomplete build exists (directory without marker)
100
168
  if (fs.existsSync(layerPath) && !fs.existsSync(completionMarkerPath)) {
101
169
  console.log('⚠ Incomplete Prisma layer detected - will be cleaned by buildPrismaLayer()');
170
+ } else if (fs.existsSync(completionMarkerPath)) {
171
+ console.log(`⚠ Built Prisma layer does not match ${JSON.stringify(inputs)} - rebuilding`);
102
172
  }
103
173
 
104
174
  // Build layer
@@ -119,12 +189,21 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
119
189
 
120
190
  try {
121
191
  // Build layer WITHOUT CLI (runtime only for minimal size)
122
- await buildPrismaLayer(databaseConfig);
192
+ await buildPrismaLayer({ databaseConfig, prismaBinaryTarget });
123
193
 
124
194
  // Create completion marker
125
195
  fs.writeFileSync(
126
196
  completionMarkerPath,
127
- `Build completed: ${new Date().toISOString()}\nNode: ${process.version}\nPlatform: ${process.platform}\n`
197
+ JSON.stringify(
198
+ {
199
+ ...inputs,
200
+ builtAt: new Date().toISOString(),
201
+ node: process.version,
202
+ platform: process.platform,
203
+ },
204
+ null,
205
+ 2
206
+ )
128
207
  );
129
208
 
130
209
  console.log('✓ Prisma Lambda Layer built successfully (~10-15MB)\n');
@@ -155,5 +234,6 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
155
234
 
156
235
  module.exports = {
157
236
  ensurePrismaLayerExists,
237
+ parseLayerMarker,
158
238
  };
159
239