-
Notifications
You must be signed in to change notification settings - Fork 901
/
functionsEmulator.ts
1474 lines (1314 loc) · 49.6 KB
/
functionsEmulator.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
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
import * as fs from "fs";
import * as path from "path";
import * as express from "express";
import * as clc from "colorette";
import * as http from "http";
import * as jwt from "jsonwebtoken";
import * as cors from "cors";
import { URL } from "url";
import { EventEmitter } from "events";
import { Account } from "../auth";
import { logger } from "../logger";
import { track, trackEmulator } from "../track";
import { Constants } from "./constants";
import { EmulatorInfo, EmulatorInstance, Emulators, FunctionsExecutionMode } from "./types";
import * as chokidar from "chokidar";
import * as spawn from "cross-spawn";
import { ChildProcess } from "child_process";
import {
EmulatedTriggerDefinition,
SignatureType,
EventSchedule,
EventTrigger,
formatHost,
FunctionsRuntimeFeatures,
getFunctionService,
getSignatureType,
HttpConstants,
ParsedTriggerDefinition,
emulatedFunctionsFromEndpoints,
emulatedFunctionsByRegion,
getSecretLocalPath,
toBackendInfo,
prepareEndpoints,
BlockingTrigger,
getTemporarySocketPath,
} from "./functionsEmulatorShared";
import { EmulatorRegistry } from "./registry";
import { EmulatorLogger, Verbosity } from "./emulatorLogger";
import { RuntimeWorker, RuntimeWorkerPool } from "./functionsRuntimeWorker";
import { PubsubEmulator } from "./pubsubEmulator";
import { FirebaseError } from "../error";
import { WorkQueue } from "./workQueue";
import { allSettled, connectableHostname, createDestroyer, debounce } from "../utils";
import { getCredentialPathAsync } from "../defaultCredentials";
import {
AdminSdkConfig,
constructDefaultAdminSdkConfig,
getProjectAdminSdkConfigOrCached,
} from "./adminSdkConfig";
import { functionIdsAreValid } from "../deploy/functions/validate";
import { Extension, ExtensionSpec, ExtensionVersion } from "../extensions/types";
import { accessSecretVersion } from "../gcp/secretManager";
import * as runtimes from "../deploy/functions/runtimes";
import * as backend from "../deploy/functions/backend";
import * as functionsEnv from "../functions/env";
import { AUTH_BLOCKING_EVENTS, BEFORE_CREATE_EVENT } from "../functions/events/v1";
import { BlockingFunctionsConfig } from "../gcp/identityPlatform";
import { resolveBackend } from "../deploy/functions/build";
import { setEnvVarsForEmulators } from "./env";
const EVENT_INVOKE = "functions:invoke"; // event name for UA
const EVENT_INVOKE_GA4 = "functions_invoke"; // event name GA4 (alphanumertic)
/*
* The Realtime Database emulator expects the `path` field in its trigger
* definition to be relative to the database root. This regex is used to extract
* that path from the `resource` member in the trigger definition used by the
* functions emulator.
*
* Groups:
* 1 - instance
* 2 - path
*/
const DATABASE_PATH_PATTERN = new RegExp("^projects/[^/]+/instances/([^/]+)/refs(/.*)$");
/**
* EmulatableBackend represents a group of functions to be emulated.
* This can be a CF3 module, or an Extension.
*/
export interface EmulatableBackend {
functionsDir: string;
env: Record<string, string>;
secretEnv: backend.SecretEnvVar[];
codebase: string;
predefinedTriggers?: ParsedTriggerDefinition[];
nodeMajorVersion?: number;
nodeBinary?: string;
extensionInstanceId?: string;
extension?: Extension; // Only present for published extensions
extensionVersion?: ExtensionVersion; // Only present for published extensions
extensionSpec?: ExtensionSpec; // Only present for local extensions
}
/**
* BackendInfo is an API type used by the Emulator UI containing info about an Extension or CF3 module.
*/
export interface BackendInfo {
directory: string;
env: Record<string, string>; // TODO: Consider exposing more information about where param values come from & if they are locally overwritten.
functionTriggers: ParsedTriggerDefinition[];
extensionInstanceId?: string;
extension?: Extension; // Only present for published extensions
extensionVersion?: ExtensionVersion; // Only present for published extensions
extensionSpec?: ExtensionSpec; // Only present for local extensions
}
export interface FunctionsEmulatorArgs {
projectId: string;
projectDir: string;
emulatableBackends: EmulatableBackend[];
account?: Account;
port?: number;
host?: string;
quiet?: boolean;
disabledRuntimeFeatures?: FunctionsRuntimeFeatures;
debugPort?: number;
remoteEmulators?: { [key: string]: EmulatorInfo };
adminSdkConfig?: AdminSdkConfig;
projectAlias?: string;
}
// FunctionsRuntimeInstance is the handler for a running function invocation
export interface FunctionsRuntimeInstance {
process: ChildProcess;
// An emitter which sends our EmulatorLog events from the runtime.
events: EventEmitter;
// A cwd of the process
cwd: string;
// Path to socket file used for HTTP-over-IPC comms.
socketPath: string;
}
export interface InvokeRuntimeOpts {
nodeBinary: string;
extensionTriggers?: ParsedTriggerDefinition[];
ignore_warnings?: boolean;
}
interface RequestWithRawBody extends express.Request {
rawBody: Buffer;
}
interface EmulatedTriggerRecord {
backend: EmulatableBackend;
def: EmulatedTriggerDefinition;
enabled: boolean;
ignored: boolean;
url?: string;
}
export class FunctionsEmulator implements EmulatorInstance {
static getHttpFunctionUrl(
projectId: string,
name: string,
region: string,
info?: { host: string; port: number }
): string {
let url: URL;
if (info) {
url = new URL("http://" + formatHost(info));
} else {
url = EmulatorRegistry.url(Emulators.FUNCTIONS);
}
url.pathname = `/${projectId}/${region}/${name}`;
return url.toString();
}
private destroyServer?: () => Promise<void>;
private triggers: { [triggerName: string]: EmulatedTriggerRecord } = {};
// Keep a "generation number" for triggers so that we can disable functions
// and reload them with a new name.
private triggerGeneration = 0;
private workerPools: Record<string, RuntimeWorkerPool>;
private workQueue: WorkQueue;
private logger = EmulatorLogger.forEmulator(Emulators.FUNCTIONS);
private multicastTriggers: { [s: string]: string[] } = {};
private adminSdkConfig: AdminSdkConfig;
private blockingFunctionsConfig: BlockingFunctionsConfig = {};
constructor(private args: FunctionsEmulatorArgs) {
// TODO: Would prefer not to have static state but here we are!
EmulatorLogger.verbosity = this.args.quiet ? Verbosity.QUIET : Verbosity.DEBUG;
// When debugging is enabled, the "timeout" feature needs to be disabled so that
// functions don't timeout while a breakpoint is active.
if (this.args.debugPort) {
this.args.disabledRuntimeFeatures = this.args.disabledRuntimeFeatures || {};
this.args.disabledRuntimeFeatures.timeout = true;
}
this.adminSdkConfig = { ...this.args.adminSdkConfig, projectId: this.args.projectId };
const mode = this.args.debugPort
? FunctionsExecutionMode.SEQUENTIAL
: FunctionsExecutionMode.AUTO;
this.workerPools = {};
for (const backend of this.args.emulatableBackends) {
const pool = new RuntimeWorkerPool(mode);
this.workerPools[backend.codebase] = pool;
}
this.workQueue = new WorkQueue(mode);
}
private async getCredentialsEnvironment(): Promise<Record<string, string>> {
// Provide default application credentials when appropriate
const credentialEnv: Record<string, string> = {};
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
this.logger.logLabeled(
"WARN",
"functions",
`Your GOOGLE_APPLICATION_CREDENTIALS environment variable points to ${process.env.GOOGLE_APPLICATION_CREDENTIALS}. Non-emulated services will access production using these credentials. Be careful!`
);
} else if (this.args.account) {
const defaultCredPath = await getCredentialPathAsync(this.args.account);
if (defaultCredPath) {
this.logger.log("DEBUG", `Setting GAC to ${defaultCredPath}`);
credentialEnv.GOOGLE_APPLICATION_CREDENTIALS = defaultCredPath;
}
} else {
// TODO: It would be safer to set GOOGLE_APPLICATION_CREDENTIALS to /dev/null here but we can't because some SDKs don't work
// without credentials even when talking to the emulator: https://github.com/firebase/firebase-js-sdk/issues/3144
this.logger.logLabeled(
"WARN",
"functions",
"You are not signed in to the Firebase CLI. If you have authorized this machine using gcloud application-default credentials those may be discovered and used to access production services."
);
}
return credentialEnv;
}
createHubServer(): express.Application {
// TODO(samstern): Should not need this here but some tests are directly calling this method
// because FunctionsEmulator.start() used to not be test safe.
this.workQueue.start();
const hub = express();
const dataMiddleware: express.RequestHandler = (req, res, next) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => {
chunks.push(chunk);
});
req.on("end", () => {
(req as RequestWithRawBody).rawBody = Buffer.concat(chunks);
next();
});
};
// The URL for the function that the other emulators (Firestore, etc) use.
// TODO(abehaskins): Make the other emulators use the route below and remove this.
const backgroundFunctionRoute = `/functions/projects/:project_id/triggers/:trigger_name(*)`;
// The URL that the developer sees, this is the same URL that the legacy emulator used.
const httpsFunctionRoute = `/${this.args.projectId}/:region/:trigger_name`;
// The URL for events meant to trigger multiple functions
const multicastFunctionRoute = `/functions/projects/:project_id/trigger_multicast`;
// A trigger named "foo" needs to respond at "foo" as well as "foo/*" but not "fooBar".
const httpsFunctionRoutes = [httpsFunctionRoute, `${httpsFunctionRoute}/*`];
// The URL for the listBackends endpoint, which is used by the Emulator UI.
const listBackendsRoute = `/backends`;
const httpsHandler: express.RequestHandler = (req, res) => {
this.workQueue.submit(() => {
return this.handleHttpsTrigger(req, res);
});
};
const multicastHandler: express.RequestHandler = (req: express.Request, res) => {
const projectId = req.params.project_id;
const rawBody = (req as RequestWithRawBody).rawBody;
const event = JSON.parse(rawBody.toString());
let triggerKey: string;
if (req.headers["content-type"]?.includes("cloudevent")) {
triggerKey = `${this.args.projectId}:${event.type}`;
} else {
triggerKey = `${this.args.projectId}:${event.eventType}`;
}
if (event.data.bucket) {
triggerKey += `:${event.data.bucket}`;
}
const triggers = this.multicastTriggers[triggerKey] || [];
const { host, port } = this.getInfo();
triggers.forEach((triggerId) => {
this.workQueue.submit(() => {
return new Promise((resolve, reject) => {
const trigReq = http.request(
{
host: connectableHostname(host),
port,
method: req.method,
path: `/functions/projects/${projectId}/triggers/${triggerId}`,
headers: req.headers,
},
resolve
);
trigReq.on("error", reject);
trigReq.write(rawBody);
trigReq.end();
});
});
});
res.json({ status: "multicast_acknowledged" });
};
const listBackendsHandler: express.RequestHandler = (req, res) => {
res.json({ backends: this.getBackendInfo() });
};
// The ordering here is important. The longer routes (background)
// need to be registered first otherwise the HTTP functions consume
// all events.
hub.get(listBackendsRoute, cors({ origin: true }), listBackendsHandler); // This route needs CORS so the Emulator UI can call it.
hub.post(backgroundFunctionRoute, dataMiddleware, httpsHandler);
hub.post(multicastFunctionRoute, dataMiddleware, multicastHandler);
hub.all(httpsFunctionRoutes, dataMiddleware, httpsHandler);
hub.all("*", dataMiddleware, (req, res) => {
logger.debug(`Functions emulator received unknown request at path ${req.path}`);
res.sendStatus(404);
});
return hub;
}
async sendRequest(trigger: EmulatedTriggerDefinition, body?: any) {
const record = this.getTriggerRecordByKey(this.getTriggerKey(trigger));
const pool = this.workerPools[record.backend.codebase];
if (!pool.readyForWork(trigger.id)) {
await this.startRuntime(record.backend, trigger);
}
const worker = pool.getIdleWorker(trigger.id)!;
const reqBody = JSON.stringify(body);
const headers = {
"Content-Type": "application/json",
"Content-Length": `${reqBody.length}`,
};
return new Promise((resolve, reject) => {
const req = http.request(
{
path: `/`,
socketPath: worker.runtime.socketPath,
headers: headers,
},
resolve
);
req.on("error", reject);
req.write(reqBody);
req.end();
});
}
async start(): Promise<void> {
for (const backend of this.args.emulatableBackends) {
backend.nodeBinary = this.getNodeBinary(backend);
}
const credentialEnv = await this.getCredentialsEnvironment();
for (const e of this.args.emulatableBackends) {
e.env = { ...credentialEnv, ...e.env };
}
if (Object.keys(this.adminSdkConfig || {}).length <= 1) {
const adminSdkConfig = await getProjectAdminSdkConfigOrCached(this.args.projectId);
if (adminSdkConfig) {
this.adminSdkConfig = adminSdkConfig;
} else {
this.logger.logLabeled(
"WARN",
"functions",
"Unable to fetch project Admin SDK configuration, Admin SDK behavior in Cloud Functions emulator may be incorrect."
);
this.adminSdkConfig = constructDefaultAdminSdkConfig(this.args.projectId);
}
}
const { host, port } = this.getInfo();
this.workQueue.start();
const server = this.createHubServer().listen(port, host);
this.destroyServer = createDestroyer(server);
return Promise.resolve();
}
async connect(): Promise<void> {
for (const backend of this.args.emulatableBackends) {
this.logger.logLabeled(
"BULLET",
"functions",
`Watching "${backend.functionsDir}" for Cloud Functions...`
);
const watcher = chokidar.watch(backend.functionsDir, {
ignored: [
/.+?[\\\/]node_modules[\\\/].+?/, // Ignore node_modules
/(^|[\/\\])\../, // Ignore files which begin the a period
/.+\.log/, // Ignore files which have a .log extension
],
persistent: true,
});
const debouncedLoadTriggers = debounce(() => this.loadTriggers(backend), 1000);
watcher.on("change", (filePath) => {
this.logger.log("DEBUG", `File ${filePath} changed, reloading triggers`);
return debouncedLoadTriggers();
});
await this.loadTriggers(backend, /* force= */ true);
}
await this.performPostLoadOperations();
return;
}
async stop(): Promise<void> {
try {
await this.workQueue.flush();
} catch (e: any) {
this.logger.logLabeled(
"WARN",
"functions",
"Functions emulator work queue did not empty before stopping"
);
}
this.workQueue.stop();
for (const pool of Object.values(this.workerPools)) {
pool.exit();
}
if (this.destroyServer) {
await this.destroyServer();
}
}
async discoverTriggers(
emulatableBackend: EmulatableBackend
): Promise<EmulatedTriggerDefinition[]> {
if (emulatableBackend.predefinedTriggers) {
return emulatedFunctionsByRegion(
emulatableBackend.predefinedTriggers,
emulatableBackend.secretEnv
);
} else {
const runtimeConfig = this.getRuntimeConfig(emulatableBackend);
const runtimeDelegateContext: runtimes.DelegateContext = {
projectId: this.args.projectId,
projectDir: this.args.projectDir,
sourceDir: emulatableBackend.functionsDir,
};
if (emulatableBackend.nodeMajorVersion) {
runtimeDelegateContext.runtime = `nodejs${emulatableBackend.nodeMajorVersion}`;
}
const runtimeDelegate = await runtimes.getRuntimeDelegate(runtimeDelegateContext);
logger.debug(`Validating ${runtimeDelegate.name} source`);
await runtimeDelegate.validate();
logger.debug(`Building ${runtimeDelegate.name} source`);
await runtimeDelegate.build();
logger.debug(`Analyzing ${runtimeDelegate.name} backend spec`);
// Don't include user envs when parsing triggers, but we need some of the options for handling params
const firebaseConfig = this.getFirebaseConfig();
const environment = {
...this.getSystemEnvs(),
...this.getEmulatorEnvs(),
FIREBASE_CONFIG: firebaseConfig,
...emulatableBackend.env,
};
const userEnvOpt: functionsEnv.UserEnvsOpts = {
functionsSource: emulatableBackend.functionsDir,
projectId: this.args.projectId,
projectAlias: this.args.projectAlias,
};
const discoveredBuild = await runtimeDelegate.discoverBuild(runtimeConfig, environment);
const resolution = await resolveBackend(
discoveredBuild,
JSON.parse(firebaseConfig),
userEnvOpt,
environment
);
const discoveredBackend = resolution.backend;
const endpoints = backend.allEndpoints(discoveredBackend);
prepareEndpoints(endpoints);
for (const e of endpoints) {
e.codebase = emulatableBackend.codebase;
}
return emulatedFunctionsFromEndpoints(endpoints);
}
}
/**
* When a user changes their code, we need to look for triggers defined in their updates sources.
*
* TODO(b/216167890): Gracefully handle removal of deleted function definitions
*/
async loadTriggers(emulatableBackend: EmulatableBackend, force = false): Promise<void> {
if (!emulatableBackend.nodeBinary) {
throw new FirebaseError(
`No node binary for ${emulatableBackend.functionsDir}. This should never happen.`
);
}
let triggerDefinitions: EmulatedTriggerDefinition[] = [];
try {
triggerDefinitions = await this.discoverTriggers(emulatableBackend);
this.logger.logLabeled(
"SUCCESS",
"functions",
`Loaded functions definitions from source: ${triggerDefinitions
.map((t) => t.entryPoint)
.join(", ")}.`
);
} catch (e) {
this.logger.logLabeled(
"ERROR",
"functions",
`Failed to load function definition from source: ${e}`
);
return;
}
// Before loading any triggers we need to make sure there are no 'stale' workers
// in the pool that would cause us to run old code.
this.workerPools[emulatableBackend.codebase].refresh();
// reset blocking functions config for reloads
this.blockingFunctionsConfig = {};
// When force is true we set up all triggers, otherwise we only set up
// triggers which have a unique function name
const toSetup = triggerDefinitions.filter((definition) => {
if (force) {
return true;
}
// We want to add a trigger if we don't already have an enabled trigger
// with the same entryPoint / trigger.
const anyEnabledMatch = Object.values(this.triggers).some((record) => {
const sameEntryPoint = record.def.entryPoint === definition.entryPoint;
// If they both have event triggers, make sure they match
const sameEventTrigger =
JSON.stringify(record.def.eventTrigger) === JSON.stringify(definition.eventTrigger);
if (sameEntryPoint && !sameEventTrigger) {
this.logger.log(
"DEBUG",
`Definition for trigger ${definition.entryPoint} changed from ${JSON.stringify(
record.def.eventTrigger
)} to ${JSON.stringify(definition.eventTrigger)}`
);
}
return record.enabled && sameEntryPoint && sameEventTrigger;
});
return !anyEnabledMatch;
});
for (const definition of toSetup) {
// Skip function with invalid id.
try {
// Note - in the emulator, functionId = {region}-{functionName}, but in prod, functionId=functionName.
// To match prod behavior, only validate functionName
functionIdsAreValid([{ ...definition, id: definition.name }]);
} catch (e: any) {
throw new FirebaseError(`functions[${definition.id}]: Invalid function id: ${e.message}`);
}
let added = false;
let url: string | undefined = undefined;
if (definition.httpsTrigger) {
added = true;
url = FunctionsEmulator.getHttpFunctionUrl(
this.args.projectId,
definition.name,
definition.region
);
} else if (definition.eventTrigger) {
const service: string = getFunctionService(definition);
const key = this.getTriggerKey(definition);
const signature = getSignatureType(definition);
switch (service) {
case Constants.SERVICE_FIRESTORE:
added = await this.addFirestoreTrigger(
this.args.projectId,
key,
definition.eventTrigger
);
break;
case Constants.SERVICE_REALTIME_DATABASE:
added = await this.addRealtimeDatabaseTrigger(
this.args.projectId,
key,
definition.eventTrigger,
signature,
definition.region
);
break;
case Constants.SERVICE_PUBSUB:
added = await this.addPubsubTrigger(
definition.name,
key,
definition.eventTrigger,
signature,
definition.schedule
);
break;
case Constants.SERVICE_EVENTARC:
added = await this.addEventarcTrigger(
this.args.projectId,
key,
definition.eventTrigger
);
break;
case Constants.SERVICE_AUTH:
added = this.addAuthTrigger(this.args.projectId, key, definition.eventTrigger);
break;
case Constants.SERVICE_STORAGE:
added = this.addStorageTrigger(this.args.projectId, key, definition.eventTrigger);
break;
default:
this.logger.log("DEBUG", `Unsupported trigger: ${JSON.stringify(definition)}`);
break;
}
} else if (definition.blockingTrigger) {
url = FunctionsEmulator.getHttpFunctionUrl(
this.args.projectId,
definition.name,
definition.region
);
added = this.addBlockingTrigger(url, definition.blockingTrigger);
} else {
this.logger.log(
"WARN",
`Unsupported function type on ${definition.name}. Expected either an httpsTrigger, eventTrigger, or blockingTrigger.`
);
}
const ignored = !added;
this.addTriggerRecord(definition, { backend: emulatableBackend, ignored, url });
const type = definition.httpsTrigger
? "http"
: Constants.getServiceName(getFunctionService(definition));
if (ignored) {
const msg = `function ignored because the ${type} emulator does not exist or is not running.`;
this.logger.logLabeled("BULLET", `functions[${definition.id}]`, msg);
} else {
const msg = url
? `${clc.bold(type)} function initialized (${url}).`
: `${clc.bold(type)} function initialized.`;
this.logger.logLabeled("SUCCESS", `functions[${definition.id}]`, msg);
}
}
// In debug mode, we eagerly start a runtime process to allow debuggers to attach
// before invoking a function.
if (this.args.debugPort) {
await this.startRuntime(emulatableBackend);
}
}
addEventarcTrigger(projectId: string, key: string, eventTrigger: EventTrigger): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.EVENTARC)) {
return Promise.resolve(false);
}
const bundle = {
eventTrigger: {
...eventTrigger,
service: "eventarc.googleapis.com",
},
};
logger.debug(`addEventarcTrigger`, JSON.stringify(bundle));
return EmulatorRegistry.client(Emulators.EVENTARC)
.post(`/emulator/v1/projects/${projectId}/triggers/${key}`, bundle)
.then(() => true)
.catch((err) => {
this.logger.log("WARN", "Error adding Eventarc function: " + err);
return false;
});
}
async performPostLoadOperations(): Promise<void> {
if (
!this.blockingFunctionsConfig.triggers &&
!this.blockingFunctionsConfig.forwardInboundCredentials
) {
return;
}
if (!EmulatorRegistry.isRunning(Emulators.AUTH)) {
return;
}
const path = `/identitytoolkit.googleapis.com/v2/projects/${this.getProjectId()}/config?updateMask=blockingFunctions`;
try {
const client = EmulatorRegistry.client(Emulators.AUTH);
await client.patch(
path,
{ blockingFunctions: this.blockingFunctionsConfig },
{
headers: { Authorization: "Bearer owner" },
}
);
} catch (err) {
this.logger.log(
"WARN",
"Error updating blocking functions config to the auth emulator: " + err
);
throw err;
}
}
private getV1DatabaseApiAttributes(projectId: string, key: string, eventTrigger: EventTrigger) {
const result: string[] | null = DATABASE_PATH_PATTERN.exec(eventTrigger.resource!);
if (result === null || result.length !== 3) {
this.logger.log(
"WARN",
`Event function "${key}" has malformed "resource" member. ` + `${eventTrigger.resource!}`
);
throw new FirebaseError(`Event function ${key} has malformed resource member`);
}
const instance = result[1];
const bundle = JSON.stringify({
name: `projects/${projectId}/locations/_/functions/${key}`,
path: result[2], // path stored in the second capture group
event: eventTrigger.eventType,
topic: `projects/${projectId}/topics/${key}`,
});
let apiPath = "/.settings/functionTriggers.json";
if (instance !== "") {
apiPath += `?ns=${instance}`;
} else {
this.logger.log(
"WARN",
`No project in use. Registering function for sentinel namespace '${Constants.DEFAULT_DATABASE_EMULATOR_NAMESPACE}'`
);
}
return { bundle, apiPath, instance };
}
private getV2DatabaseApiAttributes(
projectId: string,
key: string,
eventTrigger: EventTrigger,
region: string
) {
const instance =
eventTrigger.eventFilters?.instance || eventTrigger.eventFilterPathPatterns?.instance;
if (!instance) {
throw new FirebaseError("A database instance must be supplied.");
}
const ref = eventTrigger.eventFilterPathPatterns?.ref;
if (!ref) {
throw new FirebaseError("A database reference must be supplied.");
}
// The 'namespacePattern' determines that we are using the v2 interface
const bundle = JSON.stringify({
name: `projects/${projectId}/locations/${region}/triggers/${key}`,
path: ref,
event: eventTrigger.eventType,
topic: `projects/${projectId}/topics/${key}`,
namespacePattern: instance,
});
// The query parameter '?ns=${instance}' is ignored in v2
const apiPath = "/.settings/functionTriggers.json";
return { bundle, apiPath, instance };
}
async addRealtimeDatabaseTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger,
signature: SignatureType,
region: string
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.DATABASE)) {
return false;
}
const { bundle, apiPath, instance } =
signature === "cloudevent"
? this.getV2DatabaseApiAttributes(projectId, key, eventTrigger, region)
: this.getV1DatabaseApiAttributes(projectId, key, eventTrigger);
logger.debug(`addRealtimeDatabaseTrigger[${instance}]`, JSON.stringify(bundle));
const client = EmulatorRegistry.client(Emulators.DATABASE);
try {
await client.post(apiPath, bundle, { headers: { Authorization: "Bearer owner" } });
} catch (err: any) {
this.logger.log("WARN", "Error adding Realtime Database function: " + err);
throw err;
}
return true;
}
async addFirestoreTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.FIRESTORE)) {
return Promise.resolve(false);
}
const bundle = JSON.stringify({
eventTrigger: {
...eventTrigger,
service: "firestore.googleapis.com",
},
});
logger.debug(`addFirestoreTrigger`, JSON.stringify(bundle));
const client = EmulatorRegistry.client(Emulators.FIRESTORE);
try {
await client.put(`/emulator/v1/projects/${projectId}/triggers/${key}`, bundle);
} catch (err: any) {
this.logger.log("WARN", "Error adding firestore function: " + err);
throw err;
}
return true;
}
async addPubsubTrigger(
triggerName: string,
key: string,
eventTrigger: EventTrigger,
signatureType: SignatureType,
schedule: EventSchedule | undefined
): Promise<boolean> {
const pubsubEmulator = EmulatorRegistry.get(Emulators.PUBSUB) as PubsubEmulator | undefined;
if (!pubsubEmulator) {
return false;
}
logger.debug(`addPubsubTrigger`, JSON.stringify({ eventTrigger }));
// "resource":\"projects/{PROJECT_ID}/topics/{TOPIC_ID}";
const resource = eventTrigger.resource!;
let topic;
if (schedule) {
// In production this topic looks like
// "firebase-schedule-{FUNCTION_NAME}-{DEPLOY-LOCATION}", we simply drop
// the deploy location to match as closely as possible.
topic = "firebase-schedule-" + triggerName;
} else {
const resourceParts = resource.split("/");
topic = resourceParts[resourceParts.length - 1];
}
try {
await pubsubEmulator.addTrigger(topic, key, signatureType);
return true;
} catch (e: any) {
return false;
}
}
addAuthTrigger(projectId: string, key: string, eventTrigger: EventTrigger): boolean {
logger.debug(`addAuthTrigger`, JSON.stringify({ eventTrigger }));
const eventTriggerId = `${projectId}:${eventTrigger.eventType}`;
const triggers = this.multicastTriggers[eventTriggerId] || [];
triggers.push(key);
this.multicastTriggers[eventTriggerId] = triggers;
return true;
}
addStorageTrigger(projectId: string, key: string, eventTrigger: EventTrigger): boolean {
logger.debug(`addStorageTrigger`, JSON.stringify({ eventTrigger }));
const bucket = eventTrigger.resource!.startsWith("projects/_/buckets/")
? eventTrigger.resource!.split("/")[3]
: eventTrigger.resource;
const eventTriggerId = `${projectId}:${eventTrigger.eventType}:${bucket}`;
const triggers = this.multicastTriggers[eventTriggerId] || [];
triggers.push(key);
this.multicastTriggers[eventTriggerId] = triggers;
return true;
}
addBlockingTrigger(url: string, blockingTrigger: BlockingTrigger): boolean {
logger.debug(`addBlockingTrigger`, JSON.stringify({ blockingTrigger }));
const eventType = blockingTrigger.eventType;
if (!AUTH_BLOCKING_EVENTS.includes(eventType as any)) {
return false;
}
if (blockingTrigger.eventType === BEFORE_CREATE_EVENT) {
this.blockingFunctionsConfig.triggers = {
...this.blockingFunctionsConfig.triggers,
beforeCreate: {
functionUri: url,
},
};
} else {
this.blockingFunctionsConfig.triggers = {
...this.blockingFunctionsConfig.triggers,
beforeSignIn: {
functionUri: url,
},
};
}
this.blockingFunctionsConfig.forwardInboundCredentials = {
accessToken: !!blockingTrigger.options!.accessToken,
idToken: !!blockingTrigger.options!.idToken,
refreshToken: !!blockingTrigger.options!.refreshToken,
};
return true;
}
getProjectId(): string {
return this.args.projectId;
}
getInfo(): EmulatorInfo {
const host = this.args.host || Constants.getDefaultHost();
const port = this.args.port || Constants.getDefaultPort(Emulators.FUNCTIONS);
return {
name: this.getName(),
host,
port,
};
}
getName(): Emulators {
return Emulators.FUNCTIONS;
}
getTriggerDefinitions(): EmulatedTriggerDefinition[] {
return Object.values(this.triggers).map((record) => record.def);
}
getTriggerRecordByKey(triggerKey: string): EmulatedTriggerRecord {
const record = this.triggers[triggerKey];
if (!record) {
logger.debug(`Could not find key=${triggerKey} in ${JSON.stringify(this.triggers)}`);
throw new FirebaseError(`No function with key ${triggerKey}`);
}
return record;
}
getTriggerKey(def: EmulatedTriggerDefinition): string {
// For background triggers we attach the current generation as a suffix
if (def.eventTrigger) {
const triggerKey = `${def.id}-${this.triggerGeneration}`;
return def.eventTrigger.channel ? `${triggerKey}-${def.eventTrigger.channel}` : triggerKey;
} else {
return def.id;
}
}
getBackendInfo(): BackendInfo[] {
const cf3Triggers = this.getCF3Triggers();
return this.args.emulatableBackends.map((e: EmulatableBackend) => {
return toBackendInfo(e, cf3Triggers);
});
}
getCF3Triggers(): ParsedTriggerDefinition[] {
return Object.values(this.triggers)
.filter((t) => !t.backend.extensionInstanceId)
.map((t) => t.def);
}
addTriggerRecord(
def: EmulatedTriggerDefinition,
opts: {
ignored: boolean;
backend: EmulatableBackend;
url?: string;
}
): void {
const key = this.getTriggerKey(def);
this.triggers[key] = {
def,
enabled: true,
backend: opts.backend,
ignored: opts.ignored,
url: opts.url,
};
}
setTriggersForTesting(triggers: EmulatedTriggerDefinition[], backend: EmulatableBackend) {