-
Notifications
You must be signed in to change notification settings - Fork 530
Expand file tree
/
Copy pathNetSimRouterNode.js
More file actions
2055 lines (1847 loc) · 58.2 KB
/
Copy pathNetSimRouterNode.js
File metadata and controls
2055 lines (1847 loc) · 58.2 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
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
/**
* @overview Router node simulation entity. Also contains logic for the
* auto-DNS system.
*/
var _ = require('lodash');
var i18n = require('@cdo/netsim/locale');
var ObservableEventDEPRECATED = require('../ObservableEventDEPRECATED');
var utils = require('../utils'); // Provides Function.prototype.inherits
var DataConverters = require('./DataConverters');
var NetSimConstants = require('./NetSimConstants');
var NetSimEntity = require('./NetSimEntity');
var NetSimGlobals = require('./NetSimGlobals');
var NetSimLogEntry = require('./NetSimLogEntry');
var NetSimLogger = require('./NetSimLogger');
var NetSimMessage = require('./NetSimMessage');
var NetSimNode = require('./NetSimNode');
var NetSimNodeFactory = require('./NetSimNodeFactory');
var NetSimUtils = require('./NetSimUtils');
var NetSimWire = require('./NetSimWire');
var Packet = require('./Packet');
var serializeNumber = NetSimUtils.serializeNumber;
var deserializeNumber = NetSimUtils.deserializeNumber;
var asciiToBinary = DataConverters.asciiToBinary;
var DnsMode = NetSimConstants.DnsMode;
var NodeType = NetSimConstants.NodeType;
var BITS_PER_BYTE = NetSimConstants.BITS_PER_BYTE;
var logger = NetSimLogger.getSingleton();
/**
* @type {number}
* @readonly
*/
var MAX_CLIENT_CONNECTIONS = 6;
/**
* Conveniently, a router's address in its local network is always zero.
* @type {number}
* @readonly
*/
var ROUTER_LOCAL_ADDRESS = 0;
/**
* Address that can only be used for the auto-dns node.
* May eventually be replaced with a dynamically assigned address.
* @type {number}
* @readonly
*/
var AUTO_DNS_RESERVED_ADDRESS = 15;
/**
* Hostname assigned to the automatic dns 'node' in the local network.
* There will only be one of these, so it can be simple.
* @type {string}
* @readonly
*/
var AUTO_DNS_HOSTNAME = 'dns';
/**
* Value the auto-DNS will return instead of an address when it can't
* locate a node with the given hostname in the local network.
* @type {string}
* @readonly
*/
var AUTO_DNS_NOT_FOUND = 'NOT_FOUND';
/**
* Maximum packet lifetime in the router queue, sort of a primitive Time-To-Live
* system that helps prevent a queue from being indefinitely blocked by a very
* large packet. Packets that exceed this time will silently fail delivery.
* @type {number}
* @readonly
*/
var PACKET_MAX_LIFETIME_MS = 10 * 60 * 1000;
/**
* To avoid calculating a totally unreasonable number of addresses, this is
* the most addresses we will consider when picking one for a new host.
* This means full support up to a 12-bit address part, which should be more
* than enough.
* @type {number}
*/
var ADDRESS_OPTION_LIMIT = 4096;
/**
* Client model of simulated router
*
* Represents the client's view of a given router, provides methods for
* letting the client interact with the router, and wraps the client's
* work doing part of the router simulation.
*
* A router -exists- when it has a row in the lobby table of type 'router'
* A router is connected to a user when a 'user' row exists in the lobby
* table that has a status 'Connected to {router ID} by wires {X, Y}'.
* A router will also share a wire (simplex) or wires (duplex) with each user,
* which appear in the wire table.
*
* @param {!NetSimShard} shard
* @param {RouterRow} [routerRow] - Lobby row for this router.
* @constructor
* @augments NetSimNode
*/
var NetSimRouterNode = (module.exports = function (shard, row) {
row = row !== undefined ? row : {};
NetSimNode.call(this, shard, row);
var levelConfig = NetSimGlobals.getLevelConfig();
/**
* This router's identifying number, which gets translated into its address.
* Should be unique among routers on the shard.
* @type {number}
*/
this.routerNumber = row.routerNumber;
/**
* Unix timestamp (local) of router creation time.
* @type {number}
*/
this.creationTime = utils.valueOr(row.creationTime, Date.now());
/**
* Sets current DNS mode for the router's local network.
* This value is manipulated by all clients.
* @type {DnsMode}
* @private
*/
this.dnsMode = utils.valueOr(row.dnsMode, levelConfig.defaultDnsMode);
/**
* Sets current DNS node ID for the router's local network.
* This value is manipulated by all clients.
* @type {number}
* @private
*/
this.dnsNodeID = row.dnsNodeID;
/**
* Speed (in bits per second) at which messages are processed.
* @type {number}
*/
this.bandwidth = utils.valueOr(
deserializeNumber(row.bandwidth),
levelConfig.defaultRouterBandwidth
);
/**
* Amount of data (in bits) that the router queue can hold before it starts
* dropping packets.
* @type {number}
*/
this.memory = utils.valueOr(
deserializeNumber(row.memory),
levelConfig.defaultRouterMemory
);
/**
* Percent chance (0-1) that a packet being routed will be dropped for no
* reason.
* @type {number}
*/
this.randomDropChance = utils.valueOr(
row.randomDropChance,
levelConfig.defaultRandomDropChance
);
/**
* Determines a subset of connection and message events that this
* router will respond to, only managing events from the given node ID,
* to avoid conflicting with other clients also simulating this router.
*
* Not persisted on server.
*
* @type {number}
* @private
*/
this.simulateForSender_ = undefined;
/**
* Local cache of the last tick time in the local simulation.
* Allows us to schedule/timestamp events that don't happen inside the
* tick event.
* @type {number}
* @private
*/
this.simulationTime_ = 0;
/**
* Packet format specification this router will use to parse, route, and log
* packets that it receives. Set on router that is simulated by client.
*
* Not persisted on server.
*
* @type {Packet.HeaderType[]}
* @private
*/
this.packetSpec_ = [];
/**
* Local cache of our remote row, used to decide whether our state has
* changed.
*
* Not persisted to server.
*
* @type {Object}
* @private
*/
this.stateCache_ = {};
/**
* Event others can observe, which we fire when our own remote row changes.
*
* @type {ObservableEventDEPRECATED}
*/
this.stateChange = new ObservableEventDEPRECATED();
/**
* Event others can observe, which we fire when the router statistics
* change (which may be very frequent...)
*
* @type {ObservableEventDEPRECATED}
*/
this.statsChange = new ObservableEventDEPRECATED();
/**
* Local cache of wires attached to this router, used for detecting and
* broadcasting relevant changes.
*
* Not persisted on server.
*
* @type {Array}
* @private
*/
this.myWireRowCache_ = [];
/**
* Event others can observe, which we fire when the router's set of wires
* changes indicating a change in the local network.
*
* @type {ObservableEventDEPRECATED}
*/
this.wiresChange = new ObservableEventDEPRECATED();
/**
* Local cache of log rows associated with this router, used for detecting
* and broadcasting relevant changes.
*
* @type {Array}
* @private
*/
this.myLogRowCache_ = [];
/**
* Event others can observe, which we fire when the router's log content
* changes.
*
* @type {ObservableEventDEPRECATED}
*/
this.logChange = new ObservableEventDEPRECATED();
/**
* Whether router is in the middle of work. Keeps router from picking up
* its own change notifications or interrupting its own processes.
* @type {boolean}
* @private
*/
this.isRouterProcessing_ = false;
/**
* Local cache of messages that need to be processed by (any simulation
* of) the router. Used for tracking router memory, throughput, etc.
* @type {NetSimMessage[]}
* @private
*/
this.routerQueueCache_ = [];
/**
* Set of scheduled 'routing events'
* @type {Object[]}
* @private
*/
this.localRoutingSchedule_ = [];
/**
* @type {boolean}
* @private
*/
this.isAutoDnsProcessing_ = false;
/**
* Local cache of messages that need to be processed by (any simulation
* of) the auto-DNS. Used for stats and limiting.
* @type {NetSimMessage[]}
* @private
*/
this.autoDnsQueue_ = [];
/**
* Most clients that can be connected to this router.
* Moved to instance variable so that tests can override it in certain cases.
* @type {number}
* @private
*/
this.maxClientConnections_ = MAX_CLIENT_CONNECTIONS;
});
NetSimRouterNode.inherits(NetSimNode);
/**
* Static async creation method. See NetSimEntity.create().
* @param {!NetSimShard} shard
* @param {!NodeStyleCallback} onComplete - Method that will be given the
* created entity, or null if entity creation failed.
*/
NetSimRouterNode.create = function (shard, onComplete) {
var nextRouterNumber = 1;
shard.nodeTable.readAll().forEach(function (node) {
if (
NodeType.ROUTER === node.type &&
node.routerNumber >= nextRouterNumber
) {
nextRouterNumber = node.routerNumber + 1;
}
});
var entity = new NetSimRouterNode(shard, {routerNumber: nextRouterNumber});
entity.getTable().create(entity.buildRow(), function (err, row) {
if (err) {
onComplete(err, null);
return;
}
onComplete(null, new NetSimRouterNode(shard, row));
});
};
/**
* Static async retrieval method. See NetSimEntity.get().
* @param {!number} routerID - The row ID for the entity you'd like to find.
* @param {!NetSimShard} shard
* @param {!NodeStyleCallback} onComplete - Method that will be given the
* found entity, or null if entity search failed.
*/
NetSimRouterNode.get = function (routerID, shard, onComplete) {
NetSimEntity.get(NetSimRouterNode, routerID, shard, onComplete);
};
/**
* @typedef {Object} RouterRow
* @property {number} creationTime - Unix timestamp (local)
* @property {number} bandwidth - Router max transmission/processing rate
* in bits/second
* @property {number} memory - Router max queue capacity in bits
* @property {DnsMode} dnsMode - Current DNS mode for the local network
* @property {number} dnsNodeID - Entity ID of the current DNS node in the
* local network.
* @property {number} randomDropChance - Odds (0-1) that a packet being routed
* will be dropped for no reason.
*/
/**
* Build table row for this node.
* @returns {RouterRow}
* @private
* @override
*/
NetSimRouterNode.prototype.buildRow = function () {
return utils.extend(NetSimRouterNode.superPrototype.buildRow.call(this), {
routerNumber: this.routerNumber,
creationTime: this.creationTime,
bandwidth: serializeNumber(this.bandwidth),
memory: serializeNumber(this.memory),
dnsMode: this.dnsMode,
dnsNodeID: this.dnsNodeID,
randomDropChance: this.randomDropChance,
});
};
/**
* Load state from remoteRow into local model, then notify anything observing
* us that we've changed.
* @param {RouterRow} remoteRow
* @private
*/
NetSimRouterNode.prototype.onMyStateChange_ = function (remoteRow) {
this.routerNumber = remoteRow.routerNumber;
this.creationTime = remoteRow.creationTime;
this.bandwidth = deserializeNumber(remoteRow.bandwidth);
this.memory = deserializeNumber(remoteRow.memory);
this.dnsMode = remoteRow.dnsMode;
this.dnsNodeID = remoteRow.dnsNodeID;
this.randomDropChance = remoteRow.randomDropChance;
this.stateChange.notifyObservers(this);
};
/**
* Performs queued routing and DNS operations.
* @param {RunLoop.Clock} clock
*/
NetSimRouterNode.prototype.tick = function (clock) {
this.simulationTime_ = clock.time;
this.routeOverdueMessages_(clock);
if (this.dnsMode === DnsMode.AUTOMATIC) {
this.tickAutoDns_(clock);
}
};
/**
* This name is a bit of a misnomer, but it's memorable; we actually route
* all messages that are DUE or OVERDUE.
* @param {RunLoop.Clock} clock
* @private
*/
NetSimRouterNode.prototype.routeOverdueMessages_ = function (clock) {
if (this.isRouterProcessing_) {
return;
}
// Separate out messages whose scheduled time has arrived or is past.
// Flag them so we can remove them later.
var readyScheduleMessages = [];
var expiredScheduleMessages = [];
this.localRoutingSchedule_.forEach(function (item) {
if (clock.time >= item.completionTime) {
item.beingRouted = true;
readyScheduleMessages.push(item.message);
} else if (clock.time >= item.expirationTime) {
item.beingRouted = true;
expiredScheduleMessages.push(item.message);
}
});
// If no messages are ready, we're done.
if (readyScheduleMessages.length + expiredScheduleMessages.length === 0) {
return;
}
// First, remove the expired items. They just silently vanish
this.isRouterProcessing_ = true;
NetSimEntity.destroyEntities(
expiredScheduleMessages,
function () {
// Next, process the messages that are ready for routing
this.routeMessages_(
readyScheduleMessages,
function () {
// Finally, remove all the schedule entries that we flagged earlier
this.localRoutingSchedule_ = this.localRoutingSchedule_.filter(
function (item) {
return !item.beingRouted;
}
);
this.isRouterProcessing_ = false;
}.bind(this)
);
}.bind(this)
);
};
/**
* Examine the queue, and add/adjust schedule entries for packets that
* should be handled by the local simulation. If a packet has no entry,
* it should be added to the schedule. If it does and we can see that its
* scheduled completion time is too far in the future, we should move it up.
*/
NetSimRouterNode.prototype.recalculateSchedule = function () {
// To calculate our schedule, we keep a rolling "Pessimistic completion time"
// as we walk down the queue. This "pessimistic time" is when the packet
// would finish processing, assuming all of the packets ahead of it in the
// queue must be processed first and the first packet in the queue is just
// starting to process now. We do this because the first packet might be
// owned by a remote client, so we won't have partial progress information
// on it.
//
// Thus, the pessimistic time is the _latest_ we would expect the router
// to be done processing the packet given the current bandwidth setting,
// if the router was an actual hardware device.
//
// The estimate is actually _optimistic_ in the sense that it doesn't wait
// for notification that a remotely-simulated packet is done before
// processing a locally-simulated one. We're making our best guess about
// how the packets would be timed with no latency introducing gaps between
// packets.
//
// If the client simulating the packet at the head of the queue disconnects
// it won't block other packets from being sent, but it will increase their
// "pessimistic estimates" until that orphaned packet gets cleaned up.
var queueSizeInBits = 0;
var pessimisticCompletionTime = this.simulationTime_;
var queuedMessage;
var processingDuration;
for (var i = 0; i < this.routerQueueCache_.length; i++) {
queuedMessage = this.routerQueueCache_[i];
queueSizeInBits += queuedMessage.payload.length;
processingDuration =
this.calculateProcessingDurationForMessage_(queuedMessage);
pessimisticCompletionTime += processingDuration;
// Don't schedule beyond memory capacity; we're going to drop those packets
if (
this.localSimulationOwnsMessage_(queuedMessage) &&
queueSizeInBits <= this.memory
) {
this.scheduleRoutingForMessage(queuedMessage, pessimisticCompletionTime);
}
}
};
/**
* Checks the schedule for the queued row. If no schedule entry exists, adds
* a new one with the provided pessimistic completion time. If it's already
* scheduled and the pessimistic time given is BETTER than the previously
* scheduled completion time, will update the schedule entry with the better
* time.
* @param {NetSimMessage} queuedMessage
* @param {number} pessimisticCompletionTime - in local simulation time
*/
NetSimRouterNode.prototype.scheduleRoutingForMessage = function (
queuedMessage,
pessimisticCompletionTime
) {
var scheduleItem = _.find(this.localRoutingSchedule_, function (item) {
return item.message.entityID === queuedMessage.entityID;
});
if (scheduleItem) {
// When our pessimistic time is better than our scheduled time we
// should update the scheduled time. This can happen when messages
// earlier in the queue expire, or are otherwise removed earlier than
// their size led us to expect.
if (pessimisticCompletionTime < scheduleItem.completionTime) {
scheduleItem.completionTime = pessimisticCompletionTime;
}
} else {
// If the item doesn't have a schedule entry at all, add it
this.addMessageToSchedule_(queuedMessage, pessimisticCompletionTime);
}
};
/**
* Adds a new entry to the routing schedule, with a default expiration time.
* @param {NetSimMessage} queuedMessage - message to route
* @param {number} completionTime - in simulation time
* @private
*/
NetSimRouterNode.prototype.addMessageToSchedule_ = function (
queuedMessage,
completionTime
) {
this.localRoutingSchedule_.push({
message: queuedMessage,
completionTime: completionTime,
expirationTime: this.simulationTime_ + PACKET_MAX_LIFETIME_MS,
beingRouted: false,
});
};
/**
* Takes a message out of the routing schedule. Modifies the schedule,
* should not be called while iterating through the schedule!
* Does nothing if the message isn't present in the schedule.
* @param {NetSimMessage} queuedMessage
* @private
*/
NetSimRouterNode.prototype.removeMessageFromSchedule_ = function (
queuedMessage
) {
var scheduleIdx;
for (var i = 0; i < this.localRoutingSchedule_.length; i++) {
if (
this.localRoutingSchedule_[i].message.entityID === queuedMessage.entityID
) {
scheduleIdx = i;
}
}
if (scheduleIdx !== undefined) {
this.localRoutingSchedule_.splice(scheduleIdx, 1);
}
};
/**
* Lets the auto-DNS part of the router simulation handle its requests.
* For now, auto-DNS can do "batch" processing, no throughput limits.
* @private
*/
NetSimRouterNode.prototype.tickAutoDns_ = function () {
if (this.isAutoDnsProcessing_) {
return;
}
// Filter DNS queue down to requests the local simulation should handle.
var localSimDnsRequests = this.autoDnsQueue_.filter(
this.localSimulationOwnsMessage_.bind(this)
);
// If there's nothing we can process, we're done.
if (localSimDnsRequests.length === 0) {
return;
}
// Process DNS requests
this.isAutoDnsProcessing_ = true;
this.processAutoDnsRequests_(
localSimDnsRequests,
function () {
this.isAutoDnsProcessing_ = false;
}.bind(this)
);
};
/** @inheritdoc */
NetSimRouterNode.prototype.getDisplayName = function () {
if (NetSimGlobals.getLevelConfig().broadcastMode) {
return i18n.roomNumberX({
x: this.getRouterNumber(),
});
}
return i18n.routerNumberX({
x: this.getRouterNumber(),
});
};
/**
* Given the level address format string (e.g. "4.4.4.4") which it pulls from
* globals, returns an array of the parsed lengths of each format part in order
* (e.g. [4, 4, 4, 4]).
* @returns {number[]}
*/
function getAddressFormatParts() {
return NetSimGlobals.getLevelConfig()
.addressFormat.split(/\D+/)
.filter(function (part) {
return part.length > 0;
})
.map(function (part) {
return parseInt(part, 10);
});
}
/**
* Helper that prevents the router's display number or address from being beyond
* the representable size of the the router part in the address format (if
* two-part addresses are being used).
* Does not do anything special to prevent collisions, just returns entityID
* modulo the assignable address space - but this will be better than having
* non-conflicting routers you can never address at all.
* @returns {number}
*/
NetSimRouterNode.prototype.getRouterNumber = function () {
// If two or more parts, limit our router number to the maximum value of
// the second-to-last address part.
var addressFormatParts = getAddressFormatParts();
if (addressFormatParts.length >= 2) {
var assignableAddressValues = Math.pow(2, addressFormatParts.reverse()[1]);
return this.routerNumber % assignableAddressValues;
}
return this.routerNumber;
};
/**
* Get the maximum number of routers that will be allowed on the shard.
* In most levels this is a strict global value (probably 20).
* In levels using an address format with two or more parts the second-to-last
* part determines the addressable space for routers, and the max routers
* will be the minimum of the global max and the addressable space.
*
* @example If the global max routers is 20, but the address format is 4.4,
* we can only address 16 routers (less than 20) so 16 is our max
* routers per shard value.
*
* @returns {number}
*/
NetSimRouterNode.getMaximumRoutersPerShard = function () {
// If two or more parts, limit our routers to the maximum value of
// the second-to-last address part.
var addressFormatParts = getAddressFormatParts();
if (addressFormatParts.length >= 2) {
return Math.min(
NetSimGlobals.getGlobalMaxRouters(),
Math.pow(2, addressFormatParts.reverse()[1])
);
}
return NetSimGlobals.getGlobalMaxRouters();
};
/**
* Get node's own address, which is dependent on the address format
* configured in the level but for routers always ends in zero.
* @returns {string}
*/
NetSimRouterNode.prototype.getAddress = function () {
return this.makeLocalNetworkAddress_(ROUTER_LOCAL_ADDRESS);
};
/**
* Get local network's auto-dns address, which is dependent on the address
* format configured for the level but the last part should always be 15.
* @returns {string}
*/
NetSimRouterNode.prototype.getAutoDnsAddress = function () {
return this.makeLocalNetworkAddress_(AUTO_DNS_RESERVED_ADDRESS);
};
/**
* Get node's hostname, a modified version of its display name.
* @returns {string}
* @override
*/
NetSimRouterNode.prototype.getHostname = function () {
// Use regex to strip anything that's not a word-character or a digit
// from the node's display name. For routers, we don't append the node ID
// because it's already part of the display name.
return this.getDisplayName()
.replace(/[^\w\d]/g, '')
.toLowerCase();
};
/** @inheritdoc */
NetSimRouterNode.prototype.getNodeType = function () {
return NodeType.ROUTER;
};
/** @inheritdoc */
NetSimRouterNode.prototype.getStatus = function () {
var levelConfig = NetSimGlobals.getLevelConfig();
var connectionCount = this.countConnections();
if (connectionCount === 0) {
if (levelConfig.broadcastMode) {
return i18n.roomStatusNoConnections({
maximumClients: this.maxClientConnections_,
});
}
return i18n.routerStatusNoConnections({
maximumClients: this.maxClientConnections_,
});
}
var connectedNodeNames = this.getConnectedNodeNames_().join(', ');
if (connectionCount >= this.maxClientConnections_) {
if (levelConfig.broadcastMode) {
return i18n.roomStatusFull({
connectedClients: connectedNodeNames,
});
}
return i18n.routerStatusFull({
connectedClients: connectedNodeNames,
});
}
if (levelConfig.broadcastMode) {
return i18n.roomStatus({
connectedClients: connectedNodeNames,
remainingSpace: this.maxClientConnections_ - connectionCount,
});
}
return i18n.routerStatus({
connectedClients: connectedNodeNames,
remainingSpace: this.maxClientConnections_ - connectionCount,
});
};
/**
* @returns {string[]} the names of all the nodes connected to this router.
* @private
*/
NetSimRouterNode.prototype.getConnectedNodeNames_ = function () {
var cachedNodeRows = this.shard_.nodeTable.readAll();
return this.getConnections().map(function (wire) {
var nodeRow = _.find(cachedNodeRows, function (nodeRow) {
return nodeRow.id === wire.localNodeID;
});
if (nodeRow) {
return nodeRow.name;
}
return i18n.unknownNode();
});
};
/** @inheritdoc */
NetSimRouterNode.prototype.isFull = function () {
// Determine status based on cached wire data
var cachedWireRows = this.shard_.wireTable.readAll();
var incomingWireRows = cachedWireRows.filter(function (wireRow) {
return wireRow.remoteNodeID === this.entityID;
}, this);
return incomingWireRows.length >= this.maxClientConnections_;
};
/**
* Makes sure that the given specification contains the fields that this
* router needs to do its job.
* @param {Packet.HeaderType[]} packetSpec
* @private
*/
NetSimRouterNode.prototype.validatePacketSpec_ = function (packetSpec) {
// There are no requirements in broadcast mode
if (NetSimGlobals.getLevelConfig().broadcastMode) {
return;
}
// Require TO_ADDRESS for routing
if (
!packetSpec.some(function (headerField) {
return headerField === Packet.HeaderType.TO_ADDRESS;
})
) {
logger.warn('Packet specification does not have a toAddress field.');
}
// Require FROM_ADDRESS for auto-DNS tasks
if (
!packetSpec.some(function (headerField) {
return headerField === Packet.HeaderType.FROM_ADDRESS;
})
) {
logger.warn('Packet specification does not have a fromAddress field.');
}
};
/**
* Puts this router controller into a mode where it will only
* simulate for connection and messages -from- the given node.
* @param {!number} nodeID
*/
NetSimRouterNode.prototype.initializeSimulation = function (nodeID) {
this.simulateForSender_ = nodeID;
this.packetSpec_ = NetSimGlobals.getLevelConfig().routerExpectsPacketHeader;
this.validatePacketSpec_(this.packetSpec_);
if (nodeID !== undefined) {
var nodeChangeEvent = this.shard_.nodeTable.tableChange;
var nodeChangeHandler = this.onNodeTableChange_.bind(this);
this.nodeChangeKey_ = nodeChangeEvent.register(nodeChangeHandler);
var wireChangeEvent = this.shard_.wireTable.tableChange;
var wireChangeHandler = this.onWireTableChange_.bind(this);
this.wireChangeKey_ = wireChangeEvent.register(wireChangeHandler);
var logChangeEvent = this.shard_.logTable.tableChange;
var logChangeHandler = this.onLogTableChange_.bind(this);
this.logChangeKey_ = logChangeEvent.register(logChangeHandler);
var newMessageEvent = this.shard_.messageTable.tableChange;
var newMessageHandler = this.onMessageTableChange_.bind(this);
this.newMessageEventKey_ = newMessageEvent.register(newMessageHandler);
// Populate router wire cache with initial data
this.onWireTableChange_();
// Populate router log cache with initial data
this.onLogTableChange_();
}
};
/**
* Gives the simulating node a chance to unregister from anything it
* was observing.
*/
NetSimRouterNode.prototype.stopSimulation = function () {
if (this.nodeChangeKey_ !== undefined) {
var nodeChangeEvent = this.shard_.nodeTable.tableChange;
nodeChangeEvent.unregister(this.nodeChangeKey_);
this.nodeChangeKey_ = undefined;
}
if (this.wireChangeKey_ !== undefined) {
var wireChangeEvent = this.shard_.wireTable.tableChange;
wireChangeEvent.unregister(this.wireChangeKey_);
this.wireChangeKey_ = undefined;
}
if (this.logChangeKey_ !== undefined) {
var logChangeEvent = this.shard_.logTable.tableChange;
logChangeEvent.unregister(this.logChangeKey_);
this.logChangeKey_ = undefined;
}
if (this.newMessageEventKey_ !== undefined) {
var newMessageEvent = this.shard_.messageTable.tableChange;
newMessageEvent.unregister(this.newMessageEventKey_);
this.newMessageEventKey_ = undefined;
}
};
/**
* Puts the router into the given DNS mode, triggers a remote update,
* and creates/destroys the network's automatic DNS node.
* @param {DnsMode} newDnsMode
*/
NetSimRouterNode.prototype.setDnsMode = function (newDnsMode) {
if (this.dnsMode === newDnsMode) {
return;
}
if (this.dnsMode === DnsMode.NONE) {
this.dnsNodeID = undefined;
} else if (this.dnsMode === DnsMode.AUTOMATIC) {
this.dnsNodeID = AUTO_DNS_RESERVED_ADDRESS;
}
this.dnsMode = newDnsMode;
this.update();
};
/**
* @param {number} newBandwidth in bits per second
*/
NetSimRouterNode.prototype.setBandwidth = function (newBandwidth) {
if (this.bandwidth === newBandwidth) {
return;
}
this.bandwidth = newBandwidth;
this.recalculateSchedule();
this.update();
};
/**
* @param {number} newMemory in bits
*/
NetSimRouterNode.prototype.setMemory = function (newMemory) {
if (this.memory === newMemory) {
return;
}
this.memory = newMemory;
this.enforceMemoryLimit_();
this.update();
};
/**
* @returns {NetSimWire[]} all of the wires that are attached to this router.
*/
NetSimRouterNode.prototype.getConnections = function () {
var shard = this.shard_;
var routerID = this.entityID;
return shard.wireTable
.readAll()
.filter(function (wireRow) {
return wireRow.remoteNodeID === routerID;
})
.map(function (wireRow) {
return new NetSimWire(shard, wireRow);
});
};
/**
* @returns {number} total number of wires connected to this router.
*/
NetSimRouterNode.prototype.countConnections = function () {
return this.getConnections().length;
};
/**
* Add a router log entry (not development logging, this is user-facing!)
* @param {string} packet - binary log payload
* @param {string} senderName - name of user/node that sent the message
* @param {NetSimLogEntry.LogStatus} status
*/
NetSimRouterNode.prototype.log = function (packet, senderName, status) {
NetSimLogEntry.create(
this.shard_,
this.entityID,
packet,
status,
senderName,
function () {}
);
};
/**
* @param {Array} haystack
* @param {*} needle
* @returns {boolean} TRUE if needle found in haystack
*/
var contains = function (haystack, needle) {
return haystack.some(function (element) {
return element === needle;
});
};
/**
* Called when another node establishes a connection to this one, giving this
* node a chance to reject the connection.
*
* The router checks against its connection limit, and rejects the connection
* if its limit is now exceeded.
*
* @param {!NetSimNode} otherNode attempting to connect to this one