forked from mozilla-b2g/gaia
-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.js
1911 lines (1783 loc) · 66.3 KB
/
log.js
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
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Raindrop Code.
*
* The Initial Developer of the Original Code is
* The Mozilla Foundation
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Andrew Sutherland <asutherland@asutherland.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Raindrop-specific testing/logging setup; right now holds initial 'loggest'
* implementation details that should get refactored out into their own
* thing.
*
* The permutations of logger logic is getting a bit ugly and may be burning
* more cycles than is strictly necessary. The long-term plan is some kind
* of simple (runtime) code generation. The biggest win for that is considered
* that it will simplify our code in here and generate an obvious byproduct
* that is easily understood. In cases where startup time is a concern, the
* generated code can also be persisted (like via RequireJS optimizer stage).
* This is not happening yet.
*
*
* There is a need for raindrop-specific logging logic because names tend to
* be application specific things as well as the determination of what is
* interesting.
*
* @typedef[ListyLogEntry @list[
* @param[eventName String]
* @rest[Object]
* ]]{
* The current format is meant to be generally human-readable. We put the
* name of the event at the front because it most concisely expresses what
* is happening. We put the details of the event after that, with the
* timestamp second from last and the global sequence number last. The timing
* information goes last because the timestamp (uS) is going to tend to be a
* big number that is hard for a human to process, but serves as a nice visual
* delimiter for the sequence id that comes after that humans can understand.
* It is not useful to have it earlier because it would offset the details of
* the event too far from the event name.
* }
* @typedef[ActorUniqueName Number]{
* A positive (> 0) unique value for the effective namespace.
* }
* @typedef[ThingUniqueName Number]{
* A negative (< 0) unique value for the effective namespace.
* }
* @typedef[UniqueName @oneof[ActorUniqueName ThingUniqueName]]{
* Actor/logger names are positive, thing names are negative. We do this so
* that even without resolving the identifiers we can present a human
* comprehensible understanding of semantic identifiers.
* }
* @typedef[SemanticIdent @oneof[
* @case[String]{
* A human readable string with no special significance.
* }
* @case[@listof[@oneof[UniqueName String]]]{
* A list containing human-readable strings with interspersed references to
* loggers/actors and things. When displayed, the unique name references
* should be replaced with custom display objects (possibly just hyperlinks)
* which should include a human-understandable representation of what the
* name is referencing. Entries in the list should be joined so that
* whitespace is inserted if the adjacent object is not a string or the
* string does not already contain whitespace or punctuation that does not
* require whitespace at the given point. More specifically, the "inside"
* of parentheses/brackets/braces and the left side of
* colons/semicolons/commas do not require whitespace. We also
* automatically insert commas-with-whitespace between consecutive named
* references.
*
* String literals must not be adjacent to other string literals; you must
* coalesce them. The whitespace logic can optimize based on this
* assumption.
* }
* ]]
* @typedef[HierLogFrag @dict[
* @key[loggerIdent String]{
* The schema name that defines this logger; the key in the dictionary
* passed to `register`.
* }
* @key[semanticIdent SemanticIdent]{
* Explains to humans what this logger is about. It is not required to be
* unique, but if code always passes in the same constant string, it's
* probably not being super helpful.
*
* Examples include:
* - Test case names.
* - Parameterized test steps. (Client A sending a message to Client B.)
* - Parameterized connections. (Server A talking to Server B.)
* }
* @key[uniqueName UniqueName]{
* A unique identifier not previously used in the effective namespace
* of the root HierLogFrag for this tree and all its descendents.
* }
* @key[born #:optional TimestampUS]{
* Timestamp of when this logger was instantiated.
* }
* @key[died #:optional TimestampUS]{
* Timestamp of when this logger was marked dead.
* }
* @key[entries @listof[ListyLogEntry]]{
* The log entries for this logger this time-slice.
* }
* @key[kids #:optional @listof[HierLogFrag]]{
* Log fragments of loggers deemed to be conceptually children of the logger
* that produced this logger. For example, an HTTP server would have a
* logger and its connection workers would be loggers that are children of
* the server.
* }
* ]]{
* Loggers are organized into hierarchies
* }
* @typedef[HierLogTimeSlice @dict[
* @key[begin TimestampUS]
* @key[end TimestampUS]
* @key[logFrag HierLogFrag]
* ]]{
*
* }
*
* @typedef[ActorLifecycleNotifFunc @func[
* @args[
* @param[event @oneof["attach" "dead"]]
* @param[instance Object]{
* The instance associated with the logger.
* }
* @param[logger Logger]
* ]
* ]]{
* Notification function to be invoked when an actor gets attached to its
* matching logger.
* }
*
* == Original Brainstorming ==
* + Unit Test Understanding
* - Want to know what the participants are and the high-level messages that
* are being exchanged, plus the ability to drill down into the messages.
* => logging should expose the actor (with type available)
* => message transmission should optionally have high-level logging
* associated in a way that provides us with the message or lets us
* sniff the payload
* + Unit Test Failure Diagnosis
* - Want to know what a good run looked like, and the differences between
* this run and that run.
* => the viewer has access to a data-store.
* + Debugging (General)
* - Want to be able to trace message delivery and related activities
* across the system.
* => Use global names where possible, perhaps identity key and message
* hashes and TCP endpoint identifiers should allow reconstitution.
* x> Having clients pass around extra identifiers seems dangerous. (Do
* not provide attackers with anything they do not already have,
* although debugging tools will of course make making use of that
* info easier.)
* + System Understanding (Initial, non-live, investigative)
* - Likely want what unit test understanding provides but with higher level
* capabilities.
* + System Understanding (Steady-state with testing system)
* - Likely want initial understanding unit test-level data but with only
* the traffic information and no ability to see the (private) data.
* + Automated Performance Runs / Regression Detection
* - Want timestamps of progress of message delivery.
* - Want easily comparable data.
* + At Scale Performance Understanding
* - Want to know throughput, latency of the various parts of the system,
* plus the ability to sample specific trace timelines.
* + At Scale Debugging of specific failures (ex: 1 user having trouble)
* - Want to be able to enable logging for the specific user, trace
* across the system.
*
* + General
* - Want to be able to easily diff for notable changes...
* => Markup or something should indicate values that will vary between
* runs. (Maybe as part of context?)
*
* + Logging efficiency
* - Want minimal impact when not enabled.
* - But willing to accept some hit for the benefit of logging.
* - Assume JITs can try and help us out if we help them.
* - Don't want to clutter up the code with logging code.
* - Don't want debugging logging code that can compromise privacy
* accidentally active.
* => Use decoration/monkeypatching for debugging logging, isolated in
* a sub-tree that can be completely excluded from the production
* build process. Have the decoration/monkeypatching be loud
* about what it's doing or able to fail, etc.
* - Nice if it's obvious that we can log/trace at a point.
* => Place always-on event logging in the code at hand.
* => Use (pre-computed) conditionals or maybe alternate classes for
* runtime optional logging.
*
* + Storage / Transit efficiency
* - Want logging for test runs broken up into initialization logging and
* per-test compartments.
* => Time-bucketing (per "channel") likely sufficient for debugging logging
* purposes.
* => Performance stuff that can't be reduced to time-series probably wants
* its own channel, and its data should be strongly biased to aggregates.
**/
define(
[
'./deferred',
'./microtime',
'./extransform',
'exports'
],
function(
Deferred,
$microtime,
$extransform,
exports
) {
var rawGimmeStack = $extransform.gimmeStack;
var gimmeStack = function() {
// Slice off the logger calling us and ourselves.
return rawGimmeStack().slice(2);
};
/**
* Per-thread/process sequence identifier to provide unambiguous ordering of
* logging events in the hopeful event we go faster than the timestamps can
* track.
*
* The long-term idea is that this gets periodically reset in an unambiguous
* fashion. Because we also package timestamps in the logs, right now we
* can get away with just making sure not to reset the sequence more than
* once in a given timestamp unit (currently 1 microsecond). This seems
* quite do-able.
*
* Note: Timestamp granularity was initially millisecond level, which was when
* this really was important.
*/
var gSeq = 0;
exports.getCurrentSeq = function() {
return gSeq;
};
/**
* Per-thread/process next unique actor/logger name to allocate.
*/
var gUniqueActorName = 1;
/**
* Per-thread/process next unique thing name to allocate.
*/
var gUniqueThingName = -1;
var ThingProto = exports.ThingProto = {
get digitalName() {
return this.__diginame;
},
set digitalName(val) {
this.__diginame = val;
},
toString: function() {
return '[Thing:' + this.__type + ']';
},
toJSON: function() {
var o = {
type: this.__type,
name: this.__name,
dname: this.__diginame,
uniqueName: this._uniqueName,
};
if (this.__hardcodedFamily)
o.family = this.__hardcodedFamily;
return o;
},
};
/**
* Create a thing with the given type, name, and prototype hierarchy and which
* is allocated with a unique name.
*
* This should not be called directly by user code; it is being surfaced for use
* by `testcontext.js` in order to define things with names drawn from an
* over-arching global namespace. The caller needs to take on the
* responsibility of exposing the thing via a logger or the like.
*/
exports.__makeThing = function makeThing(type, humanName, digitalName, proto) {
var thing;
if (proto === undefined)
proto = ThingProto;
thing = Object.create(proto);
thing.__type = type;
thing.__name = humanName;
thing.__diginame = digitalName;
thing.__hardcodedFamily = null;
thing._uniqueName = gUniqueThingName--;
return thing;
};
function NOP() {
}
/**
* Dummy logger prototype; instances gather statistics but do not generate
* detailed log events.
*/
var DummyLogProtoBase = {
_kids: undefined,
logLevel: 'dummy',
toString: function() {
return '[DummyLog]';
},
toJSON: function() {
// will this actually break JSON.stringify or just cause it to not use us?
throw new Error("I WAS NOT PLANNING ON BEING SERIALIZED");
},
__die: NOP,
__updateIdent: NOP,
};
/**
* Full logger prototype; instances accumulate log details but are intended by
* policy to not log anything considered user-private. This differs from
* `TestLogProtoBase` which, in the name of debugging and system understanding
* can capture private data but which should accordingly be test data.
*/
var LogProtoBase = {
/**
* For use by `TestContext` to poke things' names in. Actors'/loggers' names
* are derived from the list of kids. An alternate mechanism might be in
* order for this, since it is so extremely specialized. This was
* determined better than adding yet another generic logger mechanism until
* a need is shown or doing monkeypatching; at least for the time-being.
*/
_named: null,
logLevel: 'safe',
toJSON: function() {
var jo = {
loggerIdent: this.__defName,
semanticIdent: this._ident,
uniqueName: this._uniqueName,
born: this._born,
died: this._died,
events: this._eventMap,
entries: this._entries,
kids: this._kids
};
if (this.__latchedVars.length) {
var latchedVars = this.__latchedVars, olv = {};
for (var i = 0; i < latchedVars.length; i++) {
olv[latchedVars[i]] = this[':' + latchedVars[i]];
}
jo.latched = olv;
}
if (this._named)
jo.named = this._named;
return jo;
},
__die: function() {
this._died = $microtime.now();
if (this.__FAB._onDeath)
this.__FAB._onDeath(this);
},
__updateIdent: function(ident) {
// NOTE: you need to update useSemanticIdent if you change this.
// normalize all object references to unique name references.
if (Array.isArray(ident)) {
var normIdent = [];
for (var i = 0; i < ident.length; i++) {
var identBit = ident[i];
if (typeof(identBit) !== "object" || identBit == null)
normIdent.push(identBit);
else
normIdent.push(identBit._uniqueName);
}
ident = normIdent;
}
this._ident = ident;
},
};
/**
* Test (full) logger prototype; instances generate notifications for actor
* expectation checking on all calls and observe arguments that may contain
* user-private data (but which should only contain definitively non-private
* test data.)
*
* For simplicity of implementation, this class currently just takes the
* functions implemented by LogProtoBase and wraps them with a parameterized
* decorator.
*/
var TestLogProtoBase = Object.create(LogProtoBase);
TestLogProtoBase.logLevel = 'dangerous';
TestLogProtoBase.__unexpectedEntry = function(iEntry, unexpEntry) {
var entry = ['!unexpected', unexpEntry];
this._entries[iEntry] = entry;
};
TestLogProtoBase.__mismatchEntry = function(iEntry, expected, actual) {
var entry = ['!mismatch', expected, actual];
this._entries[iEntry] = entry;
};
TestLogProtoBase.__failedExpectation = function(exp) {
var entry = ['!failedexp', exp, $microtime.now(), gSeq++];
this._entries.push(entry);
};
TestLogProtoBase.__die = function() {
this._died = $microtime.now();
var testActor = this._actor;
if (testActor) {
if (testActor._expectDeath) {
testActor._expectDeath = false;
testActor.__loggerFired();
}
if (testActor._lifecycleListener)
testActor._lifecycleListener.call(null, 'dead', this.__instance, this);
}
};
var DIED_EVENTNAME = '(died)', DIED_EXP = [DIED_EVENTNAME];
var TestActorProtoBase = {
toString: function() {
return '[Actor ' + this.__defName + ': ' + this.__name + ']';
},
toJSON: function() {
return {
actorIdent: this.__defName,
semanticIdent: this.__name,
uniqueName: this._uniqueName,
parentUniqueName: this._parentUniqueName,
loggerUniqueName: this._logger ? this._logger._uniqueName : null,
};
},
/**
* Invoked to attach a logger to an instance; exists to provide the
* possibility to generate a notification event.
*/
__attachToLogger: function(logger) {
logger._actor = this;
this._logger = logger;
if (this._lifecycleListener)
this._lifecycleListener.call(null, 'attach', logger.__instance, logger);
},
/**
* Invoke a notification function when this actor gets attached to its
* matching logger. This function should be invoked as soon as possible
* after the creation of the actor.
*
* @args[
* @param[func ActorLifecycleNotifFunc]
* ]
*/
attachLifecycleListener: function(func) {
this._lifecycleListener = func;
},
/**
* Indicate that the caller is going to schedule some test events
* asynchronously while the step is running, so we should make sure to
* forbid our actor from resolving itself before a matching call to
* `asyncEventsAllDoneDoResolve` is made.
*/
asyncEventsAreComingDoNotResolve: function() {
if (!this._activeForTestStep)
throw new Error("Attempt to set expectations on an actor (" +
this.__defName + ": " + this.__name + ") that is not " +
"participating in this test step!");
if (this._resolved)
throw new Error("Attempt to add expectations when already resolved!");
// (sorta evil-hack)
// We can reuse the _expectDeath flag as a means to ensure that we don't
// resolve the promise prematurely, although it's semantically suspect.
// (And bad things will happen if the test logger does actually die...)
if (this._expectDeath)
throw new Error("death expectation incompatible with async events");
this._expectDeath = true;
},
/**
* Indiate that the caller is all done dynamically scheduling test events
* while a test step is running, and that accordingly we can allow our
* test actor to resolve its promise when all the events have completed.
*/
asyncEventsAllDoneDoResolve: function() {
// stop saying we are expecting our death; new events will trigger
// resolution
this._expectDeath = false;
// pretend something happened to potentially trigger things now.
this.__loggerFired();
},
/**
* Expect nothing to be logged this turn, and therefore also that no
* expectations will be added.
*/
expectNothing: function() {
if (this._expectations.length)
throw new Error("Already expecting something this turn! " +
JSON.stringify(this._expectations[0]));
this._expectNothing = true;
},
/**
* Indicate that the only expectation we have on this actor is that its
* logger will die during this step.
*/
expectOnly__die: function() {
if (!this._activeForTestStep)
throw new Error("Attempt to set expectations on an actor (" +
this.__defName + ": " + this.__name + ") that is not " +
"participating in this test step!");
if (this._resolved)
throw new Error("Attempt to add expectations when already resolved!");
if (this._expectDeath)
throw new Error("Already expecting our death! " +
"Are you using asyncEventsAreComingDoNotResolve?");
this._expectDeath = true;
},
/**
* Set this actor to use 'set' matching for only this round; the list of
* expectations will be treated as an unordered set of expectations to
* match instead of an ordered list that must be matched exactly in order.
* Failures will still be generated if an entry is encountered that does not
* have a corresponding entry in the expectation list.
*
* One side-effect of this mode is that we no longer can detect what
* constitutes a mismatch, so we call everything unexpected that doesn't
* match.
*/
expectUseSetMatching: function() {
this._unorderedSetMode = true;
},
/**
* Prepare for activity in a test step. If we do not already have a paired
* logger, this will push us onto the tracking list so we will be paired when
* the logger is created.
*/
__prepForTestStep: function(testRuntimeContext) {
if (!this._logger)
testRuntimeContext.reportPendingActor(this);
// we should have no expectations going into a test step.
if (this._activeForTestStep)
this.__resetExpectations();
this._activeForTestStep = true;
// and also all current entries should not be considered for expectations
// (We originally considered that we could let loggers accumulate entries
// in the background and then specify expectations about them in a
// subsequent step. That seems confusing. Seems far better for us to
// just slice a single step into multiple perspectives...)
if (this._logger)
this._iEntry = this._logger._entries.length;
},
/**
* Issue a promise that will be resolved when all expectations of this actor
* have been resolved. If no expectations have been issued, just return
* null.
*/
__waitForExpectations: function() {
if (this._expectNothing &&
(this._expectations.length || this._iExpectation))
return false;
// Fail immediately if a synchronous check already failed. (It would
// have tried to generate a rejection, but there was no deferral at the
// time.)
if (!this._expectationsMetSoFar)
return false;
if ((this._iExpectation >= this._expectations.length) &&
(this._expectDeath ? (this._logger && this._logger._died) : true)) {
this._resolved = true;
return this._expectationsMetSoFar;
}
if (!this._deferred) {
this._deferred = new Deferred();
}
return this._deferred.promise;
},
__stepCleanup: null,
/**
* Cleanup state at the end of the step; also, check if we moved into a
* failure state after resolving our promise.
*
* @return["success" Boolean]{
* True if everything is (still) satisfied, false if a failure occurred
* at some point.
* }
*/
__resetExpectations: function() {
if (this.__stepCleanup)
this.__stepCleanup();
var expectationsWereMet = this._expectationsMetSoFar;
this._expectationsMetSoFar = true;
// kill all processed entries.
this._iExpectation = 0;
this._ignore = null;
this._expectations.splice(0, this._expectations.length);
this._expectNothing = false;
this._expectDeath = false;
this._unorderedSetMode = false;
this._deferred = null;
this._resolved = false;
this._activeForTestStep = false;
return expectationsWereMet;
},
__failUnmetExpectations: function() {
if (this._iExpectation < this._expectations.length && this._logger) {
for (var i = this._iExpectation; i < this._expectations.length; i++) {
this._logger.__failedExpectation(this._expectations[i]);
}
}
if (this._expectDeath && !this._logger._died)
this._logger.__failedExpectation(DIED_EXP);
},
/**
* Invoked by the test-logger associated with this actor to let us know that
* something has been logged so that we can perform an expectation check and
* fulfill our promise/reject our promise, as appropriate.
*/
__loggerFired: function() {
// we can't do anything if we don't have an actor.
var entries = this._logger._entries, expy, entry;
// -- unordered mode
if (this._unorderedSetMode) {
while (this._iExpectation < this._expectations.length &&
this._iEntry < entries.length) {
entry = entries[this._iEntry++];
// ignore meta-entries (which are prefixed with a '!')
if (entry[0][0] === "!")
continue;
// ignore ignored entries
if (this._ignore && this._ignore.hasOwnProperty(entry[0]))
continue;
// - try all the expectations for a match
var foundMatch = false;
for (var iExp = this._iExpectation; iExp < this._expectations.length;
iExp++) {
expy = this._expectations[iExp];
// - on matches, reorder the expectation and bump our pointer
if (expy[0] === entry[0] &&
this['_verify_' + expy[0]](expy, entry)) {
if (iExp !== this._iExpectation) {
this._expectations[iExp] = this._expectations[this._iExpectation];
this._expectations[this._iExpectation] = expy;
}
this._iExpectation++;
foundMatch = true;
break;
}
}
if (!foundMatch) {
this._logger.__unexpectedEntry(this._iEntry - 1, entry);
this._expectationsMetSoFar = false;
if (this._deferred)
this._deferred.reject([this.__defName, expy, entry]);
}
}
// - generate an unexpected failure if we ran out of expectations
if ((this._iExpectation === this._expectations.length) &&
(entries.length > this._iEntry)) {
// note: as below, there is no point trying to generate a rejection
// at this stage.
this._expectationsMetSoFar = false;
// no need to -1 because we haven't incremented past the entry.
this._logger.__unexpectedEntry(this._iEntry, entries[this._iEntry]);
// do increment past...
this._iEntry++;
}
// - generate success if we have used up our expectations
else if ((this._iExpectation >= this._expectations.length) &&
this._deferred &&
(this._expectDeath ? (this._logger && this._logger._died)
: true)) {
this._resolved = true;
this._deferred.resolve();
}
return;
}
// -- ordered mode
while (this._iExpectation < this._expectations.length &&
this._iEntry < entries.length) {
expy = this._expectations[this._iExpectation];
entry = entries[this._iEntry++];
// ignore meta-entries (which are prefixed with a '!')
if (entry[0][0] === "!")
continue;
// ignore ignored entries
if (this._ignore && this._ignore.hasOwnProperty(entry[0]))
continue;
// Currently, require exact pairwise matching between entries and
// expectations.
if (expy[0] !== entry[0]) {
this._logger.__unexpectedEntry(this._iEntry - 1, entry);
// (fallout, triggers error)
}
else if (!this['_verify_' + expy[0]](expy, entry)) {
this._logger.__mismatchEntry(this._iEntry - 1, expy, entry);
// things did line up correctly though, so boost the expecation number
// so we don't convert subsequent expectations into unexpected ones.
this._iExpectation++;
// (fallout, triggers error)
}
else {
this._iExpectation++;
continue;
}
// (only bad cases fall out without hitting a continue)
if (this._expectationsMetSoFar) {
this._expectationsMetSoFar = false;
if (this._deferred)
this._deferred.reject([this.__defName, expy, entry]);
}
return;
}
// - unexpected log events should count as failure
// We only care if: 1) we were marked active, 2) we had at least one
// expectation this step OR we were explicitly marked to have no
// expectations this step.
// Because we will already have resolved() our promise if we get here,
// it's up to the test driver to come back and check us for this weird
// failure, possibly after waiting a tick to see if any additional events
// come in.
if (this._activeForTestStep &&
((this._expectations.length &&
(this._iExpectation === this._expectations.length) &&
(entries.length > this._iEntry)) ||
(!this._expectations.length &&
this._expectNothing))) {
// Only get upset if this is not an ignored event.
if (!this._ignore ||
!this._ignore.hasOwnProperty(entries[this._iEntry][0])) {
this._expectationsMetSoFar = false;
this._logger.__unexpectedEntry(this._iEntry, entries[this._iEntry]);
}
// We intentionally increment iEntry because otherwise we'll keep marking
// the same entry as unexpected when that is in fact not what we desire.
// In previous parts of this function it made sense not to increment, but
// here it just causes confusion.
this._iEntry++;
}
if ((this._iExpectation >= this._expectations.length) && this._deferred &&
(this._expectDeath ? (this._logger && this._logger._died) : true)) {
this._resolved = true;
this._deferred.resolve();
}
},
};
exports.TestActorProtoBase = TestActorProtoBase;
/**
* Recursive traverse objects looking for (and eliding) very long strings. We
* do this because our logs are getting really large (6 megs!), and a likely
* source of useless bloat are the encrypted message strings. Although we
* care how big the strings get, the reality is that until we switch to
* avro/a binary encoding, they are going to bloat horribly under JSON,
* especially when nested levels of encryption and JSON enter the picture.
*
* We will go a maximum of 3 layers deep. Because this complicates having an
* efficient fast-path where we detect that we don't need to clone-and-modify,
* we currently always just clone-and-modify.
*/
function simplifyInsaneObjects(obj, dtype, curDepth) {
if (obj == null || typeof(obj) !== "object")
return obj;
if (!curDepth)
curDepth = 0;
var nextDepth = curDepth + 1;
var limitStrings = 64;
if (dtype) {
if (dtype === 'tostring') {
if (Array.isArray(obj))
return obj.join('');
else if (typeof(obj) !== 'string')
return obj.toString();
}
}
var oot = {};
for (var key in obj) {
var val = obj[key];
switch (typeof(val)) {
case "string":
if (limitStrings && val.length > limitStrings) {
oot[key] = "OMITTED STRING, originally " + val.length +
" bytes long";
}
else {
oot[key] = val;
}
break;
case "object":
if (val == null ||
Array.isArray(val) ||
("toJSON" in val) ||
curDepth >= 2) {
oot[key] = val;
}
else {
oot[key] = simplifyInsaneObjects(val, null, nextDepth);
}
break;
default:
oot[key] = val;
break;
}
}
return oot;
}
/**
* Maximum comparison depth for argument equivalence in expectation checking.
* This value gets bumped every time I throw something at it that fails that
* still seems reasonable to me.
*/
var COMPARE_DEPTH = 6;
function boundedCmpObjs(a, b, depthLeft) {
var aAttrCount = 0, bAttrCount = 0, key, nextDepth = depthLeft - 1;
if ('toJSON' in a)
a = a.toJSON();
if ('toJSON' in b)
b = b.toJSON();
for (key in a) {
aAttrCount++;
if (!(key in b))
return false;
if (depthLeft) {
if (!smartCompareEquiv(a[key], b[key], nextDepth))
return false;
}
else {
if (a[key] !== b[key])
return false;
}
}
// the theory is that if every key in a is in b and its value is equal, and
// there are the same number of keys in b, then they must be equal.
for (key in b) {
bAttrCount++;
}
if (aAttrCount !== bAttrCount)
return false;
return true;
}
/**
* @return[Boolean]{
* True when equivalent, false when not equivalent.
* }
*/
function smartCompareEquiv(a, b, depthLeft) {
var ta = typeof(a), tb = typeof(b);
if (ta !== 'object' || (tb !== ta) || (a == null) || (b == null))
return a === b;
// fast-path for identical objects
if (a === b)
return true;
if (Array.isArray(a)) {
if (!Array.isArray(b))
return false;
if (a.length !== b.length)
return false;
for (var iArr = 0; iArr < a.length; iArr++) {
if (!smartCompareEquiv(a[iArr], b[iArr], depthLeft - 1))
return false;
}
return true;
}
return boundedCmpObjs(a, b, depthLeft);
}
exports.smartCompareEquiv = smartCompareEquiv;
function makeIgnoreFunc(name) {
return function ignoreFunc() {
if (!this._ignore)
this._ignore = {};
this._ignore[name] = true;
};
};
/**
* Builds the logging and testing helper classes for the `register` driver.
*
* It operates in a similar fashion to wmsy's ProtoFab mechanism; state is
* provided to helpers by lexically closed over functions. No code generation
* is used, but it's intended to be an option.
*/
function LoggestClassMaker(moduleFab, name) {
this.moduleFab = moduleFab;
this.name = name;
this._latchedVars = [];
// steady-state minimal logging logger (we always want statistics!)
var dummyProto = this.dummyProto = Object.create(DummyLogProtoBase);
dummyProto.__defName = name;
dummyProto.__latchedVars = this._latchedVars;
dummyProto.__FAB = this.moduleFab;
// full-logging logger
var logProto = this.logProto = Object.create(LogProtoBase);
logProto.__defName = name;
logProto.__latchedVars = this._latchedVars;
logProto.__FAB = this.moduleFab;
// testing full-logging logger
var testLogProto = this.testLogProto = Object.create(TestLogProtoBase);
testLogProto.__defName = name;
testLogProto.__latchedVars = this._latchedVars;
testLogProto.__FAB = this.moduleFab;
// testing actor for expectations, etc.
var testActorProto = this.testActorProto = Object.create(TestActorProtoBase);
testActorProto.__defName = name;
/** Maps helper names to their type for collision reporting by `_define`. */
this._definedAs = {};
}
LoggestClassMaker.prototype = {
/**
* Name collision detection helper; to be invoked prior to defining a name
* with the type of name being defined so we can tell you both types that
* are colliding.
*/
_define: function(name, type) {
if (this._definedAs.hasOwnProperty(name)) {
throw new Error("Attempt to define '" + name + "' as a " + type +
" when it is already defined as a " +
this._definedAs[name] + "!");
}
this._definedAs[name] = type;
},
/**
* Wrap a logProto method to be a testLogProto invocation that generates a
* constraint checking thing.
*/
_wrapLogProtoForTest: function(name) {
var logFunc = this.logProto[name];
this.testLogProto[name] = function() {
var rval = logFunc.apply(this, arguments);
var testActor = this._actor;
if (testActor)
testActor.__loggerFired();
return rval;
};
},
addStateVar: function(name) {
this._define(name, 'state');