@friggframework/devtools 2.0.0--canary.730.f2ba24a.0 → 2.0.0--canary.731.ffe61d3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/infrastructure/README.md +27 -0
  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 +16 -0
  12. package/infrastructure/domains/database/migration-builder.js +21 -2
  13. package/infrastructure/domains/database/migration-builder.test.js +55 -0
  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 +16 -0
  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 +47 -0
  24. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
  25. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
  26. package/infrastructure/infrastructure-composer.js +12 -1
  27. package/infrastructure/infrastructure-composer.test.js +71 -0
  28. package/infrastructure/scripts/build-prisma-layer.js +136 -50
  29. package/infrastructure/scripts/build-prisma-layer.test.js +100 -0
  30. package/package.json +7 -7
@@ -303,6 +303,33 @@ const appDefinition = {
303
303
 
304
304
  With the opt-out, each nested package resolves whatever version is hoisted to the root, and a package whose root copy is a dev dependency is not shipped at all. The first `require` of such a package fails at Lambda init with `Runtime.ImportModuleError`.
305
305
 
306
+ **Lambda architecture (arm64 / Graviton):**
307
+
308
+ Every function, the Prisma layer and the migration worker deploy as x86_64 unless the app definition sets `architecture`:
309
+
310
+ ```javascript
311
+ const appDefinition = {
312
+ name: 'my-app',
313
+ architecture: 'arm64', // or 'x86_64'; unset keeps today's template
314
+ integrations: [{ Definition: { name: 'hubspot' } }],
315
+ };
316
+ ```
317
+
318
+ An explicit value sets `provider.architecture` and the layer's `compatibleArchitectures`, builds the layer with that architecture's Prisma query engine, ships the migration worker with its schema engine and query engine library, and pins the migrate CLI to them through `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY`. With `usePrismaLambdaLayer: false`, each function bundles only that engine. An unset key adds no field to the template.
319
+
320
+ Before you flip an app to `arm64`:
321
+
322
+ - It needs a `@friggframework/core` release whose generated Prisma clients include the `linux-arm64-openssl-3.0.x` engine (both schemas list it in `binaryTargets`). With an older core the layer build fails naming the core version.
323
+ - The deploy host must reach Prisma's engine CDN (`binaries.prisma.sh`) at package time: the migration worker's engines for the target are fetched there, and packaging fails if either is missing.
324
+ - This runs on every compose where the migration worker is enabled, and downloads only when the target's engines are missing from the app's `node_modules/@prisma/engines`.
325
+ - Air-gapped or offline deploy hosts set `PRISMA_ENGINES_MIRROR` to an internal mirror of the CDN. Prisma's download honours it (`@prisma/fetch-engine` 6.19.3, `dist/chunk-LONQL55G.js`, where the download URL is built from `PRISMA_BINARIES_MIRROR || PRISMA_ENGINES_MIRROR || "https://binaries.prisma.sh"`).
326
+ - The app must have `prisma` installed in its own `node_modules`, not only in a hoisted parent: the worker ships its engines from there, and packaging fails otherwise. The worker runs the app's own `prisma` CLI and pins `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY` to that `@prisma/engines`, so the CLI and its engines always agree. That `prisma` must still be able to run the schema and migrations of `@friggframework/core`.
327
+ - Published core carries one more query engine per generated client (about 15 MB unpacked each).
328
+ - Native addons of the app itself (`sharp`, `bcrypt`, and the like) are built for the deploy host's architecture by `npm ci`, not for the target. Build them for arm64 or replace them.
329
+ - During the stack update, functions run mixed for a short time, so flip in a low-traffic window.
330
+ - The cached layer under `layers/prisma` rebuilds on the flip: its marker records the Prisma binary target, the client set and the core and `@prisma/client` versions, and a mismatch rebuilds.
331
+ - The first compose after upgrading to a Frigg release with this support rebuilds the Prisma layer once, because cache markers written by older releases never match.
332
+
306
333
  ## Usage Examples
307
334
 
308
335
  ### Basic Deployment
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Shared cases for every builder whose functions bundle Prisma when the
3
+ * Prisma layer is off.
4
+ * @param {(usePrismaLayer: boolean, architecture?: string) => Promise<Object[]>|Object[]} functionsOf
5
+ * Builds the app and returns its function definitions
6
+ */
7
+ function itBundlesOnlyTheTargetPrismaEngine(functionsOf) {
8
+ it.each([
9
+ [undefined, 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
10
+ ['x86_64', 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
11
+ ['arm64', 'linux-arm64-openssl-3.0.x', 'rhel-openssl-3.0.x'],
12
+ ])(
13
+ 'with the layer off and architecture %s, the bundled Prisma keeps only the %s engine',
14
+ async (architecture, target, otherTarget) => {
15
+ for (const fn of await functionsOf(false, architecture)) {
16
+ expect(fn.package.exclude).toEqual(
17
+ expect.arrayContaining([
18
+ '**/libquery_engine-debian*',
19
+ `**/libquery_engine-${otherTarget}*`,
20
+ ])
21
+ );
22
+ expect(fn.package.exclude).not.toContain(`**/libquery_engine-${target}*`);
23
+ }
24
+ }
25
+ );
26
+
27
+ it('with the layer on, adds no engine patterns, since the layer carries the engines', async () => {
28
+ for (const fn of await functionsOf(true, 'arm64')) {
29
+ expect(fn.package.exclude).not.toEqual(
30
+ expect.arrayContaining(['**/libquery_engine-rhel-openssl-3.0.x*'])
31
+ );
32
+ expect(fn.package.exclude).not.toEqual(
33
+ expect.arrayContaining(['**/libquery_engine-debian*'])
34
+ );
35
+ }
36
+ });
37
+ }
38
+
39
+ module.exports = { itBundlesOnlyTheTargetPrismaEngine };
@@ -37,6 +37,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
37
37
  }),
38
38
  };
