-
Notifications
You must be signed in to change notification settings - Fork 903
/
functionsEmulatorRuntime.ts
806 lines (691 loc) · 27.3 KB
/
functionsEmulatorRuntime.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
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
import { EmulatorLog } from "./types";
import { DeploymentOptions } from "firebase-functions";
import {
EmulatedTrigger,
EmulatedTriggerDefinition,
EmulatedTriggerMap,
findModuleRoot,
FunctionsRuntimeBundle,
FunctionsRuntimeFeatures,
getEmulatedTriggersFromDefinitions,
getTemporarySocketPath,
} from "./functionsEmulatorShared";
import * as express from "express";
import { extractParamsFromPath } from "./functionsEmulatorUtils";
import { spawnSync } from "child_process";
import * as path from "path";
import * as admin from "firebase-admin";
import * as bodyParser from "body-parser";
let app: admin.app.App;
let adminModuleProxy: typeof admin;
/*
This method is a hacky way of "resolving" Node modules. Normally, when you "require()" a package,
Node looks for that package in a set of locations or paths. The logic varies slightly between
Nodejs versions and there's no consistent way to make sure the exact same resolution is happening
all the time.
Since functionsEmulatorRuntime.js lives inside the firebase-tools installation, it's always tempted
to resolve from the same places that firebase-tools gets it's modules. Normally this is fine, but
in order to provide mocks to a developer's functions we need to resolve modules as if we were in the
same filesystem location as the user's code. Some versions of Node let us do this by calling
require.resolve() with a list of paths to look in, but that's not a fix for all versions.
slowRequireResolve works around this by spinning up another node process which doesn't have a
file path to look at for resolutions (code is passed via -e flag) so it uses the cwd instead.
This allows us to easily resolve modules as if we had code in that folder. Sadly, this is incredibly
sllooooow. It's about 100-200ms per resolution, which means the majority of time spent on a
Cloud Function invocation is spent right here.
It's made even worse because we occasionally need to resolve a dependency as if we were a different
depedency, so that requires two slowRequireResolves - it's bad.
For the initial release of the emulator, we went for consistency and simplicity over execution speed
going forward, there's many paths to look into for optimization, for example we could cache results
in an inter-process memory store, look into ways to help node believe our runtime is in the user's
code directory, or move to native require.resolve on newer node versions and deal with the inconsistencies
between versions.
*/
function slowRequireResolve(moduleName: string, cwd?: string): string {
const resolver = `console.log(require.resolve("${moduleName}"))`;
const result = spawnSync(process.execPath, ["-e", resolver], {
cwd: path.resolve(cwd || process.cwd()),
});
return result.stdout.toString().trim();
}
/*
This helper is used to create mocks for Firebase SDKs. It simplifies creation of Proxy objects
by allowing us to easily overide some or all of an objects methods. When placed back into require's
cache the proxy will be automatically used when the module is imported so we can influence the runtime
behavior of Firebase SDKs in user code.
const px = new Proxied({"value": 1});
px.when("incremented", (original) => original["value"] + 1);
const obj = px.finalize();
obj.value == 1;
obj.incremented == 2;
*/
class Proxied<T> {
proxy: any;
private anyValue?: (target: any, key: string) => any;
private appliedValue?: () => any;
private rewrites: {
[key: string]: (target: any, key: string) => any;
} = {};
constructor(private original: any) {
/*
When initialized an original object is passed. This object is supplied to both .when()
and .any() functions so the original value of the object is accessible. When no
.any() is provided, the original value of the object is returned when the field
key does not match any known rewrite.
*/
this.proxy = new Proxy(this.original, {
get: (target, key) => {
key = key.toString();
if (this.rewrites[key]) {
return this.rewrites[key](target, key);
}
if (this.anyValue) {
return this.anyValue(target, key);
}
return this.getOriginal(target, key);
},
apply: (target, thisArg, argArray) => {
if (this.appliedValue) {
return this.appliedValue.apply(thisArg, argArray);
} else {
return this.applyOriginal(target, thisArg, argArray);
}
},
});
}
when(key: string, value: (target: any, key: string) => any): Proxied<T> {
/*
Calling .when("a", () => "b") will rewrite obj["a"] to be equal to "b"
*/
this.rewrites[key] = value;
return this as Proxied<T>;
}
any(value: (target: any, key: string) => any): Proxied<T> {
/*
Calling .any(() => "b") will rewrite all fields on obj to be equal to "b"
*/
this.anyValue = value;
return this as Proxied<T>;
}
applied(value: () => any): Proxied<T> {
/*
Calling .applied(() => "b") will make obj() equal to "b"
*/
this.appliedValue = value;
return this as Proxied<T>;
}
getOriginal(target: any, key: string): any {
const value = target[key];
if (!isExists(value)) {
return undefined;
} else if (isConstructor(value) || typeof value !== "function") {
return value;
} else {
return value.bind(target);
}
}
applyOriginal(target: any, thisArg: any, argArray: any[]): any {
return target.apply(thisArg, argArray);
}
finalize(): T {
return this.proxy as T;
}
}
function isConstructor(obj: any): boolean {
return !!obj.prototype && !!obj.prototype.constructor.name;
}
function isExists(obj: any): boolean {
return obj !== undefined;
}
function verifyDeveloperNodeModules(frb: FunctionsRuntimeBundle): boolean {
let pkg;
try {
pkg = require(`${frb.cwd}/package.json`);
} catch (err) {
new EmulatorLog("SYSTEM", "missing-package-json", "").log();
return false;
}
const modBundles = [
{ name: "firebase-admin", isDev: false, minVersion: 7 },
{ name: "firebase-functions", isDev: false, minVersion: 2 },
{ name: "firebase-functions-test", isDev: true, minVersion: 0 },
];
for (const modBundle of modBundles) {
const dependencies = pkg.dependencies || {};
const devDependencies = pkg.devDependencies || {};
const isInPackageJSON = dependencies[modBundle.name] || devDependencies[modBundle.name];
/*
If there's no reference to the module in their package.json, prompt them to install it
*/
if (!isInPackageJSON) {
new EmulatorLog("SYSTEM", "missing-module", "", modBundle).log();
return false;
}
/*
Once we know it's in the package.json, make sure it's actually `npm install`ed
*/
let modResolution: string;
try {
modResolution = slowRequireResolve(modBundle.name, frb.cwd);
} catch (err) {
new EmulatorLog("SYSTEM", "uninstalled-module", "", modBundle).log();
return false;
}
const modPackageJSON = require(path.join(
findModuleRoot(modBundle.name, modResolution),
"package.json"
));
const modMajorVersion = parseInt((modPackageJSON.version || "0").split("."), 10);
if (modMajorVersion < modBundle.minVersion) {
new EmulatorLog("SYSTEM", "out-of-date-module", "", modBundle).log();
return false;
}
}
return true;
}
/*
We mock out a ton of different paths that we can take to network I/O. It doesn't matter if they
overlap (like TLS and HTTPS) because the dev will either whitelist, block, or allow for one
invocation on the first prompt, so we can be aggressive here.
Sadly, these vary a lot between Node versions and it will always be possible to route around
this, it's not security - just a helper. A good example of something difficult to catch is
any I/O done via node-gyp (https://github.com/nodejs/node-gyp) since that I/O will be done in
C, we have to catch it before then (which is how the google-gax blocker could work). As of this note,
GRPC uses a native extension to do I/O (I think because old node lacks native HTTP2?), so that's
a place to keep an eye on. Luckily, mostly only Google uses GRPC and most Google APIs go via
google-gax which is mocked elsewhere, but still.
So yeah, we'll try our best and hopefully we can catch 90% of requests.
*/
function InitializeNetworkFiltering(frb: FunctionsRuntimeBundle): void {
const networkingModules = [
{ name: "http", module: require("http"), path: ["request"] },
{ name: "http", module: require("http"), path: ["get"] },
{ name: "https", module: require("https"), path: ["request"] },
{ name: "https", module: require("https"), path: ["get"] },
{ name: "net", module: require("net"), path: ["connect"] },
// HTTP2 is not currently mocked due to the inability to quiet Experiment warnings in Node.
];
try {
const gcFirestore = findModuleRoot(
"@google-cloud/firestore",
slowRequireResolve("@google-cloud/firestore", frb.cwd)
);
const gaxPath = slowRequireResolve("google-gax", gcFirestore);
const gaxModule = {
module: require(gaxPath),
path: ["GrpcClient"],
name: "google-gax",
};
networkingModules.push(gaxModule);
new EmulatorLog("DEBUG", "runtime-status", `Found google-gax at ${gaxPath}`).log();
} catch (err) {
new EmulatorLog(
"DEBUG",
"runtime-status",
`Couldn't find google-cloud/firestore or google-gax`
).log();
}
const history: { [href: string]: boolean } = {};
const results = networkingModules.map((bundle) => {
let obj = bundle.module;
for (const field of bundle.path.slice(0, -1)) {
obj = obj[field];
}
const method = bundle.path.slice(-1)[0];
const original = obj[method].bind(bundle.module);
/* tslint:disable:only-arrow-functions */
// This can't be an arrow function because it needs to be new'able
obj[method] = function(...args: any[]): any {
const hrefs = args
.map((arg) => {
if (typeof arg === "string") {
try {
const _ = new URL(arg);
return arg;
} catch (err) {
return;
}
} else if (typeof arg === "object") {
return arg.href;
} else {
return;
}
})
.filter((v) => v);
const href = (hrefs.length && hrefs[0]) || "";
if (href && !history[href]) {
history[href] = true;
if (href.indexOf("googleapis.com") !== -1) {
new EmulatorLog("SYSTEM", "googleapis-network-access", "", {
href,
module: bundle.name,
}).log();
} else {
new EmulatorLog("SYSTEM", "unidentified-network-access", "", {
href,
module: bundle.name,
}).log();
}
}
try {
return original(...args);
} catch (e) {
const newed = new original(...args);
if (bundle.name === "google-gax") {
const cs = newed.constructSettings;
newed.constructSettings = (...csArgs: any[]) => {
(csArgs[3] as any).authorization = "Bearer owner";
return cs.bind(newed)(...csArgs);
};
}
return newed;
}
};
return { name: bundle.name, status: "mocked" };
});
new EmulatorLog("DEBUG", "runtime-status", "Outgoing network have been stubbed.", results).log();
}
/*
This stub handles a very specific use-case, when a developer (incorrectly) provides a HTTPS handler
which returns a promise. In this scenario, we can't catch errors which get raised in user code,
because they're happening async and then the errors get lost when firebase-functions drops the return value.
Currently, Node is willing to raise the error as an ugly un-handled promise, but this is hard to
read and long-term will be silenced by Node. Instead, we stub out onRequest and put a special reference
directly to the handler so we can invoke it directly and catch the errors in our normal reporting chain.
The relevant firebase-functions code is:
https://github.com/firebase/firebase-functions/blob/9e3bda13565454543b4c7b2fd10fb627a6a3ab97/src/providers/https.ts#L66
*/
function InitializeFirebaseFunctionsStubs(functionsDir: string): void {
const firebaseFunctionsResolution = slowRequireResolve("firebase-functions", functionsDir);
const firebaseFunctionsRoot = findModuleRoot("firebase-functions", firebaseFunctionsResolution);
const httpsProviderResolution = path.join(firebaseFunctionsRoot, "lib/providers/https");
const httpsProvider = require(httpsProviderResolution);
const _onRequestWithOpts = httpsProvider._onRequestWithOpts;
httpsProvider._onRequestWithOpts = (
handler: (req: Request, resp: Response) => void,
opts: DeploymentOptions
) => {
const cf = _onRequestWithOpts(handler, opts);
cf.__emulator_func = handler;
return cf;
};
/*
If you take a look at the link above, you'll see that onRequest relies on _onRequestWithOpts
so in theory, we should only need to mock _onRequestWithOpts, however that is not the case
because onRequest is defined in the same scope as _onRequestWithOpts, so replacing
the definition of _onRequestWithOpts does not replace the link to the original function
which onRequest uses, so we need to manually force it to use our error-handle-able version.
*/
httpsProvider.onRequest = (handler: (req: Request, resp: Response) => void) => {
return httpsProvider._onRequestWithOpts(handler, {});
};
}
/*
This stub is the most important and one of the only non-optional stubs. This feature redirects
writes from the admin SDK back into emulated resources. Currently, this is only Firestore writes.
To do this, we replace initializeApp so it drops the developers config options and returns a restricted,
unauthenticated app.
We also mock out .settings() so we can merge the emulator settings with the developer's.
If you ever see an error from the admin SDK related to default credentials, that means this mock is
failing in some way and admin is attempting to access prod resources. This error isn't pretty,
but it's hard to catch and better than accidentally talking to prod.
*/
function InitializeFirebaseAdminStubs(frb: FunctionsRuntimeBundle): typeof admin {
const adminResolution = slowRequireResolve("firebase-admin", frb.cwd);
const grpc = require(slowRequireResolve("grpc", frb.cwd));
const localAdminModule = require(adminResolution);
let hasInitializedSettings = false;
const initializeSettings = (userSettings: any) => {
const isEnabled = isFeatureEnabled(frb, "admin_stubs");
if (!isEnabled) {
if (!hasInitializedSettings) {
app.firestore().settings(userSettings);
hasInitializedSettings = true;
}
return;
}
if (!hasInitializedSettings && frb.ports.firestore) {
app.firestore().settings({
projectId: frb.projectId,
port: frb.ports.firestore,
servicePath: "localhost",
service: "firestore.googleapis.com",
sslCreds: grpc.credentials.createInsecure(),
...userSettings,
});
} else if (!frb.ports.firestore && frb.triggerId) {
new EmulatorLog(
"WARN",
"runtime-status",
"The Cloud Firestore emulator is not running so database operations will fail with a " +
"'default credentials' error."
).log();
}
hasInitializedSettings = true;
};
adminModuleProxy = new Proxied<typeof admin>(localAdminModule)
.when("initializeApp", (adminModuleTarget) => (opts: any, appName: any) => {
if (appName) {
new EmulatorLog("SYSTEM", "non-default-admin-app-used", "", { appName }).log();
return adminModuleTarget.initializeApp(opts, appName);
}
new EmulatorLog("SYSTEM", "default-admin-app-used", "").log();
app = adminModuleTarget.initializeApp({
...JSON.parse(process.env.FIREBASE_CONFIG || "{}"),
...opts,
});
return app;
})
.when("firestore", (adminModuleTarget) => {
const proxied = new Proxied<typeof admin.firestore>(adminModuleTarget.firestore);
return proxied
.applied(() => {
return new Proxied(adminModuleTarget.firestore())
.when("settings", () => {
return (settings: any) => {
initializeSettings(settings);
};
})
.any((target, field) => {
initializeSettings({});
return proxied.getOriginal(target, field);
})
.finalize();
})
.finalize();
})
.finalize();
require.cache[adminResolution] = {
exports: adminModuleProxy,
};
new EmulatorLog("DEBUG", "runtime-status", "firebase-admin has been stubbed.", {
adminResolution,
}).log();
return adminModuleProxy;
}
/*
Here we set up some environment configs, but more importantly, we break GOOGLE_APPLICATION_CREDENTIALS
and FIREBASE_CONFIG so that there's no way we (google-auth) can automatically auth. This is a safety
fallback for situations where a stub does not properly redirect to the emulator and we attempt to
access a production resource. By removing the auth fields, we help reduce the risk of this situation.
*/
function ProtectEnvironmentalVariables(): void {
process.env.GOOGLE_APPLICATION_CREDENTIALS = "";
}
function InitializeEnvironmentalVariables(projectId: string): void {
process.env.GCLOUD_PROJECT = projectId;
/*
Do our best to provide reasonable FIREBASE_CONFIG, based on firebase-functions implementation
https://github.com/firebase/firebase-functions/blob/master/src/index.ts#L70
*/
process.env.FIREBASE_CONFIG = JSON.stringify({
databaseURL: process.env.DATABASE_URL || `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
storageBucket: process.env.STORAGE_BUCKET_URL || `${process.env.GCLOUD_PROJECT}.appspot.com`,
projectId: process.env.GCLOUD_PROJECT,
});
}
function InitializeFunctionsConfigHelper(functionsDir: string): void {
const functionsResolution = slowRequireResolve("firebase-functions", functionsDir);
const ff = require(functionsResolution);
new EmulatorLog("DEBUG", "runtime-status", "Checked functions.config()", {
config: ff.config(),
}).log();
const originalConfig = ff.config();
const proxiedConfig = new Proxied(originalConfig)
.any((parentConfig, parentKey) => {
new EmulatorLog("DEBUG", "runtime-status", "config() parent accessed!", {
parentKey,
parentConfig,
}).log();
return new Proxied(parentConfig[parentKey] || ({} as { [key: string]: any }))
.any((childConfig, childKey) => {
const value = childConfig[childKey];
if (value) {
return value;
} else {
const valuePath = [parentKey, childKey].join(".");
new EmulatorLog("SYSTEM", "functions-config-missing-value", "", { valuePath }).log();
return undefined;
}
})
.finalize();
})
.finalize();
ff.config = () => proxiedConfig;
}
async function ProcessHTTPS(frb: FunctionsRuntimeBundle, trigger: EmulatedTrigger): Promise<void> {
const ephemeralServer = express();
const socketPath = getTemporarySocketPath(process.pid);
await new Promise((resolveEphemeralServer, rejectEphemeralServer) => {
const handler = async (req: express.Request, res: express.Response) => {
try {
new EmulatorLog("DEBUG", "runtime-status", `Ephemeral server used!`).log();
const func = trigger.getRawFunction();
res.on("finish", () => {
instance.close();
resolveEphemeralServer();
});
await Run([req, res], func);
} catch (err) {
rejectEphemeralServer(err);
}
};
ephemeralServer.use(bodyParser.json({}));
ephemeralServer.use(bodyParser.text({}));
ephemeralServer.use(bodyParser.urlencoded({ extended: true }));
ephemeralServer.use(bodyParser.raw({ type: "*/*" }));
ephemeralServer.get("/*", handler);
ephemeralServer.post("/*", handler);
const instance = ephemeralServer.listen(socketPath, () => {
new EmulatorLog("SYSTEM", "runtime-status", "ready", { socketPath }).log();
});
});
}
async function ProcessBackground(
frb: FunctionsRuntimeBundle,
trigger: EmulatedTrigger
): Promise<void> {
const { Change } = require("firebase-functions");
new EmulatorLog("SYSTEM", "runtime-status", "ready").log();
const proto = frb.proto;
adminModuleProxy.firestore().settings({});
const makeFirestoreSnapshot = (app.firestore() as any).snapshot_.bind(app.firestore());
const resourcePath = proto.context.resource.name;
const params = extractParamsFromPath(trigger.definition.eventTrigger.resource, resourcePath);
/*
We use an internal Firestore method makeFirestoreSnapshot to generate Snapshots which we pass to firebase-function's
Change object. If we have a value for new / old snap, then we create a valid snapshot, otherwise we
invoke makeFirestoreSnapshot with a different signature describe here...
https://github.com/googleapis/nodejs-firestore/blob/114de25d1af3fc7441da3242f6bc8cc8354ffa09/dev/test/index.ts#L574
To create a snapshot where .exists() fails.
*/
let newSnap;
if (proto.data.value) {
newSnap = makeFirestoreSnapshot(proto.data.value, new Date().toISOString(), "json");
} else {
newSnap = makeFirestoreSnapshot(resourcePath, new Date().toISOString(), "json");
}
let oldSnap;
if (proto.data.oldValue) {
oldSnap = makeFirestoreSnapshot(proto.data.oldValue, new Date().toISOString(), "json");
} else {
oldSnap = makeFirestoreSnapshot(resourcePath, new Date().toISOString(), "json");
}
let data;
switch (trigger.definition.eventTrigger.eventType) {
case "providers/cloud.firestore/eventTypes/document.write":
data = Change.fromObjects(oldSnap, newSnap);
break;
case "providers/cloud.firestore/eventTypes/document.update":
data = Change.fromObjects(oldSnap, newSnap);
break;
case "providers/cloud.firestore/eventTypes/document.delete":
data = oldSnap;
break;
case "providers/cloud.firestore/eventTypes/document.create":
data = newSnap;
break;
}
const ctx = {
eventId: proto.context.eventId,
timestamp: proto.context.timestamp,
params,
auth: {},
authType: "UNAUTHENTICATED",
};
new EmulatorLog("DEBUG", "runtime-status", `Requesting a wrapped function.`).log();
const fftResolution = slowRequireResolve("firebase-functions-test", frb.cwd);
const func = trigger.getWrappedFunction(require(fftResolution));
await Run([data, ctx], func);
}
// TODO(abehaskins): This signature could probably use work lol
async function Run(args: any[], func: (a: any, b: any) => Promise<any>): Promise<any> {
if (args.length < 2) {
throw new Error("Function must be passed 2 args.");
}
/* tslint:disable:no-console */
const log = console.log;
console.log = (...messages: any[]) => {
new EmulatorLog("USER", "function-log", messages.join(" ")).log();
};
let caughtErr;
try {
await func(args[0], args[1]);
} catch (err) {
caughtErr = err;
}
console.log = log;
new EmulatorLog("DEBUG", "runtime-status", `Ephemeral server survived.`).log();
if (caughtErr) {
throw caughtErr;
}
return;
}
function isFeatureEnabled(
frb: FunctionsRuntimeBundle,
feature: keyof FunctionsRuntimeFeatures
): boolean {
return frb.disabled_features ? !frb.disabled_features[feature] : true;
}
async function main(): Promise<void> {
const serializedFunctionsRuntimeBundle = process.argv[2] || "{}";
const serializedFunctionTrigger = process.argv[3];
new EmulatorLog("DEBUG", "runtime-status", "Functions runtime initialized.", {
cwd: process.cwd(),
node_version: process.versions.node,
}).log();
const frb = JSON.parse(serializedFunctionsRuntimeBundle) as FunctionsRuntimeBundle;
if (frb.triggerId) {
new EmulatorLog("INFO", "runtime-status", `Beginning execution of "${frb.triggerId}"`, {
frb,
}).log();
}
new EmulatorLog(
"DEBUG",
"runtime-status",
`Disabled runtime features: ${JSON.stringify(frb.disabled_features)}`
).log();
const verified = verifyDeveloperNodeModules(frb);
if (!verified) {
// If we can't verify the node modules, then just leave, soemthing bad will happen during runtime.
new EmulatorLog(
"INFO",
"runtime-status",
`Your functions could not be parsed due to an issue with your node_modules (see above)`
).log();
return;
}
InitializeEnvironmentalVariables(frb.projectId);
if (isFeatureEnabled(frb, "protect_env")) {
ProtectEnvironmentalVariables();
}
if (isFeatureEnabled(frb, "network_filtering")) {
InitializeNetworkFiltering(frb);
}
if (isFeatureEnabled(frb, "functions_config_helper")) {
InitializeFunctionsConfigHelper(frb.cwd);
}
InitializeFirebaseFunctionsStubs(frb.cwd);
InitializeFirebaseAdminStubs(frb);
let triggers: EmulatedTriggerMap;
const triggerDefinitions: EmulatedTriggerDefinition[] = [];
let triggerModule;
if (serializedFunctionTrigger) {
/* tslint:disable:no-eval */
triggerModule = eval(serializedFunctionTrigger)();
} else {
triggerModule = require(frb.cwd);
}
require("../extractTriggers")(triggerModule, triggerDefinitions);
triggers = await getEmulatedTriggersFromDefinitions(triggerDefinitions, triggerModule);
new EmulatorLog("SYSTEM", "triggers-parsed", "", { triggers, triggerDefinitions }).log();
if (!frb.triggerId) {
/*
This is a purely diagnostic call, it's used as a check to make sure developer code compiles and runs as
expected, so we don't have any function to invoke.
*/
return;
}
if (!triggers[frb.triggerId]) {
new EmulatorLog(
"FATAL",
"runtime-status",
`Could not find trigger "${frb.triggerId}" in your functions directory.`
).log();
return;
} else {
new EmulatorLog(
"DEBUG",
"runtime-status",
`Trigger "${frb.triggerId}" has been found, beginning invocation!`
).log();
}
const trigger = triggers[frb.triggerId];
new EmulatorLog("DEBUG", "runtime-status", "", trigger.definition).log();
const mode = trigger.definition.httpsTrigger ? "HTTPS" : "BACKGROUND";
new EmulatorLog("DEBUG", "runtime-status", `Running ${frb.triggerId} in mode ${mode}`).log();
if (!app) {
new EmulatorLog("SYSTEM", "admin-not-initialized", "").log();
return;
}
let seconds = 0;
const timerId = setInterval(() => {
seconds++;
}, 1000);
let timeoutId;
if (isFeatureEnabled(frb, "timeout")) {
timeoutId = setTimeout(() => {
new EmulatorLog(
"WARN",
"runtime-status",
`Your function timed out after ~${trigger.definition.timeout ||
"60s"}. To configure this timeout, see
https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.`
).log();
process.exit();
}, trigger.timeoutMs);
}
switch (mode) {
case "BACKGROUND":
await ProcessBackground(frb, triggers[frb.triggerId]);
break;
case "HTTPS":
await ProcessHTTPS(frb, triggers[frb.triggerId]);
break;
}
if (timeoutId) {
clearTimeout(timeoutId);
}
clearInterval(timerId);
new EmulatorLog(
"INFO",
"runtime-status",
`Finished "${frb.triggerId}" in ~${Math.max(seconds, 1)}s`
).log();
}
if (require.main === module) {
main().catch((err) => {
new EmulatorLog("FATAL", "runtime-error", err.stack ? err.stack : err).log();
process.exit();
});
}