forked from anomalyco/sst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.js
More file actions
1785 lines (1612 loc) · 51.5 KB
/
Copy pathstart.js
File metadata and controls
1785 lines (1612 loc) · 51.5 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const os = require("os");
const zlib = require("zlib");
const path = require("path");
const util = require("util");
const AWS = require("aws-sdk");
const fs = require("fs-extra");
const chalk = require("chalk");
const WebSocket = require("ws");
const esbuild = require("esbuild");
const spawn = require("cross-spawn");
const {
logger,
getChildLogger,
STACK_DEPLOY_STATUS,
} = require("@serverless-stack/core");
const s3 = new AWS.S3();
const paths = require("./util/paths");
const {
sleep,
synth,
deploy,
loadCache,
updateCache,
isGoRuntime,
isNodeRuntime,
isJavaRuntime,
isDotnetRuntime,
isPythonRuntime,
prepareCdk,
writeConfig,
getTsBinPath,
checkFileExists,
getEsbuildTarget,
writeOutputsFile,
printDeployResults,
generateStackChecksums,
loadEsbuildConfigOverrides,
reTranspile: reTranpileCdk,
} = require("./util/cdkHelpers");
const array = require("../lib/array");
const Watcher = require("./util/Watcher");
const objectUtil = require("../lib/object");
const CdkWatcherState = require("./util/CdkWatcherState");
const LambdaWatcherState = require("./util/LambdaWatcherState");
const LambdaRuntimeServer = require("./util/LambdaRuntimeServer");
const { serializeError, deserializeError } = require("../lib/serializeError");
// Setup logger
const wsLogger = getChildLogger("websocket");
const clientLogger = getChildLogger("client");
const WEBSOCKET_CLOSE_CODE = {
NEW_CLIENT_CONNECTED: 4901,
};
const MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS = 0;
let watcher;
let cdkWatcherState;
let lambdaWatcherState;
let esbuildService;
let lambdaServer;
let debugEndpoint;
let debugBucketArn;
let debugBucketName;
const clientState = {
ws: null,
wsKeepAliveTimer: null,
};
const IS_TEST = process.env.__TEST__ === "true";
module.exports = async function (argv, config, cliInfo) {
const { inputFiles: cdkInputFiles } = await prepareCdk(argv, cliInfo, config);
// Load cache
const cacheData = loadCache();
// Deploy debug stack
const debugStackOutputs = await deployDebugStack(
argv,
config,
cliInfo,
cacheData
);
debugEndpoint = debugStackOutputs.Endpoint;
debugBucketArn = debugStackOutputs.BucketArn;
debugBucketName = debugStackOutputs.BucketName;
// Add input listener
addInputListener();
// Deploy app
const appStackDeployRet = await deployApp(argv, config, cliInfo, cacheData);
const lambdaHandlers = await getDeployedLambdaHandlers();
await updateStaticSiteEnvironmentOutputs(appStackDeployRet);
logger.info("");
logger.info("==========================");
logger.info(" Starting Live Lambda Dev");
logger.info("==========================");
logger.info("");
cdkWatcherState = new CdkWatcherState({
inputFiles: cdkInputFiles,
checksumData: cacheData.appStacks.checksumData,
onReBuild: handleCdkReBuild,
onLint: (inputFiles) => handleCdkLint(inputFiles, config),
onTypeCheck: (inputFiles) => handleCdkTypeCheck(inputFiles, config),
onSynth: () => handleCdkSynth(cliInfo),
onReDeploy: ({ checksumData }) =>
handleCdkReDeploy(cliInfo, cacheData, checksumData),
onAddWatchedFiles: handleAddWatchedFiles,
onRemoveWatchedFiles: handleRemoveWatchedFiles,
});
lambdaWatcherState = new LambdaWatcherState({
lambdaHandlers,
onTranspileNode: (entrypointData) =>
handleTranspileNode(entrypointData, config),
onRunLint: (srcPath, inputFiles) =>
handleRunLint(srcPath, inputFiles, config),
onRunTypeCheck: (srcPath, inputFiles, tsconfig) =>
handleRunTypeCheck(srcPath, inputFiles, tsconfig, config),
onCompileGo: handleCompileGo,
onBuildJava: handleBuildJava,
onBuildDotnet: handleBuildDotnet,
onBuildPython: handleBuildPython,
onAddWatchedFiles: handleAddWatchedFiles,
onRemoveWatchedFiles: handleRemoveWatchedFiles,
});
await lambdaWatcherState.runInitialBuild(IS_TEST);
// Save Lambda watcher state to file
if (IS_TEST) {
const testOutputPath = path.join(
paths.appPath,
paths.appBuildDir,
"test-output.json"
);
fs.writeFileSync(
testOutputPath,
JSON.stringify(lambdaWatcherState.getState())
);
process.exit(0);
return;
}
// Start code watcher, Lambda runtime server, and websocket client
await startWatcher();
await startRuntimeServer(argv.port);
startWebSocketClient();
};
async function deployDebugStack(argv, config, cliInfo, cacheData) {
// Do not deploy if running test
if (IS_TEST) {
return {
Endpoint: "ws://test-endpoint",
BucketArn: "bucket-arn",
BucketName: "bucket-name",
};
}
logger.info("");
logger.info("=======================");
logger.info(" Deploying debug stack");
logger.info("=======================");
logger.info("");
const stackName = `${config.stage}-${config.name}-debug-stack`;
const appBuildLibPath = path.join(paths.appBuildPath, "lib");
const cdkOptions = {
...cliInfo.cdkOptions,
app: `node bin/index.js ${stackName} ${config.stage} ${config.region} ${paths.appPath} ${appBuildLibPath}`,
output: "cdk.out",
};
// Change working directory
// Note: When deploying the debug stack, the current working directory is user's app.
// Setting the current working directory to debug stack cdk app directory to allow
// Lambda Function construct be able to reference code with relative path.
process.chdir(path.join(paths.ownPath, "assets", "debug-stack"));
// Build
const cdkManifest = await synth(cdkOptions);
const cdkOutPath = path.join(
paths.ownPath,
"assets",
"debug-stack",
"cdk.out"
);
const checksumData = generateStackChecksums(cdkManifest, cdkOutPath);
// Deploy
const isCacheChanged = checkCacheChanged(cacheData.debugStack, checksumData);
const deployRet = isCacheChanged
? await deploy(cdkOptions)
: cacheData.debugStack.deployRet;
logger.debug("deployRet", deployRet);
// Restore working directory
process.chdir(paths.appPath);
// Get WebSocket endpoint
if (
!deployRet ||
deployRet.length !== 1 ||
deployRet[0].status === STACK_DEPLOY_STATUS.FAILED
) {
throw new Error(`Failed to deploy debug stack ${stackName}`);
} else if (!deployRet[0].outputs || !deployRet[0].outputs.Endpoint) {
throw new Error(
`Failed to get the endpoint from the deployed debug stack ${stackName}`
);
}
// Cache changed => Update cache
if (isCacheChanged) {
cacheData.debugStack = { checksumData, deployRet };
updateCache(cacheData);
}
// Cache NOT changed => Print stack results since deploy was skipped
else {
await printMockedDeployResults(deployRet);
}
return deployRet[0].outputs;
}
async function deployApp(argv, config, cliInfo, cacheData) {
logger.info("");
logger.info("===============");
logger.info(" Deploying app");
logger.info("===============");
logger.info("");
await writeConfig({
...config,
debugEndpoint,
debugBucketArn,
debugBucketName,
debugIncreaseTimeout: argv.increaseTimeout || false,
});
// Build
const cdkManifest = await synth(cliInfo.cdkOptions);
const cdkOutPath = path.join(paths.appBuildPath, "cdk.out");
const checksumData = generateStackChecksums(cdkManifest, cdkOutPath);
let deployRet;
if (IS_TEST) {
deployRet = [];
cacheData.appStacks = { checksumData, deployRet };
} else {
// Deploy
const isCacheChanged = checkCacheChanged(cacheData.appStacks, checksumData);
deployRet = isCacheChanged
? await deploy(cliInfo.cdkOptions)
: cacheData.appStacks.deployRet;
// Check all stacks deployed successfully
if (
deployRet.some((stack) => stack.status === STACK_DEPLOY_STATUS.FAILED)
) {
throw new Error(`Failed to deploy the app`);
}
// Cache changed => Update cache
if (isCacheChanged) {
cacheData.appStacks = { checksumData, deployRet };
updateCache(cacheData);
}
// Cache NOT changed => Print stack results since deploy was skipped
else {
// print a empty line before printing deploy results
logger.info("");
await printMockedDeployResults(deployRet);
}
}
// Write outputsFile
if (argv.outputsFile) {
await writeOutputsFile(
deployRet,
path.join(paths.appPath, argv.outputsFile)
);
}
return deployRet;
}
async function startWatcher() {
// Watcher will build all the Lambda handlers on start and rebuild on code change
watcher = new Watcher({
cdkFiles: cdkWatcherState.getWatchedFiles(),
lambdaFiles: lambdaWatcherState.getWatchedFiles(),
onFileChange: (file) => {
cdkWatcherState.handleFileChange(file);
lambdaWatcherState.handleFileChange(file);
},
});
}
async function startRuntimeServer(port) {
// note: 0.0.0.0 does not work on Windows
lambdaServer = new LambdaRuntimeServer();
await lambdaServer.start("127.0.0.1", port);
}
function addInputListener() {
if (IS_TEST) {
return;
}
process.stdin.on("data", () => {
cdkWatcherState && cdkWatcherState.handleInput();
});
process.on("SIGINT", function () {
console.log(
chalk.yellow(
"\nStopping Live Lambda Dev, run `sst deploy` to deploy the latest changes."
)
);
process.exit(0);
});
// Note: the "readline" way of listening for each keystroke did not play well
// with the "prompts" modules, as the "prompts" module closes the rl
// interface. For now, we will listen for the SIGINT event above.
//const rl = readline.createInterface({
// input: process.stdin,
// output: process.stdout
//});
//process.stdin.on('keypress', async (c, k) => {
// //console.log("keypress", JSON.stringify({ c, k }));
// if (!k) { return; }
// // CTRL+c or CTRL+d
// if ((k.name === "c" || k.name === "d") && k.ctrl === true) {
// console.log(chalk.yellow("\nStopping Live Lambda Dev, run `sst deploy` to deploy the latest changes.\n"));
// process.exit(0);
// }
// else if (k.name === "enter") {
// cdkWatcherState && cdkWatcherState.handleInput();
// }
//});
}
////////////////////////////
// CDK Reloader functions //
////////////////////////////
async function handleCdkReBuild() {
try {
const inputFiles = await reTranpileCdk();
cdkWatcherState.handleReBuildSucceeded({ inputFiles });
} catch (e) {
cdkWatcherState.handleReBuildFailed(e);
}
}
function handleCdkLint(inputFiles, config) {
// Validate lint enabled
if (!config.lint) {
return null;
}
inputFiles = inputFiles.filter(
(file) =>
file.indexOf("node_modules") === -1 &&
(file.endsWith(".ts") || file.endsWith(".js"))
);
// Validate inputFiles
if (inputFiles.length === 0) {
return null;
}
const cp = spawn(
"node",
[
path.join(paths.appBuildPath, "eslint.js"),
process.env.NO_COLOR === "true" ? "--no-color" : "--color",
...inputFiles,
],
{ stdio: "inherit", cwd: paths.ownPath }
);
cp.on("close", (code) => {
cdkWatcherState.handleLintDone({ cp, code });
});
return cp;
}
function handleCdkTypeCheck(inputFiles, config) {
// Validate typeCheck enabled
if (!config.typeCheck) {
return null;
}
const tsFiles = inputFiles.filter((file) => file.endsWith(".ts"));
// Validate tsFiles
if (tsFiles.length === 0) {
return null;
}
const cp = spawn(
getTsBinPath(),
[
"--noEmit",
"--pretty",
process.env.NO_COLOR === "true" ? "false" : "true",
],
{
stdio: "inherit",
cwd: paths.appPath,
}
);
cp.on("close", (code) => {
cdkWatcherState.handleTypeCheckDone({ cp, code });
});
return cp;
}
function handleCdkSynth(cliInfo) {
const synthPromise = synth(cliInfo.cdkOptions);
synthPromise
.then((cdkManifest) => {
const cdkOutPath = path.join(paths.appBuildPath, "cdk.out");
const checksumData = generateStackChecksums(cdkManifest, cdkOutPath);
cdkWatcherState.handleSynthDone({ hasError: false, checksumData });
})
.catch((e) => {
cdkWatcherState.handleSynthDone({
hasError: true,
isCancelled: e.cancelled,
});
});
return synthPromise;
}
async function handleCdkReDeploy(cliInfo, cacheData, checksumData) {
try {
// While deploying, synth might run again if another change is made. That
// can cause the value of 'lastSynthedChecksumData' to change. So we need
// to clone the value.
checksumData = { ...checksumData };
const deployRet = await deploy(cliInfo.cdkOptions);
if (
deployRet.some((stack) => stack.status === STACK_DEPLOY_STATUS.FAILED)
) {
// Throw a dummy error. Watcher just need to catch something and prints
// out that redeploy failed. Do not need to throw with an error message
// b/c deploy status is printed out onto the terminal.
throw null;
}
// Update Lambda state
const lambdaHandlers = await getDeployedLambdaHandlers();
lambdaWatcherState.handleUpdateLambdaHandlers(lambdaHandlers);
// Update StaticSite environment outputs
await updateStaticSiteEnvironmentOutputs(deployRet);
// Update cache
cacheData.appStacks = { checksumData, deployRet };
updateCache(cacheData);
cdkWatcherState.handleReDeployDone({ hasError: false });
} catch (e) {
cdkWatcherState.handleReDeployDone({ hasError: true });
}
}
function handleAddWatchedFiles(files) {
if (files.length > 0) {
watcher.addFiles(files);
}
}
async function handleRemoveWatchedFiles(files) {
if (files.length > 0) {
await watcher.removeFiles(files);
}
}
////////////////////////////////////////
// Lambda Reloader functions - NodeJS //
////////////////////////////////////////
async function handleTranspileNode(
{ srcPath, handler, bundle, esbuilder, onSuccess, onFailure },
config
) {
// Sample input:
// srcPath 'service'
// handler 'src/lambda.handler'
//
// Sample output path:
// metafile 'services/user-service/.build/.esbuild.service-src-lambda-hander.json'
// fullPath 'services/user-service/src/lambda.js'
// outSrcPath 'services/user-service/.build/src'
//
// Transpiled .js and .js.map are output in .build folder with original handler structure path
try {
const metafile = getEsbuildMetafilePath(paths.appPath, srcPath, handler);
const fullPath = await getHandlerFilePath(paths.appPath, srcPath, handler);
const outSrcPath = path.join(
srcPath,
paths.appBuildDir,
path.dirname(handler)
);
const handlerParts = path.basename(handler).split(".");
const outHandler = handlerParts.pop();
const outEntry = `${handlerParts.join(".")}.js`;
// Get tsconfig
const tsconfigPath = path.join(paths.appPath, srcPath, "tsconfig.json");
const isTs = await checkFileExists(tsconfigPath);
const tsconfig = isTs ? tsconfigPath : undefined;
// Transpile
esbuilder = esbuilder
? await runReTranspileNode(esbuilder)
: await runTranspileNode(
config,
srcPath,
handler,
bundle,
metafile,
tsconfig,
fullPath,
outSrcPath
);
onSuccess({
tsconfig,
esbuilder,
outEntryPoint: {
entry: outEntry,
handler: outHandler,
srcPath: outSrcPath,
origHandlerFullPosixPath: getHandlerFullPosixPath(srcPath, handler),
},
inputFiles: await getInputFilesFromEsbuildMetafile(metafile),
});
} catch (e) {
logger.debug("handleTranspileNode error", e);
onFailure(e);
}
}
async function runTranspileNode(
config,
srcPath,
handler,
bundle,
metafile,
tsconfig,
fullPath,
outSrcPath
) {
logger.debug(`Transpiling ${handler}...`);
// Start esbuild service is has not started
if (!esbuildService) {
esbuildService = esbuild;
}
// Get custom esbuild config
const esbuildConfig = config.esbuildConfig || bundle.esbuildConfig;
const esbuildConfigOverrides = esbuildConfig
? await loadEsbuildConfigOverrides(esbuildConfig)
: {};
const result = await esbuildService.build({
external: await getEsbuildExternal(srcPath),
loader: getEsbuildLoader(bundle),
metafile: true,
tsconfig,
bundle: true,
format: "cjs",
sourcemap: true,
platform: "node",
incremental: true,
entryPoints: [fullPath],
target: [getEsbuildTarget()],
color: process.env.NO_COLOR !== "true",
outdir: path.join(paths.appPath, outSrcPath),
logLevel: process.env.DEBUG ? "warning" : "error",
...esbuildConfigOverrides,
});
require('fs').writeFileSync(metafile, JSON.stringify(result.metafile))
return result
}
async function runReTranspileNode(esbuilder) {
await esbuilder.rebuild();
// Mock esbuild taking long to rebuild
if (MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS) {
logger.debug(
`Mock rebuild wait (${MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS}ms)...`
);
await sleep(MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS);
logger.debug(`Mock rebuild wait done`);
}
return esbuilder;
}
function handleRunLint(srcPath, inputFiles, config) {
// Validate lint enabled
// note: invoke LambdaWatcherState.handleLintDone() even if it's not run. B/c
// if both Lint and TypeCheck are disabled, neither handleLintDone() or
// handleTypeCheckDone() will be called. And in turn updateState() will
// not be called in LambdaWatcherState. This will lead to the state stuck
// in the "Rebuilding code..." state.
// Hence, call handleLintDone() in a setTimeout to mimic the lint
// process has completed.
if (!config.lint) {
setTimeout(() => lambdaWatcherState.handleLintDone(srcPath), 0);
return null;
}
inputFiles = inputFiles.filter(
(file) =>
file.indexOf("node_modules") === -1 &&
(file.endsWith(".ts") || file.endsWith(".js"))
);
// Validate inputFiles
if (inputFiles.length === 0) {
setTimeout(() => lambdaWatcherState.handleLintDone(srcPath), 0);
return null;
}
const cp = spawn(
"node",
[
path.join(paths.appBuildPath, "eslint.js"),
process.env.NO_COLOR === "true" ? "--no-color" : "--color",
...inputFiles,
],
{ stdio: "inherit", cwd: paths.ownPath }
);
cp.on("close", (code) => {
logger.debug(`linter exited with code ${code}`);
lambdaWatcherState.handleLintDone(srcPath);
});
return cp;
}
function handleRunTypeCheck(srcPath, inputFiles, tsconfig, config) {
// Validate typeCheck enabled
// note: invoke LambdaWatcherState.handleTypeCheckDone() even if it's not run. B/c
// if both Lint and TypeCheck are disabled, neither handleLintDone() or
// handleTypeCheckDone() will be called. And in turn updateState() will
// not be called in LambdaWatcherState. This will lead to the state stuck
// in the "Rebuilding code..." state.
// Hence, call handleTypeCheckDone() in a setTimeout to mimic the type check
// process has completed.
if (!config.typeCheck) {
setTimeout(() => lambdaWatcherState.handleTypeCheckDone(srcPath), 0);
return null;
}
const tsFiles = inputFiles.filter((file) => file.endsWith(".ts"));
// Validate tsFiles
if (tsFiles.length === 0) {
setTimeout(() => lambdaWatcherState.handleTypeCheckDone(srcPath), 0);
return null;
}
if (tsconfig === undefined) {
logger.error(
`Cannot find a "tsconfig.json" in the function's srcPath: ${path.resolve(
srcPath
)}`
);
setTimeout(() => lambdaWatcherState.handleTypeCheckDone(srcPath), 0);
return null;
}
const cp = spawn(
getTsBinPath(),
[
"--noEmit",
"--pretty",
process.env.NO_COLOR === "true" ? "false" : "true",
],
{
stdio: "inherit",
cwd: path.join(paths.appPath, srcPath),
}
);
cp.on("close", (code) => {
logger.debug(`type checker exited with code ${code}`);
lambdaWatcherState.handleTypeCheckDone(srcPath);
});
return cp;
}
async function getHandlerFilePath(appPath, srcPath, handler) {
// Check entry path exists
let entryPath;
const entryPathExists = [".ts", ".tsx", ".js", ".jsx"].some((ext) => {
entryPath = path.join(
appPath,
srcPath,
addExtensionToHandler(handler, ext)
);
return fs.existsSync(entryPath);
});
// Print out the error message and throw
if (!entryPathExists) {
const handlerPosixPath = getHandlerFullPosixPath(srcPath, handler);
const errorMessage = `Cannot find a handler file for "${handlerPosixPath}"`;
logger.error(`${chalk.red("error")} ${errorMessage}\n`);
throw new Error(errorMessage);
}
return entryPath;
}
async function getEsbuildExternal(srcPath) {
let externals;
try {
const packageJson = await fs.readJson(path.join(srcPath, "package.json"));
externals = Object.keys({
...(packageJson.dependencies || {}),
...(packageJson.devDependencies || {}),
...(packageJson.peerDependencies || {}),
});
} catch (e) {
logger.warn(`No package.json found in ${srcPath}`);
externals = [];
}
// Always include "aws-sdk" in externals
// Note: this helps with the case where "aws-sdk" is not listed in the srcPath's
// package.json. It could be in parent directories' package.json.
//
// Example 1: the SST app is a package inside a yarn workspace, and
// "aws-sdk" is in repo root's package.json.
// Example 2: the SST app is at the repo root, but the Lambda function has
// a srcPath. And "aws-sdk" is in repo root's package.json.
//
// The long term fix is to run `esbuild` and if the input files contain
// "node_modules/XYZ", kill the esbuild service. And remember "XYZ". And
// the next time the function gets invoked, start a new esbuild process,
// and set "XYZ" as an external. Need to check other packages in the Yarn
// workspace do not show up as "node_modules" in the input files. Because
// we want them to be included in input files and watch them.
if (!externals.includes("aws-sdk")) {
externals.push("aws-sdk");
}
return externals;
}
function getEsbuildLoader(bundle) {
if (bundle) {
return bundle.loader || {};
}
return undefined;
}
function getEsbuildMetafilePath(appPath, srcPath, handler) {
const key = `${srcPath}/${handler}`.replace(/[/.]/g, "-");
const outSrcFullPath = path.join(appPath, srcPath, paths.appBuildDir);
return path.join(outSrcFullPath, `.esbuild.${key}.json`);
}
async function getInputFilesFromEsbuildMetafile(file) {
let metaJson;
try {
metaJson = await fs.readJson(file);
} catch (e) {
logger.error("There was a problem reading the build metafile", e);
}
return Object.keys(metaJson.inputs).map((input) => path.resolve(input));
}
////////////////////////////////////
// Lambda Reloader functions - Go //
////////////////////////////////////
async function handleCompileGo({ srcPath, handler, onSuccess, onFailure }) {
try {
const { outEntry } = await runCompile(srcPath, handler);
onSuccess({
outEntryPoint: {
entry: outEntry,
origHandlerFullPosixPath: getHandlerFullPosixPath(srcPath, handler),
},
inputFiles: [],
});
} catch (e) {
logger.debug("handleCompileGo error", e);
onFailure(e);
}
}
function runCompile(srcPath, handler) {
// Sample input:
// srcPath 'services/user-service'
// handler 'src/lambda.go'
//
// Sample output path:
// absHandlerPath 'services/user-service/src/lambda.go'
// relBinPath -> if handler is 'src/lambda.go' => '.build/src/lambda'
// -> if handler is 'src' => '.build/src/main'
// binPath 'services/user-service/.build/src/lambda'
//
// Transpiled Go executables are output in .build folder with original handler structure path
const absSrcPath = path.join(paths.appPath, srcPath);
const absHandlerPath = path.join(paths.appPath, srcPath, handler);
let relBinPath;
if (handler.endsWith(".go")) {
relBinPath = path.join(
paths.appBuildDir,
path.dirname(handler),
path.basename(handler).slice(0, -3)
);
} else {
relBinPath = path.join(paths.appBuildDir, handler, "main");
}
// Append ".exe" for Windows
if (process.platform === "win32") {
relBinPath = `${relBinPath}.exe`;
}
logger.debug(`Building ${absHandlerPath}...`);
return new Promise((resolve, reject) => {
const cp = spawn(
"go",
[
"build",
"-ldflags",
"-s -w",
"-o",
relBinPath,
// specify absolute path b/c if "handler" can be a folder, and a relative path does not work
absHandlerPath,
],
{
stdio: "inherit",
env: {
...process.env,
// Compile for local runtime b/c the go executable will be run locally
//GOOS: "linux",
},
cwd: absSrcPath,
}
);
cp.on("error", (e) => {
logger.debug("go build error", e);
});
cp.on("close", (code) => {
logger.debug(`go build exited with code ${code}`);
if (code !== 0) {
reject(
new Error(
`There was an problem compiling the handler at "${absHandlerPath}".`
)
);
} else {
resolve({
outEntry: path.join(absSrcPath, relBinPath),
});
}
});
});
}
//////////////////////////////////////
// Lambda Reloader functions - Java //
//////////////////////////////////////
async function handleBuildJava({ srcPath, handler, onSuccess, onFailure }) {
try {
const { outEntry } = await runBuildJava(srcPath, handler);
onSuccess({
outEntryPoint: {
entry: outEntry,
handler,
origHandlerFullPosixPath: getHandlerFullPosixPath(srcPath, handler),
},
inputFiles: [],
});
} catch (e) {
logger.debug("handleBuildJava error", e);
onFailure(e);
}
}
function runBuildJava(srcPath, handler) {
// Sample input:
// srcPath 'services/user-service'
// handler 'Api.MyClass::MyFn'
//
// Sample output path:
// absSrcPath 'services/user-service'
// absHandlerPath 'services/user-service/Api.MyClass::MyFn'
// absOutputPath 'services/user-service/.build/Api.MyClass-MyFn'
// outEntry 'services/user-service/.build/Api.MyClass-MyFn/index.jar'
const absSrcPath = path.join(paths.appPath, srcPath);
const absHandlerPath = path.join(paths.appPath, srcPath, handler);
// On Windows, you cannot have ":" in a folder name
const absOutputPath = path
.join(paths.appPath, srcPath, paths.appBuildDir, handler)
.replace(/::/g, "-");
const outEntry = path.join(absOutputPath, "index.jar");
logger.debug(`Building ${absHandlerPath}...`);
return new Promise((resolve, reject) => {
const cp = spawn(
"sbt",
[
"set test in assembly := {}",
`set assemblyOutputPath in assembly := new File("${outEntry}")`,
"assembly",
],
{
stdio: "inherit",
cwd: absSrcPath,
}
);
cp.on("error", (e) => {
logger.debug("Java build error", e);
});
cp.on("close", (code) => {
logger.debug(`Java build exited with code ${code}`);
if (code !== 0) {
reject(
new Error(
`There was an problem compiling the handler at "${absHandlerPath}".`
)
);
} else {
resolve({ outEntry });
}
});
});
}
//////////////////////////////////////
// Lambda Reloader functions - .NET //
//////////////////////////////////////
async function handleBuildDotnet({ srcPath, handler, onSuccess, onFailure }) {
try {
const { outEntry } = await runBuildDotnet(srcPath, handler);
onSuccess({
outEntryPoint: {
entry: outEntry,
handler,
origHandlerFullPosixPath: getHandlerFullPosixPath(srcPath, handler),
},
inputFiles: [],
});
} catch (e) {
logger.debug("handleBuildDotnet error", e);
onFailure(e);
}
}
function runBuildDotnet(srcPath, handler) {
// Sample input:
// srcPath 'services/user-service'
// handler 'Api::Api.MyClass::MyFn'
//
// Sample output path:
// assembly 'Api'
// absSrcPath 'services/user-service'
// absHandlerPath 'services/user-service/Api::Api.MyClass::MyFn'
// absOutputPath 'services/user-service/.build/Api-Api.MyClass-MyFn'
// outEntry 'services/user-service/.build/Api-Api.MyClass-MyFn/Api.dll'
const assembly = handler.split("::")[0];
const absSrcPath = path.join(paths.appPath, srcPath);
const absHandlerPath = path.join(paths.appPath, srcPath, handler);
// On Windows, you cannot have ":" in a folder name
const absOutputPath = path
.join(paths.appPath, srcPath, paths.appBuildDir, handler)
.replace(/::/g, "-");
const outEntry = path.join(absOutputPath, `${assembly}.dll`);
logger.debug(`Building ${absHandlerPath}...`);