@capsulos/provider-lambda 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +219 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -3
- package/src/index.ts +260 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type LambdaMicrovmsClientConfig } from '@aws-sdk/client-lambda-microvms';
|
|
2
|
+
import { type CapsuleHandle, type CapsuleInfo, type CapsuleSpec, type Connection, type CreateOptions, type HeadersOptions, type Provider } from '@capsulos/sdk';
|
|
3
|
+
export interface LambdaProviderOptions {
|
|
4
|
+
region: string;
|
|
5
|
+
/** AWS account id, used to build image ARNs from template names. */
|
|
6
|
+
accountId: string;
|
|
7
|
+
credentials?: LambdaMicrovmsClientConfig['credentials'];
|
|
8
|
+
/** Ingress connector; defaults to the service's ALL_INGRESS. */
|
|
9
|
+
ingressConnectorArn?: string;
|
|
10
|
+
/** Egress connector (e.g. a VPC connector with a deny-all security group). Omit for internet egress. */
|
|
11
|
+
egressConnectorArn?: string;
|
|
12
|
+
/** IAM role the capsule assumes (S3 mounts, etc.). */
|
|
13
|
+
executionRoleArn?: string;
|
|
14
|
+
/** Default hard limit per capsule. */
|
|
15
|
+
maxDurationSeconds?: number;
|
|
16
|
+
/** Minutes before an endpoint token is re-minted (service max is 60). */
|
|
17
|
+
tokenTtlMinutes?: number;
|
|
18
|
+
/** Ports the endpoint token allows; 8080 (capsulod) is always included. */
|
|
19
|
+
allowedPorts?: number[];
|
|
20
|
+
}
|
|
21
|
+
export declare class LambdaProvider implements Provider {
|
|
22
|
+
private readonly opts;
|
|
23
|
+
readonly name = "lambda";
|
|
24
|
+
private readonly client;
|
|
25
|
+
private readonly tokens;
|
|
26
|
+
constructor(opts: LambdaProviderOptions);
|
|
27
|
+
/** Templates are MicrovmImages; the API wants the full ARN (a plain name fails). */
|
|
28
|
+
imageArn(template: string): string;
|
|
29
|
+
create(spec: CapsuleSpec, opts?: CreateOptions): Promise<CapsuleHandle>;
|
|
30
|
+
get(id: string): Promise<CapsuleInfo | null>;
|
|
31
|
+
/** All microVMs of one template (the API lists per image). */
|
|
32
|
+
list(template?: string): Promise<CapsuleInfo[]>;
|
|
33
|
+
terminate(id: string): Promise<void>;
|
|
34
|
+
connect(id: string): Promise<Connection>;
|
|
35
|
+
/** A Connection from an endpoint already in hand (get() returns it): no extra GetMicrovm. */
|
|
36
|
+
connectionFor(id: string, endpoint: string): Connection;
|
|
37
|
+
/** Headers to reach another port of the capsule through the same endpoint. */
|
|
38
|
+
portHeaders(id: string, port: number, opts?: HeadersOptions): Promise<Record<string, string>>;
|
|
39
|
+
/** Forget the cached endpoint token: the next request mints a new one. */
|
|
40
|
+
invalidateToken(id: string): void;
|
|
41
|
+
private infoOf;
|
|
42
|
+
private token;
|
|
43
|
+
/**
|
|
44
|
+
* Poll until the VM runs. A SUSPENDED VM (a clientToken that recovered an
|
|
45
|
+
* idle one) counts as alive: the first request auto-resumes it. Timeout and
|
|
46
|
+
* abort throw a CapsuleError that names the VM (capsuleId) for the caller
|
|
47
|
+
* to clean up; create() does that itself.
|
|
48
|
+
*/
|
|
49
|
+
private waitForRunning;
|
|
50
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Provider for AWS Lambda MicroVMs. One capsule = one microVM. The SDK talks
|
|
2
|
+
// to AWS with the caller's credentials and to capsulod through the microVM's
|
|
3
|
+
// HTTPS endpoint (header X-aws-proxy-auth). No control plane in between.
|
|
4
|
+
//
|
|
5
|
+
// Verified on the service (docs/lambda-microvms-findings.md):
|
|
6
|
+
// - the image must be built with additionalOsCapabilities: ['ALL'] for mounts
|
|
7
|
+
// - executionRoleArn gives the capsule an IAM identity (S3 without secrets)
|
|
8
|
+
// - endpoint tokens expire after at most 60 min: cached in memory, re-minted
|
|
9
|
+
// - other ports are addressed with the X-aws-proxy-port header
|
|
10
|
+
// - the idle policy suspends and the first request auto-resumes (~0.8 s)
|
|
11
|
+
// - clientToken is both idempotency and recovery (same token → same VM);
|
|
12
|
+
// a recovered VM may be SUSPENDED, which create() accepts as alive
|
|
13
|
+
import { LambdaMicrovmsClient, RunMicrovmCommand, GetMicrovmCommand, ListMicrovmsCommand, TerminateMicrovmCommand, CreateMicrovmAuthTokenCommand, } from '@aws-sdk/client-lambda-microvms';
|
|
14
|
+
import { CapsuleError, } from '@capsulos/sdk';
|
|
15
|
+
const CAPSULOD_PORT = 8080;
|
|
16
|
+
function toState(s) {
|
|
17
|
+
switch (s) {
|
|
18
|
+
case 'PENDING':
|
|
19
|
+
return 'pending';
|
|
20
|
+
case 'RUNNING':
|
|
21
|
+
return 'running';
|
|
22
|
+
case 'SUSPENDING':
|
|
23
|
+
case 'SUSPENDED':
|
|
24
|
+
return 'suspended';
|
|
25
|
+
case 'TERMINATING':
|
|
26
|
+
case 'TERMINATED':
|
|
27
|
+
return 'terminated';
|
|
28
|
+
default:
|
|
29
|
+
return 'unknown';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class LambdaProvider {
|
|
33
|
+
opts;
|
|
34
|
+
name = 'lambda';
|
|
35
|
+
client;
|
|
36
|
+
tokens = new Map();
|
|
37
|
+
constructor(opts) {
|
|
38
|
+
this.opts = opts;
|
|
39
|
+
this.client = new LambdaMicrovmsClient({
|
|
40
|
+
region: opts.region,
|
|
41
|
+
...(opts.credentials ? { credentials: opts.credentials } : {}),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Templates are MicrovmImages; the API wants the full ARN (a plain name fails). */
|
|
45
|
+
imageArn(template) {
|
|
46
|
+
if (template.startsWith('arn:'))
|
|
47
|
+
return template;
|
|
48
|
+
return `arn:aws:lambda:${this.opts.region}:${this.opts.accountId}:microvm-image:${template}`;
|
|
49
|
+
}
|
|
50
|
+
async create(spec, opts = {}) {
|
|
51
|
+
const ingress = this.opts.ingressConnectorArn ??
|
|
52
|
+
`arn:aws:lambda:${this.opts.region}:aws:network-connector:aws-network-connector:ALL_INGRESS`;
|
|
53
|
+
const res = await this.client.send(new RunMicrovmCommand({
|
|
54
|
+
imageIdentifier: this.imageArn(spec.template),
|
|
55
|
+
ingressNetworkConnectors: [ingress],
|
|
56
|
+
...(this.opts.egressConnectorArn ? { egressNetworkConnectors: [this.opts.egressConnectorArn] } : {}),
|
|
57
|
+
...(this.opts.executionRoleArn ? { executionRoleArn: this.opts.executionRoleArn } : {}),
|
|
58
|
+
...(spec.idle
|
|
59
|
+
? {
|
|
60
|
+
idlePolicy: {
|
|
61
|
+
maxIdleDurationSeconds: spec.idle.suspendAfterSeconds,
|
|
62
|
+
suspendedDurationSeconds: spec.idle.destroyAfterSeconds,
|
|
63
|
+
autoResumeEnabled: true,
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
: {}),
|
|
67
|
+
maximumDurationInSeconds: spec.maxDurationSeconds ?? this.opts.maxDurationSeconds ?? 8 * 3600,
|
|
68
|
+
...(spec.clientToken ? { clientToken: spec.clientToken } : {}),
|
|
69
|
+
// The daemon receives mounts + metadata through the /run hook (never secrets).
|
|
70
|
+
runHookPayload: JSON.stringify({ mounts: spec.mounts ?? {}, metadata: spec.metadata ?? {} }),
|
|
71
|
+
}));
|
|
72
|
+
if (!res.microvmId)
|
|
73
|
+
throw new CapsuleError('RunMicrovm returned no microvmId');
|
|
74
|
+
const id = res.microvmId;
|
|
75
|
+
let info;
|
|
76
|
+
try {
|
|
77
|
+
info = await this.waitForRunning(id, opts);
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
// Never leave a VM running without an owner: the caller gets an error,
|
|
81
|
+
// not a capsule, so the VM goes too (the error still names it).
|
|
82
|
+
if (err instanceof CapsuleError && err.capsuleId === id) {
|
|
83
|
+
await this.terminate(id).catch(() => undefined);
|
|
84
|
+
throw new CapsuleError(`${err.message}; terminated it`, err.status, { capsuleId: id });
|
|
85
|
+
}
|
|
86
|
+
throw err;
|
|
87
|
+
}
|
|
88
|
+
if (!info.endpoint)
|
|
89
|
+
throw new CapsuleError(`microVM ${id} is ${info.state} but has no endpoint`, undefined, { capsuleId: id });
|
|
90
|
+
return { ...info, connection: this.connectionFor(id, info.endpoint) };
|
|
91
|
+
}
|
|
92
|
+
async get(id) {
|
|
93
|
+
try {
|
|
94
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }));
|
|
95
|
+
return this.infoOf(id, vm);
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (err instanceof Error && err.name === 'ResourceNotFoundException')
|
|
99
|
+
return null;
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** All microVMs of one template (the API lists per image). */
|
|
104
|
+
async list(template) {
|
|
105
|
+
if (!template)
|
|
106
|
+
throw new CapsuleError('LambdaProvider.list needs a template: the API lists microVMs per image');
|
|
107
|
+
const out = [];
|
|
108
|
+
let nextToken;
|
|
109
|
+
do {
|
|
110
|
+
const page = await this.client.send(new ListMicrovmsCommand({ imageIdentifier: this.imageArn(template), nextToken }));
|
|
111
|
+
for (const item of page.items ?? []) {
|
|
112
|
+
if (!item.microvmId)
|
|
113
|
+
continue;
|
|
114
|
+
// The list item carries no endpoint, terminatedAt or stateReason: get() does.
|
|
115
|
+
out.push({
|
|
116
|
+
id: item.microvmId,
|
|
117
|
+
provider: this.name,
|
|
118
|
+
state: toState(item.state),
|
|
119
|
+
template: item.imageArn ?? null,
|
|
120
|
+
templateVersion: item.imageVersion ?? null,
|
|
121
|
+
createdAt: item.startedAt ?? null,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
nextToken = page.nextToken;
|
|
125
|
+
} while (nextToken);
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
async terminate(id) {
|
|
129
|
+
try {
|
|
130
|
+
await this.client.send(new TerminateMicrovmCommand({ microvmIdentifier: id }));
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
if (err instanceof Error && err.name === 'ResourceNotFoundException')
|
|
134
|
+
return;
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
this.tokens.delete(id);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async connect(id) {
|
|
142
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }));
|
|
143
|
+
if (!vm.endpoint)
|
|
144
|
+
throw new CapsuleError(`microVM ${id} has no endpoint yet (state ${vm.state})`, undefined, { capsuleId: id });
|
|
145
|
+
return this.connectionFor(id, vm.endpoint);
|
|
146
|
+
}
|
|
147
|
+
/** A Connection from an endpoint already in hand (get() returns it): no extra GetMicrovm. */
|
|
148
|
+
connectionFor(id, endpoint) {
|
|
149
|
+
return {
|
|
150
|
+
baseUrl: endpoint.startsWith('https://') ? endpoint : `https://${endpoint}`,
|
|
151
|
+
headers: async (opts) => ({ 'X-aws-proxy-auth': await this.token(id, opts?.fresh) }),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/** Headers to reach another port of the capsule through the same endpoint. */
|
|
155
|
+
async portHeaders(id, port, opts) {
|
|
156
|
+
return { 'X-aws-proxy-auth': await this.token(id, opts?.fresh), 'X-aws-proxy-port': String(port) };
|
|
157
|
+
}
|
|
158
|
+
/** Forget the cached endpoint token: the next request mints a new one. */
|
|
159
|
+
invalidateToken(id) {
|
|
160
|
+
this.tokens.delete(id);
|
|
161
|
+
}
|
|
162
|
+
infoOf(id, vm) {
|
|
163
|
+
return {
|
|
164
|
+
id,
|
|
165
|
+
provider: this.name,
|
|
166
|
+
state: toState(vm.state),
|
|
167
|
+
template: vm.imageArn ?? null,
|
|
168
|
+
templateVersion: vm.imageVersion ?? null,
|
|
169
|
+
createdAt: vm.startedAt ?? null,
|
|
170
|
+
terminatedAt: vm.terminatedAt ?? null,
|
|
171
|
+
stateReason: vm.stateReason ?? null,
|
|
172
|
+
endpoint: vm.endpoint ? `https://${vm.endpoint}` : null,
|
|
173
|
+
maxDurationSeconds: vm.maximumDurationInSeconds ?? null,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
async token(id, fresh = false) {
|
|
177
|
+
const cached = this.tokens.get(id);
|
|
178
|
+
if (cached && cached.expiresAt > Date.now() && !fresh)
|
|
179
|
+
return cached.value;
|
|
180
|
+
const ttl = Math.min(this.opts.tokenTtlMinutes ?? 60, 60);
|
|
181
|
+
const ports = new Set([CAPSULOD_PORT, ...(this.opts.allowedPorts ?? [])]);
|
|
182
|
+
const res = await this.client.send(new CreateMicrovmAuthTokenCommand({
|
|
183
|
+
microvmIdentifier: id,
|
|
184
|
+
expirationInMinutes: ttl,
|
|
185
|
+
allowedPorts: [...ports].map((port) => ({ port })),
|
|
186
|
+
}));
|
|
187
|
+
const value = res.authToken?.['X-aws-proxy-auth'];
|
|
188
|
+
if (!value)
|
|
189
|
+
throw new CapsuleError('CreateMicrovmAuthToken returned no X-aws-proxy-auth');
|
|
190
|
+
// Re-mint a few minutes early; never persist the token anywhere.
|
|
191
|
+
this.tokens.set(id, { value, expiresAt: Date.now() + (ttl - 5) * 60_000 });
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Poll until the VM runs. A SUSPENDED VM (a clientToken that recovered an
|
|
196
|
+
* idle one) counts as alive: the first request auto-resumes it. Timeout and
|
|
197
|
+
* abort throw a CapsuleError that names the VM (capsuleId) for the caller
|
|
198
|
+
* to clean up; create() does that itself.
|
|
199
|
+
*/
|
|
200
|
+
async waitForRunning(id, opts = {}) {
|
|
201
|
+
const timeoutMs = opts.timeoutMs ?? 120_000;
|
|
202
|
+
const t0 = Date.now();
|
|
203
|
+
for (;;) {
|
|
204
|
+
if (opts.signal?.aborted)
|
|
205
|
+
throw new CapsuleError(`creation of microVM ${id} aborted`, undefined, { capsuleId: id });
|
|
206
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }), { abortSignal: opts.signal });
|
|
207
|
+
if (vm.state === 'RUNNING' || vm.state === 'SUSPENDED')
|
|
208
|
+
return this.infoOf(id, vm);
|
|
209
|
+
if (vm.state === 'TERMINATED' || vm.state === 'TERMINATING') {
|
|
210
|
+
throw new CapsuleError(`microVM ${id} died while starting: ${vm.stateReason ?? vm.state}`, undefined, { capsuleId: id });
|
|
211
|
+
}
|
|
212
|
+
if (Date.now() - t0 > timeoutMs) {
|
|
213
|
+
throw new CapsuleError(`microVM ${id} did not run within ${timeoutMs}ms (state ${vm.state})`, undefined, { capsuleId: id });
|
|
214
|
+
}
|
|
215
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,EAAE;AACF,8DAA8D;AAC9D,gFAAgF;AAChF,8EAA8E;AAC9E,+EAA+E;AAC/E,iEAAiE;AACjE,2EAA2E;AAC3E,2EAA2E;AAC3E,uEAAuE;AACvE,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,uBAAuB,EACvB,6BAA6B,GAE9B,MAAM,i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C,MAAM,CAAC,IAAI,CAAC,IAAI,iBAAiB,CAAC,EAAE,iBAAiB,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YAClH,IAAI,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,CAAC,KAAK,KAAK,WAAW;gBAAE,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YACnF,IAAI,EAAE,CAAC,KAAK,KAAK,YAAY,IAAI,EAAE,CAAC,KAAK,KAAK,aAAa,EAAE,CAAC;gBAC5D,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,yBAAyB,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC;YAC3H,CAAC;YACD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,SAAS,EAAE,CAAC;gBAChC,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,uBAAuB,SAAS,aAAa,EAAE,CAAC,KAAK,GAAG,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC;YAC9H,CAAC;YACD,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capsulos/provider-lambda",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "capsulos provider for AWS Lambda MicroVMs: capsules on your own AWS account.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"sandbox",
|
|
8
|
+
"ai-agents",
|
|
9
|
+
"aws",
|
|
10
|
+
"lambda",
|
|
11
|
+
"microvm",
|
|
12
|
+
"firecracker",
|
|
13
|
+
"e2b",
|
|
14
|
+
"daytona"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://github.com/tornoai/capsulos#readme",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/tornoai/capsulos.git",
|
|
20
|
+
"directory": "packages/provider-lambda"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/tornoai/capsulos/issues"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22"
|
|
27
|
+
},
|
|
28
|
+
"type": "module",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"main": "./dist/index.js",
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"src"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@aws-sdk/client-lambda-microvms": "^3.1158.0",
|
|
47
|
+
"@capsulos/sdk": "0.1.1"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/node": "^22.20.1",
|
|
51
|
+
"typescript": "^5.9.0",
|
|
52
|
+
"vitest": "^4.1.10"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"typecheck": "tsc --noEmit",
|
|
56
|
+
"build": "tsc -p tsconfig.build.json",
|
|
57
|
+
"test": "vitest run --passWithNoTests"
|
|
58
|
+
}
|
|
6
59
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// Provider for AWS Lambda MicroVMs. One capsule = one microVM. The SDK talks
|
|
2
|
+
// to AWS with the caller's credentials and to capsulod through the microVM's
|
|
3
|
+
// HTTPS endpoint (header X-aws-proxy-auth). No control plane in between.
|
|
4
|
+
//
|
|
5
|
+
// Verified on the service (docs/lambda-microvms-findings.md):
|
|
6
|
+
// - the image must be built with additionalOsCapabilities: ['ALL'] for mounts
|
|
7
|
+
// - executionRoleArn gives the capsule an IAM identity (S3 without secrets)
|
|
8
|
+
// - endpoint tokens expire after at most 60 min: cached in memory, re-minted
|
|
9
|
+
// - other ports are addressed with the X-aws-proxy-port header
|
|
10
|
+
// - the idle policy suspends and the first request auto-resumes (~0.8 s)
|
|
11
|
+
// - clientToken is both idempotency and recovery (same token → same VM);
|
|
12
|
+
// a recovered VM may be SUSPENDED, which create() accepts as alive
|
|
13
|
+
import {
|
|
14
|
+
LambdaMicrovmsClient,
|
|
15
|
+
RunMicrovmCommand,
|
|
16
|
+
GetMicrovmCommand,
|
|
17
|
+
ListMicrovmsCommand,
|
|
18
|
+
TerminateMicrovmCommand,
|
|
19
|
+
CreateMicrovmAuthTokenCommand,
|
|
20
|
+
type LambdaMicrovmsClientConfig,
|
|
21
|
+
} from '@aws-sdk/client-lambda-microvms';
|
|
22
|
+
import {
|
|
23
|
+
CapsuleError,
|
|
24
|
+
type CapsuleHandle,
|
|
25
|
+
type CapsuleInfo,
|
|
26
|
+
type CapsuleSpec,
|
|
27
|
+
type CapsuleState,
|
|
28
|
+
type Connection,
|
|
29
|
+
type CreateOptions,
|
|
30
|
+
type HeadersOptions,
|
|
31
|
+
type Provider,
|
|
32
|
+
} from '@capsulos/sdk';
|
|
33
|
+
|
|
34
|
+
export interface LambdaProviderOptions {
|
|
35
|
+
region: string;
|
|
36
|
+
/** AWS account id, used to build image ARNs from template names. */
|
|
37
|
+
accountId: string;
|
|
38
|
+
credentials?: LambdaMicrovmsClientConfig['credentials'];
|
|
39
|
+
/** Ingress connector; defaults to the service's ALL_INGRESS. */
|
|
40
|
+
ingressConnectorArn?: string;
|
|
41
|
+
/** Egress connector (e.g. a VPC connector with a deny-all security group). Omit for internet egress. */
|
|
42
|
+
egressConnectorArn?: string;
|
|
43
|
+
/** IAM role the capsule assumes (S3 mounts, etc.). */
|
|
44
|
+
executionRoleArn?: string;
|
|
45
|
+
/** Default hard limit per capsule. */
|
|
46
|
+
maxDurationSeconds?: number;
|
|
47
|
+
/** Minutes before an endpoint token is re-minted (service max is 60). */
|
|
48
|
+
tokenTtlMinutes?: number;
|
|
49
|
+
/** Ports the endpoint token allows; 8080 (capsulod) is always included. */
|
|
50
|
+
allowedPorts?: number[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const CAPSULOD_PORT = 8080;
|
|
54
|
+
|
|
55
|
+
function toState(s: string | undefined): CapsuleState {
|
|
56
|
+
switch (s) {
|
|
57
|
+
case 'PENDING':
|
|
58
|
+
return 'pending';
|
|
59
|
+
case 'RUNNING':
|
|
60
|
+
return 'running';
|
|
61
|
+
case 'SUSPENDING':
|
|
62
|
+
case 'SUSPENDED':
|
|
63
|
+
return 'suspended';
|
|
64
|
+
case 'TERMINATING':
|
|
65
|
+
case 'TERMINATED':
|
|
66
|
+
return 'terminated';
|
|
67
|
+
default:
|
|
68
|
+
return 'unknown';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class LambdaProvider implements Provider {
|
|
73
|
+
readonly name = 'lambda';
|
|
74
|
+
private readonly client: LambdaMicrovmsClient;
|
|
75
|
+
private readonly tokens = new Map<string, { value: string; expiresAt: number }>();
|
|
76
|
+
|
|
77
|
+
constructor(private readonly opts: LambdaProviderOptions) {
|
|
78
|
+
this.client = new LambdaMicrovmsClient({
|
|
79
|
+
region: opts.region,
|
|
80
|
+
...(opts.credentials ? { credentials: opts.credentials } : {}),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Templates are MicrovmImages; the API wants the full ARN (a plain name fails). */
|
|
85
|
+
imageArn(template: string): string {
|
|
86
|
+
if (template.startsWith('arn:')) return template;
|
|
87
|
+
return `arn:aws:lambda:${this.opts.region}:${this.opts.accountId}:microvm-image:${template}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async create(spec: CapsuleSpec, opts: CreateOptions = {}): Promise<CapsuleHandle> {
|
|
91
|
+
const ingress =
|
|
92
|
+
this.opts.ingressConnectorArn ??
|
|
93
|
+
`arn:aws:lambda:${this.opts.region}:aws:network-connector:aws-network-connector:ALL_INGRESS`;
|
|
94
|
+
const res = await this.client.send(
|
|
95
|
+
new RunMicrovmCommand({
|
|
96
|
+
imageIdentifier: this.imageArn(spec.template),
|
|
97
|
+
ingressNetworkConnectors: [ingress],
|
|
98
|
+
...(this.opts.egressConnectorArn ? { egressNetworkConnectors: [this.opts.egressConnectorArn] } : {}),
|
|
99
|
+
...(this.opts.executionRoleArn ? { executionRoleArn: this.opts.executionRoleArn } : {}),
|
|
100
|
+
...(spec.idle
|
|
101
|
+
? {
|
|
102
|
+
idlePolicy: {
|
|
103
|
+
maxIdleDurationSeconds: spec.idle.suspendAfterSeconds,
|
|
104
|
+
suspendedDurationSeconds: spec.idle.destroyAfterSeconds,
|
|
105
|
+
autoResumeEnabled: true,
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
: {}),
|
|
109
|
+
maximumDurationInSeconds: spec.maxDurationSeconds ?? this.opts.maxDurationSeconds ?? 8 * 3600,
|
|
110
|
+
...(spec.clientToken ? { clientToken: spec.clientToken } : {}),
|
|
111
|
+
// The daemon receives mounts + metadata through the /run hook (never secrets).
|
|
112
|
+
runHookPayload: JSON.stringify({ mounts: spec.mounts ?? {}, metadata: spec.metadata ?? {} }),
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
if (!res.microvmId) throw new CapsuleError('RunMicrovm returned no microvmId');
|
|
116
|
+
const id = res.microvmId;
|
|
117
|
+
let info: CapsuleInfo;
|
|
118
|
+
try {
|
|
119
|
+
info = await this.waitForRunning(id, opts);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
// Never leave a VM running without an owner: the caller gets an error,
|
|
122
|
+
// not a capsule, so the VM goes too (the error still names it).
|
|
123
|
+
if (err instanceof CapsuleError && err.capsuleId === id) {
|
|
124
|
+
await this.terminate(id).catch(() => undefined);
|
|
125
|
+
throw new CapsuleError(`${err.message}; terminated it`, err.status, { capsuleId: id });
|
|
126
|
+
}
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
if (!info.endpoint) throw new CapsuleError(`microVM ${id} is ${info.state} but has no endpoint`, undefined, { capsuleId: id });
|
|
130
|
+
return { ...info, connection: this.connectionFor(id, info.endpoint) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async get(id: string): Promise<CapsuleInfo | null> {
|
|
134
|
+
try {
|
|
135
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }));
|
|
136
|
+
return this.infoOf(id, vm);
|
|
137
|
+
} catch (err) {
|
|
138
|
+
if (err instanceof Error && err.name === 'ResourceNotFoundException') return null;
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** All microVMs of one template (the API lists per image). */
|
|
144
|
+
async list(template?: string): Promise<CapsuleInfo[]> {
|
|
145
|
+
if (!template) throw new CapsuleError('LambdaProvider.list needs a template: the API lists microVMs per image');
|
|
146
|
+
const out: CapsuleInfo[] = [];
|
|
147
|
+
let nextToken: string | undefined;
|
|
148
|
+
do {
|
|
149
|
+
const page = await this.client.send(
|
|
150
|
+
new ListMicrovmsCommand({ imageIdentifier: this.imageArn(template), nextToken }),
|
|
151
|
+
);
|
|
152
|
+
for (const item of page.items ?? []) {
|
|
153
|
+
if (!item.microvmId) continue;
|
|
154
|
+
// The list item carries no endpoint, terminatedAt or stateReason: get() does.
|
|
155
|
+
out.push({
|
|
156
|
+
id: item.microvmId,
|
|
157
|
+
provider: this.name,
|
|
158
|
+
state: toState(item.state),
|
|
159
|
+
template: item.imageArn ?? null,
|
|
160
|
+
templateVersion: item.imageVersion ?? null,
|
|
161
|
+
createdAt: item.startedAt ?? null,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
nextToken = page.nextToken;
|
|
165
|
+
} while (nextToken);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async terminate(id: string): Promise<void> {
|
|
170
|
+
try {
|
|
171
|
+
await this.client.send(new TerminateMicrovmCommand({ microvmIdentifier: id }));
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (err instanceof Error && err.name === 'ResourceNotFoundException') return;
|
|
174
|
+
throw err;
|
|
175
|
+
} finally {
|
|
176
|
+
this.tokens.delete(id);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async connect(id: string): Promise<Connection> {
|
|
181
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }));
|
|
182
|
+
if (!vm.endpoint) throw new CapsuleError(`microVM ${id} has no endpoint yet (state ${vm.state})`, undefined, { capsuleId: id });
|
|
183
|
+
return this.connectionFor(id, vm.endpoint);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A Connection from an endpoint already in hand (get() returns it): no extra GetMicrovm. */
|
|
187
|
+
connectionFor(id: string, endpoint: string): Connection {
|
|
188
|
+
return {
|
|
189
|
+
baseUrl: endpoint.startsWith('https://') ? endpoint : `https://${endpoint}`,
|
|
190
|
+
headers: async (opts?: HeadersOptions) => ({ 'X-aws-proxy-auth': await this.token(id, opts?.fresh) }),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Headers to reach another port of the capsule through the same endpoint. */
|
|
195
|
+
async portHeaders(id: string, port: number, opts?: HeadersOptions): Promise<Record<string, string>> {
|
|
196
|
+
return { 'X-aws-proxy-auth': await this.token(id, opts?.fresh), 'X-aws-proxy-port': String(port) };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Forget the cached endpoint token: the next request mints a new one. */
|
|
200
|
+
invalidateToken(id: string): void {
|
|
201
|
+
this.tokens.delete(id);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private infoOf(id: string, vm: { state?: string; imageArn?: string; imageVersion?: string; startedAt?: Date; terminatedAt?: Date; stateReason?: string; endpoint?: string; maximumDurationInSeconds?: number }): CapsuleInfo {
|
|
205
|
+
return {
|
|
206
|
+
id,
|
|
207
|
+
provider: this.name,
|
|
208
|
+
state: toState(vm.state),
|
|
209
|
+
template: vm.imageArn ?? null,
|
|
210
|
+
templateVersion: vm.imageVersion ?? null,
|
|
211
|
+
createdAt: vm.startedAt ?? null,
|
|
212
|
+
terminatedAt: vm.terminatedAt ?? null,
|
|
213
|
+
stateReason: vm.stateReason ?? null,
|
|
214
|
+
endpoint: vm.endpoint ? `https://${vm.endpoint}` : null,
|
|
215
|
+
maxDurationSeconds: vm.maximumDurationInSeconds ?? null,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private async token(id: string, fresh = false): Promise<string> {
|
|
220
|
+
const cached = this.tokens.get(id);
|
|
221
|
+
if (cached && cached.expiresAt > Date.now() && !fresh) return cached.value;
|
|
222
|
+
const ttl = Math.min(this.opts.tokenTtlMinutes ?? 60, 60);
|
|
223
|
+
const ports = new Set([CAPSULOD_PORT, ...(this.opts.allowedPorts ?? [])]);
|
|
224
|
+
const res = await this.client.send(
|
|
225
|
+
new CreateMicrovmAuthTokenCommand({
|
|
226
|
+
microvmIdentifier: id,
|
|
227
|
+
expirationInMinutes: ttl,
|
|
228
|
+
allowedPorts: [...ports].map((port) => ({ port })),
|
|
229
|
+
}),
|
|
230
|
+
);
|
|
231
|
+
const value = res.authToken?.['X-aws-proxy-auth'];
|
|
232
|
+
if (!value) throw new CapsuleError('CreateMicrovmAuthToken returned no X-aws-proxy-auth');
|
|
233
|
+
// Re-mint a few minutes early; never persist the token anywhere.
|
|
234
|
+
this.tokens.set(id, { value, expiresAt: Date.now() + (ttl - 5) * 60_000 });
|
|
235
|
+
return value;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Poll until the VM runs. A SUSPENDED VM (a clientToken that recovered an
|
|
240
|
+
* idle one) counts as alive: the first request auto-resumes it. Timeout and
|
|
241
|
+
* abort throw a CapsuleError that names the VM (capsuleId) for the caller
|
|
242
|
+
* to clean up; create() does that itself.
|
|
243
|
+
*/
|
|
244
|
+
private async waitForRunning(id: string, opts: CreateOptions = {}): Promise<CapsuleInfo> {
|
|
245
|
+
const timeoutMs = opts.timeoutMs ?? 120_000;
|
|
246
|
+
const t0 = Date.now();
|
|
247
|
+
for (;;) {
|
|
248
|
+
if (opts.signal?.aborted) throw new CapsuleError(`creation of microVM ${id} aborted`, undefined, { capsuleId: id });
|
|
249
|
+
const vm = await this.client.send(new GetMicrovmCommand({ microvmIdentifier: id }), { abortSignal: opts.signal });
|
|
250
|
+
if (vm.state === 'RUNNING' || vm.state === 'SUSPENDED') return this.infoOf(id, vm);
|
|
251
|
+
if (vm.state === 'TERMINATED' || vm.state === 'TERMINATING') {
|
|
252
|
+
throw new CapsuleError(`microVM ${id} died while starting: ${vm.stateReason ?? vm.state}`, undefined, { capsuleId: id });
|
|
253
|
+
}
|
|
254
|
+
if (Date.now() - t0 > timeoutMs) {
|
|
255
|
+
throw new CapsuleError(`microVM ${id} did not run within ${timeoutMs}ms (state ${vm.state})`, undefined, { capsuleId: id });
|
|
256
|
+
}
|
|
257
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
package/README.md
DELETED