@mayurajs/deploy-aws-lambda 0.0.0-stage → 1.2.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.
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +55 -2
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +106 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +113 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Mayura
|
|
2
|
+
Copyright 2026 The Mayura Authors
|
|
3
|
+
|
|
4
|
+
This product includes software developed by the Mayura contributors.
|
|
5
|
+
|
|
6
|
+
Third-party dependencies retain their own copyright and license terms. Exact
|
|
7
|
+
resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
|
|
8
|
+
artifact and dependency qualification procedures.
|
package/README.md
CHANGED
|
@@ -1,3 +1,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/deploy-aws-lambda
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[AWS Lambda](https://aws.amazon.com/lambda/) as a `mayura deploy` target. One container image serves three
|
|
4
|
+
functions: the API behind a function URL, the workflows function that EventBridge Scheduler invokes every minute,
|
|
5
|
+
and a migration function that each release runs before anything else is updated. Lambda support in Mayura is
|
|
6
|
+
experimental (see [Serverless functions](https://mayurajs.com/docs/guides/deployment/#serverless-functions)).
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install --save-dev @mayurajs/deploy-aws-lambda
|
|
10
|
+
mayura deploy init --target aws-lambda --apply
|
|
11
|
+
mayura deploy --target aws-lambda # prints the plan and its digest
|
|
12
|
+
mayura deploy --target aws-lambda --apply --confirm <digest>
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**Your module.** Write the serverless module the deployment guide describes (`src/mayura.ts`, with request-bound runs
|
|
16
|
+
and `pool: { max: 1 }`), and add a migration to it:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
export async function migrate() { await ready; return { schemaVersion: 1 }; }
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**`deploy init` writes:**
|
|
23
|
+
- `deploy/aws-lambda/Dockerfile`: built on AWS's Lambda Node.js base image in both stages, so native modules match
|
|
24
|
+
Amazon Linux;
|
|
25
|
+
- `api.mjs`, `workflows.mjs` and `migrate.mjs`: three handlers that call `handle`, `advanceWorkflows` and `migrate`
|
|
26
|
+
from your compiled module (`dist/src/mayura.js` by default).
|
|
27
|
+
|
|
28
|
+
**Once, before the first release**, create the three functions from the image:
|
|
29
|
+
- `<name>-api` with the image command `deploy/aws-lambda/api.handler`, a function URL and a timeout above your agents'
|
|
30
|
+
`maxDurationMs`;
|
|
31
|
+
- `<name>-workflows` with `deploy/aws-lambda/workflows.handler`, a 60-second timeout and an EventBridge Scheduler rule
|
|
32
|
+
every minute;
|
|
33
|
+
- `<name>-migrate` with `deploy/aws-lambda/migrate.handler` and a timeout of up to 900 seconds.
|
|
34
|
+
|
|
35
|
+
Give them their environment (`DATABASE_URL` and the app's variables, for example from Secrets Manager) and, for a
|
|
36
|
+
private database, the VPC.
|
|
37
|
+
|
|
38
|
+
**A release:**
|
|
39
|
+
1. Checks the signed-in account.
|
|
40
|
+
2. Builds the image for one platform (`linux/amd64`, or `arm64`) without a provenance attestation, which Lambda would
|
|
41
|
+
refuse, and pushes it.
|
|
42
|
+
3. Points `<name>-migrate` at the image, waits for the update, invokes it, and requires that it reports no function
|
|
43
|
+
error.
|
|
44
|
+
4. Only then updates `<name>-api` and `<name>-workflows`, waiting for each.
|
|
45
|
+
|
|
46
|
+
Each step's output is checked: an unexpected answer stops the release.
|
|
47
|
+
|
|
48
|
+
**Settings** in `mayura.deploy.json` under `targets.aws-lambda`:
|
|
49
|
+
- `region`;
|
|
50
|
+
- `nodeVersion` (22 or 24);
|
|
51
|
+
- `architecture` (`x86_64` or `arm64`);
|
|
52
|
+
- `module`.
|
|
53
|
+
|
|
54
|
+
The AWS CLI uses its own credentials; Mayura reads none.
|
|
55
|
+
|
|
56
|
+
See [Deploy with mayura deploy](https://mayurajs.com/docs/cli/deploy/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface AwsLambdaSettings {
|
|
2
|
+
readonly region: string;
|
|
3
|
+
/** The Lambda Node.js base image's major version: 22 by default. */
|
|
4
|
+
readonly nodeVersion: 22 | 24;
|
|
5
|
+
/** The instruction set the functions run on: `x86_64` (default) or `arm64`. */
|
|
6
|
+
readonly architecture: 'x86_64' | 'arm64';
|
|
7
|
+
/**
|
|
8
|
+
* The compiled module that exports `handle(request)`, `advanceWorkflows()` and `migrate()`, relative to the project:
|
|
9
|
+
* by default `mayura.js` next to the app module, such as `dist/src/mayura.js`.
|
|
10
|
+
*/
|
|
11
|
+
readonly module: string;
|
|
12
|
+
}
|
|
13
|
+
/** Deploys to AWS Lambda from one container image: the migration function first, then the API and workflows functions. */
|
|
14
|
+
export declare const awsLambdaTarget: import("mayura/cli/deploy").DeployTarget<AwsLambdaSettings>;
|
|
15
|
+
export default awsLambdaTarget;
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oEAAoE;IACpE,QAAQ,CAAC,WAAW,EAAE,EAAE,GAAG,EAAE,CAAC;IAC9B,+EAA+E;IAC/E,QAAQ,CAAC,YAAY,EAAE,QAAQ,GAAG,OAAO,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAiED,0HAA0H;AAC1H,eAAO,MAAM,eAAe,6DA8B1B,CAAC;eAEY,eAAe"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import { defineDeployTarget, dockerignore } from 'mayura/cli/deploy';
|
|
3
|
+
const allowed = ['region', 'nodeVersion', 'architecture', 'module'];
|
|
4
|
+
const fail = (message) => { throw new MayuraError('INVALID_CONFIG', message); };
|
|
5
|
+
function settings(value, project) {
|
|
6
|
+
const raw = (value ?? {});
|
|
7
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some(key => !allowed.includes(key)))
|
|
8
|
+
return fail(`targets.aws-lambda allows only ${allowed.join(', ')}.`);
|
|
9
|
+
const region = raw['region'];
|
|
10
|
+
const nodeVersion = raw['nodeVersion'] ?? 22;
|
|
11
|
+
const architecture = raw['architecture'] ?? 'x86_64';
|
|
12
|
+
const module = raw['module'] ?? `${project.app.slice(0, project.app.lastIndexOf('/') + 1)}mayura.js`;
|
|
13
|
+
if (region !== undefined && (typeof region !== 'string' || !/^[a-z]{2}(?:-[a-z]+)+-\d$/u.test(region)))
|
|
14
|
+
fail('targets.aws-lambda.region must be an AWS region, such as eu-west-1.');
|
|
15
|
+
if (nodeVersion !== 22 && nodeVersion !== 24)
|
|
16
|
+
fail('targets.aws-lambda.nodeVersion must be 22 or 24.');
|
|
17
|
+
if (architecture !== 'x86_64' && architecture !== 'arm64')
|
|
18
|
+
fail('targets.aws-lambda.architecture must be x86_64 or arm64.');
|
|
19
|
+
if (typeof module !== 'string' || !/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9_][A-Za-z0-9_./-]{0,255}\.(?:js|mjs)$/u.test(module))
|
|
20
|
+
fail('targets.aws-lambda.module must be the compiled module\'s path inside the project, such as dist/src/mayura.js.');
|
|
21
|
+
return { ...(region === undefined ? {} : { region: region }), nodeVersion, architecture, module: module };
|
|
22
|
+
}
|
|
23
|
+
/** The Lambda base image for both stages, so native modules are built for the Amazon Linux the functions run on. */
|
|
24
|
+
function lambdaDockerfile(lambda) {
|
|
25
|
+
const base = `public.ecr.aws/lambda/nodejs:${lambda.nodeVersion}`;
|
|
26
|
+
return `# The Lambda image: one build, three functions that differ only in their handler (set once per function).
|
|
27
|
+
FROM ${base} AS build
|
|
28
|
+
WORKDIR /build
|
|
29
|
+
COPY package.json package-lock.json* ./
|
|
30
|
+
RUN npm install --no-audit --no-fund
|
|
31
|
+
COPY . .
|
|
32
|
+
RUN npx tsc -p tsconfig.json && npm prune --omit=dev
|
|
33
|
+
|
|
34
|
+
FROM ${base}
|
|
35
|
+
COPY --from=build /build/package.json \${LAMBDA_TASK_ROOT}/
|
|
36
|
+
COPY --from=build /build/node_modules \${LAMBDA_TASK_ROOT}/node_modules
|
|
37
|
+
COPY --from=build /build/dist \${LAMBDA_TASK_ROOT}/dist
|
|
38
|
+
COPY deploy/aws-lambda/*.mjs \${LAMBDA_TASK_ROOT}/deploy/aws-lambda/
|
|
39
|
+
ENV NODE_ENV=production MAYURA_ENV=production
|
|
40
|
+
CMD ["deploy/aws-lambda/api.handler"]
|
|
41
|
+
`;
|
|
42
|
+
}
|
|
43
|
+
function handlers(lambda) {
|
|
44
|
+
const from = `../../${lambda.module}`;
|
|
45
|
+
return {
|
|
46
|
+
'deploy/aws-lambda/api.mjs': `// The API function, behind a function URL: each event becomes a Request for Mayura's handle().
|
|
47
|
+
import { handle } from '${from}';
|
|
48
|
+
|
|
49
|
+
export async function handler(event) {
|
|
50
|
+
const query = event.rawQueryString ? \`?\${event.rawQueryString}\` : '';
|
|
51
|
+
const method = event.requestContext.http.method;
|
|
52
|
+
const body = event.body === undefined || method === 'GET' || method === 'HEAD' ? undefined : event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body;
|
|
53
|
+
const response = await handle(new Request(\`https://\${event.requestContext.domainName}\${event.rawPath}\${query}\`, { method, headers: event.headers, body }));
|
|
54
|
+
return { statusCode: response.status, headers: Object.fromEntries(response.headers), body: await response.text() };
|
|
55
|
+
}
|
|
56
|
+
`,
|
|
57
|
+
'deploy/aws-lambda/workflows.mjs': `// The workflows function, invoked every minute by EventBridge Scheduler: advances what is due, then returns.
|
|
58
|
+
import { advanceWorkflows } from '${from}';
|
|
59
|
+
|
|
60
|
+
export const handler = () => advanceWorkflows();
|
|
61
|
+
`,
|
|
62
|
+
'deploy/aws-lambda/migrate.mjs': `// The migration function, invoked by mayura deploy before the other functions are updated.
|
|
63
|
+
import { migrate } from '${from}';
|
|
64
|
+
|
|
65
|
+
export const handler = () => migrate();
|
|
66
|
+
`,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** Deploys to AWS Lambda from one container image: the migration function first, then the API and workflows functions. */
|
|
70
|
+
export const awsLambdaTarget = defineDeployTarget({
|
|
71
|
+
id: 'aws-lambda', description: 'Deploy to AWS Lambda from one container image: migrate first, then the API and workflows functions.', tools: ['aws', 'docker'],
|
|
72
|
+
settings,
|
|
73
|
+
files: ({ settings: lambda }) => ({ '.dockerignore': dockerignore, 'deploy/aws-lambda/Dockerfile': lambdaDockerfile(lambda), ...handlers(lambda) }),
|
|
74
|
+
plan: async ({ project, settings: lambda, release, readFile }) => {
|
|
75
|
+
for (const path of ['deploy/aws-lambda/Dockerfile', 'deploy/aws-lambda/api.mjs', 'deploy/aws-lambda/workflows.mjs', 'deploy/aws-lambda/migrate.mjs'])
|
|
76
|
+
await readFile(path);
|
|
77
|
+
if (lambda.region === undefined)
|
|
78
|
+
return fail('Set targets.aws-lambda.region in mayura.deploy.json.');
|
|
79
|
+
if (release.image === undefined)
|
|
80
|
+
return fail('Lambda runs an image: set "image" in mayura.deploy.json to an ECR repository.');
|
|
81
|
+
const image = release.image;
|
|
82
|
+
const at = ['--region', lambda.region];
|
|
83
|
+
const platform = lambda.architecture === 'arm64' ? 'linux/arm64' : 'linux/amd64';
|
|
84
|
+
// The invocation's result goes nowhere: the step checks only whether the function reported an error.
|
|
85
|
+
const discard = globalThis.process?.platform === 'win32' ? 'NUL' : '/dev/null';
|
|
86
|
+
const update = (role) => [
|
|
87
|
+
{ id: `update-${role}`, description: `Point ${project.name}-${role} at the new image`, tool: 'aws',
|
|
88
|
+
args: ['lambda', 'update-function-code', ...at, '--function-name', `${project.name}-${role}`, '--image-uri', image, '--query', 'FunctionName', '--output', 'text'],
|
|
89
|
+
output: { match: `${project.name}-${role}` } },
|
|
90
|
+
{ id: `wait-${role}`, description: `Wait until ${project.name}-${role} is updated`, tool: 'aws', args: ['lambda', 'wait', 'function-updated-v2', ...at, '--function-name', `${project.name}-${role}`] },
|
|
91
|
+
];
|
|
92
|
+
return [
|
|
93
|
+
{ id: 'check-account', description: 'Check that the AWS CLI is signed in', tool: 'aws', args: ['sts', 'get-caller-identity', ...at, '--query', 'Account', '--output', 'text'], output: { match: '\\d{12}' } },
|
|
94
|
+
// Lambda takes a single-platform image manifest, so no provenance attestation is attached.
|
|
95
|
+
{ id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--file', 'deploy/aws-lambda/Dockerfile', '--platform', platform, '--provenance=false', '--tag', image, '.'] },
|
|
96
|
+
{ id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },
|
|
97
|
+
...update('migrate'),
|
|
98
|
+
// A function error (the migration threw) prints its type here; success prints None.
|
|
99
|
+
{ id: 'migrate', description: 'Run the migration and check it succeeded', tool: 'aws',
|
|
100
|
+
args: ['lambda', 'invoke', ...at, '--function-name', `${project.name}-migrate`, '--cli-read-timeout', '900', '--query', 'FunctionError', '--output', 'text', discard], output: { match: 'None' } },
|
|
101
|
+
...update('api'), ...update('workflows'),
|
|
102
|
+
];
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
export default awsLambdaTarget;
|
|
106
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmC,MAAM,QAAQ,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAsB,MAAM,mBAAmB,CAAC;AAezF,MAAM,OAAO,GAAG,CAAC,QAAQ,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC;AACpE,MAAM,IAAI,GAAG,CAAC,OAAe,EAAS,EAAE,GAAG,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/F,SAAS,QAAQ,CAAC,KAA4B,EAAE,OAAsB;IACpE,MAAM,GAAG,GAAG,CAAC,KAAK,IAAI,EAAE,CAAe,CAAC;IACxC,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC,kCAAkC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxL,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC;IAAC,MAAM,WAAW,GAAG,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IAAC,MAAM,YAAY,GAAG,GAAG,CAAC,cAAc,CAAC,IAAI,QAAQ,CAAC;IACjI,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,GAAG,C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E,EAAE,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;YACzF,GAAG,MAAM,CAAC,SAAS,CAAC;YACpB,oFAAoF;YACpF,EAAE,EAAE,EAAE,SAAS,EAAE,WAAW,EAAE,0CAA0C,EAAE,IAAI,EAAE,KAAK;gBACnF,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,IAAI,UAAU,EAAE,oBAAoB,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACpM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC;SACzC,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,eAAe,eAAe,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type JsonValue } from 'mayura';\nimport { defineDeployTarget, dockerignore, type DeployProject } from 'mayura/cli/deploy';\n\nexport interface AwsLambdaSettings {\n readonly region: string;\n /** The Lambda Node.js base image's major version: 22 by default. */\n readonly nodeVersion: 22 | 24;\n /** The instruction set the functions run on: `x86_64` (default) or `arm64`. */\n readonly architecture: 'x86_64' | 'arm64';\n /**\n * The compiled module that exports `handle(request)`, `advanceWorkflows()` and `migrate()`, relative to the project:\n * by default `mayura.js` next to the app module, such as `dist/src/mayura.js`.\n */\n readonly module: string;\n}\n\nconst allowed = ['region', 'nodeVersion', 'architecture', 'module'];\nconst fail = (message: string): never => { throw new MayuraError('INVALID_CONFIG', message); };\n\nfunction settings(value: JsonValue | undefined, project: DeployProject): AwsLambdaSettings {\n const raw = (value ?? {}) as JsonObject;\n if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some(key => !allowed.includes(key))) return fail(`targets.aws-lambda allows only ${allowed.join(', ')}.`);\n const region = raw['region']; const nodeVersion = raw['nodeVersion'] ?? 22; const architecture = raw['architecture'] ?? 'x86_64';\n const module = raw['module'] ?? `${project.app.slice(0, project.app.lastIndexOf('/') + 1)}mayura.js`;\n if (region !== undefined && (typeof region !== 'string' || !/^[a-z]{2}(?:-[a-z]+)+-\\d$/u.test(region))) fail('targets.aws-lambda.region must be an AWS region, such as eu-west-1.');\n if (nodeVersion !== 22 && nodeVersion !== 24) fail('targets.aws-lambda.nodeVersion must be 22 or 24.');\n if (architecture !== 'x86_64' && architecture !== 'arm64') fail('targets.aws-lambda.architecture must be x86_64 or arm64.');\n if (typeof module !== 'string' || !/^(?!\\/)(?!.*(?:^|\\/)\\.\\.?(?:\\/|$))[A-Za-z0-9_][A-Za-z0-9_./-]{0,255}\\.(?:js|mjs)$/u.test(module)) fail('targets.aws-lambda.module must be the compiled module\\'s path inside the project, such as dist/src/mayura.js.');\n return { ...(region === undefined ? {} : { region: region as string }), nodeVersion, architecture, module: module as string } as AwsLambdaSettings;\n}\n\n/** The Lambda base image for both stages, so native modules are built for the Amazon Linux the functions run on. */\nfunction lambdaDockerfile(lambda: AwsLambdaSettings): string {\n const base = `public.ecr.aws/lambda/nodejs:${lambda.nodeVersion}`;\n return `# The Lambda image: one build, three functions that differ only in their handler (set once per function).\nFROM ${base} AS build\nWORKDIR /build\nCOPY package.json package-lock.json* ./\nRUN npm install --no-audit --no-fund\nCOPY . .\nRUN npx tsc -p tsconfig.json && npm prune --omit=dev\n\nFROM ${base}\nCOPY --from=build /build/package.json \\${LAMBDA_TASK_ROOT}/\nCOPY --from=build /build/node_modules \\${LAMBDA_TASK_ROOT}/node_modules\nCOPY --from=build /build/dist \\${LAMBDA_TASK_ROOT}/dist\nCOPY deploy/aws-lambda/*.mjs \\${LAMBDA_TASK_ROOT}/deploy/aws-lambda/\nENV NODE_ENV=production MAYURA_ENV=production\nCMD [\"deploy/aws-lambda/api.handler\"]\n`;\n}\n\nfunction handlers(lambda: AwsLambdaSettings): Record<string, string> {\n const from = `../../${lambda.module}`;\n return {\n 'deploy/aws-lambda/api.mjs': `// The API function, behind a function URL: each event becomes a Request for Mayura's handle().\nimport { handle } from '${from}';\n\nexport async function handler(event) {\n const query = event.rawQueryString ? \\`?\\${event.rawQueryString}\\` : '';\n const method = event.requestContext.http.method;\n const body = event.body === undefined || method === 'GET' || method === 'HEAD' ? undefined : event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body;\n const response = await handle(new Request(\\`https://\\${event.requestContext.domainName}\\${event.rawPath}\\${query}\\`, { method, headers: event.headers, body }));\n return { statusCode: response.status, headers: Object.fromEntries(response.headers), body: await response.text() };\n}\n`,\n 'deploy/aws-lambda/workflows.mjs': `// The workflows function, invoked every minute by EventBridge Scheduler: advances what is due, then returns.\nimport { advanceWorkflows } from '${from}';\n\nexport const handler = () => advanceWorkflows();\n`,\n 'deploy/aws-lambda/migrate.mjs': `// The migration function, invoked by mayura deploy before the other functions are updated.\nimport { migrate } from '${from}';\n\nexport const handler = () => migrate();\n`,\n };\n}\n\n/** Deploys to AWS Lambda from one container image: the migration function first, then the API and workflows functions. */\nexport const awsLambdaTarget = defineDeployTarget<AwsLambdaSettings>({\n id: 'aws-lambda', description: 'Deploy to AWS Lambda from one container image: migrate first, then the API and workflows functions.', tools: ['aws', 'docker'],\n settings,\n files: ({ settings: lambda }) => ({ '.dockerignore': dockerignore, 'deploy/aws-lambda/Dockerfile': lambdaDockerfile(lambda), ...handlers(lambda) }),\n plan: async ({ project, settings: lambda, release, readFile }) => {\n for (const path of ['deploy/aws-lambda/Dockerfile', 'deploy/aws-lambda/api.mjs', 'deploy/aws-lambda/workflows.mjs', 'deploy/aws-lambda/migrate.mjs']) await readFile(path);\n if (lambda.region === undefined) return fail('Set targets.aws-lambda.region in mayura.deploy.json.');\n if (release.image === undefined) return fail('Lambda runs an image: set \"image\" in mayura.deploy.json to an ECR repository.');\n const image = release.image; const at = ['--region', lambda.region];\n const platform = lambda.architecture === 'arm64' ? 'linux/arm64' : 'linux/amd64';\n // The invocation's result goes nowhere: the step checks only whether the function reported an error.\n const discard = (globalThis as { readonly process?: { readonly platform?: string } }).process?.platform === 'win32' ? 'NUL' : '/dev/null';\n const update = (role: string) => [\n { id: `update-${role}`, description: `Point ${project.name}-${role} at the new image`, tool: 'aws',\n args: ['lambda', 'update-function-code', ...at, '--function-name', `${project.name}-${role}`, '--image-uri', image, '--query', 'FunctionName', '--output', 'text'],\n output: { match: `${project.name}-${role}` } },\n { id: `wait-${role}`, description: `Wait until ${project.name}-${role} is updated`, tool: 'aws', args: ['lambda', 'wait', 'function-updated-v2', ...at, '--function-name', `${project.name}-${role}`] },\n ];\n return [\n { id: 'check-account', description: 'Check that the AWS CLI is signed in', tool: 'aws', args: ['sts', 'get-caller-identity', ...at, '--query', 'Account', '--output', 'text'], output: { match: '\\\\d{12}' } },\n // Lambda takes a single-platform image manifest, so no provenance attestation is attached.\n { id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--file', 'deploy/aws-lambda/Dockerfile', '--platform', platform, '--provenance=false', '--tag', image, '.'] },\n { id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },\n ...update('migrate'),\n // A function error (the migration threw) prints its type here; success prints None.\n { id: 'migrate', description: 'Run the migration and check it succeeded', tool: 'aws',\n args: ['lambda', 'invoke', ...at, '--function-name', `${project.name}-migrate`, '--cli-read-timeout', '900', '--query', 'FunctionError', '--output', 'text', discard], output: { match: 'None' } },\n ...update('api'), ...update('workflows'),\n ];\n },\n});\n\nexport default awsLambdaTarget;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/deploy-aws-lambda",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "AWS Lambda as a mayura deploy target: one container image, the migration function first, then the API and workflows functions.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Aryabh",
|
|
7
|
+
"email": "dev@rokad.co"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/KartikeyAI/mayura.git",
|
|
13
|
+
"directory": "extensions/deploy-aws-lambda"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/KartikeyAI/mayura#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/KartikeyAI/mayura/issues"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.12.0 <23 || >=24.14.1 <25"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src/**/*.ts",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"NOTICE"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"mayura": "^1.2.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { MayuraError, type JsonObject, type JsonValue } from 'mayura';
|
|
2
|
+
import { defineDeployTarget, dockerignore, type DeployProject } from 'mayura/cli/deploy';
|
|
3
|
+
|
|
4
|
+
export interface AwsLambdaSettings {
|
|
5
|
+
readonly region: string;
|
|
6
|
+
/** The Lambda Node.js base image's major version: 22 by default. */
|
|
7
|
+
readonly nodeVersion: 22 | 24;
|
|
8
|
+
/** The instruction set the functions run on: `x86_64` (default) or `arm64`. */
|
|
9
|
+
readonly architecture: 'x86_64' | 'arm64';
|
|
10
|
+
/**
|
|
11
|
+
* The compiled module that exports `handle(request)`, `advanceWorkflows()` and `migrate()`, relative to the project:
|
|
12
|
+
* by default `mayura.js` next to the app module, such as `dist/src/mayura.js`.
|
|
13
|
+
*/
|
|
14
|
+
readonly module: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const allowed = ['region', 'nodeVersion', 'architecture', 'module'];
|
|
18
|
+
const fail = (message: string): never => { throw new MayuraError('INVALID_CONFIG', message); };
|
|
19
|
+
|
|
20
|
+
function settings(value: JsonValue | undefined, project: DeployProject): AwsLambdaSettings {
|
|
21
|
+
const raw = (value ?? {}) as JsonObject;
|
|
22
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some(key => !allowed.includes(key))) return fail(`targets.aws-lambda allows only ${allowed.join(', ')}.`);
|
|
23
|
+
const region = raw['region']; const nodeVersion = raw['nodeVersion'] ?? 22; const architecture = raw['architecture'] ?? 'x86_64';
|
|
24
|
+
const module = raw['module'] ?? `${project.app.slice(0, project.app.lastIndexOf('/') + 1)}mayura.js`;
|
|
25
|
+
if (region !== undefined && (typeof region !== 'string' || !/^[a-z]{2}(?:-[a-z]+)+-\d$/u.test(region))) fail('targets.aws-lambda.region must be an AWS region, such as eu-west-1.');
|
|
26
|
+
if (nodeVersion !== 22 && nodeVersion !== 24) fail('targets.aws-lambda.nodeVersion must be 22 or 24.');
|
|
27
|
+
if (architecture !== 'x86_64' && architecture !== 'arm64') fail('targets.aws-lambda.architecture must be x86_64 or arm64.');
|
|
28
|
+
if (typeof module !== 'string' || !/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9_][A-Za-z0-9_./-]{0,255}\.(?:js|mjs)$/u.test(module)) fail('targets.aws-lambda.module must be the compiled module\'s path inside the project, such as dist/src/mayura.js.');
|
|
29
|
+
return { ...(region === undefined ? {} : { region: region as string }), nodeVersion, architecture, module: module as string } as AwsLambdaSettings;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The Lambda base image for both stages, so native modules are built for the Amazon Linux the functions run on. */
|
|
33
|
+
function lambdaDockerfile(lambda: AwsLambdaSettings): string {
|
|
34
|
+
const base = `public.ecr.aws/lambda/nodejs:${lambda.nodeVersion}`;
|
|
35
|
+
return `# The Lambda image: one build, three functions that differ only in their handler (set once per function).
|
|
36
|
+
FROM ${base} AS build
|
|
37
|
+
WORKDIR /build
|
|
38
|
+
COPY package.json package-lock.json* ./
|
|
39
|
+
RUN npm install --no-audit --no-fund
|
|
40
|
+
COPY . .
|
|
41
|
+
RUN npx tsc -p tsconfig.json && npm prune --omit=dev
|
|
42
|
+
|
|
43
|
+
FROM ${base}
|
|
44
|
+
COPY --from=build /build/package.json \${LAMBDA_TASK_ROOT}/
|
|
45
|
+
COPY --from=build /build/node_modules \${LAMBDA_TASK_ROOT}/node_modules
|
|
46
|
+
COPY --from=build /build/dist \${LAMBDA_TASK_ROOT}/dist
|
|
47
|
+
COPY deploy/aws-lambda/*.mjs \${LAMBDA_TASK_ROOT}/deploy/aws-lambda/
|
|
48
|
+
ENV NODE_ENV=production MAYURA_ENV=production
|
|
49
|
+
CMD ["deploy/aws-lambda/api.handler"]
|
|
50
|
+
`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function handlers(lambda: AwsLambdaSettings): Record<string, string> {
|
|
54
|
+
const from = `../../${lambda.module}`;
|
|
55
|
+
return {
|
|
56
|
+
'deploy/aws-lambda/api.mjs': `// The API function, behind a function URL: each event becomes a Request for Mayura's handle().
|
|
57
|
+
import { handle } from '${from}';
|
|
58
|
+
|
|
59
|
+
export async function handler(event) {
|
|
60
|
+
const query = event.rawQueryString ? \`?\${event.rawQueryString}\` : '';
|
|
61
|
+
const method = event.requestContext.http.method;
|
|
62
|
+
const body = event.body === undefined || method === 'GET' || method === 'HEAD' ? undefined : event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body;
|
|
63
|
+
const response = await handle(new Request(\`https://\${event.requestContext.domainName}\${event.rawPath}\${query}\`, { method, headers: event.headers, body }));
|
|
64
|
+
return { statusCode: response.status, headers: Object.fromEntries(response.headers), body: await response.text() };
|
|
65
|
+
}
|
|
66
|
+
`,
|
|
67
|
+
'deploy/aws-lambda/workflows.mjs': `// The workflows function, invoked every minute by EventBridge Scheduler: advances what is due, then returns.
|
|
68
|
+
import { advanceWorkflows } from '${from}';
|
|
69
|
+
|
|
70
|
+
export const handler = () => advanceWorkflows();
|
|
71
|
+
`,
|
|
72
|
+
'deploy/aws-lambda/migrate.mjs': `// The migration function, invoked by mayura deploy before the other functions are updated.
|
|
73
|
+
import { migrate } from '${from}';
|
|
74
|
+
|
|
75
|
+
export const handler = () => migrate();
|
|
76
|
+
`,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Deploys to AWS Lambda from one container image: the migration function first, then the API and workflows functions. */
|
|
81
|
+
export const awsLambdaTarget = defineDeployTarget<AwsLambdaSettings>({
|
|
82
|
+
id: 'aws-lambda', description: 'Deploy to AWS Lambda from one container image: migrate first, then the API and workflows functions.', tools: ['aws', 'docker'],
|
|
83
|
+
settings,
|
|
84
|
+
files: ({ settings: lambda }) => ({ '.dockerignore': dockerignore, 'deploy/aws-lambda/Dockerfile': lambdaDockerfile(lambda), ...handlers(lambda) }),
|
|
85
|
+
plan: async ({ project, settings: lambda, release, readFile }) => {
|
|
86
|
+
for (const path of ['deploy/aws-lambda/Dockerfile', 'deploy/aws-lambda/api.mjs', 'deploy/aws-lambda/workflows.mjs', 'deploy/aws-lambda/migrate.mjs']) await readFile(path);
|
|
87
|
+
if (lambda.region === undefined) return fail('Set targets.aws-lambda.region in mayura.deploy.json.');
|
|
88
|
+
if (release.image === undefined) return fail('Lambda runs an image: set "image" in mayura.deploy.json to an ECR repository.');
|
|
89
|
+
const image = release.image; const at = ['--region', lambda.region];
|
|
90
|
+
const platform = lambda.architecture === 'arm64' ? 'linux/arm64' : 'linux/amd64';
|
|
91
|
+
// The invocation's result goes nowhere: the step checks only whether the function reported an error.
|
|
92
|
+
const discard = (globalThis as { readonly process?: { readonly platform?: string } }).process?.platform === 'win32' ? 'NUL' : '/dev/null';
|
|
93
|
+
const update = (role: string) => [
|
|
94
|
+
{ id: `update-${role}`, description: `Point ${project.name}-${role} at the new image`, tool: 'aws',
|
|
95
|
+
args: ['lambda', 'update-function-code', ...at, '--function-name', `${project.name}-${role}`, '--image-uri', image, '--query', 'FunctionName', '--output', 'text'],
|
|
96
|
+
output: { match: `${project.name}-${role}` } },
|
|
97
|
+
{ id: `wait-${role}`, description: `Wait until ${project.name}-${role} is updated`, tool: 'aws', args: ['lambda', 'wait', 'function-updated-v2', ...at, '--function-name', `${project.name}-${role}`] },
|
|
98
|
+
];
|
|
99
|
+
return [
|
|
100
|
+
{ id: 'check-account', description: 'Check that the AWS CLI is signed in', tool: 'aws', args: ['sts', 'get-caller-identity', ...at, '--query', 'Account', '--output', 'text'], output: { match: '\\d{12}' } },
|
|
101
|
+
// Lambda takes a single-platform image manifest, so no provenance attestation is attached.
|
|
102
|
+
{ id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--file', 'deploy/aws-lambda/Dockerfile', '--platform', platform, '--provenance=false', '--tag', image, '.'] },
|
|
103
|
+
{ id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },
|
|
104
|
+
...update('migrate'),
|
|
105
|
+
// A function error (the migration threw) prints its type here; success prints None.
|
|
106
|
+
{ id: 'migrate', description: 'Run the migration and check it succeeded', tool: 'aws',
|
|
107
|
+
args: ['lambda', 'invoke', ...at, '--function-name', `${project.name}-migrate`, '--cli-read-timeout', '900', '--query', 'FunctionError', '--output', 'text', discard], output: { match: 'None' } },
|
|
108
|
+
...update('api'), ...update('workflows'),
|
|
109
|
+
];
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
export default awsLambdaTarget;
|