-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScoreUpdateService.cs
More file actions
482 lines (418 loc) · 24.4 KB
/
Copy pathScoreUpdateService.cs
File metadata and controls
482 lines (418 loc) · 24.4 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
using FantasyBasket.API.Data;
using FantasyBasket.API.Interfaces;
using FantasyBasket.API.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.SignalR;
using System.IO;
using FantasyBasket.API.Models;
using System.Globalization;
using StackExchange.Redis;
namespace FantasyBasket.API.Services;
public class ScoreUpdateService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<ScoreUpdateService> _logger;
private readonly IHubContext<FantasyBasket.API.Hubs.AppHub> _hubContext;
private readonly IBackgroundJobRunner _bgJobs;
private readonly IConnectionMultiplexer? _redis;
// Lock distribuito sull'esecuzione live (ogni 60s): se l'app gira su >1 istanza,
// evita che entrambe leggano NBA + scrivano score in parallelo. TTL 90s > 60s loop:
// se l'istanza che ha il lock crasha, l'altra subentra al ciclo successivo.
private const string LiveTickLockKey = "score-update:live-tick";
private static readonly TimeSpan LiveTickLockTtl = TimeSpan.FromSeconds(90);
private DateTime _lastFullScheduleUpdate = DateTime.MinValue;
private DateTime _lastScoreRefresh = DateTime.MinValue;
private DateTime _lastMediumUpdate = DateTime.MinValue;
private DateTime _lastInjuryUpdate = DateTime.MinValue;
private bool _areGamesLive = false;
private Dictionary<ProLeagueType, List<int>> _cachedPlayerIds = new();
private Dictionary<ProLeagueType, List<int>> _cachedLeagueIds = new();
private DateTime _lastSalaryFullUpdate = DateTime.MinValue;
// Catturato in ExecuteAsync per propagarlo ai task fire-and-forget avviati dall'esterno.
private CancellationToken _stoppingToken = CancellationToken.None;
public ScoreUpdateService(IServiceScopeFactory scopeFactory, ILogger<ScoreUpdateService> logger, IHubContext<FantasyBasket.API.Hubs.AppHub> hubContext, IBackgroundJobRunner bgJobs, IConnectionMultiplexer? redis = null)
{
_scopeFactory = scopeFactory;
_logger = logger;
_hubContext = hubContext;
_bgJobs = bgJobs;
_redis = redis;
}
// "Oggi" in Eastern Time, ritornato come DateTime UTC-kind allineato al campo
// NbaGames.GameDate (che è salvato come date a mezzanotte UTC). Usare UtcNow.AddHours(-12)
// dava risultati incoerenti con NbaDataService che ragiona in ET → la finestra LIVE
// poteva guardare il giorno sbagliato.
private static DateTime GetNbaTodayUtc()
{
try
{
var tzId = OperatingSystem.IsWindows() ? "Eastern Standard Time" : "America/New_York";
var etNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(tzId));
return DateTime.SpecifyKind(etNow.Date, DateTimeKind.Utc);
}
catch
{
return DateTime.SpecifyKind(DateTime.UtcNow.AddHours(-5).Date, DateTimeKind.Utc);
}
}
// Chiude (Status = "Final") qualsiasi partita con GameDate antecedente al cutoff
// calcolato in funzione dell'ora ET corrente:
// - prima delle 06:00 ET → solo partite con GameDate < ieri-ET (margine per OT a cavallo della mezzanotte)
// - dalle 06:00 ET in poi → anche le partite di ieri-ET vengono forzate (sicuramente finite)
// Salta PPD/Final già esistenti.
private async Task CloseStaleGamesAsync(Data.ApplicationDbContext context, ProLeagueType[] leagueTypes, DateTime todayNbaUtc, CancellationToken ct)
{
try
{
DateTime etNow;
try
{
var tzId = OperatingSystem.IsWindows() ? "Eastern Standard Time" : "America/New_York";
etNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(tzId));
}
catch { etNow = DateTime.UtcNow.AddHours(-5); }
var staleCutoff = etNow.Hour >= 6
? todayNbaUtc // include ieri-ET
: todayNbaUtc.AddDays(-1); // esclude ieri-ET fino alle 06:00 ET
var staleGames = await context.NbaGames
.Where(g => leagueTypes.Contains(g.LeagueType)
&& g.GameDate < staleCutoff
&& !g.Status.StartsWith("Final")
&& !g.Status.Contains("PPD"))
.ToListAsync(ct);
if (staleGames.Count == 0) return;
foreach (var g in staleGames) g.Status = "Final";
await context.SaveChangesAsync(ct);
_logger.LogWarning("Housekeeping: chiuse {Count} partite stuck (Status→Final) con GameDate < {Cutoff:yyyy-MM-dd}.", staleGames.Count, staleCutoff);
}
catch (Exception ex)
{
_logger.LogError(ex, "Housekeeping CloseStaleGamesAsync fallita — proseguo comunque.");
}
}
// Tenta di acquisire un lock distribuito (SET NX). Ritorna true se acquisito.
// Se Redis non è disponibile o errore: fail-open (true), così single-istanza non si blocca.
private async Task<bool> TryAcquireLiveTickLockAsync()
{
if (_redis is null) return true;
try
{
return await _redis.GetDatabase().StringSetAsync(LiveTickLockKey, Environment.MachineName, LiveTickLockTtl, when: When.NotExists);
}
catch (Exception ex)
{
_logger.LogWarning("Redis live-tick lock acquire failed: {Msg} — fail-open.", ex.Message);
return true;
}
}
private async Task ProcessLeaguesInParallelAsync(List<int> leagueIds)
{
if (leagueIds == null || !leagueIds.Any()) return;
// I punteggi si CALCOLANO per tutte le leghe (standings e risultati non
// dipendono da chi è online), ma il BROADCAST va solo alle leghe con
// almeno un client connesso: ogni publish sul backplane Upstash è
// fatturato a request e un gruppo vuoto è lavoro buttato.
// Fail-open: se Redis non risponde, broadcast a tutte (comportamento storico).
HashSet<int>? activeLeagues = null;
if (_redis is not null)
{
try
{
var members = await _redis.GetDatabase().SetMembersAsync(Common.HubPresenceKeys.ActiveLeagues);
activeLeagues = members.Select(m => (int)m).ToHashSet();
}
catch (Exception ex)
{
_logger.LogWarning("Lettura ActiveLeagues fallita: {Msg} — broadcast a tutte le leghe.", ex.Message);
}
}
// Invece di farle 5 alla volta col rischio di saturare PgBouncer con migliaia di query,
// ne facciamo 50 alla volta in UN'UNICA query al database!
var chunks = leagueIds.Chunk(50);
foreach (var chunk in chunks)
{
using var innerScope = _scopeFactory.CreateScope();
var innerMatchupService = innerScope.ServiceProvider.GetRequiredService<MatchupService>();
// LA MAGIA AVVIENE QUI: Passiamo l'intera lista di leghe in un colpo solo
await innerMatchupService.UpdateLiveScoresBulk(chunk.ToList());
if (_hubContext != null && _areGamesLive)
{
// Notifichiamo via WebSocket le app dei giocatori (solo leghe con utenti).
// Evento camelCase per convenzione (il client JS normalizza comunque).
foreach (var leagueId in chunk)
{
if (activeLeagues != null && !activeLeagues.Contains(leagueId)) continue;
await _hubContext.Clients.Group($"League_{leagueId}").SendAsync("receiveScoreUpdate");
}
}
}
}
public Task ForceManualRun()
{
_logger.LogWarning("⚠️ MANUALE: Avvio forzato aggiornamento punteggi...");
_areGamesLive = true;
_bgJobs.Run("ForceScoreUpdate", async (sp, ct) =>
{
var nbaService = sp.GetRequiredService<INbaDataService>();
var context = sp.GetRequiredService<ApplicationDbContext>();
var today = GetNbaTodayUtc();
foreach (var leagueType in new[] { ProLeagueType.NBA, ProLeagueType.WNBA })
{
ct.ThrowIfCancellationRequested();
var activePlayerIds = await context.Players
.Where(p => p.LeagueType == leagueType)
.Select(p => p.Id).ToListAsync(ct);
if (activePlayerIds.Any())
{
await nbaService.GetFantasyPointsByDate(today, activePlayerIds, leagueType);
}
var leagueIds = await context.Leagues.Where(l => l.Type == leagueType).Select(l => l.Id).ToListAsync(ct);
await ProcessLeaguesInParallelAsync(leagueIds);
var scheduleService = sp.GetRequiredService<ScheduleService>();
await scheduleService.CheckAndTriggerPlayoffsAsync(force: true);
await scheduleService.ResolvePlayoffAdvancementAsync();
}
_logger.LogInformation("✅ MANUALE: Aggiornamento completato.");
});
return Task.CompletedTask;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_stoppingToken = stoppingToken;
_logger.LogInformation("Score Update Service avviato per NBA e WNBA.");
try
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var nbaService = scope.ServiceProvider.GetRequiredService<INbaDataService>();
var matchupService = scope.ServiceProvider.GetRequiredService<MatchupService>();
foreach (var leagueType in new[] { ProLeagueType.NBA, ProLeagueType.WNBA })
{
// Controlla se esistono partite recenti o future (ultimi 30 giorni in poi).
// Se no, significa che il calendario della stagione corrente non è stato importato
// (es. nuova stagione WNBA, DB con solo dati stagione precedente).
var lookbackDate = DateTime.SpecifyKind(DateTime.UtcNow.Date.AddDays(-30), DateTimeKind.Utc);
bool hasCurrentGames = await context.NbaGames.AnyAsync(
g => g.LeagueType == leagueType && g.GameDate >= lookbackDate, stoppingToken);
if (!hasCurrentGames)
{
_logger.LogInformation($"Nessuna partita recente/futura per {leagueType}: Avvio download massivo Calendario stagione corrente...");
await nbaService.ImportSeasonScheduleAsync(leagueType);
}
}
await matchupService.ProcessCompletedMatchups(stoppingToken);
var leagueIds = await context.Leagues.Select(l => l.Id).ToListAsync(stoppingToken);
await ProcessLeaguesInParallelAsync(leagueIds); // 🔥 Usa il nuovo helper!
// NOTA: il download dei modelli ML da Supabase è gestito UNA volta a startup in
// Program.cs con la naming convention nuova ({cat}_{nba|wnba}.zip × 24 modelli).
// Il PredictionEnginePool ha watchForChanges:true → ricarica i modelli quando il
// file viene aggiornato dal training settimanale. Niente bootstrap qui dentro.
}
catch (Exception ex) { _logger.LogError(ex, "Errore durante il bootstrap iniziale."); }
while (!stoppingToken.IsCancellationRequested)
{
int nextLoopDelaySeconds = 15 * 60;
// Le aste di mercato scadute sono processate SOLO da AuctionMonitorService
// (ciclo attivo + safety-cycle 30s in letargo). La chiamata duplicata che
// viveva qui creava due processori concorrenti sulle stesse aste.
try
{
using var scope = _scopeFactory.CreateScope();
var nbaService = scope.ServiceProvider.GetRequiredService<INbaDataService>();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var injuryService = scope.ServiceProvider.GetRequiredService<OfficialInjuryService>();
var dvpService = scope.ServiceProvider.GetRequiredService<DvPCalculatorService>();
var trainerService = scope.ServiceProvider.GetRequiredService<ITrainerService>();
var matchupService = scope.ServiceProvider.GetRequiredService<MatchupService>();
var espnSalaryService = scope.ServiceProvider.GetRequiredService<IEspnSalaryService>();
var today = GetNbaTodayUtc();
var leagueTypes = new[] { ProLeagueType.NBA, ProLeagueType.WNBA };
// Housekeeping: chiudi (forza Status="Final") le partite "stuck" su uno status
// intermedio (es. "End of Q4") che il boxscore CDN non è riuscito a finalizzare.
// Una partita dura max ~3h; al cutoff calcolato sotto è impossibile sia ancora live.
// Senza questa pulizia, la query di rilevamento LIVE matcha eternamente quegli
// status residui e la "Finestra LIVE" non si spegne mai.
await CloseStaleGamesAsync(context, leagueTypes, today, stoppingToken);
bool shouldBeLiveMode = false;
var gamesTodayStatus = await context.NbaGames
.Where(g => leagueTypes.Contains(g.LeagueType) && g.GameDate == today
&& !g.Status.StartsWith("Final") // Esclude "Final", "Final/OT", "Final/2OT" …
&& !g.Status.Contains("PPD"))
.Select(g => g.Status)
.ToListAsync(stoppingToken);
if (gamesTodayStatus.Any())
{
if (DateTime.UtcNow > _lastMediumUpdate.AddMinutes(5))
{
foreach (var leagueType in leagueTypes) await nbaService.UpdateDailyNbaSchedule(today, leagueType);
_lastMediumUpdate = DateTime.UtcNow;
gamesTodayStatus = await context.NbaGames
.Where(g => leagueTypes.Contains(g.LeagueType) && g.GameDate == today
&& !g.Status.StartsWith("Final")
&& !g.Status.Contains("PPD"))
.Select(g => g.Status)
.ToListAsync(stoppingToken);
}
foreach (var status in gamesTodayStatus)
{
string statusLower = status.ToLower();
if (statusLower.Contains("live") || statusLower.Contains("q1") || statusLower.Contains("q2") || statusLower.Contains("q3") || statusLower.Contains("q4") || statusLower.Contains("half") || statusLower.Contains("ot") || statusLower.Contains("end"))
{
shouldBeLiveMode = true; break;
}
// Status sconosciuto/non riconosciuto → NON forziamo LIVE.
// La vecchia logica catch-all marcava live qualunque cosa non fosse
// un orario futuro/scheduled/final, causando finestre LIVE bloccate
// su status residui (es. "End of Q4" mai finalizzato). Lo logghiamo
// come warning per visibilità e la housekeeping si occuperà di
// chiudere le partite stuck. Per attivare il live mode servono
// status espliciti gestiti sopra.
if (!statusLower.StartsWith("final") &&
!statusLower.Contains("pm") && !statusLower.Contains("am") &&
!statusLower.Contains("et") && !statusLower.Contains("pt") &&
statusLower != "scheduled" &&
!string.IsNullOrWhiteSpace(statusLower))
{
_logger.LogWarning("ScoreUpdate: status partita sconosciuto '{Status}' — skip (non forzo LIVE).", status);
continue;
}
var timeStr = status.Replace(" ET", "", StringComparison.OrdinalIgnoreCase).Replace(" PT", "", StringComparison.OrdinalIgnoreCase).Trim();
if (DateTime.TryParseExact(timeStr, new[] { "h:mm tt", "hh:mm tt" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedTime))
{
try
{
var tzId = OperatingSystem.IsWindows() ? "Eastern Standard Time" : "America/New_York";
var estZone = TimeZoneInfo.FindSystemTimeZoneById(tzId);
var gameTimeUtc = TimeZoneInfo.ConvertTimeToUtc(today.Date + parsedTime.TimeOfDay, estZone);
if (DateTime.UtcNow >= gameTimeUtc) { shouldBeLiveMode = true; break; }
}
catch { }
}
}
}
_areGamesLive = shouldBeLiveMode;
if (_areGamesLive)
{
_logger.LogInformation("🔥 Finestra LIVE attiva! Aggiornamento punti ogni 60 secondi via CDN...");
nextLoopDelaySeconds = 60;
// Multi-istanza: se un altro pod sta già processando il tick, salta.
if (!await TryAcquireLiveTickLockAsync())
{
_logger.LogDebug("Live tick già in corso su un'altra istanza — skip.");
await Task.Delay(TimeSpan.FromSeconds(nextLoopDelaySeconds), stoppingToken);
continue;
}
foreach (var leagueType in leagueTypes)
{
if (!_cachedPlayerIds.TryGetValue(leagueType, out var activePlayerIds) || activePlayerIds.Count == 0)
{
activePlayerIds = await context.Players.AsNoTracking()
.Where(p => p.LeagueType == leagueType)
.Select(p => p.Id).ToListAsync(stoppingToken);
_cachedPlayerIds[leagueType] = activePlayerIds;
}
if (activePlayerIds.Any())
await nbaService.GetFantasyPointsByDate(today, activePlayerIds, leagueType);
if (!_cachedLeagueIds.TryGetValue(leagueType, out var targetLeagueIds) || targetLeagueIds.Count == 0)
{
targetLeagueIds = await context.Leagues.Where(l => l.Type == leagueType).Select(l => l.Id).ToListAsync(stoppingToken);
_cachedLeagueIds[leagueType] = targetLeagueIds;
}
await ProcessLeaguesInParallelAsync(targetLeagueIds);
}
}
else
{
_logger.LogInformation("💤 Finestra di Riposo. Prossimo check tra 15 minuti.");
nextLoopDelaySeconds = 15 * 60;
_cachedPlayerIds.Clear();
_cachedLeagueIds.Clear();
// --- BLOCCO 4 ORE: Aggiornamento punteggi latenti e FINALIZZAZIONE MATCHUP ---
if (DateTime.UtcNow > _lastScoreRefresh.AddHours(4))
{
foreach (var leagueType in leagueTypes)
{
var activePlayerIds = await context.Players.AsNoTracking()
.Where(p => p.LeagueType == leagueType)
.Select(p => p.Id).ToListAsync(stoppingToken);
if (activePlayerIds.Any())
{
await nbaService.GetFantasyPointsByDate(today, activePlayerIds, leagueType);
await nbaService.GetFantasyPointsByDate(today.AddDays(-1), activePlayerIds, leagueType);
}
if (!_cachedLeagueIds.TryGetValue(leagueType, out var targetLeagueIds) || targetLeagueIds.Count == 0)
{
targetLeagueIds = await context.Leagues.Where(l => l.Type == leagueType).Select(l => l.Id).ToListAsync(stoppingToken);
_cachedLeagueIds[leagueType] = targetLeagueIds;
}
await ProcessLeaguesInParallelAsync(targetLeagueIds);
}
// 🔥 FIX LOGICO: I matchup vengono finalizzati massimo 4 ore dopo la fine della giornata
await matchupService.ProcessCompletedMatchups(stoppingToken);
// 🚀 INNESCO AUTO-PLAYOFF: Controlliamo se qualche lega ha appena finito la stagione
var scheduleService = scope.ServiceProvider.GetRequiredService<ScheduleService>();
await scheduleService.CheckAndTriggerPlayoffsAsync();
// 🏆 AVANZAMENTO BRACKET: propaga vincenti/perdenti (round 2+, Play-In) dopo la finalizzazione.
await scheduleService.ResolvePlayoffAdvancementAsync();
_lastScoreRefresh = DateTime.UtcNow;
}
// --- BLOCCO 24 ORE: Sincronizzazione massiva e DvP ---
if (DateTime.UtcNow > _lastFullScheduleUpdate.AddHours(24))
{
foreach (var leagueType in leagueTypes)
{
await nbaService.SyncPlayersAsync(leagueType);
await nbaService.UpdateDailyNbaSchedule(today.AddDays(-1), leagueType);
await nbaService.UpdateDailyNbaSchedule(today.AddDays(1), leagueType);
await nbaService.ImportAdvancedTeamStatsAsync(nbaService.GetCurrentSeason(leagueType), leagueType);
await dvpService.CalculateDvPAsync(leagueType);
//await espnSalaryService.SyncAllSalariesAsync(leagueType);
}
_lastFullScheduleUpdate = DateTime.UtcNow;
}
}
var ora = DateTime.UtcNow;
bool isTradeDeadlinePeriod = (ora.Month == 2 && ora.Day >= 10 && ora.Day <= 15); // Fine Trade Deadline
bool isPreSeasonPeriod = (ora.Month == 10 && ora.Day >= 1 && ora.Day <= 10); // Prima del tip-off NBA
bool isOffSeasonStart = (ora.Month == 7 && ora.Day >= 1 && ora.Day <= 7); // Apertura Free Agency
if (isTradeDeadlinePeriod || isPreSeasonPeriod || isOffSeasonStart)
{
// Verifichiamo che non sia già stato fatto oggi per non loopare
if (DateTime.UtcNow > _lastSalaryFullUpdate.AddHours(24))
{
_logger.LogInformation("🚀 Finestra di aggiornamento salari rilevata. Avvio sincronizzazione massiva...");
foreach (var leagueType in leagueTypes)
{
try
{
await espnSalaryService.SyncAllSalariesAsync(leagueType);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Errore durante il Sync salari stagionale per {leagueType}");
}
}
_lastSalaryFullUpdate = DateTime.UtcNow;
_logger.LogInformation("✅ Sincronizzazione salari completata per la finestra attuale.");
}
}
// --- BLOCCO INDIPENDENTE: 2 ORE (INFORTUNI) ---
// 🔥 FIX LOGICO: Aggiorna gli infortuni via ESPN ogni 2 ore, che sia live o a riposo
if (DateTime.UtcNow > _lastInjuryUpdate.AddHours(2))
{
foreach (var leagueType in leagueTypes)
{
await injuryService.UpdateInjuriesFromOfficialReportAsync(leagueType);
}
_lastInjuryUpdate = DateTime.UtcNow;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Errore nel ciclo NBA Smart Worker.");
nextLoopDelaySeconds = 5 * 60;
}
await Task.Delay(TimeSpan.FromSeconds(nextLoopDelaySeconds), stoppingToken);
}
}
}