-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathbackend.spec.ts
More file actions
656 lines (578 loc) · 20.1 KB
/
backend.spec.ts
File metadata and controls
656 lines (578 loc) · 20.1 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
import { expect } from "chai";
import * as sinon from "sinon";
import { FirebaseError } from "../../error";
import * as args from "./args";
import * as backend from "./backend";
import * as gcf from "../../gcp/cloudfunctions";
import * as gcfV2 from "../../gcp/cloudfunctionsv2";
import * as run from "../../gcp/runv2";
import * as experiments from "../../experiments";
import * as utils from "../../utils";
import * as projectConfig from "../../functions/projectConfig";
describe("Backend", () => {
const FUNCTION_NAME: backend.TargetIds = {
id: "id",
region: "region",
project: "project",
};
const ENDPOINT: Omit<backend.Endpoint, "httpsTrigger"> = {
platform: "gcfv1",
...FUNCTION_NAME,
entryPoint: "function",
runtime: "nodejs16",
codebase: projectConfig.DEFAULT_CODEBASE,
state: "ACTIVE",
};
const CLOUD_FUNCTION: Omit<gcf.CloudFunction, gcf.OutputOnlyFields> = {
name: "projects/project/locations/region/functions/id",
entryPoint: "function",
runtime: "nodejs16",
};
const CLOUD_FUNCTION_V2_SOURCE: gcfV2.StorageSource = {
bucket: "sample",
object: "source.zip",
generation: 42,
};
const CLOUD_FUNCTION_V2: gcfV2.InputCloudFunction = {
name: "projects/project/locations/region/functions/id",
buildConfig: {
entryPoint: "function",
runtime: "nodejs16",
source: {
storageSource: CLOUD_FUNCTION_V2_SOURCE,
},
environmentVariables: {},
},
serviceConfig: {
service: "projects/project/locations/region/services/service",
availableCpu: "1",
maxInstanceRequestConcurrency: 80,
},
};
const GCF_URL = "https://region-project.cloudfunctions.net/id";
const HAVE_CLOUD_FUNCTION_V2: gcfV2.OutputCloudFunction = {
...CLOUD_FUNCTION_V2,
serviceConfig: {
service: "service",
uri: GCF_URL,
availableCpu: "1",
maxInstanceRequestConcurrency: 80,
},
url: GCF_URL,
state: "ACTIVE",
updateTime: new Date(),
};
const RUN_SERVICE: run.Service = {
name: "projects/project/locations/region/services/id",
labels: {
"goog-managed-by": "cloud-functions",
"goog-cloudfunctions-runtime": "nodejs16",
"firebase-functions-codebase": "default",
},
annotations: {
"cloudfunctions.googleapis.com/function-id": "id",
"cloudfunctions.googleapis.com/trigger-type": "HTTP_TRIGGER",
},
template: {
containers: [
{
name: "worker",
image: "image",
env: [{ name: "FUNCTION_TARGET", value: "function" }],
resources: {
limits: {
cpu: "1",
memory: "256Mi",
},
},
},
],
containerConcurrency: 80,
},
generation: 1,
createTime: "2023-01-01T00:00:00Z",
updateTime: "2023-01-01T00:00:00Z",
creator: "user",
lastModifier: "user",
etag: "etag",
};
const HAVE_CLOUD_FUNCTION: gcf.CloudFunction = {
...CLOUD_FUNCTION,
buildId: "buildId",
versionId: 1,
updateTime: new Date(),
status: "ACTIVE",
};
describe("Helper functions", () => {
it("isEmptyBackend", () => {
expect(backend.isEmptyBackend(backend.empty())).to.be.true;
expect(
backend.isEmptyBackend({
...backend.empty(),
requiredAPIs: [{ api: "foo.googleapis.com", reason: "foo" }],
}),
).to.be.false;
expect(backend.isEmptyBackend(backend.of({ ...ENDPOINT, httpsTrigger: {} })));
});
it("names", () => {
expect(backend.functionName(ENDPOINT)).to.equal(
"projects/project/locations/region/functions/id",
);
});
it("merge", () => {
const BASE_ENDPOINT = { ...ENDPOINT, httpsTrigger: {} };
const e1 = { ...BASE_ENDPOINT, id: "1" };
const e21 = { ...BASE_ENDPOINT, id: "2.1" };
const e22 = { ...BASE_ENDPOINT, id: "2.2" };
const e3 = { ...BASE_ENDPOINT, id: "3" };
const b1 = backend.of(e1);
b1.environmentVariables = { foo: "bar" };
b1.requiredAPIs = [
{ reason: "a", api: "a.com" },
{ reason: "b", api: "b.com" },
];
const b2 = backend.of(e21, e22);
b2.environmentVariables = { bar: "foo" };
const b3 = backend.of(e3);
b3.requiredAPIs = [{ reason: "a", api: "a.com" }];
const got = backend.merge(b3, b2, b1);
expect(backend.allEndpoints(got)).to.have.deep.members([e1, e21, e22, e3]);
expect(got.environmentVariables).to.deep.equal({ foo: "bar", bar: "foo" });
expect(got.requiredAPIs).to.have.deep.members([
{ reason: "a", api: "a.com" },
{ reason: "b", api: "b.com" },
]);
});
});
describe("existing backend", () => {
let listAllFunctions: sinon.SinonStub;
let listAllFunctionsV2: sinon.SinonStub;
let listServices: sinon.SinonStub;
let logLabeledWarning: sinon.SinonSpy;
let isEnabled: sinon.SinonStub;
beforeEach(() => {
listAllFunctions = sinon.stub(gcf, "listAllFunctions").rejects("Unexpected call");
listAllFunctionsV2 = sinon.stub(gcfV2, "listAllFunctions").rejects("Unexpected v2 call");
listServices = sinon.stub(run, "listServices").rejects("Unexpected run call");
logLabeledWarning = sinon.spy(utils, "logLabeledWarning");
isEnabled = sinon.stub(experiments, "isEnabled").returns(false);
});
afterEach(() => {
listAllFunctions.restore();
listAllFunctionsV2.restore();
listServices.restore();
logLabeledWarning.restore();
isEnabled.restore();
});
function newContext(): args.Context {
return {} as args.Context;
}
describe("existingBackend", () => {
it("should throw error when functions list fails", async () => {
const context = newContext();
listAllFunctions.rejects(new FirebaseError("Failed to list functions"));
await expect(backend.existingBackend(context)).to.be.rejected;
});
it("should cache", async () => {
const context = newContext();
listAllFunctions.onFirstCall().resolves({
functions: [
{
...HAVE_CLOUD_FUNCTION,
httpsTrigger: {},
},
],
unreachable: ["region"],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});
const firstBackend = await backend.existingBackend(context);
const secondBackend = await backend.existingBackend(context);
await backend.checkAvailability(context, backend.empty());
expect(firstBackend).to.deep.equal(secondBackend);
expect(listAllFunctions).to.be.calledOnce;
expect(listAllFunctionsV2).to.be.calledOnce;
});
it("should translate functions", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [
{
...HAVE_CLOUD_FUNCTION,
httpsTrigger: {},
},
],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});
const have = await backend.existingBackend(newContext());
expect(have).to.deep.equal(backend.of({ ...ENDPOINT, httpsTrigger: {} }));
});
it("should throw an error if v2 list api throws an error", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.throws(
new FirebaseError("HTTP Error: 500, Internal Error", { status: 500 }),
);
await expect(backend.existingBackend(newContext())).to.be.rejectedWith(
"HTTP Error: 500, Internal Error",
);
});
it("should read v2 functions when enabled", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [HAVE_CLOUD_FUNCTION_V2],
unreachable: [],
});
const have = await backend.existingBackend(newContext());
expect(have).to.deep.equal(
backend.of({
...ENDPOINT,
platform: "gcfv2",
concurrency: 80,
cpu: 1,
httpsTrigger: {},
runServiceId: HAVE_CLOUD_FUNCTION_V2.serviceConfig?.service,
source: HAVE_CLOUD_FUNCTION_V2.buildConfig?.source,
uri: HAVE_CLOUD_FUNCTION_V2.serviceConfig?.uri,
}),
);
});
it("should deduce features of scheduled functions", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [
{
...HAVE_CLOUD_FUNCTION,
eventTrigger: {
eventType: "google.pubsub.topic.publish",
resource: "projects/project/topics/topic",
},
labels: {
"deployment-scheduled": "true",
},
},
],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});
const have = await backend.existingBackend(newContext());
const want = backend.of({
...ENDPOINT,
scheduleTrigger: {},
labels: {
"deployment-scheduled": "true",
},
});
expect(have).to.deep.equal(want);
});
it("should read v2 functions from Cloud Run when experiment is enabled", async () => {
isEnabled.withArgs("functionsrunapionly").returns(true);
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listServices.onFirstCall().resolves([RUN_SERVICE]);
const have = await backend.existingBackend(newContext());
const wantEndpoint = {
...ENDPOINT,
platform: "gcfv2" as const,
concurrency: 80,
cpu: 1,
httpsTrigger: {},
availableMemoryMb: 256 as const,
environmentVariables: {
FUNCTION_TARGET: "function",
},
labels: {
"goog-managed-by": "cloud-functions",
"goog-cloudfunctions-runtime": "nodejs16",
"firebase-functions-codebase": "default",
},
secretEnvironmentVariables: [],
};
delete wantEndpoint.state;
expect(have).to.deep.equal(backend.of(wantEndpoint));
expect(listAllFunctionsV2).to.not.have.been.called;
});
it("should handle Cloud Run list errors gracefully when experiment is enabled", async () => {
isEnabled.withArgs("functionsrunapionly").returns(true);
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listServices.rejects(new Error("Random error"));
const context = newContext();
await backend.existingBackend(context);
expect(context.unreachableRegions?.run).to.deep.equal(["unknown"]);
});
});
describe("checkAvailability", () => {
it("should throw error when functions list fails", async () => {
const context = newContext();
listAllFunctions.rejects(new FirebaseError("Failed to list functions"));
await expect(backend.checkAvailability(context, backend.empty())).to.be.rejected;
});
it("should do nothing when regions are all avalable", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});
await backend.checkAvailability(newContext(), backend.empty());
expect(listAllFunctions).to.have.been.called;
expect(listAllFunctionsV2).to.have.been.called;
expect(logLabeledWarning).to.not.have.been.called;
});
it("should warn if an unused GCFv1 backend is unavailable", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: ["region"],
});
listAllFunctionsV2.resolves({
functions: [],
unreachable: [],
});
await backend.checkAvailability(newContext(), backend.empty());
expect(listAllFunctions).to.have.been.called;
expect(listAllFunctionsV2).to.have.been.called;
expect(logLabeledWarning).to.have.been.called;
});
it("should warn if an unused GCFv2 backend is unavailable", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: ["region"],
});
await backend.checkAvailability(newContext(), backend.empty());
expect(listAllFunctions).to.have.been.called;
expect(listAllFunctionsV2).to.have.been.called;
expect(logLabeledWarning).to.have.been.called;
});
it("should throw if a needed GCFv1 region is unavailable", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: ["region"],
});
listAllFunctionsV2.resolves({
functions: [],
unreachable: [],
});
const want = backend.of({ ...ENDPOINT, httpsTrigger: {} });
await expect(backend.checkAvailability(newContext(), want)).to.eventually.be.rejectedWith(
FirebaseError,
/The following Cloud Functions regions are currently unreachable:/,
);
});
it("should throw if a GCFv2 needed region is unavailable", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: ["region"],
});
const want: backend.Backend = backend.of({
...ENDPOINT,
platform: "gcfv2",
httpsTrigger: {},
});
await expect(backend.checkAvailability(newContext(), want)).to.eventually.be.rejectedWith(
FirebaseError,
/The following Cloud Functions V2 regions are currently unreachable:/,
);
});
it("Should only warn when deploying GCFv1 and GCFv2 is unavailable.", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: ["us-central1"],
});
const want = backend.of({ ...ENDPOINT, httpsTrigger: {} });
await backend.checkAvailability(newContext(), want);
expect(listAllFunctions).to.have.been.called;
expect(listAllFunctionsV2).to.have.been.called;
expect(logLabeledWarning).to.have.been.called;
});
it("Should only warn when deploying GCFv2 and GCFv1 is unavailable.", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: ["us-central1"],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});
const want: backend.Backend = backend.of({ ...ENDPOINT, httpsTrigger: {} });
await backend.checkAvailability(newContext(), want);
expect(listAllFunctions).to.have.been.called;
expect(listAllFunctionsV2).to.have.been.called;
expect(logLabeledWarning).to.have.been.called;
});
});
});
describe("compareFunctions", () => {
const fnMembers = {
project: "project",
runtime: "nodejs14" as const,
httpsTrigger: {},
};
it("should compare different platforms", () => {
const left: backend.Endpoint = {
id: "v1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "v1",
...fnMembers,
};
const right: backend.Endpoint = {
id: "v2",
region: "us-west1",
platform: "gcfv2",
entryPoint: "v2",
...fnMembers,
};
expect(backend.compareFunctions(left, right)).to.eq(1);
expect(backend.compareFunctions(right, left)).to.eq(-1);
});
it("should compare different regions, same platform", () => {
const left: backend.Endpoint = {
id: "v1",
region: "us-west1",
platform: "gcfv1",
entryPoint: "v1",
...fnMembers,
};
const right: backend.Endpoint = {
id: "newV1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "newV1",
...fnMembers,
};
expect(backend.compareFunctions(left, right)).to.eq(1);
expect(backend.compareFunctions(right, left)).to.eq(-1);
});
it("should compare different ids, same platform & region", () => {
const left: backend.Endpoint = {
id: "v1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "v1",
...fnMembers,
};
const right: backend.Endpoint = {
id: "newV1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "newV1",
...fnMembers,
};
expect(backend.compareFunctions(left, right)).to.eq(1);
expect(backend.compareFunctions(right, left)).to.eq(-1);
});
it("should compare same ids", () => {
const left: backend.Endpoint = {
id: "v1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "v1",
...fnMembers,
};
const right: backend.Endpoint = {
id: "v1",
region: "us-central1",
platform: "gcfv1",
entryPoint: "v1",
...fnMembers,
};
expect(backend.compareFunctions(left, right)).to.eq(0);
});
});
describe("comprehension helpers", () => {
const endpointUS: backend.Endpoint = {
id: "endpointUS",
project: "project",
region: "us-west1",
platform: "gcfv2",
runtime: "nodejs16",
entryPoint: "ep",
httpsTrigger: {},
};
const endpointEU: backend.Endpoint = {
...endpointUS,
id: "endpointEU",
region: "europe-west1",
};
const bkend: backend.Backend = {
...backend.empty(),
};
bkend.endpoints[endpointUS.region] = { [endpointUS.id]: endpointUS };
bkend.endpoints[endpointEU.region] = { [endpointEU.id]: endpointEU };
bkend.requiredAPIs = [{ api: "api.google.com", reason: "required" }];
it("allEndpoints", () => {
const have = backend.allEndpoints(bkend).sort(backend.compareFunctions);
const want = [endpointUS, endpointEU].sort(backend.compareFunctions);
expect(have).to.deep.equal(want);
});
it("matchingBackend", () => {
const have = backend.matchingBackend(bkend, (fn) => fn.id === "endpointUS");
const want: backend.Backend = {
...backend.empty(),
endpoints: {
[endpointUS.region]: {
[endpointUS.id]: endpointUS,
},
},
requiredAPIs: [{ api: "api.google.com", reason: "required" }],
};
expect(have).to.deep.equal(want);
});
it("someEndpoint", () => {
expect(backend.someEndpoint(bkend, (fn) => fn.id === "endpointUS")).to.be.true;
expect(backend.someEndpoint(bkend, (fn) => fn.id === "missing")).to.be.false;
});
it("findEndpoint", () => {
expect(backend.findEndpoint(bkend, (fn) => fn.id === "endpointUS")).to.be.deep.equal(
endpointUS,
);
expect(backend.findEndpoint(bkend, (fn) => fn.id === "missing")).to.be.undefined;
});
it("regionalEndpoints", () => {
const have = backend.regionalEndpoints(bkend, endpointUS.region);
const want = [endpointUS];
expect(have).to.deep.equal(want);
});
it("hasEndpoint", () => {
const smallBackend = backend.matchingBackend(bkend, (fn) => fn.id === "endpointUS");
expect(backend.hasEndpoint(smallBackend)(endpointUS)).to.be.true;
expect(backend.hasEndpoint(smallBackend)(endpointEU)).to.be.false;
});
it("missingEndpoint", () => {
const smallBackend = backend.matchingBackend(bkend, (fn) => fn.id === "endpointUS");
expect(backend.missingEndpoint(smallBackend)(endpointUS)).to.be.false;
expect(backend.missingEndpoint(smallBackend)(endpointEU)).to.be.true;
});
});
});