Repository navigation
Expand file tree
/
Copy pathMeshNetwork.lua
More file actions
2590 lines (2582 loc) · 80.8 KB
/
Copy pathMeshNetwork.lua
File metadata and controls
2590 lines (2582 loc) · 80.8 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
-- Directory bootstrap and bounded public-interest routing. Directory entries
-- and introductions are addresses, never accepted player observations.
local QT = _G.QuestTogether
local MAX_NEIGHBORS, MAX_CANDIDATES, MAX_PENDING = 8, 512, 3
local RESERVATION_SECONDS, RECIPROCAL_SECONDS = 30, 120
-- Three callers can wait through three 120s rotation turns plus a paced
-- reciprocal exchange. Repeated hellos never extend this queue lifetime.
local ADMISSION_INTENT_SECONDS = 480
local MAX_SEEDS, SEED_LIFETIME = 64, 86400
local LEASE_SECONDS, RENEW_SECONDS, MAX_INTERESTS = 120, 40, 32
local NEIGHBOR_SECONDS, CHALLENGE_SECONDS = 180, 120
local FANOUT, MAX_HOPS, DIRECTORY_INTERVAL = 3, 8, 300
local MAX_PENDING_INTERESTS = 24
local MAX_DIRECTORY_ROWS, ROWS_PER_TICK = 1500, 32
local CONTACT_SECONDS, CONTACT_EVENT_SECONDS, CONTACT_EVENT_LIMIT = 300, 10, 16
local CONTACT_SOURCES = { friend = true, bnet = true, chat = true, visible = true }
local RetirePeerRoutes, PersistFailure, RestoreFailure, ForgetFailure, MakeReplacementRoom
local MAX_FAILURES, FAILURE_LIFETIME, MAX_STALE_PROBES = 512, 86400, 3
local function Now(a)
return a:SafeToNumber(a.API.GetTime()) or 0
end
local function Server(a)
return a:GetAnnouncementServerTime() or 0
end
local function Count(t)
local n = 0
for _ in pairs(t or {}) do
n = n + 1
end
return n
end
local function Metric(s, key)
s.metrics[key] = (s.metrics[key] or 0) + 1
end
local function Name(a, value)
if
not a:CanAccessValue(value)
or type(value) ~= "string"
or #value > 120
or value == ""
or value:find("[%c|,:]")
then
return nil
end
local normalized = a:NormalizeMemberName(value)
return type(normalized) == "string" and #normalized <= 120 and normalized ~= "" and normalized or nil
end
local function Own(a)
return Name(a, a:GetPlayerFullName())
end
local function Allowed(a)
return a:IsPublicSharingAllowed() and a.isEnabled
and not a.isLoggingOut
and not a:IsRuntimeRestricted()
and not a:IsRuntimeRestrictionTypeActive("chat")
end
local function LifetimeCurrent(a, s)
return rawget(a, "meshNetworkState") == s
and a.isEnabled
and not a.isLoggingOut
and rawget(a, "communicationState") == s.communication
and not s.communication.departing
and (not a.db or a.db.profile == s.profile)
end
local function Current(a, s)
return a:IsPublicSharingAllowed() and LifetimeCurrent(a, s)
end
local function ValidZone(a, zone)
zone = a:SafeToNumber(zone)
return zone and zone >= 0 and zone <= 1000000 and zone == math.floor(zone) and zone or nil
end
local function Zone(scope)
return scope == "global" and 0 or tonumber(scope)
end
local function Key(destination, id)
return destination .. ":" .. id
end
local function Route(name)
return { { distribution = "WHISPER", target = name, meshTraffic = true } }
end
local function Invoke(callback, ...)
if callback then
pcall(callback, ...)
end
end
local function IsCurrent(predicate)
if not predicate then
return true
end
local ok, result = pcall(predicate)
return ok and result == true
end
local function Native(a, method, ...)
local callback = a.API[method]
if type(callback) ~= "function" then
return nil
end
local ok, one, two, three, four, five, six, seven, eight = pcall(callback, ...)
if not ok then
return nil
end
return { one, two, three, four, five, six, seven, eight }
end
local function RetryCandidate(a, row, now, remoteFailure)
row.delay = math.min(1800, math.max(300, (row.delay or 150) * 2))
row.retryAt = now + row.delay
row.failureSerial = (row.failureSerial or 0) + 1
if remoteFailure then
local fresh = (row.evidenceAt or 0) > (row.failureEvidenceAt or 0)
or (row.evidenceSerial or 0) > (row.failureEvidenceSerial or 0)
row.probeFailures = math.min(MAX_STALE_PROBES, (fresh and 0 or row.probeFailures or 0) + 1)
row.failureEvidenceAt, row.failureAt = row.evidenceAt or 0, Server(a)
row.failureEvidenceSerial = row.evidenceSerial or 0
PersistFailure(a, row)
end
end
local function ProbeEligible(a, row)
if row.failureAt and Server(a) - row.failureAt >= FAILURE_LIFETIME then
row.probeFailures, row.failureEvidenceAt, row.failureAt = nil, nil, nil
ForgetFailure(a, row.name)
end
return (row.probeFailures or 0) < MAX_STALE_PROBES
or (row.evidenceAt or 0) > (row.failureEvidenceAt or 0)
or (row.evidenceSerial or 0) > (row.failureEvidenceSerial or 0)
end
local function RetireOldestCandidate(s, now)
local oldest, at
for name, candidate in pairs(s.candidates) do
if
not s.neighbors[name]
and not s.pending[name]
and not s.reservations[name]
and not (s.admissionIntents and s.admissionIntents[name])
and candidate.retryAt <= now
and (not candidate.contactAt or now - candidate.contactAt >= CONTACT_SECONDS)
and (not at or candidate.heardAt < at)
then
oldest, at = name, candidate.heardAt
end
end
if not oldest then
return false
end
s.candidates[oldest] = nil
return true
end
local function Retry(row, now)
row.delay = math.min(900, math.max(5, (row.delay or 2.5) * 2))
row.retryAt = now + row.delay
end
local function Neighbor(a, s, name)
local row = s.neighbors[name]
return row and Now(a) < row.expires and not a:IsIgnoredPlayerName(name) and row or nil
end
function QT:IsConfirmedMeshNeighbor(value)
local s = rawget(self, "meshNetworkState")
local name = Name(self, value)
return s ~= nil and Current(self, s) and name ~= nil and Neighbor(self, s, name) ~= nil
end
local function Reserved(a, s, name)
local reservation = s.reservations[name]
return reservation and Now(a) < reservation.expires and not a:IsIgnoredPlayerName(name) and reservation or nil
end
local function Reserve(a, s, name, reciprocal)
if Neighbor(a, s, name) then
return true
end
local existing = Reserved(a, s, name)
if reciprocal and not (existing and existing.reciprocal) then
local waiting = 0
for peer in pairs(s.reservations) do
local reservation = Reserved(a, s, peer)
if reservation and reservation.reciprocal then
waiting = waiting + 1
end
end
if waiting >= MAX_PENDING then
return false, "reciprocal_capacity"
end
end
if existing then
if reciprocal and not existing.reciprocal then
existing.reciprocal, existing.expires = true, Now(a) + RECIPROCAL_SECONDS
end
return true
end
local occupied = {}
for peer in pairs(s.neighbors) do
if Neighbor(a, s, peer) then
occupied[peer] = true
end
end
for peer in pairs(s.reservations) do
if Reserved(a, s, peer) then
occupied[peer] = true
end
end
if Count(occupied) >= MAX_NEIGHBORS then
return false, "capacity"
end
s.reservations[name] = {
expires = Now(a) + (reciprocal and RECIPROCAL_SECONDS or RESERVATION_SECONDS),
reciprocal = reciprocal == true,
}
return true
end
local function ScopedStore(a, field)
local global = a.db and a.db.global
if type(global) ~= "table" then
return nil
end
local namespace = Native(a, "GetPlayerNotesNamespace")
namespace = namespace and namespace[1]
local character = Own(a)
if type(namespace) ~= "string" or namespace == "" or not character then
return nil
end
if type(global[field]) ~= "table" then
global[field] = {}
end
local key = namespace .. ":" .. character
if type(global[field][key]) ~= "table" then
global[field][key] = {}
end
return global[field][key]
end
local function SeedStore(a)
return ScopedStore(a, "meshPeerSeeds")
end
local function FailureStore(a)
return ScopedStore(a, "meshPeerFailures")
end
local function Finite(a, value)
local n = a:SafeToNumber(value)
return n and n == n and n ~= math.huge and n ~= -math.huge and n or nil
end
local function PruneFailures(a, rows)
local now, kept = Server(a), {}
for key, row in pairs(rows or {}) do
local at = type(row) == "table" and Finite(a, row.at)
local delay = type(row) == "table" and Finite(a, row.delay)
local untilAt = type(row) == "table" and Finite(a, row.untilAt)
local failures = type(row) == "table" and Finite(a, row.failures)
local evidence = type(row) == "table" and Finite(a, row.evidenceAt)
if
not Name(a, key)
or key ~= key:lower()
or a:IsIgnoredPlayerName(key)
or not at
or at <= 0
or at > now
or now - at >= FAILURE_LIFETIME
or not delay
or delay < 300
or delay > 1800
or not untilAt
or untilAt < at
or untilAt > at + 1800
or not failures
or failures < 1
or failures > MAX_STALE_PROBES
or failures % 1 ~= 0
or not evidence
or evidence < 0
or evidence > at
then
rows[key] = nil
else
-- Rebuild rather than retaining unexpected nested or oversized values
-- from a damaged saved-variable record.
rows[key] = { at = at, delay = delay, untilAt = untilAt, failures = failures, evidenceAt = evidence }
kept[#kept + 1] = { key = key, at = at }
end
end
table.sort(kept, function(one, two)
return one.at > two.at or one.at == two.at and one.key < two.key
end)
for index = MAX_FAILURES + 1, #kept do
rows[kept[index].key] = nil
end
end
PersistFailure = function(a, row)
local rows, stamp = FailureStore(a), Server(a)
if not rows or stamp <= 0 then
return
end
rows[row.name:lower()] = {
at = stamp,
untilAt = stamp + row.delay,
delay = row.delay,
failures = row.probeFailures,
evidenceAt = math.min(stamp, row.failureEvidenceAt or 0),
}
PruneFailures(a, rows)
end
RestoreFailure = function(a, row, preserveDirectEvidence)
local rows = FailureStore(a)
local old = rows and rows[row.name:lower()]
if old then
row.delay = old.delay
row.retryAt = Now(a) + math.max(0, old.untilAt - Server(a))
row.probeFailures, row.failureEvidenceAt, row.failureAt = old.failures, old.evidenceAt, old.at
-- A repeated address after a reset is not a newly observed live player.
if not preserveDirectEvidence or not row.evidenceSerial then
row.evidenceAt = math.min(row.evidenceAt or old.evidenceAt, old.evidenceAt)
end
end
end
ForgetFailure = function(a, name)
local rows = FailureStore(a)
if rows then
rows[name:lower()] = nil
end
end
local function RememberSeed(a, name)
local seeds, stamp = SeedStore(a), Server(a)
if not seeds or stamp <= 0 then
return
end
seeds[name] = stamp
local n, oldest, oldestAt = 0
for candidate, at in pairs(seeds) do
local valid = Name(a, candidate)
at = a:SafeToNumber(at)
if not valid or not at or at > stamp or stamp - at >= SEED_LIFETIME then
seeds[candidate] = nil
else
n = n + 1
if not oldestAt or at < oldestAt then
oldest, oldestAt = candidate, at
end
end
end
if n > MAX_SEEDS then
seeds[oldest] = nil
end
end
function QT:InitializeMeshNetwork()
local s = rawget(self, "meshNetworkState")
if s and LifetimeCurrent(self, s) then
return s
end
if s then
self:ResetMeshNetwork()
end
local now = Now(self)
s = {
communication = self:InitializeCommunications(),
profile = self.db and self.db.profile,
startedAt = now,
nextTick = now,
nextHandshake = now + 1,
nextDirectory = now + 2,
nextGuild = now + 2,
nextContacts = now + 2,
contactCursors = { friend = 1, bnet = 1 },
nextRotation = now + 120,
directoryCursors = {},
directoryCycle = 0,
candidates = {},
neighbors = {},
reservations = {},
admissionIntents = {},
pending = {},
pendingInterests = {},
localInterests = {},
localHistory = {},
interests = {},
joins = {},
forwarded = {},
pendingPublications = {},
interestHistory = {},
interestSelections = {},
destinations = {},
metrics = {},
serial = 0,
serviceSerial = 0,
}
self.meshNetworkState = s
s.failureRows = FailureStore(self)
PruneFailures(self, s.failureRows)
local seeds, stamp = SeedStore(self), Server(self)
if not self:IsPublicSharingAllowed() then return s end
local loaded = 0
for name, at in pairs(seeds or {}) do
at = self:SafeToNumber(at)
if at and at <= stamp and stamp - at < SEED_LIFETIME and loaded < MAX_SEEDS then
if self:RememberMeshCandidate(name, "saved", nil, at) then
loaded = loaded + 1
else
seeds[name] = nil
end
else
seeds[name] = nil
end
end
return s
end
function QT:RememberMeshCandidate(value, source, zone, observedAt)
local s = rawget(self, "meshNetworkState")
local name = Name(self, value)
if not s or not Current(self, s) or not name or self:IsSelfSender(name) or self:IsIgnoredPlayerName(name) then
return false
end
local now, row = Now(self), s.candidates[name]
if not row then
if Count(s.candidates) >= MAX_CANDIDATES then
if not RetireOldestCandidate(s, now) then
Metric(s, "candidateCapacity")
return false
end
end
local random = Native(self, "Random", 1, 1000000)
row = {
name = name,
retryAt = now,
heardAt = now,
discoveredAt = now,
rank = random and random[1] or 0,
evidenceAt = observedAt or Server(self),
}
RestoreFailure(self, row)
s.candidates[name] = row
Metric(s, "candidatesAdded")
end
-- Cached rosters, introductions and saved seeds are addresses. Only a
-- direct native observation can reopen an exhausted probe allowance.
if source == "hello" or source == "confirmed" then
row.evidenceAt = Server(self)
row.evidenceSerial = (row.evidenceSerial or 0) + 1
end
row.heardAt, row.source = now, source
if zone then
row.zone = zone
end
return true
end
-- Native sightings provide addresses only. In particular, neither an ordinary
-- chat message nor a friend-list entry proves that this character uses QT.
function QT:ObserveMeshContact(value, source, zone)
local s = rawget(self, "meshNetworkState")
if not CONTACT_SOURCES[source] or not s or not Current(self, s) or not Allowed(self) then
return false
end
local name = Name(self, value)
if not name or self:IsSelfSender(name) or self:IsIgnoredPlayerName(name) then
return false
end
local now, row = Now(self), s.candidates[name]
if not row then
-- Bound event-driven work even on a busy city chat/nameplate stream.
-- Roster reads already share the runtime's paced row budget.
if source == "chat" or source == "visible" then
if not s.contactEventAt or now - s.contactEventAt >= CONTACT_EVENT_SECONDS then
s.contactEventAt, s.contactEventCount = now, 0
end
if s.contactEventCount >= CONTACT_EVENT_LIMIT then
Metric(s, "contactRateDrops")
return false
end
s.contactEventCount = s.contactEventCount + 1
end
if Count(s.candidates) >= MAX_CANDIDATES then
if not RetireOldestCandidate(s, now) then
Metric(s, "contactCapacityDrops")
return false
end
end
if not self:RememberMeshCandidate(name, source, ValidZone(self, zone)) then
return false
end
row = s.candidates[name]
Metric(s, "contactsAdded_" .. source)
else
row.heardAt = now
-- Do not reset triedAt, retryAt, delay, or promote to a neighbor.
-- A repeated sighting is not evidence of a successful QT handshake.
local validZone = ValidZone(self, zone)
if validZone then
row.zone = validZone
end
end
if source == "chat" or source == "visible" then
row.evidenceAt = Server(self)
row.evidenceSerial = (row.evidenceSerial or 0) + 1
end
row.contactAt, row.contactSource = now, source
return true
end
function QT:ObserveMeshUnit(unitToken)
local s = rawget(self, "meshNetworkState")
if
not s
or not Current(self, s)
or not Allowed(self)
or not self:CanAccessValue(unitToken)
or type(unitToken) ~= "string"
or not (unitToken == "target" or unitToken == "mouseover" or unitToken:match("^nameplate%d+$"))
then
return false
end
local result = Native(self, "GetMeshUnitPlayerName", unitToken)
local geo = rawget(self, "geographicCommsState")
return result and self:ObserveMeshContact(result[1], "visible", geo and geo.currentZone) or false
end
function QT:ScheduleMeshContactScan()
local s = rawget(self, "meshNetworkState")
if s and Current(self, s) and Allowed(self) then
s.nextContacts = math.min(s.nextContacts, math.max(Now(self), (s.lastContactScan or -30) + 30))
end
end
local function Confirm(a, s, name, context, sharedDelivery)
local row = s.neighbors[name]
local fresh = row == nil
if not row and (not Reserved(a, s, name) or Count(s.neighbors) >= MAX_NEIGHBORS) then
return nil
end
if row and row.session and context and context.session ~= row.session then
RetirePeerRoutes(a, s, name)
if not Current(a, s) then
return nil
end
Metric(s, "neighborSessionChanges")
end
a:RememberMeshCandidate(name, "confirmed")
local now = Now(a)
row = row or { name = name, connectedAt = now }
row.at, row.expires, row.session = now, now + NEIGHBOR_SECONDS, context and context.session
row.sharedDelivery = sharedDelivery == true
s.neighbors[name] = row
s.reservations[name] = nil
s.admissionIntents[name] = nil
local candidate = s.candidates[name]
if candidate then
candidate.delay, candidate.retryAt = nil, now + CHALLENGE_SECONDS
candidate.probeFailures, candidate.failureEvidenceAt, candidate.failureAt = nil, nil, nil
ForgetFailure(a, name)
end
RememberSeed(a, name)
if fresh then
for _, lease in pairs(s.localInterests) do
if Count(lease.downstreams) == 0 then
lease.renewAt = math.min(lease.renewAt or now, now)
end
end
end
Metric(s, "handshakesConfirmed")
local waiting = s.pendingInterests[name]
s.pendingInterests[name] = nil
for _, item in ipairs(waiting or {}) do
if not Current(a, s) then
break
end
-- Reserved senders are not graph peers. Their early control messages
-- become eligible only after our independent challenge confirms the
-- same native session, and the normal handler rechecks every field.
if item.session == row.session then
a:HandleMeshInterest(item.record, name, { distribution = "WHISPER", session = row.session })
else
Metric(s, "pendingInterestDrops")
end
end
return row
end
local function DiscoveryPressure(a)
local transport = a:GetTransportMetrics()
local publications = rawget(a, "meshPublicationState")
return (transport.queuedPackets or 0) >= 8
or (transport.oldestAge or 0) >= 4
or (transport.packetRate or 4) < 4
or publications and (publications.pending or 0) >= 8
end
local function Introductions(a, s, target)
local names = {}
for name in pairs(s.neighbors) do
if name ~= target and Neighbor(a, s, name) then
names[#names + 1] = name
end
end
table.sort(names)
local peers = {}
for _, name in ipairs(names) do
if #peers < 8 then
peers[#peers + 1] = { name = name }
end
end
return peers
end
local function PruneAdmissionIntents(a, s, now)
for name, intent in pairs(s.admissionIntents) do
local candidate = s.candidates[name]
if
now >= intent.expiresAt
or not candidate
or Neighbor(a, s, name)
or a:IsIgnoredPlayerName(name)
or (candidate.failureSerial or 0) ~= intent.failureSerial
then
s.admissionIntents[name] = nil
Metric(s, now >= intent.expiresAt and "admissionIntentsExpired" or "admissionIntentsCancelled")
end
end
end
local function QueueAdmissionIntent(a, s, name, candidate, now)
PruneAdmissionIntents(a, s, now)
if s.admissionIntents[name] then
return
end
if Count(s.admissionIntents) >= MAX_PENDING then
Metric(s, "admissionIntentDrops")
return
end
-- Remember an explicit native protocol request, not a trusted edge. Do not
-- let repeated hellos extend this wait or jump ahead of another caller.
s.admissionIntents[name] = {
queuedAt = now,
expiresAt = now + ADMISSION_INTENT_SECONDS,
failureSerial = candidate.failureSerial or 0,
}
Metric(s, "admissionIntentsQueued")
end
function QT:HandleMeshHello(record, sender, context)
local s = self:InitializeMeshNetwork()
sender = Name(self, sender)
if
not Allowed(self)
or not Current(self, s)
or not sender
or self:IsSelfSender(sender)
or self:IsIgnoredPlayerName(sender)
or not context
or context.distribution ~= "WHISPER"
or record.protocol ~= 3
or record.capabilities ~= "mesh1"
then
return false
end
local now = Now(self)
self:RememberMeshCandidate(sender, "hello")
local previous = s.candidates[sender]
if previous and previous.replyAt and now - previous.replyAt < 10 then
return false
end
if not previous then
return false
end
previous.replyAt = now
local prospective = s.pending[sender]
if
prospective
and prospective.exploring
and now < prospective.expires
and not Neighbor(self, s, sender)
and not Reserved(self, s, sender)
then
MakeReplacementRoom(self, s, sender)
if not Current(self, s) then
return false
end
end
local admitted = Reserve(self, s, sender, true)
if not admitted then
Metric(s, "handshakeBusyReplies")
QueueAdmissionIntent(self, s, sender, previous, now)
else
s.admissionIntents[sender] = nil
end
-- A hello is only an address hint. A correlated reply to our independent
-- challenge is required before that sender owns any graph edge.
if admitted or not previous.triedAt then
previous.retryAt = math.min(previous.retryAt, now)
end
if admitted then
-- Finish an admitted reciprocal exchange promptly. This only makes it
-- eligible for the shared scheduler; it does not bypass send budgets.
s.nextHandshake = math.min(s.nextHandshake, math.max(now, (s.lastHandshakeAt or now - 1) + 1))
end
return self:Respond(
"MACK",
{
requestId = record.requestId,
version = self.version or self.VERSION or "3",
protocol = 3,
capabilities = "mesh1",
sharedDelivery = true,
admitted = admitted,
peers = admitted and Introductions(self, s, sender) or {},
},
Route(sender),
{
owner = previous,
requestId = record.requestId,
meshTraffic = true,
priority = "background",
expires = now + 15,
isCurrent = function()
return Current(self, s)
and not self:IsIgnoredPlayerName(sender)
and (not admitted or Neighbor(self, s, sender) ~= nil or Reserved(self, s, sender) ~= nil)
end,
}
)
end
local function StartHandshake(a, s, candidate)
local name, now = candidate.name, Now(a)
if a.CanRecordAddonWhisperAttempt then
local ready, reason = a:CanRecordAddonWhisperAttempt(name, true)
if not ready and reason == "filter-unavailable" then
s.nextHandshake = now + 1
Metric(s, "handshakeLocalDeferrals")
return
end
end
local reservation = Reserved(a, s, name)
if not (reservation and reservation.reciprocal) then
-- Another spelling may have completed a silent timeout since this
-- candidate was learned. Read the shared address history before probing.
RestoreFailure(a, candidate, true)
if now < candidate.retryAt or not ProbeEligible(a, candidate) then
s.nextHandshake = now + 0.2
return
end
-- Directory/chat spellings can arrive after a failed address was retired.
-- Share its remaining backoff before attempting a native probe. This is
-- one bounded candidate scan per probe opportunity, not per queued packet
-- or per candidate during selection, and creates no second identity store.
local key, blocked, reachable = name:lower(), nil, false
for otherName, other in pairs(s.candidates) do
if otherName ~= name and otherName:lower() == key then
if Neighbor(a, s, otherName) then
reachable = true
end
if other.delay and other.retryAt > now and (not blocked or other.retryAt > blocked.retryAt) then
blocked = other
end
end
end
if blocked and not reachable then
candidate.retryAt = blocked.retryAt
candidate.delay = math.max(candidate.delay or 0, blocked.delay)
s.nextHandshake = now + 0.2
return
end
end
local exploring = not Neighbor(a, s, name) and not reservation and Count(s.neighbors) >= MAX_NEIGHBORS
if exploring then
for _, pending in pairs(s.pending) do
if pending.exploring then
s.nextHandshake = now + 1
return
end
end
end
if not exploring and not Reserve(a, s, name) then
-- Local occupancy says nothing about this peer. Wait for a slot instead
-- of imposing an unreachable-peer cooldown before any packet is sent.
candidate.lastHandshakeOutcome, candidate.lastHandshakeAt = "local_capacity", now
candidate.lastHandshakeReason, candidate.lastHandshakeCode = "capacity", nil
s.nextHandshake = now + 1
Metric(s, "handshakeCapacity")
return
end
local pending = { submitting = true, exploring = exploring, expires = now + 20 }
if exploring then
s.nextRotation = now + 120
end
s.pending[name] = pending
candidate.triedAt = now
local function Finish(success, outcome, reason, detail)
if not Current(a, s) or s.pending[name] ~= pending then
return
end
s.pending[name] = nil
candidate.lastHandshakeOutcome, candidate.lastHandshakeAt = outcome, Now(a)
candidate.lastHandshakeReason = a:CanAccessValue(reason)
and type(reason) == "string"
and #reason <= 64
and not reason:find("[%c|]")
and reason
or nil
candidate.lastHandshakeCode = a:CanAccessValue(detail) and type(detail) == "number" and a:SafeToNumber(detail)
or nil
if not success then
RetryCandidate(a, candidate, Now(a), outcome == "timeout")
local metric = ({
busy = "handshakeBusy",
timeout = "handshakeTimeouts",
admission_failed = "handshakeAdmissionFailures",
send_failed = "handshakeSendFailures",
queue_expired = "handshakeQueueExpiries",
confirmation_failed = "handshakeConfirmationFailures",
cancelled = "handshakeCancelled",
})[outcome]
if metric then
Metric(s, metric)
end
end
end
local admitted, admissionReason, _, requestId = a:Request(
"MHEL",
{ version = a.version or a.VERSION or "3", protocol = 3, capabilities = "mesh1", sharedDelivery = true },
Route(name),
{
owner = pending,
meshTraffic = true,
priority = "background",
expires = now + 20,
isCurrent = function()
return Current(a, s) and s.pending[name] == pending and not a:IsIgnoredPlayerName(name)
end,
onComplete = function(sent, reason, _, _, outcomes)
if sent or reason == "ambiguous" or outcomes and (outcomes.accepted or outcomes.ambiguous) then
pending.sentAt = Now(a)
end
end,
onExpire = function(reason, detail)
local outcome = reason == "expired" and (pending.sentAt and "timeout" or "queue_expired")
or reason == "cancelled" and "cancelled"
or pending.submitting and "admission_failed"
or "send_failed"
Finish(false, outcome, reason, detail)
end,
onResponse = function(record, sender, context)
if
not Current(a, s)
or s.pending[name] ~= pending
or Now(a) >= pending.expires
or Name(a, sender) ~= name
or a:IsIgnoredPlayerName(name)
or record.protocol ~= 3
or record.capabilities ~= "mesh1"
then
return false
end
if a.RememberPlayerHandshakeVersion then
a:RememberPlayerHandshakeVersion(sender, record.version, context)
end
if record.admitted ~= true then
Finish(false, "busy", "busy")
a:CancelCommRequest(record.requestId, "rejected")
return true
end
if pending.exploring and not Neighbor(a, s, name) and not Reserved(a, s, name) then
if not MakeReplacementRoom(a, s, name) or s.pending[name] ~= pending or not Reserve(a, s, name) then
Finish(false, "confirmation_failed", "capacity")
return false
end
end
if s.admissionIntents[name] then
Metric(s, "admissionReservations")
end
local confirmed = Confirm(a, s, name, context, record.sharedDelivery)
if not confirmed then
Finish(false, "confirmation_failed", "confirmation_failed")
return false
end
for index, peer in ipairs(record.peers or {}) do
if index > 8 then
break
end
a:RememberMeshCandidate(peer.name, "introduction")
end
Finish(true, "confirmed", "accepted")
a:CancelCommRequest(record.requestId, "completed")
return true
end,
}
)
pending.submitting = false
pending.requestId = requestId
if not admitted then
Finish(false, "admission_failed", admissionReason)
end
Metric(s, "handshakesStarted")
s.lastHandshakeAt = now
local random = Native(a, "Random", 20, 30)
local delay = math.min(30, math.max(20, a:SafeToNumber(random and random[1]) or 25))
s.regularHandshakeAt = now + delay
if s.metrics.handshakesStarted < 3 then
delay = 4
elseif Count(s.neighbors) < MAX_NEIGHBORS and not DiscoveryPressure(a) then
local bootstrap = Native(a, "Random", 4, 6)
delay = math.min(6, math.max(4, a:SafeToNumber(bootstrap and bootstrap[1]) or 5))
Metric(s, "bootstrapProbes")
end
s.nextHandshake = now + delay
end
function QT:EnsureMeshDirectoryJoined(channelName)
local s = self:InitializeMeshNetwork()
if not Current(self, s) or not Allowed(self) or type(channelName) ~= "string" or #channelName > 120 then
return false
end
if self:GetAnnouncementChannelLocalID(channelName) then
return self:EnsureAnnouncementChannelJoined(channelName)
end
-- Waiting for normal login/zone channels is not a failed directory join.
-- Do not consume retry backoff, channel slots or discovery metrics yet.
if not self:CanJoinAnnouncementChannel() then return false end
local now = Now(self)
local join = s.joins[channelName]
if not join then
if Count(s.joins) >= 8 then
return false
end
join = {}
s.joins[channelName] = join
end
if now < (join.retryAt or 0) then
return false
end
Retry(join, now)
Metric(s, "directoryJoinAttempts")
-- Free the former global directory's slot before attempting its replacement.
-- A full channel list must not delay discovery until a failed join backs off.
if channelName == self.announcementChannelName and channelName == "QuestTogether" then
local previous = Native(self, "GetChannelName", "QuestTogether3")
local previousID = previous and self:SafeToNumber(previous[1])
if previousID and previousID > 0 then
Native(self, "LeaveChannelByName", "QuestTogether3")
previous = Native(self, "GetChannelName", "QuestTogether3")
previousID = previous and self:SafeToNumber(previous[1])
if not previous or (previousID and previousID > 0) then return false end
end
end
return self:EnsureAnnouncementChannelJoined(channelName)
end
function QT:RecordMeshDirectoryRefusal(channelName)
local s = rawget(self, "meshNetworkState")
if not s or type(channelName) ~= "string" then
return
end
local join = s.joins[channelName]
if join then
Retry(join, Now(self))
Metric(s, "directoryRefusals")
end
end
local function DisplayRows(a)
local total = Native(a, "GetNumDisplayChannels")
total = total and a:SafeToNumber(total[1]) or 0
local rows = {}
for index = 1, math.min(60, total) do
local info = Native(a, "GetChannelDisplayInfo", index)
local name = info and a:SafeToString(info[1], "")
if name and name ~= "" and info[2] ~= true and info[6] ~= false then
rows[#rows + 1] = { index = index, name = name }
end
end
return rows
end
local function ClearDirectoryRestore(a)
a.meshDirectoryRestore = nil
Native(a, "CancelChannelSelectionRestore")
end
function QT:RestoreMeshDirectorySelection()
local pending = rawget(self, "meshDirectoryRestore")
if not pending then
return true
end
local selected = Native(self, "GetSelectedDisplayChannel")
local info = selected and Native(self, "GetChannelDisplayInfo", selected[1])
local ui = Native(self, "IsChannelWindowShown")
if not info or info[1] ~= pending.selectedName or (ui and ui[1]) then
ClearDirectoryRestore(self)
return true
end
for _, row in ipairs(DisplayRows(self)) do
if row.name == pending.previousName then
local restored = Native(self, "SetSelectedDisplayChannel", row.index)
if restored and restored[1] then
ClearDirectoryRestore(self)
return true
end
if not pending.scheduled then
local scheduled = Native(self, "RequestChannelSelectionRestore", function(allowed)
if rawget(self, "meshDirectoryRestore") ~= pending then
return
end
pending.scheduled = nil
if allowed then
self:RestoreMeshDirectorySelection()
else
ClearDirectoryRestore(self)
end
end)
pending.scheduled = scheduled and scheduled[1] == true
end
return false
end
end
-- The prior channel was left while we were waiting; no replacement index
-- is ours to select.
ClearDirectoryRestore(self)
return true
end
local function DirectoryRestore(a, s)