39
39
  });
40
+ jest.mock('../domains/database/migration-engines', () => ({
41
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
42
+ }));
40
43
 
41
44
  // createIntegrationRouter loads the app definition from the consuming
42
45
  // backend; give it an empty one so the router can be built in isolation.
@@ -36,6 +36,9 @@ const accountWithDefaultVpc = (overrides = {}) => ({
36
36
  defaultRouteTableId: 'rtb-12345',
37
37
  ...overrides,
38
38
  });
39
+ jest.mock('../domains/database/migration-engines', () => ({
40
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
41
+ }));
39
42
 
40
43
  const postgresApp = (postgres, extra = {}) => ({
41
44
  name: 'test-app',
@@ -146,3 +146,6 @@ describe('frigg init default infrastructure', () => {
146
146
  expect(definition.provider.logRetentionInDays).toBe(14);
147
147
  });
148
148
  });
149
+ jest.mock('../domains/database/migration-engines', () => ({
150
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
151
+ }));
@@ -24,6 +24,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
24
24
  }),
25
25
  };
26
26
  });
27
+ jest.mock('../domains/database/migration-engines', () => ({
28
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
29
+ }));
27
30
 
28
31
  const buildApp = (overrides = {}) => ({
29
32
  name: 'scoped-test-app',
@@ -23,6 +23,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
23
23
  }),
24
24
  };
25
25
  });
26
+ jest.mock('../domains/database/migration-engines', () => ({
27
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
28
+ }));
26
29
 
27
30
  const buildApp = (overrides = {}) => ({
28
31
  name: 'preload-test',
@@ -631,6 +631,9 @@ describe('CloudFormation Template Generation', () => {
631
631
  });
632
632
  });
633
633
  });
634
+ jest.mock('../domains/database/migration-engines', () => ({
635
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
636
+ }));
634
637
 
635
638
  // Helper functions
