-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnapshotService.lua
More file actions
525 lines (466 loc) · 19 KB
/
SnapshotService.lua
File metadata and controls
525 lines (466 loc) · 19 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
local _, ns = ...
local Constants = ns.Constants
local ApiCompat = ns.ApiCompat
local BuildHash = ns.BuildHash
local SnapshotService = {}
local function buildFallbackSnapshot(reason)
local localizedClass, englishClass, classId = ApiCompat.GetPlayerClassInfo()
local localizedRace, englishRace, raceId = ApiCompat.GetPlayerRaceInfo()
local specIndex = ApiCompat.GetSpecialization()
local specId, specName, _, specIcon, role = ApiCompat.GetSpecializationInfo(specIndex)
local snapshot = {
reason = reason,
capturedAt = ApiCompat.GetServerTime(),
guid = ApiCompat.GetPlayerGUID(),
name = ApiCompat.GetPlayerName(),
realm = ApiCompat.GetNormalizedRealmName(),
className = localizedClass,
classFile = englishClass,
classId = classId,
raceName = localizedRace,
raceFile = englishRace,
raceId = raceId,
specIndex = specIndex,
specId = specId,
specName = specName,
specIcon = specIcon,
role = role,
activeConfigId = nil,
heroTalentSpecId = nil,
importString = nil,
talentNodes = {},
pvpTalents = {},
averageItemLevel = nil,
equippedItemLevel = nil,
pvpItemLevel = nil,
masteryEffect = nil,
versatilityDamageDone = nil,
versatilityDamageTaken = nil,
critPct = nil,
spellCritPct = nil,
hastePct = nil,
gear = {},
weapons = {},
trinkets = {},
captureFlags = {
buildSnapshot = Constants.CAPTURE_QUALITY.DEGRADED,
},
}
snapshot.buildHash = BuildHash.FromSnapshot(snapshot)
snapshot.buildId = BuildHash.ComputeBuildId(snapshot)
snapshot.loadoutId = BuildHash.ComputeLoadoutId(snapshot)
snapshot.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.DEGRADED
return snapshot
end
local function hasTalentConfigData(configId)
if not configId then
return false
end
local configInfo = ApiCompat.GetConfigInfo(configId)
return configInfo and configInfo.treeIDs and #configInfo.treeIDs > 0 or false
end
local function captureTalentNodes(configId)
local nodes = {}
if not configId then
return nodes
end
local configInfo = ApiCompat.GetConfigInfo(configId)
if not configInfo or not configInfo.treeIDs then
return nodes
end
for _, treeId in ipairs(configInfo.treeIDs) do
local treeNodes = ApiCompat.GetTreeNodes(treeId) or {}
for _, nodeId in ipairs(treeNodes) do
local nodeInfo = ApiCompat.GetNodeInfo(configId, nodeId)
if nodeInfo and nodeInfo.activeEntry and nodeInfo.activeEntry.entryID then
local entryInfo = ApiCompat.GetEntryInfo(configId, nodeInfo.activeEntry.entryID)
local definitionInfo = entryInfo and entryInfo.definitionID and ApiCompat.GetDefinitionInfo(entryInfo.definitionID) or nil
nodes[#nodes + 1] = {
nodeId = nodeId,
entryId = nodeInfo.activeEntry.entryID,
activeRank = nodeInfo.currentRank or 0,
definitionId = entryInfo and entryInfo.definitionID or nil,
definitionSpellId = definitionInfo and definitionInfo.spellID or nil,
}
end
end
end
table.sort(nodes, function(left, right)
return (left.nodeId or 0) < (right.nodeId or 0)
end)
return nodes
end
local function captureEquipment()
local gear = {}
local weapons = {}
local trinkets = {}
for _, slot in ipairs(Constants.INVENTORY_SLOTS) do
local itemLink = ApiCompat.GetInventoryItemLink("player", slot)
local itemId = ApiCompat.GetInventoryItemID("player", slot)
if itemId then
local _, _, _, _, _, itemClassId, itemSubclassId = ApiCompat.GetItemInfoInstant(itemLink or itemId)
local record = {
slot = slot,
itemId = itemId,
itemLink = itemLink,
classId = itemClassId,
subclassId = itemSubclassId,
}
gear[#gear + 1] = record
if slot == 13 or slot == 14 then
trinkets[#trinkets + 1] = record
elseif slot == 16 or slot == 17 then
weapons[#weapons + 1] = record
end
end
end
return gear, weapons, trinkets
end
local function capturePvpTalents()
local selected = ApiCompat.GetAllSelectedPvpTalentIDs() or {}
local talents = {}
for _, talentId in ipairs(selected) do
talents[#talents + 1] = talentId
end
table.sort(talents)
return talents
end
local function buildSpecSnapshot(specIndex)
if not specIndex then
return {
specIndex = nil,
specId = nil,
specName = nil,
specIcon = nil,
role = nil,
}
end
local specId, specName, _, icon, role = ApiCompat.GetSpecializationInfo(specIndex)
return {
specIndex = specIndex,
specId = specId,
specName = specName,
specIcon = icon,
role = role,
}
end
function SnapshotService:Initialize()
self.initialized = true
self.pendingFullRefresh = true
self:RefreshPlayerSnapshot("initialize")
end
function SnapshotService:IsFullSnapshotReady()
local specIndex = ApiCompat.GetSpecialization()
local activeConfigId = ApiCompat.GetActiveConfigID()
return specIndex ~= nil and hasTalentConfigData(activeConfigId)
end
function SnapshotService:CapturePlayerSnapshot(reason)
ns.Addon:Trace("snapshot.capture.begin", { reason = reason or "refresh" })
local localizedClass, englishClass, classId = ApiCompat.GetPlayerClassInfo()
local localizedRace, englishRace, raceId = ApiCompat.GetPlayerRaceInfo()
local specIndex = ApiCompat.GetSpecialization()
local specSnapshot = buildSpecSnapshot(specIndex)
local averageItemLevel, equippedItemLevel, pvpItemLevel = ApiCompat.GetAverageItemLevel()
local masteryEffect = ApiCompat.GetMasteryEffect()
local versatilityDamageDone, versatilityDamageTaken = ApiCompat.GetVersatilityBonuses()
local critPct = ApiCompat.GetCritChance()
local spellCritPct = ApiCompat.GetSpellCritChance()
local hastePct = ApiCompat.GetHaste()
local activeConfigId = ApiCompat.GetActiveConfigID()
local heroTalentSpecId = ApiCompat.GetActiveHeroTalentSpec()
ns.Addon:Trace("snapshot.capture.state", {
activeConfigId = activeConfigId or 0,
heroTalentSpecId = heroTalentSpecId or 0,
specIndex = specIndex or 0,
})
local importString = activeConfigId and ApiCompat.GenerateImportString(activeConfigId) or nil
ns.Addon:Trace("snapshot.capture.import", {
activeConfigId = activeConfigId or 0,
hasImport = importString and true or false,
})
local talentNodes = captureTalentNodes(activeConfigId)
ns.Addon:Trace("snapshot.capture.talents", {
activeConfigId = activeConfigId or 0,
nodeCount = #talentNodes,
})
local gear, weapons, trinkets = captureEquipment()
local pvpTalents = capturePvpTalents()
ns.Addon:Trace("snapshot.capture.pvp", {
pvpTalentCount = #pvpTalents,
trinketCount = #trinkets,
weaponCount = #weapons,
})
local snapshot = {
reason = reason,
capturedAt = ApiCompat.GetServerTime(),
guid = ApiCompat.GetPlayerGUID(),
name = ApiCompat.GetPlayerName(),
realm = ApiCompat.GetNormalizedRealmName(),
className = localizedClass,
classFile = englishClass,
classId = classId,
raceName = localizedRace,
raceFile = englishRace,
raceId = raceId,
specIndex = specSnapshot.specIndex,
specId = specSnapshot.specId,
specName = specSnapshot.specName,
specIcon = specSnapshot.specIcon,
role = specSnapshot.role,
activeConfigId = activeConfigId,
heroTalentSpecId = heroTalentSpecId,
importString = importString,
talentNodes = talentNodes,
pvpTalents = pvpTalents,
averageItemLevel = averageItemLevel,
equippedItemLevel = equippedItemLevel,
pvpItemLevel = pvpItemLevel,
masteryEffect = masteryEffect,
versatilityDamageDone = versatilityDamageDone,
versatilityDamageTaken = versatilityDamageTaken,
critPct = critPct,
spellCritPct = spellCritPct,
hastePct = hastePct,
gear = gear,
weapons = weapons,
trinkets = trinkets,
captureFlags = {},
}
snapshot.buildHash = BuildHash.FromSnapshot(snapshot)
snapshot.buildId = BuildHash.ComputeBuildId(snapshot)
snapshot.loadoutId = BuildHash.ComputeLoadoutId(snapshot)
snapshot.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.FRESH
-- T035: embed a stat profile in the session-start snapshot.
snapshot.statProfile = self:CaptureStatProfile(snapshot.statProfile)
return snapshot
end
-- T033/T034: Capture secondary stats into a StatProfile table.
-- Accepts an optional existingProfile — if it is already FRESH and the new
-- capture is not, the existing profile is returned unchanged (T034 guard).
function SnapshotService:CaptureStatProfile(existingProfile)
local stats = ApiCompat.GetAllSecondaryStats()
-- Determine freshness.
local freshness
local hasCrit = stats.critPct ~= nil
local hasHaste = stats.hastePct ~= nil
local hasMastery = stats.masteryPct ~= nil
local hasVers = stats.versDamageDonePct ~= nil
if hasCrit and hasHaste and hasMastery and hasVers then
freshness = Constants.SNAPSHOT_FRESHNESS.FRESH
elseif not hasCrit and not hasHaste and not hasMastery and not hasVers then
freshness = Constants.SNAPSHOT_FRESHNESS.UNAVAILABLE
else
freshness = Constants.SNAPSHOT_FRESHNESS.DEGRADED
end
-- T034: never overwrite a FRESH profile with a degraded one.
if existingProfile ~= nil
and existingProfile.snapshotFreshness == Constants.SNAPSHOT_FRESHNESS.FRESH
and freshness ~= Constants.SNAPSHOT_FRESHNESS.FRESH then
ns.Addon:Trace("snapshot.stat_profile.skipped_degraded_overwrite", {})
return existingProfile
end
-- Capture item levels safely.
local equippedIL, pvpIL = nil, nil
if GetAverageItemLevel then
-- GetAverageItemLevel() returns (average, equipped, pvp).
-- pcall captures: ok, average, equipped.
local ok, _avgIL, eqIL = pcall(GetAverageItemLevel)
if ok then equippedIL = eqIL end
end
if C_PvP and C_PvP.GetScoreInfo then
-- pvpItemLevel may be available on the score table; kept nil here
-- as GetScoreInfo is only valid post-match (SecretInActivePvPMatch=true).
pvpIL = nil
end
local captureQuality = (freshness == Constants.SNAPSHOT_FRESHNESS.FRESH)
and Constants.CAPTURE_QUALITY.OK
or Constants.CAPTURE_QUALITY.DEGRADED
return {
capturedAt = ApiCompat.GetServerTime(),
snapshotFreshness = freshness,
captureQuality = captureQuality,
critPct = stats.critPct,
spellCritPct = stats.spellCritPct,
hastePct = stats.hastePct,
masteryPct = stats.masteryPct,
versDamageDonePct = stats.versDamageDonePct,
versDamageTakenPct = stats.versDamageTakenPct,
itemLevelEquipped = equippedIL,
itemLevelPvP = pvpIL,
}
end
function SnapshotService:RefreshPlayerSnapshot(reason)
ns.Addon:Trace("snapshot.refresh.begin", { reason = reason or "refresh" })
if not self:IsFullSnapshotReady() then
local snapshot = buildFallbackSnapshot(reason or "refresh")
snapshot.captureFlags.buildSnapshot = Constants.CAPTURE_QUALITY.DEGRADED
snapshot.captureFlags.awaitingTraitData = true
snapshot.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.PENDING_REFRESH
ns.Addon:SetLatestPlayerSnapshot(snapshot)
self.pendingFullRefresh = true
ns.Addon:Trace("snapshot.refresh.fallback", {
reason = reason or "refresh",
specId = snapshot.specId or 0,
})
return snapshot
end
local ok, snapshotOrError = xpcall(function()
return self:CapturePlayerSnapshot(reason or "refresh")
end, debugstack)
local snapshot = snapshotOrError
if not ok then
ns.Addon:Warn("Player snapshot capture degraded; continuing with a minimal snapshot.")
ns.Addon:Debug("%s", snapshotOrError)
snapshot = buildFallbackSnapshot(reason or "refresh")
snapshot.captureFlags.buildSnapshot = Constants.CAPTURE_QUALITY.DEGRADED
snapshot.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.DEGRADED
ns.Addon:Trace("snapshot.refresh.error", { reason = reason or "refresh" })
end
ns.Addon:SetLatestPlayerSnapshot(snapshot)
self.pendingFullRefresh = snapshot.captureFlags and snapshot.captureFlags.buildSnapshot == Constants.CAPTURE_QUALITY.DEGRADED or false
ns.Addon:Trace("snapshot.refresh.ready", {
buildHash = snapshot.buildHash or "unknown",
buildId = snapshot.buildId or "unknown",
freshness = snapshot.snapshotFreshness or "unknown",
pending = self.pendingFullRefresh and true or false,
specId = snapshot.specId or 0,
})
-- Notify BuildCatalogService so the catalog stays current after every refresh.
-- pcall guard: a catalog error must never break the snapshot refresh cycle.
local catalogSvc = ns.Addon:GetModule("BuildCatalogService")
if catalogSvc then
local ok, err = pcall(catalogSvc.OnSnapshotRefreshed, catalogSvc, snapshot)
if not ok then
ns.Addon:Warn("BuildCatalogService update failed after snapshot refresh: %s", tostring(err))
end
end
return snapshot
end
function SnapshotService:TryRefreshDeferredSnapshot(reason)
if not self.pendingFullRefresh and ns.Addon:GetLatestPlayerSnapshot() then
return ns.Addon:GetLatestPlayerSnapshot()
end
return self:RefreshPlayerSnapshot(reason or "deferred_refresh")
end
function SnapshotService:GetLatestPlayerSnapshot()
local snapshot = ns.Addon:GetLatestPlayerSnapshot()
if snapshot and not self.pendingFullRefresh then
return snapshot
end
return self:TryRefreshDeferredSnapshot("lazy")
end
function SnapshotService:GetSessionPlayerSnapshot(reason)
local snapshot = ns.Addon:GetLatestPlayerSnapshot()
if snapshot then
ns.Addon:Trace("snapshot.session.cached", {
pending = self.pendingFullRefresh and true or false,
reason = reason or "session_start",
specId = snapshot.specId or 0,
})
return snapshot
end
if InCombatLockdown and InCombatLockdown() then
snapshot = buildFallbackSnapshot(reason or "session_start")
snapshot.captureFlags.buildSnapshot = Constants.CAPTURE_QUALITY.DEGRADED
snapshot.captureFlags.awaitingTraitData = true
ns.Addon:SetLatestPlayerSnapshot(snapshot)
self.pendingFullRefresh = true
ns.Addon:Trace("snapshot.session.combat_fallback", {
reason = reason or "session_start",
specId = snapshot.specId or 0,
})
return snapshot
end
ns.Addon:Trace("snapshot.session.refresh", { reason = reason or "session_start" })
return self:TryRefreshDeferredSnapshot(reason or "session_start")
end
function SnapshotService:HandleTraitConfigListUpdated()
self:TryRefreshDeferredSnapshot("trait_config_ready")
end
-- Fired when the player selects or deselects an individual talent node during a
-- live editing session. Uses the existing pendingFullRefresh coalescing guard so
-- rapid node clicks produce only one refresh cycle, not one per click.
function SnapshotService:HandleTraitConfigUpdated()
if self._traitConfigUpdatedProcessing then return end
self._traitConfigUpdatedProcessing = true
self:TryRefreshDeferredSnapshot("trait_config_node_changed")
self._traitConfigUpdatedProcessing = false
end
function SnapshotService:CreateActorSnapshotFromUnit(unitToken, sourceType)
if not ApiCompat.UnitExists(unitToken) then
return nil
end
-- Wrap in pcall: Midnight returns secret values for arena enemy units
-- during PvP combat. The ApiCompat Safe wrappers handle most cases, but
-- pcall provides a final safety net against any remaining taint leaks.
local ok, snapshot = pcall(function()
local guid = ApiCompat.GetUnitGUID(unitToken)
if not guid then return nil end
local localizedClass, englishClass, classId = ApiCompat.GetUnitClass(unitToken)
local localizedRace, englishRace, raceId = ApiCompat.GetUnitRace(unitToken)
return {
guid = guid,
name = ApiCompat.GetUnitName(unitToken),
unitToken = unitToken,
sourceType = sourceType or "unit",
capturedAt = ApiCompat.GetServerTime(),
isPlayer = ApiCompat.UnitIsPlayer(unitToken),
className = localizedClass,
classFile = englishClass,
classId = classId,
raceName = localizedRace,
raceFile = englishRace,
raceId = raceId,
level = ApiCompat.GetUnitLevel(unitToken),
healthMax = ApiCompat.UnitHealthMax(unitToken),
}
end)
if not ok then return nil end
return snapshot
end
function SnapshotService:UpdateSessionActor(session, unitToken, sourceType)
if not session then
return nil
end
local snapshot = self:CreateActorSnapshotFromUnit(unitToken, sourceType)
if not snapshot or not snapshot.guid then
return nil
end
-- Guard: if guid is somehow still secret (should not happen after
-- CreateActorSnapshotFromUnit pcall, but belt-and-suspenders).
if ApiCompat.IsSecretValue(snapshot.guid) then
return nil
end
session.actors = session.actors or {}
session.actors[snapshot.guid] = session.actors[snapshot.guid] or snapshot
local current = session.actors[snapshot.guid]
for key, value in pairs(snapshot) do
if value ~= nil and not ApiCompat.IsSecretValue(value) then
current[key] = value
end
end
session.trackedActorGuids = session.trackedActorGuids or {}
session.trackedActorGuids[snapshot.guid] = true
return current
end
function SnapshotService:CaptureArenaPrep(matchRecord)
if not matchRecord then
return
end
matchRecord.prepOpponents = matchRecord.prepOpponents or {}
local opponentCount = ApiCompat.GetNumArenaOpponentSpecs()
for index = 1, opponentCount do
local specId = ApiCompat.GetArenaOpponentSpec(index)
if specId and specId > 0 then
local _, specName = ApiCompat.GetSpecializationInfoByID(specId)
matchRecord.prepOpponents[index] = {
slot = index,
observedAt = ApiCompat.GetServerTime(),
specId = specId,
specName = specName,
observationType = "arena_prep",
}
end
end
end
ns.Addon:RegisterModule("SnapshotService", SnapshotService)