-
Notifications
You must be signed in to change notification settings - Fork 200
/
inflight.ts
318 lines (281 loc) · 8.07 KB
/
inflight.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { createHash } from "crypto";
import { mkdtempSync, readFileSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { basename, dirname, join, resolve } from "path";
import { IConstruct } from "constructs";
import * as esbuild from "esbuild-wasm";
import { PREBUNDLE_SYMBOL } from "./internal";
/**
* Capture information. A capture is a reference from an Inflight to a
* construction-time resource or value. Either the "resource" or "value" field
* will be set, but not both.
*/
export interface Capture extends CaptureMetadata {
/**
* A captured resource
*/
readonly resource?: ICapturableConstruct;
/**
* A captured immutable value (like string, number, boolean, a struct, or null).
*/
readonly value?: any;
}
/**
* Extra metadata associated with a captured resource.
*/
export interface CaptureMetadata {
/**
* Which methods are called on the captured resource.
*/
readonly methods?: string[];
}
/**
* Represents something that is capturable by an Inflight.
*/
export interface ICapturable {
/**
* Captures the resource so that it can be referenced inside an Inflight
* executed in the given scope.
*
* @internal
*/
_capture(captureScope: IConstruct, metadata: CaptureMetadata): Code;
}
/**
* Represents a construct that is capturable by an Inflight.
*/
export interface ICapturableConstruct extends ICapturable, IConstruct {}
/**
* Reference to a piece of code.
*/
export abstract class Code {
/**
* The language of the code.
*/
public abstract readonly language: Language;
/**
* A path to the code in the user's file system that can be referenced
* for bundling purposes.
*/
public abstract readonly path: string;
/**
* The code contents.
*/
public get text(): string {
return readFileSync(this.path, "utf-8");
}
/**
* Generate a hash of the code contents.
*/
public get hash(): string {
return createHash("sha512").update(this.text).digest("hex");
}
}
/**
* The language of a piece of code.
*/
export enum Language {
/** Node.js */
NODE_JS = "nodejs",
}
/**
* Reference to a piece of Node.js code.
*/
export class NodeJsCode extends Code {
/**
* Reference code from a file path.
*/
public static fromFile(path: string) {
return new NodeJsCode(path);
}
/**
* Reference code directly from a string.
*/
public static fromInline(text: string) {
const tempdir = mkdtempSync(join(tmpdir(), "wingsdk."));
const file = join(tempdir, "index.js");
writeFileSync(file, text);
return new NodeJsCode(file);
}
public readonly language = Language.NODE_JS;
public readonly path: string;
private constructor(path: string) {
super();
this.path = path;
}
}
/**
* Options for `Inflight`.
*/
export interface InflightProps {
/**
* Reference to code containing the entrypoint function.
*/
readonly code: Code;
/**
* Name of the exported function to run.
*
* @example "exports.handler"
*/
readonly entrypoint: string;
/**
* Capture information. During runtime, a map containing all captured values
* will be passed as the first argument of the entrypoint function.
*
* Each key here will be the key for the final value in the map.
* @default - No captures
*/
readonly captures?: { [name: string]: Capture };
}
/**
* Represents a unit of application code that can be executed by a cloud
* resource.
*/
export class Inflight {
/**
* Reference to code containing the entrypoint function.
*/
public readonly code: Code;
/**
* Name of the exported function which will be run.
*/
public readonly entrypoint: string;
/**
* Capture information. During runtime, a map containing all captured values
* will be passed as the first argument of the entrypoint function.
*
* Each key here will be the key for the final value in the map.
*/
public readonly captures: { [name: string]: Capture };
constructor(props: InflightProps) {
this.code = props.code;
this.entrypoint = props.entrypoint;
this.captures = props.captures ?? {};
}
/**
* Bundle this inflight process so that it can be used in the given capture
* scope.
*
* Returns the path to a JavaScript file that has been rewritten to include
* all dependencies and captured values or clients. The file is isolated in
* its own directory so that it can be zipped up and uploaded to cloud
* providers.
*
* High level implementation:
* 1. Read the file (let's say its path is path/to/foo.js)
* 2. Create a new javascript file named path/to/foo.prebundle.js, including a
* map of all capture clients, a new handler that calls the original
* handler with the clients passed in, and a copy of the user's code from
* path/to/foo.js.
* 3. Use esbuild to bundle all dependencies, outputting the result to
* path/to/foo.js.bundle/index.js.
*/
public bundle(options: InflightBundleOptions): Code {
const lines = new Array<string>();
const originalCode = this.code;
const absolutePath = resolve(originalCode.path);
const workdir = dirname(absolutePath);
lines.push("const $cap = {};");
for (const [name, client] of Object.entries(options.captureClients)) {
lines.push(`$cap["${name}"] = ${client.text};`);
}
lines.push();
lines.push(originalCode.text);
lines.push();
lines.push("exports.handler = async function(event) {");
lines.push(` return await ${this.entrypoint}($cap, event);`);
lines.push("};");
const contents = lines.join("\n");
// expose the inflight code before esbuild inlines dependencies, for unit
// testing purposes... ugly
if (options.captureScope) {
(options.captureScope as any)[PREBUNDLE_SYMBOL] =
NodeJsCode.fromInline(contents);
}
const tempdir = mkdtemp("wingsdk.");
const outfile = join(tempdir, "index.js");
esbuild.buildSync({
bundle: true,
stdin: {
contents,
resolveDir: workdir,
sourcefile: "original.js",
},
target: "node16",
platform: "node",
absWorkingDir: workdir,
outfile,
minify: false,
external: options.external ?? [],
});
return NodeJsCode.fromFile(outfile);
}
/**
* Resolve this inflight's captured objects into a map of clients that be
* safely referenced at runtime.
*/
public makeClients(captureScope: IConstruct): Record<string, Code> {
const clients: Record<string, Code> = {};
for (const [name, capture] of Object.entries(this.captures)) {
clients[name] = createClient(captureScope, name, capture);
}
return clients;
}
}
/**
* Options for `Inflight.bundle`.
*/
export interface InflightBundleOptions {
/**
* Associate the inflight bundle with a given capture scope.
*/
readonly captureScope?: IConstruct;
/**
* A map of capture clients that can be bundled with the Inflight's code.
*/
readonly captureClients: Record<string, Code>;
/**
* List of dependencies to exclude from the bundle.
*/
readonly external?: string[];
}
function createClient(
captureScope: IConstruct,
captureName: string,
capture: Capture
): Code {
if (capture.value !== undefined) {
return NodeJsCode.fromInline(JSON.stringify(capture.value));
}
if (capture.resource !== undefined) {
return capture.resource._capture(captureScope, capture);
}
throw new Error(
`Unable to capture "${captureName}", no "value" or "resource" specified.`
);
}
function mkdtemp(prefix: string): string {
return mkdtempSync(join(tmpdir(), prefix));
}
/**
* Utility class with functions about inflight clients.
*/
export class InflightClient {
/**
* Creates a `Code` instance with code for creating an inflight client.
*/
public static for(
filename: string,
clientClass: string,
args: string[]
): Code {
const inflightDir = dirname(filename);
const inflightFile = basename(filename).split(".")[0] + ".inflight";
return NodeJsCode.fromInline(
`new (require("${require.resolve(
`${inflightDir}/${inflightFile}`
)}")).${clientClass}(${args.join(", ")})`
);
}
private constructor() {}
}