-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathbuild.ts
More file actions
693 lines (623 loc) · 24.3 KB
/
build.ts
File metadata and controls
693 lines (623 loc) · 24.3 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
import * as backend from "./backend";
import * as proto from "../../gcp/proto";
import * as api from "../../api";
import * as params from "./params";
import { FirebaseError } from "../../error";
import { assertExhaustive, mapObject, nullsafeVisitor } from "../../functional";
import { FirebaseConfig } from "./args";
import { Runtime } from "./runtimes/supported";
import { ExprParseError } from "./cel";
import { defineSecret } from "firebase-functions/params";
/* The union of a customer-controlled deployment and potentially deploy-time defined parameters */
export interface Build {
requiredAPIs: RequiredApi[];
endpoints: Record<string, Endpoint>;
params: params.Param[];
runtime?: Runtime;
extensions?: Record<string, DynamicExtension>;
}
/**
* A utility function that returns an empty Build.
*/
export function empty(): Build {
return {
requiredAPIs: [],
endpoints: {},
params: [],
};
}
/**
* A utility function that creates a Build containing a map of IDs to Endpoints
*/
export function of(endpoints: Record<string, Endpoint>): Build {
const build = empty();
build.endpoints = endpoints;
return build;
}
export interface RequiredApi {
// The API that should be enabled. For Google APIs, this should be a googleapis.com subdomain
// (e.g. vision.googleapis.com)
api: string;
// A reason why this codebase requires this API.
// Will be considered required for all Extensions codebases. Considered optional for Functions
// codebases.
reason?: string;
}
// Defining a StringParam with { param: "FOO" } declares that "{{ params.FOO }}" is a valid
// Expression<string> elsewhere.
// Expression<number> is always an int. Float Params, list params, and secret params cannot be used in
// expressions.
// `Expression<Foo> == Expression<Foo>` is an Expression<boolean>
// `Expression<boolean> ? Expression<T> : Expression<T>` is an Expression<T>
export type Expression<T extends string | number | boolean | string[]> = string; // eslint-disable-line
export type Field<T extends string | number | boolean> = T | Expression<T> | null;
export type ListField = Expression<string[]> | (string | Expression<string>)[] | null;
// A service account must either:
// 1. Be a project-relative email that ends with "@" (e.g. database-users@)
// 2. Be a well-known shorthand (e..g "public" and "private")
type ServiceAccount = string;
// Trigger definition for arbitrary HTTPS endpoints
export interface HttpsTrigger {
// Which service account should be able to trigger this function. No value means "make public
// on create and don't do anything on update." For more, see go/cf3-http-access-control
invoker?: Array<ServiceAccount | Expression<string>> | null;
}
// Trigger definitions for RPCs servers using the HTTP protocol defined at
// https://firebase.google.com/docs/functions/callable-reference
interface CallableTrigger {
genkitAction?: string;
}
// Trigger definitions for endpoints that should be called as a delegate for other operations.
// For example, before user login.
export interface BlockingTrigger {
eventType: string;
options?: Record<string, unknown>;
}
// Trigger definitions for endpoints that listen to CloudEvents emitted by other systems (or legacy
// Google events for GCF gen 1)
export interface EventTrigger {
eventType: string;
eventFilters?: Record<string, string | Expression<string>>;
eventFilterPathPatterns?: Record<string, string | Expression<string>>;
// whether failed function executions should retry the event execution.
// Retries are indefinite, so developers should be sure to add some end condition (e.g. event
// age)
retry: Field<boolean>;
// Region of the EventArc trigger. Must be the same region or multi-region as the event
// trigger or be us-central1. All first party triggers (all triggers as of Jan 2022) need not
// specify this field because tooling determines the correct value automatically.
// N.B. This is an Expression<string> not Field<string> because it cannot be reset
// by setting to null
region?: string | Expression<string>;
// The service account that EventArc should use to invoke this function. Setting this field
// requires the EventArc P4SA to be granted the "ActAs" permission to this service account and
// will cause the "invoker" role to be granted to this service account on the endpoint
// (Function or Route)
serviceAccount?: ServiceAccount | Expression<string> | null;
// The name of the channel where the function receives events.
// Must be provided to receive CF3v2 custom events.
channel?: string;
}
export interface TaskQueueRateLimits {
maxConcurrentDispatches?: Field<number>;
maxDispatchesPerSecond?: Field<number>;
}
export interface TaskQueueRetryConfig {
maxAttempts?: Field<number>;
maxRetrySeconds?: Field<number>;
minBackoffSeconds?: Field<number>;
maxBackoffSeconds?: Field<number>;
maxDoublings?: Field<number>;
}
export interface TaskQueueTrigger {
rateLimits?: TaskQueueRateLimits | null;
retryConfig?: TaskQueueRetryConfig | null;
// empty array means private
invoker?: Array<ServiceAccount | Expression<ServiceAccount>> | null;
}
export interface ScheduleRetryConfig {
retryCount?: Field<number>;
maxRetrySeconds?: Field<number>;
minBackoffSeconds?: Field<number>;
maxBackoffSeconds?: Field<number>;
maxDoublings?: Field<number>;
}
export interface ScheduleTrigger {
schedule: string | Expression<string>;
timeZone?: Field<string>;
retryConfig?: ScheduleRetryConfig | null;
attemptDeadlineSeconds?: Field<number>;
}
export type HttpsTriggered = { httpsTrigger: HttpsTrigger };
export type CallableTriggered = { callableTrigger: CallableTrigger };
export type BlockingTriggered = { blockingTrigger: BlockingTrigger };
export type EventTriggered = { eventTrigger: EventTrigger };
export type ScheduleTriggered = { scheduleTrigger: ScheduleTrigger };
export type TaskQueueTriggered = { taskQueueTrigger: TaskQueueTrigger };
export type Triggered =
| HttpsTriggered
| CallableTriggered
| BlockingTriggered
| EventTriggered
| ScheduleTriggered
| TaskQueueTriggered;
/** Whether something has an HttpsTrigger */
export function isHttpsTriggered(triggered: Triggered): triggered is HttpsTriggered {
return {}.hasOwnProperty.call(triggered, "httpsTrigger");
}
/** Whether something has a CallableTrigger */
export function isCallableTriggered(triggered: Triggered): triggered is CallableTriggered {
return {}.hasOwnProperty.call(triggered, "callableTrigger");
}
/** Whether something has an EventTrigger */
export function isEventTriggered(triggered: Triggered): triggered is EventTriggered {
return {}.hasOwnProperty.call(triggered, "eventTrigger");
}
/** Whether something has a ScheduleTrigger */
export function isScheduleTriggered(triggered: Triggered): triggered is ScheduleTriggered {
return {}.hasOwnProperty.call(triggered, "scheduleTrigger");
}
/** Whether something has a TaskQueueTrigger */
export function isTaskQueueTriggered(triggered: Triggered): triggered is TaskQueueTriggered {
return {}.hasOwnProperty.call(triggered, "taskQueueTrigger");
}
/** Whether something has a BlockingTrigger */
export function isBlockingTriggered(triggered: Triggered): triggered is BlockingTriggered {
return {}.hasOwnProperty.call(triggered, "blockingTrigger");
}
export interface VpcSettings {
connector: string | Expression<string>;
egressSettings?: "PRIVATE_RANGES_ONLY" | "ALL_TRAFFIC" | Expression<string> | null;
}
export interface SecretEnvVar {
key: string; // The environment variable this secret is accessible at
secret: string; // The id of the SecretVersion - ie for projects/myproject/secrets/mysecret, this is 'mysecret'
projectId: string; // The project containing the Secret
}
export type MemoryOption = 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384 | 32768;
const allMemoryOptions: MemoryOption[] = [128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768];
// Run is an automatic migration from gcfv2 and is not used on the wire.
export type FunctionsPlatform = Exclude<backend.FunctionsPlatform, "run">;
export const AllFunctionsPlatforms: FunctionsPlatform[] = ["gcfv1", "gcfv2"];
export type VpcEgressSetting = backend.VpcEgressSettings;
export const AllVpcEgressSettings: VpcEgressSetting[] = ["PRIVATE_RANGES_ONLY", "ALL_TRAFFIC"];
export type IngressSetting = backend.IngressSettings;
export const AllIngressSettings: IngressSetting[] = [
"ALLOW_ALL",
"ALLOW_INTERNAL_ONLY",
"ALLOW_INTERNAL_AND_GCLB",
];
export type Endpoint = Triggered & {
// Defaults to false. If true, the function will be ignored during the deploy process.
omit?: Field<boolean>;
// Defaults to "gcfv2". "Run" will be an additional option defined later
platform?: "gcfv1" | "gcfv2";
// Necessary for the GCF API to determine what code to load with the Functions Framework.
// Will become optional once "run" is supported as a platform
entryPoint: string;
// The services account that this function should run as.
// defaults to the GAE service account when a function is first created as a GCF gen 1 function.
// Defaults to the compute service account when a function is first created as a GCF gen 2 function.
serviceAccount?: ServiceAccount | Expression<string> | null;
// defaults to ["us-central1"], overridable in firebase-tools with
// process.env.FIREBASE_FUNCTIONS_DEFAULT_REGION
region?: ListField;
// The Cloud project associated with this endpoint.
project: string;
// The runtime being deployed to this endpoint. Currently targeting "nodejs16."
runtime: Runtime;
// Firebase default of 80. Cloud default of 1
concurrency?: Field<number>;
// Default of 256
availableMemoryMb?: Field<number>;
// Default of 1 for GCF 2nd gen;
cpu?: Field<number>;
// Default of 60
timeoutSeconds?: Field<number>;
// Default of 1000
maxInstances?: Field<number>;
// Default of 0
minInstances?: Field<number>;
vpc?: VpcSettings | null;
ingressSettings?: "ALLOW_ALL" | "ALLOW_INTERNAL_ONLY" | "ALLOW_INTERNAL_AND_GCLB" | null;
environmentVariables?: Record<string, string | Expression<string>> | null;
secretEnvironmentVariables?: SecretEnvVar[] | null;
labels?: Record<string, string | Expression<string>> | null;
};
type SecretParam = ReturnType<typeof defineSecret>;
export type DynamicExtension = {
params: Record<string, string | SecretParam>;
ref?: string;
localPath?: string;
events: string[];
labels?: Record<string, string>;
};
interface ResolveBackendOpts {
build: Build;
firebaseConfig: FirebaseConfig;
userEnvs: Record<string, string>;
nonInteractive?: boolean;
isEmulator?: boolean;
}
/**
* Resolves user-defined parameters inside a Build and generates a Backend.
* Callers are responsible for persisting resolved env vars.
*/
export async function resolveBackend(
opts: ResolveBackendOpts,
): Promise<{ backend: backend.Backend; envs: Record<string, params.ParamValue> }> {
const paramValues = await params.resolveParams(
opts.build.params,
opts.firebaseConfig,
envWithTypes(opts.build.params, opts.userEnvs),
opts.nonInteractive,
opts.isEmulator,
);
return { backend: toBackend(opts.build, paramValues), envs: paramValues };
}
// Exported for testing
/**
*
*/
export function envWithTypes(
definedParams: params.Param[],
rawEnvs: Record<string, string>,
): Record<string, params.ParamValue> {
const out: Record<string, params.ParamValue> = {};
for (const envName of Object.keys(rawEnvs)) {
const value = rawEnvs[envName];
let providedType = {
string: true,
boolean: true,
number: true,
list: true,
};
for (const param of definedParams) {
if (param.name === envName) {
if (param.type === "string") {
providedType = {
string: true,
boolean: false,
number: false,
list: false,
};
} else if (param.type === "int") {
providedType = {
string: false,
boolean: false,
number: true,
list: false,
};
} else if (param.type === "boolean") {
providedType = {
string: false,
boolean: true,
number: false,
list: false,
};
} else if (param.type === "list") {
providedType = {
string: false,
boolean: false,
number: false,
list: true,
};
} else if (param.type === "secret") {
// NOTE(danielylee): Secret values are not supposed to be
// provided in the env files. However, users may do it anyway.
// Secret values will be provided as strings in those cases.
providedType = {
string: true,
boolean: false,
number: false,
list: false,
};
}
}
}
out[envName] = new params.ParamValue(value, false, providedType);
}
return out;
}
// Utility class to make it more fluent to use proto.convertIfPresent
// The class usese const lambdas so it doesn't loose the this context when
// passing Resolver.resolveFoo as a proto.convertIfPresent arg.
// The class also recognizes that if the input is not null the output cannot be
// null.
class Resolver {
constructor(private readonly paramValues: Record<string, params.ParamValue>) {}
// NB: The (Extract<T, null> | number) says "If T can be null, the return value"
// can be null. If we know input is not null, the return type is known to not
// be null.
readonly resolveInt = <T extends Field<number>>(i: T): Extract<T, null> | number => {
if (i === null) {
return i as Extract<T, null>;
}
return params.resolveInt(i, this.paramValues);
};
readonly resolveBoolean = <T extends Field<boolean>>(i: T): Extract<T, null> | boolean => {
if (i === null) {
return i as Extract<T, null>;
}
return params.resolveBoolean(i, this.paramValues);
};
readonly resolveString = <T extends Field<string>>(i: T): Extract<T, null> | string => {
if (i === null) {
return i as Extract<T, null>;
}
return params.resolveString(i, this.paramValues);
};
resolveStrings<Key extends string>(
dest: { [K in Key]?: string | null },
src: { [K in Key]?: Field<string> },
...keys: Key[]
): void {
for (const key of keys) {
const orig = src[key];
if (typeof orig === "undefined") {
continue;
}
dest[key] = orig === null ? null : params.resolveString(orig, this.paramValues);
}
}
resolveInts<Key extends string>(
dest: { [K in Key]?: number | null },
src: { [K in Key]?: Field<number> },
...keys: Key[]
): void {
for (const key of keys) {
const orig = src[key];
if (typeof orig === "undefined") {
continue;
}
dest[key] = orig === null ? null : params.resolveInt(orig, this.paramValues);
}
}
}
/** Converts a build specification into a Backend representation, with all Params resolved and interpolated */
export function toBackend(
build: Build,
paramValues: Record<string, params.ParamValue>,
): backend.Backend {
const r = new Resolver(paramValues);
const bkEndpoints: Array<backend.Endpoint> = [];
for (const endpointId of Object.keys(build.endpoints)) {
const bdEndpoint = build.endpoints[endpointId];
if (r.resolveBoolean(bdEndpoint.omit || false)) {
continue;
}
let regions: string[] = [];
if (!bdEndpoint.region) {
regions = [api.functionsDefaultRegion()];
} else if (Array.isArray(bdEndpoint.region)) {
regions = params.resolveList(bdEndpoint.region, paramValues);
} else {
// N.B. setting region via GlobalOptions only accepts a String param.
// Therefore if we raise an exception by attempting to resolve a
// List param, we try resolving a String param instead.
try {
regions = params.resolveList(bdEndpoint.region, paramValues);
} catch (err: any) {
if (err instanceof ExprParseError) {
regions = [params.resolveString(bdEndpoint.region, paramValues)];
} else {
throw err;
}
}
}
for (const region of regions) {
const trigger = discoverTrigger(bdEndpoint, region, r);
if (typeof bdEndpoint.platform === "undefined") {
throw new FirebaseError("platform can't be undefined");
}
const bkEndpoint: backend.Endpoint = {
id: endpointId,
project: bdEndpoint.project,
region: region,
entryPoint: bdEndpoint.entryPoint,
platform: bdEndpoint.platform,
runtime: bdEndpoint.runtime,
...trigger,
};
proto.copyIfPresent(
bkEndpoint,
bdEndpoint,
"environmentVariables",
"labels",
"secretEnvironmentVariables",
);
r.resolveStrings(bkEndpoint, bdEndpoint, "serviceAccount");
proto.convertIfPresent(bkEndpoint, bdEndpoint, "ingressSettings", (from) => {
if (from !== null && !backend.AllIngressSettings.includes(from)) {
throw new FirebaseError(`Cannot set ingress settings to invalid value ${from}`);
}
return from;
});
proto.convertIfPresent(bkEndpoint, bdEndpoint, "availableMemoryMb", (from) => {
const mem = r.resolveInt(from);
if (mem !== null && !backend.isValidMemoryOption(mem)) {
throw new FirebaseError(
`Function memory (${mem}) must resolve to a supported value, if present: ${JSON.stringify(
allMemoryOptions,
)}`,
);
}
return (mem as backend.MemoryOptions) || null;
});
r.resolveStrings(bkEndpoint, bdEndpoint, "serviceAccount");
r.resolveInts(
bkEndpoint,
bdEndpoint,
"timeoutSeconds",
"maxInstances",
"minInstances",
"concurrency",
);
proto.convertIfPresent(
bkEndpoint,
bdEndpoint,
"cpu",
nullsafeVisitor((cpu) => (cpu === "gcf_gen1" ? cpu : r.resolveInt(cpu))),
);
if (bdEndpoint.vpc) {
bdEndpoint.vpc.connector = params.resolveString(bdEndpoint.vpc.connector, paramValues);
if (bdEndpoint.vpc.connector && !bdEndpoint.vpc.connector.includes("/")) {
bdEndpoint.vpc.connector = `projects/${bdEndpoint.project}/locations/${region}/connectors/${bdEndpoint.vpc.connector}`;
}
bkEndpoint.vpc = { connector: bdEndpoint.vpc.connector };
if (bdEndpoint.vpc.egressSettings) {
const egressSettings = r.resolveString(bdEndpoint.vpc.egressSettings);
if (!backend.isValidEgressSetting(egressSettings)) {
throw new FirebaseError(
`Value "${egressSettings}" is an invalid ` +
"egress setting. Valid values are PRIVATE_RANGES_ONLY and ALL_TRAFFIC",
);
}
bkEndpoint.vpc.egressSettings = egressSettings;
}
} else if (bdEndpoint.vpc === null) {
bkEndpoint.vpc = null;
}
bkEndpoints.push(bkEndpoint);
}
}
const bkend = backend.of(...bkEndpoints);
bkend.requiredAPIs = build.requiredAPIs;
return bkend;
}
function discoverTrigger(endpoint: Endpoint, region: string, r: Resolver): backend.Triggered {
if (isHttpsTriggered(endpoint)) {
const httpsTrigger: backend.HttpsTrigger = {};
if (endpoint.httpsTrigger.invoker === null) {
httpsTrigger.invoker = null;
} else if (typeof endpoint.httpsTrigger.invoker !== "undefined") {
httpsTrigger.invoker = endpoint.httpsTrigger.invoker.map(r.resolveString);
}
return { httpsTrigger };
} else if (isCallableTriggered(endpoint)) {
const trigger: CallableTriggered = { callableTrigger: {} };
proto.copyIfPresent(trigger.callableTrigger, endpoint.callableTrigger, "genkitAction");
return trigger;
} else if (isBlockingTriggered(endpoint)) {
return { blockingTrigger: endpoint.blockingTrigger };
} else if (isEventTriggered(endpoint)) {
const eventTrigger: backend.EventTrigger = {
eventType: endpoint.eventTrigger.eventType,
retry: r.resolveBoolean(endpoint.eventTrigger.retry) || false,
};
if (endpoint.eventTrigger.eventFilters) {
eventTrigger.eventFilters = mapObject(endpoint.eventTrigger.eventFilters, r.resolveString);
}
if (endpoint.eventTrigger.eventFilterPathPatterns) {
eventTrigger.eventFilterPathPatterns = mapObject(
endpoint.eventTrigger.eventFilterPathPatterns,
r.resolveString,
);
}
r.resolveStrings(eventTrigger, endpoint.eventTrigger, "serviceAccount", "region", "channel");
return { eventTrigger };
} else if (isScheduleTriggered(endpoint)) {
const bkSchedule: backend.ScheduleTrigger = {
schedule: r.resolveString(endpoint.scheduleTrigger.schedule),
};
if (endpoint.scheduleTrigger.timeZone !== undefined) {
bkSchedule.timeZone = r.resolveString(endpoint.scheduleTrigger.timeZone);
}
if (endpoint.scheduleTrigger.retryConfig) {
const bkRetry: backend.ScheduleRetryConfig = {};
r.resolveInts(
bkRetry,
endpoint.scheduleTrigger.retryConfig,
"maxBackoffSeconds",
"minBackoffSeconds",
"maxRetrySeconds",
"retryCount",
"maxDoublings",
);
bkSchedule.retryConfig = bkRetry;
} else if (endpoint.scheduleTrigger.retryConfig === null) {
bkSchedule.retryConfig = null;
}
if (typeof endpoint.scheduleTrigger.attemptDeadlineSeconds !== "undefined") {
const attemptDeadlineSeconds = r.resolveInt(endpoint.scheduleTrigger.attemptDeadlineSeconds);
if (
attemptDeadlineSeconds !== null &&
!backend.isValidAttemptDeadline(attemptDeadlineSeconds)
) {
throw new FirebaseError(
`attemptDeadlineSeconds must be between ${backend.MIN_ATTEMPT_DEADLINE_SECONDS} and ${backend.MAX_ATTEMPT_DEADLINE_SECONDS} seconds (inclusive).`,
);
}
bkSchedule.attemptDeadlineSeconds = attemptDeadlineSeconds;
}
return { scheduleTrigger: bkSchedule };
} else if ("taskQueueTrigger" in endpoint) {
const taskQueueTrigger: backend.TaskQueueTrigger = {};
if (endpoint.taskQueueTrigger.rateLimits) {
taskQueueTrigger.rateLimits = {};
r.resolveInts(
taskQueueTrigger.rateLimits,
endpoint.taskQueueTrigger.rateLimits,
"maxConcurrentDispatches",
"maxDispatchesPerSecond",
);
} else if (endpoint.taskQueueTrigger.rateLimits === null) {
taskQueueTrigger.rateLimits = null;
}
if (endpoint.taskQueueTrigger.retryConfig) {
taskQueueTrigger.retryConfig = {};
r.resolveInts(
taskQueueTrigger.retryConfig,
endpoint.taskQueueTrigger.retryConfig,
"maxAttempts",
"maxBackoffSeconds",
"minBackoffSeconds",
"maxRetrySeconds",
"maxDoublings",
);
} else if (endpoint.taskQueueTrigger.retryConfig === null) {
taskQueueTrigger.retryConfig = null;
}
if (endpoint.taskQueueTrigger.invoker) {
taskQueueTrigger.invoker = endpoint.taskQueueTrigger.invoker.map(r.resolveString);
} else if (endpoint.taskQueueTrigger.invoker === null) {
taskQueueTrigger.invoker = null;
}
return { taskQueueTrigger };
}
assertExhaustive(endpoint);
}
/**
* Prefixes all endpoint IDs and secret names in a build with a given prefix.
* This ensures that functions and their associated secrets from different codebases
* remain isolated and don't conflict when deployed to the same project.
*/
export function applyPrefix(build: Build, prefix: string): void {
if (!prefix) {
return;
}
const newEndpoints: Record<string, Endpoint> = {};
for (const [id, endpoint] of Object.entries(build.endpoints)) {
const newId = `${prefix}-${id}`;
// Enforce function id constraints early for clearer errors.
if (newId.length > 63) {
throw new FirebaseError(
`Function id '${newId}' exceeds 63 characters after applying prefix '${prefix}'. Please shorten the prefix or function name.`,
);
}
const fnIdRegex = /^[a-zA-Z][a-zA-Z0-9_-]{0,62}$/;
if (!fnIdRegex.test(newId)) {
throw new FirebaseError(
`Function id '${newId}' is invalid after applying prefix '${prefix}'. Function names must start with a letter and can contain letters, numbers, underscores, and hyphens, with a maximum length of 63 characters.`,
);
}
newEndpoints[newId] = endpoint;
if (endpoint.secretEnvironmentVariables) {
endpoint.secretEnvironmentVariables = endpoint.secretEnvironmentVariables.map((secret) => ({
...secret,
secret: `${prefix}-${secret.secret}`,
}));
}
}
build.endpoints = newEndpoints;
}