forked from googleapis/cloud-debug-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-firebase-controller.ts
637 lines (581 loc) · 19.3 KB
/
test-firebase-controller.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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as assert from 'assert';
import {describe, it} from 'mocha';
import {Debuggee} from '../src/debuggee';
import * as stackdriver from '../src/types/stackdriver';
import * as firebase from 'firebase-admin';
import {FirebaseController} from '../src/agent/firebase-controller';
import {DataSnapshot, EventType, Reference} from '@firebase/database-types';
/* eslint-disable @typescript-eslint/no-explicit-any */
class MockSnapshot {
key: string;
value: any;
constructor(key: string, value: any) {
this.key = key;
this.value = value;
}
val() {
return this.value;
}
exists() {
return !!this.value;
}
}
class MockReference {
key: string;
value?: any;
parentRef?: MockReference;
children = new Map<string, MockReference>();
// Simplification: there's only one listener for each event type.
listeners = new Map<EventType, (a: DataSnapshot, b?: string | null) => any>();
// Test options
shouldFailSet = false;
shouldFailGet = false;
failSetMessage?: string;
failGetMessage?: string;
constructor(key: string, parentRef?: MockReference) {
this.key = key.slice();
this.parentRef = parentRef;
}
remove(onComplete?: (a: Error | null) => any): Promise<any> {
if (this.parentRef) {
this.parentRef.childRemoved(this.key);
this.parentRef.children.delete(this.key);
}
if (onComplete) {
onComplete(null);
}
return Promise.resolve();
}
async get(): Promise<DataSnapshot> {
if (this.shouldFailGet) {
this.shouldFailGet = false;
throw new Error(this.failGetMessage);
}
return new MockSnapshot(this.key, this.value) as {} as DataSnapshot;
}
getOrAdd(key: string): MockReference {
if (!this.children.has(key)) {
this.children.set(key, new MockReference(key, this));
}
return this.children.get(key)!;
}
childRemoved(key: string) {
if (this.listeners.has('child_removed')) {
this.listeners.get('child_removed')!(
new MockSnapshot(key, {}) as {} as DataSnapshot
);
}
if (this.parentRef) {
this.parentRef.childRemoved(`${this.key}/${key}`);
}
}
childAdded(key: string, value: any) {
if (this.listeners.has('child_added')) {
this.listeners.get('child_added')!(
new MockSnapshot(key, value) as {} as DataSnapshot
);
}
if (this.parentRef) {
this.parentRef.childAdded(`${this.key}/${key}`, value);
}
}
async set(value: any, onComplete?: (a: Error | null) => any): Promise<any> {
if (this.shouldFailSet) {
this.shouldFailSet = false;
const err = new Error(this.failSetMessage);
if (onComplete) {
onComplete(err);
}
throw err;
}
let creating = false;
if (!this.value) {
creating = true;
}
this.value = value;
if (onComplete) {
onComplete(null);
}
if (creating && this.parentRef) {
this.parentRef.childAdded(this.key, value);
}
}
on(
eventType: EventType,
callback: (a: DataSnapshot, b?: string | null) => any
): (a: DataSnapshot | null, b?: string | null) => any {
this.listeners.set(eventType, callback);
// Callback will be called with each existing child: https://firebase.google.com/docs/database/admin/retrieve-data#child-added
if (eventType === 'child_added') {
this.children.forEach(child => this.childAdded(child.key, child.value));
}
// Don't care about return value.
return () => null;
}
off() {
// No-op. Needed to cleanly detach in the real firebase implementation.
}
failNextSet(errorMessage: string) {
this.shouldFailSet = true;
this.failSetMessage = errorMessage;
}
failNextGet(errorMessage: string) {
this.shouldFailGet = true;
this.failGetMessage = errorMessage;
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
class MockDatabase {
root = new MockReference('');
mockRef(path: string): MockReference {
const parts = path.split('/');
let ref = this.root;
for (let i = 0; i < parts.length; i++) {
ref = ref.getOrAdd(parts[i]);
}
return ref;
}
ref(path: string): Reference {
return this.mockRef(path) as {} as Reference;
}
}
describe('Firebase Controller', () => {
describe('register', () => {
const debuggee = new Debuggee({
project: 'fake-project',
uniquifier: 'fake-id',
description: 'unit test',
agentVersion: 'SomeName/client/SomeVersion',
labels: {
V8_version: 'v8_version',
process_title: 'node',
projectid: 'fake-project',
agent_version: '7.x',
version: 'appengine_version',
minorversion: 'minor_version',
},
});
// Debuggee Id is based on the sha1 hash of the json representation of
// the debuggee.
const debuggeeId = 'd-cbd029da';
it('should error out gracefully on presence check', done => {
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
db.mockRef(
`cdbg/debuggees/${debuggeeId}/registrationTimeUnixMsec`
).failNextGet('mocked failure');
controller.register(debuggee, err => {
try {
assert(err, 'expecting an error');
done();
} catch (err) {
done(err);
}
});
});
describe('first time', () => {
it('should write successfully', done => {
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
const expectedDebuggee = {
...debuggee,
registrationTimeUnixMsec: {'.sv': 'timestamp'},
lastUpdateTimeUnixMsec: {'.sv': 'timestamp'},
id: debuggeeId,
canaryMode: 'CANARY_MODE_UNSPECIFIED',
};
controller.register(debuggee, (err, result) => {
// try/catch block to avoid losing failed assertions to the error
// handling in controller.register.
try {
assert(!err, 'not expecting an error');
assert.ok(result);
assert.strictEqual(result!.debuggee.id, debuggeeId);
assert.deepEqual(
db.mockRef(`cdbg/debuggees/${debuggeeId}`).value,
expectedDebuggee
);
done();
} catch (err) {
done(err);
}
});
});
it('should error out gracefully', done => {
const db = new MockDatabase();
db.mockRef(`cdbg/debuggees/${debuggeeId}`).failNextSet(
'mocked failure'
);
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.register(debuggee, err => {
try {
assert(err, 'expecting an error');
done();
} catch (err) {
done(err);
}
});
});
});
describe('re-register', () => {
it('should only update the timestamp', done => {
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
// Throw an error if the debuggee is written; there should be no write.
db.mockRef(`cdbg/debuggees/${debuggeeId}`).failNextSet(
'should not be called'
);
// This is all that is required to indicate a prior registration.
db.mockRef(`cdbg/debuggees/${debuggeeId}/registrationTimeUnixMsec`).set(
12345678
);
controller.register(debuggee, (err, result) => {
try {
assert(!err, 'not expecting an error');
assert.ok(result);
// In production this would be the actual timestamp.
assert.deepEqual(
db.mockRef(`cdbg/debuggees/${debuggeeId}/lastUpdateTimeUnixMsec`)
.value,
{'.sv': 'timestamp'}
);
done();
} catch (err) {
done(err);
}
});
});
it('should error out gracefully', done => {
const db = new MockDatabase();
// This is all that is required to indicate a prior registration.
db.mockRef(`cdbg/debuggees/${debuggeeId}/registrationTimeUnixMsec`).set(
12345678
);
db.mockRef(
`cdbg/debuggees/${debuggeeId}/lastUpdateTimeUnixMsec`
).failNextSet('mocked failure');
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.register(debuggee, err => {
try {
assert(err, 'expecting an error');
done();
} catch (err) {
done(err);
}
});
});
});
});
describe('subscribeToBreakpoints', () => {
const breakpoints = [
{id: 'breakpoint-0', location: {path: 'foo.js', line: 18}},
{id: 'breakpoint-1', location: {path: 'bar.js', line: 23}},
];
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
it('should notice added and removed breakpoints', done => {
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = 'debuggeeId';
// Add a breakpoint before listening.
db.mockRef(`cdbg/breakpoints/debuggeeId/active/${breakpoints[0].id}`).set(
breakpoints[0]
);
const expectedResults = [
[breakpoints[0]],
[breakpoints[0], breakpoints[1]],
[breakpoints[1]],
];
let callbackCount = 0;
controller.subscribeToBreakpoints(debuggee, (err, bps) => {
assert(!err, 'not expecting an error');
assert.deepStrictEqual(
bps,
expectedResults[callbackCount],
'breakpoints mismatch'
);
callbackCount++;
if (callbackCount === expectedResults.length) {
controller.stop();
done();
}
});
db.mockRef(`cdbg/breakpoints/debuggeeId/active/${breakpoints[1].id}`).set(
breakpoints[1]
);
db.mockRef(
`cdbg/breakpoints/debuggeeId/active/${breakpoints[0].id}`
).remove();
});
it('should start marking the debuggee as active', done => {
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = 'debuggeeId';
controller.markActivePeriodMsec = 10; // Mark active frequently for testing purposes.
let markedActiveCount = 0;
db.mockRef('cdbg/debuggees/debuggeeId/lastUpdateTimeUnixMsec').set =
() => {
markedActiveCount += 1;
return Promise.resolve();
};
controller.subscribeToBreakpoints(debuggee, () => {});
// Let markActive trigger 2 times.
setTimeout(() => {
controller.stop();
assert(markedActiveCount >= 2);
done();
}, 50);
});
});
describe('updateBreakpoint', () => {
it('should update the database correctly for snapshots', done => {
const breakpointId = 'breakpointId';
const debuggeeId = 'debuggeeId';
const breakpoint: stackdriver.Breakpoint = {
id: breakpointId,
action: 'CAPTURE',
location: {path: 'foo.js', line: 99},
} as stackdriver.Breakpoint;
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = debuggeeId;
let removed = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/active`).on(
'child_removed',
data => {
assert.strictEqual(data.key, breakpointId);
removed = true;
}
);
let finalized = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/final`).on('child_added', data => {
assert.strictEqual(data.key, breakpointId);
assert.deepStrictEqual(data.val(), {
...breakpoint,
isFinalState: true,
finalTimeUnixMsec: {'.sv': 'timestamp'},
});
finalized = true;
});
let snapshotted = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/snapshot`).on(
'child_added',
data => {
assert.strictEqual(data.key, breakpointId);
assert.deepStrictEqual(data.val(), {
...breakpoint,
isFinalState: true,
finalTimeUnixMsec: {'.sv': 'timestamp'},
});
snapshotted = true;
}
);
controller.updateBreakpoint(debuggee as Debuggee, breakpoint, err => {
assert(!err, 'not expecting an error');
assert(removed, 'should have been removed');
assert(finalized, 'should have been finalized');
assert(snapshotted, 'should have been snapshotted');
done();
});
});
it('should update the database correctly for logpoints', done => {
const breakpointId = 'breakpointId';
const debuggeeId = 'debuggeeId';
const breakpoint: stackdriver.Breakpoint = {
id: breakpointId,
action: 'LOG',
location: {path: 'foo.js', line: 99},
} as stackdriver.Breakpoint;
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = debuggeeId;
let removed = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/active`).on(
'child_removed',
data => {
assert.strictEqual(data.key, breakpointId);
removed = true;
}
);
let finalized = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/final`).on('child_added', data => {
assert.strictEqual(data.key, breakpointId);
assert.deepStrictEqual(data.val(), {
...breakpoint,
isFinalState: true,
finalTimeUnixMsec: {'.sv': 'timestamp'},
});
finalized = true;
});
let snapshotted = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/snapshot`).on(
'child_added',
() => {
snapshotted = true;
}
);
controller.updateBreakpoint(debuggee as Debuggee, breakpoint, err => {
assert(!err, 'not expecting an error');
assert(removed, 'should have been removed');
assert(finalized, 'should have been finalized');
assert(!snapshotted, 'should not have been snapshotted');
done();
});
});
it('should throw an error if the delete fails', done => {
const breakpointId = 'breakpointId';
const debuggeeId = 'debuggeeId';
const breakpoint: stackdriver.Breakpoint = {
id: breakpointId,
action: 'CAPTURE',
location: {path: 'foo.js', line: 99},
} as stackdriver.Breakpoint;
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = debuggeeId;
db.ref(`cdbg/breakpoints/${debuggeeId}/active`).on(
'child_removed',
() => {
throw new Error('mock remove failure');
}
);
let finalized = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/final`).on('child_added', () => {
finalized = true;
});
let snapshotted = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/snapshot`).on(
'child_added',
() => {
snapshotted = true;
}
);
controller.updateBreakpoint(debuggee as Debuggee, breakpoint, err => {
assert(err, 'expecting an error');
assert(!finalized, 'should not have been finalized');
assert(!snapshotted, 'should not have been snapshotted');
done();
});
});
it('throw an error if the finalization fails', done => {
const breakpointId = 'breakpointId';
const debuggeeId = 'debuggeeId';
const breakpoint: stackdriver.Breakpoint = {
id: breakpointId,
action: 'CAPTURE',
location: {path: 'foo.js', line: 99},
} as stackdriver.Breakpoint;
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = debuggeeId;
let removed = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/active`).on(
'child_removed',
data => {
assert.strictEqual(data.key, breakpointId);
removed = true;
}
);
db.ref(`cdbg/breakpoints/${debuggeeId}/final`).on('child_added', data => {
assert.strictEqual(data.key, breakpointId);
throw new Error('mock write failure');
});
let snapshotted = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/snapshot`).on(
'child_added',
() => {
snapshotted = true;
}
);
controller.updateBreakpoint(debuggee as Debuggee, breakpoint, err => {
assert(err, 'expecting an error');
assert(removed, 'should have been removed');
assert(snapshotted, 'should have been snapshotted');
done();
});
});
it('throw an error if writing the snapshot fails', done => {
const breakpointId = 'breakpointId';
const debuggeeId = 'debuggeeId';
const breakpoint: stackdriver.Breakpoint = {
id: breakpointId,
action: 'CAPTURE',
location: {path: 'foo.js', line: 99},
} as stackdriver.Breakpoint;
const debuggee: Debuggee = {id: 'fake-debuggee'} as Debuggee;
const db = new MockDatabase();
const controller = new FirebaseController(
db as {} as firebase.database.Database
);
controller.debuggeeId = debuggeeId;
let removed = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/active`).on(
'child_removed',
data => {
assert.strictEqual(data.key, breakpointId);
removed = true;
}
);
let finalized = false;
db.ref(`cdbg/breakpoints/${debuggeeId}/final`).on('child_added', data => {
assert.strictEqual(data.key, breakpointId);
assert.deepStrictEqual(data.val(), {
...breakpoint,
isFinalState: true,
finalTimeUnixMsec: {'.sv': 'timestamp'},
});
finalized = true;
});
db.ref(`cdbg/breakpoints/${debuggeeId}/snapshot`).on(
'child_added',
() => {
throw new Error('mock snapshot write failure');
}
);
controller.updateBreakpoint(debuggee as Debuggee, breakpoint, err => {
assert(err, 'expecting an error');
assert(removed, 'should have been removed');
assert(!finalized, 'should not have been finalized');
done();
});
});
});
});