636
639
  function findAllRefs(obj, refs = []) {
@@ -40,6 +40,9 @@ jest.mock('./domains/shared/resource-discovery', () => {
40
40
  const actual = jest.requireActual('./domains/shared/resource-discovery');
41
41
  return { ...actual, gatherDiscoveredResources: jest.fn() };
42
42
  });
43
+ jest.mock('./domains/database/migration-engines', () => ({
44
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
45
+ }));
43
46
  jest.mock('./domains/shared/utilities/prisma-layer-manager', () => ({
44
47
  ensurePrismaLayerExists: jest.fn().mockResolvedValue(undefined),
45
48
  }));
@@ -278,6 +281,7 @@ const MATRIX = {
278
281
  },
279
282
  lambda: { scopedEnvironment: true, keepNestedNodeModules: false },
280
283
  usePrismaLambdaLayer: true,
284
+ architecture: 'x86_64',
281
285
  }),
282
286
  'frigg init scaffold (external db, no vpc)': () => ({
283
287
  ...base(),
@@ -294,6 +298,7 @@ const MATRIX = {
294
298
  database: { postgres: { enable: true, management: 'external' } },
295
299
  logging: { retentionInDays: 14 },
296
300
  ssm: { enable: false },
301
+ architecture: 'arm64',
297
302
  }),
298
303
  'external db, encryption none': () => ({
299
304
  ...base(),
@@ -16,6 +16,7 @@
16
16
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
17
  const { isScopedEnvironmentActive } = require('../shared/function-environments');
18
18
  const { nestedNodeModulesExcludes } = require('../shared/utilities/nested-node-modules');
19
+ const { bundledPrismaEngineExcludes } = require('../shared/lambda-architectures');
19
20
 
20
21
  class AdminScriptBuilder extends InfrastructureBuilder {
21
22
  constructor() {
@@ -412,6 +413,7 @@ class AdminScriptBuilder extends InfrastructureBuilder {
412
413
  'node_modules/@friggframework/core/generated/**',
413
414
  ]
414
415
  : []),
416
+ ...bundledPrismaEngineExcludes(appDefinition, usePrismaLayer),
415
417
  ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
416
418
  'node_modules/@friggframework/test/**',
417
419
  'node_modules/@friggframework/eslint-config/**',
@@ -10,6 +10,7 @@
10
10
 
11
11
  const { AdminScriptBuilder } = require('./admin-script-builder');
12
12
  const { ValidationResult } = require('../shared/base-builder');
13
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../__tests__/helpers/bundled-prisma-engine-excludes');
13
14
 
14
15
  describe('AdminScriptBuilder', () => {
15
16
  let adminScriptBuilder;
@@ -963,6 +964,21 @@ describe('AdminScriptBuilder', () => {
963
964
  });
964
965
  });
965
966
 
967
+ describe('Lambda architecture with usePrismaLambdaLayer=false', () => {
968
+ const functionsOf = async (usePrismaLambdaLayer, architecture) => {
969
+ const result = await adminScriptBuilder.build(
970
+ {
971
+ adminScripts: [{ Definition: { name: 'cleanup' } }],
972
+ usePrismaLambdaLayer,
973
+ ...(architecture && { architecture }),
974
+ },
975
+ {}
976
+ );
977
+ return Object.values(result.functions);
978
+ };
979
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
980
+ });
981
+
966
982
  describe('getName()', () => {
967
983
  it('should return AdminScriptBuilder', () => {
968
984
  expect(adminScriptBuilder.getName()).toBe('AdminScriptBuilder');
@@ -16,6 +16,12 @@
16
16
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
17
  const { isScopedEnvironmentActive } = require('../shared/function-environments');
18
18
  const { nestedNodeModulesExcludes } = require('../shared/utilities/nested-node-modules');
19
+ const {
20
+ resolveLambdaArchitecture,
21
+ PRISMA_ENGINES_PACKAGE_DIR,
22
+ prismaEngineFileNames,
23
+ foreignPrismaEngineExcludes,
24
+ } = require('../shared/lambda-architectures');
19
25
  const { MigrationResourceResolver } = require('./migration-resolver');
20
26
  const { createEmptyDiscoveryResult, ResourceOwnership } = require('../shared/types');
21
27
 
@@ -239,6 +245,9 @@ class MigrationBuilder extends InfrastructureBuilder {
239
245
  async createFunctionDefinitions(result, usePrismaLayer = true, appDefinition = {}) {
240
246
  console.log(' 🔍 DEBUG: createFunctionDefinitions called');
241
247
  console.log(' 🔍 DEBUG: result.functions is:', typeof result.functions, result.functions);
248
+ const architecture = resolveLambdaArchitecture(appDefinition);
249
+ const engineExcludes = foreignPrismaEngineExcludes(architecture.name);
250
+ const engines = prismaEngineFileNames(architecture.prismaBinaryTarget);
242
251
  // Migration WORKER package config (needs Prisma CLI WASM files)
243
252
  const migrationWorkerPackageConfig = {
244
253
  individually: true,
@@ -293,12 +302,14 @@ class MigrationBuilder extends InfrastructureBuilder {
293
302
  'node_modules/@friggframework/core/handlers/routers/integration-*.js',
294
303
  'node_modules/@friggframework/core/handlers/workers/integration-*.js',
295
304
 
296
- // Exclude wrong OS binaries
305
+ // Exclude the engines of every platform and architecture this
306
+ // stack does not run on
297
307
  '**/query-engine-darwin*',
298
308
  '**/schema-engine-darwin*',
299
309
  '**/libquery_engine-darwin*',
300
310
  '**/*-darwin-arm64*',
301
311
  '**/*-darwin*',
312
+ ...engineExcludes,
302
313
 
303
314
  // Migration worker DOES need Prisma CLI WASM files (for migrate deploy)
304
315
  // Only exclude runtime engine WASM (query engine internals)
@@ -385,12 +396,14 @@ class MigrationBuilder extends InfrastructureBuilder {
385
396
  'node_modules/@friggframework/core/handlers/routers/integration-*.js',
386
397
  'node_modules/@friggframework/core/handlers/workers/**',
387
398
 
388
- // Exclude wrong OS binaries
399
+ // Exclude the engines of every platform and architecture this
400
+ // stack does not run on
389
401
  '**/query-engine-darwin*',
390
402
  '**/schema-engine-darwin*',
391
403
  '**/libquery_engine-darwin*',
392
404
  '**/*-darwin-arm64*',
393
405
  '**/*-darwin*',
406
+ ...engineExcludes,
394
407
 
395
408
  // Router doesn't run migrations - exclude ALL WASM files
396
409
  '**/runtime/*.wasm',
@@ -438,6 +451,12 @@ class MigrationBuilder extends InfrastructureBuilder {
438
451
  environment: {
439
452
  // Ensure migration functions get DATABASE_URL from provider.environment
440
453
  // Note: Serverless will merge this with provider.environment
454
+
455
+ // Pin the migrate CLI to the shipped engines. With these set,
456
+ // Prisma neither downloads an engine at cold start (into the
457
+ // read-only /var/task) nor picks another file.
458
+ PRISMA_SCHEMA_ENGINE_BINARY: `/var/task/${PRISMA_ENGINES_PACKAGE_DIR}/${engines.schemaEngine}`,
459
+ PRISMA_QUERY_ENGINE_LIBRARY: `/var/task/${PRISMA_ENGINES_PACKAGE_DIR}/${engines.queryEngineLibrary}`,
441
460
  },
442
461
  events: [
443
462
  {
@@ -322,6 +322,61 @@ describe('MigrationBuilder', () => {
322
322
  });
323
323
  });
324
324
 
325
+ describe('Lambda architecture (architecture)', () => {
326
+ const baseAppDefinition = { database: { postgres: { enable: true } } };
327
+ const workerAndRouter = (result) => [
328
+ result.functions.dbMigrationWorker,
329
+ result.functions.dbMigrationRouter,
330
+ ];
331
+
332
+ it.each([
333
+ [undefined, 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
334
+ ['x86_64', 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
335
+ ['arm64', 'linux-arm64-openssl-3.0.x', 'rhel-openssl-3.0.x'],
336
+ ])(
337
+ 'with architecture %s the worker and router ship only the %s engines',
338
+ async (architecture, target, otherTarget) => {
339
+ const result = await builder.build(
340
+ { ...baseAppDefinition, ...(architecture && { architecture }) },
341
+ {}
342
+ );
343
+
344
+ for (const fn of workerAndRouter(result)) {
345
+ expect(fn.package.exclude).toEqual(
346
+ expect.arrayContaining([
347
+ '**/libquery_engine-debian*',
348
+ '**/libquery_engine-linux-musl*',
349
+ `**/libquery_engine-${otherTarget}*`,
350
+ ])
351
+ );
352
+ expect(fn.package.exclude).not.toContain(`**/libquery_engine-${target}*`);
353
+ }
354
+ }
355
+ );
356
+
357
+ it.each([
358
+ [undefined, 'rhel-openssl-3.0.x'],
359
+ ['x86_64', 'rhel-openssl-3.0.x'],
360
+ ['arm64', 'linux-arm64-openssl-3.0.x'],
361
+ ])(
362
+ 'with architecture %s the worker pins the migrate CLI to the shipped %s engines',
363
+ async (architecture, target) => {
364
+ const result = await builder.build(
365
+ { ...baseAppDefinition, ...(architecture && { architecture }) },
366
+ {}
367
+ );
368
+
369
+ expect(result.functions.dbMigrationWorker.environment).toEqual(
370
+ expect.objectContaining({
371
+ PRISMA_SCHEMA_ENGINE_BINARY: `/var/task/node_modules/@prisma/engines/schema-engine-${target}`,
372
+ PRISMA_QUERY_ENGINE_LIBRARY: `/var/task/node_modules/@prisma/engines/libquery_engine-${target}.so.node`,
373
+ })
374
+ );
375
+ expect(result.functions.dbMigrationRouter.environment.PRISMA_SCHEMA_ENGINE_BINARY).toBeUndefined();
376
+ }
377
+ );
378
+ });
379
+
325
380
  describe('scoped environment (lambda.scopedEnvironment)', () => {
326
381
  beforeEach(() => {
327
382
  delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Migration worker engines
3
+ *
4
+ * Domain Layer - Hexagonal Architecture
5
+ *
6
+ * The migration worker runs the Prisma CLI, which needs the schema engine
7
+ * and the query engine library for the Lambda architecture it runs on. Both
8
+ * ship from node_modules/@prisma/engines/, where the @prisma/engines
9
+ * postinstall put the deploy host's own engines. This fetches the deployed
10
+ * architecture's pair before packaging, and fails packaging when either is
11
+ * still missing, so a worker can never try to download an engine into the
12
+ * read-only /var/task at cold start.
13
+ */
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { execFileSync } = require('child_process');
18
+ const { prismaEngineFileNames, PRISMA_ENGINES_PACKAGE_DIR } = require('../shared/lambda-architectures');
19
+
20
+ function resolveEnginesDir(cwd) {
21
+ const enginesDir = path.join(cwd, PRISMA_ENGINES_PACKAGE_DIR);
22
+ if (!fs.existsSync(path.join(enginesDir, 'scripts', 'postinstall.js'))) {
23
+ throw new Error(
24
+ `@prisma/engines was not found at ${enginesDir}.\n` +
25
+ 'The app must have prisma installed in its own node_modules, not only in a hoisted parent: ' +
26
+ 'the migration worker ships its engines from the app\'s node_modules.'
27
+ );
28
+ }
29
+ return enginesDir;
30
+ }
31
+
32
+ /**
33
+ * Runs the @prisma/engines postinstall for one target. It downloads only
34
+ * the engines that are missing, so the host's own engines stay. The host's
35
+ * pinned engine paths are hidden from it: with them set, the postinstall
36
+ * skips those engines instead of downloading them.
37
+ */
38
+ function runEnginesPostinstall({ enginesDir, prismaBinaryTarget }) {
39
+ const hostEnv = { ...process.env };
40
+ delete hostEnv.PRISMA_SCHEMA_ENGINE_BINARY;
41
+ delete hostEnv.PRISMA_QUERY_ENGINE_LIBRARY;
42
+ execFileSync(
43
+ process.execPath,
44
+ [path.join(enginesDir, 'scripts', 'postinstall.js')],
45
+ {
46
+ cwd: enginesDir,
47
+ stdio: 'inherit',
48
+ env: { ...hostEnv, PRISMA_CLI_BINARY_TARGETS: prismaBinaryTarget },
49
+ }
50
+ );
51
+ }
52
+
53
+ /**
54
+ * @param {Object} options
55
+ * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
56
+ * @param {string} [options.cwd] - The app root
57
+ * @param {string} [options.enginesDir] - node_modules/@prisma/engines of the app
58
+ * @param {Function} [options.fetchEngines] - Fetches the target's engines into enginesDir
59
+ * @throws {Error} When either engine is missing after the fetch
60
+ */
61
+ async function ensureMigrationEngines({
62
+ prismaBinaryTarget,
63
+ cwd = process.cwd(),
64
+ enginesDir = resolveEnginesDir(cwd),
65
+ fetchEngines = runEnginesPostinstall,
66
+ }) {
67
+ const engineNames = Object.values(prismaEngineFileNames(prismaBinaryTarget));
68
+ const missing = () =>
69
+ engineNames.filter((name) => !fs.existsSync(path.join(enginesDir, name)));
70
+
71
+ if (missing().length === 0) {
72
+ console.log(`✓ Prisma ${prismaBinaryTarget} migration engines present in ${enginesDir}`);
73
+ return;
74
+ }
75
+
76
+ console.log(
77
+ `📦 Fetching ${missing().join(', ')} (Prisma ${prismaBinaryTarget}) into ${enginesDir}...`
78
+ );
79
+ fetchEngines({ enginesDir, prismaBinaryTarget });
80
+
81
+ const stillMissing = missing();
82
+ if (stillMissing.length > 0) {
83
+ throw new Error(
84
+ `Prisma migration engines for ${prismaBinaryTarget} are missing after the fetch: ` +
85
+ `${stillMissing.join(', ')} (in ${enginesDir}).\n` +
86
+ "The deploy host must reach Prisma's engine CDN (binaries.prisma.sh) at package time."
87
+ );
88
+ }
89
+ }
90
+
91
+ module.exports = {
92
+ ensureMigrationEngines,
93
+ };
@@ -0,0 +1,142 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const { ensureMigrationEngines } = require('./migration-engines');
5
+
6
+ describe('ensureMigrationEngines()', () => {
7
+ const target = 'linux-arm64-openssl-3.0.x';
8
+ const schemaEngine = `schema-engine-${target}`;
9
+ const queryEngineLibrary = `libquery_engine-${target}.so.node`;
10
+ let enginesDir;
11
+
12
+ const writeEngines = (...names) => {
13
+ for (const name of names) {
14
+ fs.writeFileSync(path.join(enginesDir, name), '');
15
+ }
16
+ };
17
+
18
+ beforeEach(() => {
19
+ enginesDir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-prisma-engines-'));
20
+ });
21
+
22
+ afterEach(() => {
23
+ fs.rmSync(enginesDir, { recursive: true, force: true });
24
+ });
25
+
26
+ it('fetches nothing when both engines for the target are already present', async () => {
27
+ writeEngines(schemaEngine, queryEngineLibrary);
28
+ const fetchEngines = jest.fn();
29
+
30
+ await ensureMigrationEngines({ prismaBinaryTarget: target, enginesDir, fetchEngines });
31
+
32
+ expect(fetchEngines).not.toHaveBeenCalled();
33
+ });
34
+
35
+ it('fetches the target engines into the engines directory when one is missing', async () => {
36
+ writeEngines(schemaEngine);
37
+ const fetchEngines = jest.fn(({ enginesDir: dir }) => {
38
+ fs.writeFileSync(path.join(dir, queryEngineLibrary), '');
39
+ });
40
+
41
+ await ensureMigrationEngines({ prismaBinaryTarget: target, enginesDir, fetchEngines });
42
+
43
+ expect(fetchEngines).toHaveBeenCalledWith({ enginesDir, prismaBinaryTarget: target });
44
+ });
45
+
46
+ it.each([
47
+ ['the schema engine', [queryEngineLibrary], schemaEngine],
48
+ ['the query engine library', [schemaEngine], queryEngineLibrary],
49
+ ['both engines', [], `${schemaEngine}, ${queryEngineLibrary}`],
50
+ ])('fails packaging naming %s when the fetch leaves it missing', async (_, present, missing) => {
51
+ writeEngines(...present);
52
+ const fetchEngines = jest.fn();
53
+
54
+ await expect(
55
+ ensureMigrationEngines({ prismaBinaryTarget: target, enginesDir, fetchEngines })
56
+ ).rejects.toThrow(missing);
57
+ });
58
+
59
+ describe('resolving the engines directory from cwd', () => {
60
+ let root;
61
+
62
+ const installEngines = (dir) => {
63
+ const engines = path.join(dir, 'node_modules', '@prisma', 'engines');
64
+ fs.mkdirSync(path.join(engines, 'scripts'), { recursive: true });
65
+ fs.writeFileSync(path.join(engines, 'scripts', 'postinstall.js'), '');
66
+ return engines;
67
+ };
68
+
69
+ beforeEach(() => {
70
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-app-root-'));
71
+ });
72
+
73
+ afterEach(() => {
74
+ fs.rmSync(root, { recursive: true, force: true });
75
+ });
76
+
77
+ it("uses the engines in the app's own node_modules", async () => {
78
+ const appDir = path.join(root, 'app');
79
+ const appEngines = installEngines(appDir);
80
+ fs.writeFileSync(path.join(appEngines, schemaEngine), '');
81
+ fs.writeFileSync(path.join(appEngines, queryEngineLibrary), '');
82
+ const fetchEngines = jest.fn();
83
+
84
+ await ensureMigrationEngines({ prismaBinaryTarget: target, cwd: appDir, fetchEngines });
85
+
86
+ expect(fetchEngines).not.toHaveBeenCalled();
87
+ });
88
+
89
+ it('fails with a readable error when only a parent directory has the engines', async () => {
90
+ installEngines(root);
91
+ const appDir = path.join(root, 'app');
92
+ fs.mkdirSync(appDir);
93
+ const fetchEngines = jest.fn();
94
+
95
+ const failure = ensureMigrationEngines({
96
+ prismaBinaryTarget: target,
97
+ cwd: appDir,
98
+ fetchEngines,
99
+ });
100
+
101
+ await expect(failure).rejects.toThrow(/prisma.*own node_modules.*hoisted parent/is);
102
+ await expect(failure).rejects.not.toHaveProperty('code', 'MODULE_NOT_FOUND');
103
+ expect(fetchEngines).not.toHaveBeenCalled();
104
+ });
105
+ });
106
+
107
+ describe('running the @prisma/engines postinstall', () => {
108
+ const pinnedEngineVars = ['PRISMA_SCHEMA_ENGINE_BINARY', 'PRISMA_QUERY_ENGINE_LIBRARY'];
109
+ let appDir;
110
+ let seenEnvPath;
111
+
112
+ beforeEach(() => {
113
+ appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-app-'));
114
+ const engines = path.join(appDir, 'node_modules', '@prisma', 'engines');
115
+ fs.mkdirSync(path.join(engines, 'scripts'), { recursive: true });
116
+ seenEnvPath = path.join(appDir, 'seen-env.json');
117
+ fs.writeFileSync(
118
+ path.join(engines, 'scripts', 'postinstall.js'),
119
+ `const fs = require('fs');
120
+ fs.writeFileSync(${JSON.stringify(seenEnvPath)}, JSON.stringify(process.env));
121
+ for (const name of ${JSON.stringify([schemaEngine, queryEngineLibrary])}) fs.writeFileSync(name, '');`
122
+ );
123
+ });
124
+
125
+ afterEach(() => {
126
+ fs.rmSync(appDir, { recursive: true, force: true });
127
+ pinnedEngineVars.forEach((name) => delete process.env[name]);
128
+ });
129
+
130
+ it("hides the host's pinned engine paths, so the postinstall does not skip the download", async () => {
131
+ pinnedEngineVars.forEach((name) => {
132
+ process.env[name] = `/host/${name}`;
133
+ });
134
+
135
+ await ensureMigrationEngines({ prismaBinaryTarget: target, cwd: appDir });
136
+
137
+ const seenEnv = JSON.parse(fs.readFileSync(seenEnvPath, 'utf-8'));
138
+ expect(seenEnv.PRISMA_CLI_BINARY_TARGETS).toBe(target);
139
+ pinnedEngineVars.forEach((name) => expect(seenEnv).not.toHaveProperty(name));
140
+ });
141
+ });
142
+ });
@@ -32,6 +32,7 @@ const {
32
32
  const {
33
33
  nestedNodeModulesExcludes,
34
34
  } = require('../shared/utilities/nested-node-modules');
35
+ const { bundledPrismaEngineExcludes } = require('../shared/lambda-architectures');
35
36
  const {
36
37
  INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
37
38
  QUEUE_MAX_RECEIVE_COUNT_ENV,
@@ -268,6 +269,7 @@ class IntegrationBuilder extends InfrastructureBuilder {
268
269
  'node_modules/@friggframework/core/generated/**',
269
270
  ]
270
271
  : []),
272
+ ...bundledPrismaEngineExcludes(appDefinition, usePrismaLayer),
271
273
 
272
274
  ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
273
275
 
@@ -10,6 +10,7 @@ const {
10
10
  } = require('@friggframework/core/queues/queue-delivery');
11
11
  const { IntegrationBuilder } = require('./integration-builder');
12
12
  const { ValidationResult } = require('../shared/base-builder');
13
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../__tests__/helpers/bundled-prisma-engine-excludes');
13
14
 
14
15
  describe('IntegrationBuilder', () => {
15
16
  let integrationBuilder;
@@ -1085,6 +1086,21 @@ describe('IntegrationBuilder', () => {
1085
1086
  });
1086
1087
 
1087
1088
 
1089
+ describe('IntegrationBuilder Lambda architecture with usePrismaLambdaLayer=false', () => {
1090
+ const functionsOf = async (usePrismaLambdaLayer, architecture) => {
1091
+ const result = await new IntegrationBuilder().build(
1092
+ {
1093
+ integrations: [{ Definition: { name: 'crm' } }],
1094
+ usePrismaLambdaLayer,
1095
+ ...(architecture && { architecture }),
1096
+ },
1097
+ {}
1098
+ );
1099
+ return Object.values(result.functions);
1100
+ };
1101
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
1102
+ });
1103
+
1088
1104
  describe('IntegrationBuilder nested node_modules (lambda.keepNestedNodeModules)', () => {
1089
1105
  const appDefinition = (lambda) => ({
1090
1106
  integrations: [{ Definition: { name: 'test', webhooks: true } }],