-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameController.cs
More file actions
640 lines (564 loc) · 21.8 KB
/
Copy pathGameController.cs
File metadata and controls
640 lines (564 loc) · 21.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
/*
* Random Steam Game
*
* Copyright (c) 2026 Kyle Givler
* Licensed under the MIT License.
*/
using ErrorOr;
using JoyfulReaperLib.MissionControl;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using RandomSteamGame.Common.Errors;
using RandomSteamGame.Events;
using RandomSteamGame.Options;
using RandomSteamGame.Services;
using RandomSteamGame.Services.Interfaces;
using RandomSteamGame.Shared.Contracts;
using SteamApiClient;
using SteamApiClient.Services;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using SteamDeckCompatibilityCategory = SteamApiClient.Contracts.SteamApi.SteamDeckCompatibilityCategory;
namespace RandomSteamGame.Controllers;
[Route("api/{provider}")]
[AllowAnonymous]
[ApiController]
[EnableRateLimiting("steam_api_limiter")]
public class GameController : ApiController
{
private const long MinSteamId = 10_000_000_000_000_000L;
private const long MaxSteamId = 99_999_999_999_999_999L;
private readonly GameProviderFactory _factory;
private readonly IOwnedGamesCacheResetTracker _ownedGamesCacheResetTracker;
private readonly IAppStatsService _appStatsService;
private readonly ISteamLibraryExportService _steamLibraryExportService;
private readonly IMissionControlClient _missionControlClient;
private readonly ApplicationOptions _applicationOptions;
private readonly ILogger<GameController> _logger;
private readonly IVisitorIdProvider _visitorIdProvider;
private readonly ILibraryExportCooldownTracker _libraryExportCooldownTracker;
public GameController(
GameProviderFactory factory,
IOwnedGamesCacheResetTracker ownedGamesCacheResetTracker,
IAppStatsService appStatsService,
ISteamLibraryExportService steamLibraryExportService,
IMissionControlClient missionControlClient,
IVisitorIdProvider visitorIdProvider,
ILibraryExportCooldownTracker libraryExportCooldownTracker,
IOptions<ApplicationOptions> applicationOptions,
ILogger<GameController> logger)
{
_missionControlClient = missionControlClient;
_visitorIdProvider = visitorIdProvider;
_applicationOptions = applicationOptions.Value;
_factory = factory;
_ownedGamesCacheResetTracker = ownedGamesCacheResetTracker;
_appStatsService = appStatsService;
_steamLibraryExportService = steamLibraryExportService;
_logger = logger;
_libraryExportCooldownTracker = libraryExportCooldownTracker;
}
/// <summary>
/// Gets the list of owned games for a specific Steam ID.
/// GET /api/steam/{steamId}/library
/// </summary>
[HttpGet("{steamId}/library")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(OwnedGamesResponse))]
public async Task<IActionResult> GetLibrary(string provider, long steamId)
{
if (!TryGetProvider(provider, out var service))
{
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
if (!IsValidSteamId(steamId))
{
return Problem([Errors.Steam.InvalidSteamId]);
}
var result = await service.GetOwnedGamesAsync(steamId);
return result.Match(Ok, Problem);
}
/// <summary>
/// Exports the list of owned games for a specific Steam ID as CSV.
/// GET /api/steam/{steamId}/library/export.csv
/// </summary>
[HttpGet("{steamId:long}/library/export.csv")]
[EnableRateLimiting("library_export_limiter")]
[Produces("text/csv")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> ExportLibrary(
string provider,
long steamId)
{
Response.Headers["Cache-Control"] = "private, no-store";
Response.Headers["CDN-Cache-Control"] = "no-store";
if (!TryGetProvider(provider, out var service))
{
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
if (!IsValidSteamId(steamId))
{
return Problem([Errors.Steam.InvalidSteamId]);
}
var occurredAt = DateTimeOffset.UtcNow;
var correlationId = Guid.NewGuid().ToString("N");
var partitionKey = LibraryExportRateLimitPartitionKey.From(HttpContext.Connection.RemoteIpAddress);
var retryAfter = _libraryExportCooldownTracker.GetRetryAfter(partitionKey);
if (retryAfter is not null)
{
var retryAfterSeconds = Math.Max(1, (long)Math.Ceiling(retryAfter.Value.TotalSeconds));
Response.Headers.RetryAfter = retryAfterSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
_ = PublishLibraryExportRejectedEventAsync(
provider,
LibraryExportRejectionReason.Cooldown,
retryAfterSeconds,
occurredAt,
correlationId);
return new ContentResult
{
StatusCode = StatusCodes.Status429TooManyRequests,
ContentType = "text/plain; charset=utf-8",
Content =
"Steam library CSV exports are limited to one per IP address " +
"every 72 hours after a successful export."
};
}
var stopwatch = Stopwatch.StartNew();
var result = await service.GetOwnedGamesAsync(steamId);
if (result.IsError)
{
return Problem(result.Errors);
}
IReadOnlyDictionary<int, SteamDeckCompatibilityCategory> deckCompatibility =
new Dictionary<int, SteamDeckCompatibilityCategory>();
if (service is ISteamDeckCompatibilityProvider deckProvider)
{
deckCompatibility = await deckProvider.GetSteamDeckCompatibilityAsync(
result.Value.Games.Select(game => game.AppId),
HttpContext.RequestAborted);
}
var csvBytes = _steamLibraryExportService.Export(result.Value, deckCompatibility);
await TrackLibraryExportedAsync();
_libraryExportCooldownTracker.MarkSucceeded(partitionKey);
var verifiedCount = 0;
var playableCount = 0;
var unsupportedCount = 0;
var unknownCount = 0;
foreach (var game in result.Value.Games)
{
var category =
deckCompatibility.TryGetValue(game.AppId, out var value)
? value
: SteamDeckCompatibilityCategory.Unknown;
switch (category)
{
case SteamDeckCompatibilityCategory.Verified:
verifiedCount++;
break;
case SteamDeckCompatibilityCategory.Playable:
playableCount++;
break;
case SteamDeckCompatibilityCategory.Unsupported:
unsupportedCount++;
break;
default:
unknownCount++;
break;
}
}
stopwatch.Stop();
await PublishLibraryExportCompletedEventAsync(
provider,
result.Value.Games.Count,
stopwatch.ElapsedMilliseconds,
verifiedCount,
playableCount,
unsupportedCount,
unknownCount,
occurredAt,
correlationId);
return File(
csvBytes,
"text/csv; charset=utf-8",
$"steam-library-{steamId}.csv");
}
/// <summary>
/// Invalidates the cached owned games for a user.
/// POST /api/steam/{userId}/library/refresh
/// </summary>
[HttpPost("{userId}/library/refresh")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> RefreshLibrary(string provider, long userId)
{
if (!TryGetProvider(provider, out var service))
{
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
if (!IsValidSteamId(userId))
{
return Problem([Errors.Steam.InvalidSteamId]);
}
var nextAvailableAt = await _ownedGamesCacheResetTracker.GetNextAvailableAtAsync(userId);
if (nextAvailableAt is not null)
{
return StatusCode(
StatusCodes.Status429TooManyRequests,
new ApiProblem
{
Title = "TooManyRequests",
Status = StatusCodes.Status429TooManyRequests,
Detail = $"Owned games cache can only be reset once every 12 hours. Try again after {nextAvailableAt.Value.ToLocalTime():f}."
});
}
await service.InvalidateOwnedGamesCacheAsync(userId);
await _ownedGamesCacheResetTracker.MarkResetAsync(userId);
return NoContent();
}
/// <summary>
/// Gets simplified game details for a random game.
/// GET /api/steam/random-game/details?userId=... OR ?vanityUrl=...
/// </summary>
[HttpGet("random-game/details")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(GameDetails))]
public async Task<IActionResult> GetRandomGameDetails(
string provider,
[FromQuery] long? userId,
[FromQuery] string? vanityUrl,
[FromQuery] bool unplayedOnly = false)
{
var occurredAt = DateTimeOffset.UtcNow;
var correlationId = Guid.NewGuid().ToString("N");
var stopwatch = Stopwatch.StartNew();
if (!TryGetProvider(provider, out var service))
{
await PublishGamePickEventAsync(
provider,
telemetry: null,
unplayedOnly,
stopwatch,
outcome: "unsupported-provider",
succeeded: false,
occurredAt,
correlationId,
identifierResolutionMilliseconds: 0);
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
var identifierValidation = ValidateIdentifier(userId, vanityUrl);
if (identifierValidation is not null)
{
await PublishGamePickEventAsync(
provider,
telemetry: null,
unplayedOnly,
stopwatch,
outcome: "invalid-identifier",
succeeded: false,
occurredAt,
correlationId,
identifierResolutionMilliseconds: 0);
return Problem([identifierValidation.Value]);
}
var identifierStopwatch = Stopwatch.StartNew();
var targetId = await ResolveIdentifier(service, userId, vanityUrl);
identifierStopwatch.Stop();
if (targetId.IsError)
{
await PublishGamePickEventAsync(
provider,
telemetry: null,
unplayedOnly,
stopwatch,
outcome: "identifier-resolution-failed",
succeeded: false,
occurredAt,
correlationId,
identifierResolutionMilliseconds: identifierStopwatch.ElapsedMilliseconds);
return Problem(targetId.Errors);
}
var result = await service.GetRandomGamePickAsync(targetId.Value, unplayedOnly);
if (!result.Succeeded)
{
await PublishGamePickEventAsync(
provider,
telemetry: result,
unplayedOnly,
stopwatch,
outcome: GetOutcome(result.Errors),
succeeded: false,
occurredAt,
correlationId,
identifierResolutionMilliseconds: identifierStopwatch.ElapsedMilliseconds);
return Problem(result.Errors.ToList());
}
await TrackRandomGameGeneratedAsync();
await PublishGamePickEventAsync(
provider,
result,
unplayedOnly,
stopwatch,
outcome: GamePickOutcome.Served,
succeeded: true,
occurredAt,
correlationId,
identifierResolutionMilliseconds: identifierStopwatch.ElapsedMilliseconds);
return Ok(result.Game);
}
private async Task PublishLibraryExportRejectedEventAsync(
string? provider,
string reason,
long? retryAfterSeconds,
DateTimeOffset occurredAt,
string correlationId)
{
try
{
await _missionControlClient.TryPublishAsync(
eventType: RandomSteamGameEventTypes.LibraryExportRejected,
payload: new LibraryExportRejectedEvent(
VisitorId: GetVisitorIdForTelemetry(),
Provider: provider,
IngressNetwork: IngressNetworkClassifier.FromHost(HttpContext.Request.Host.Host),
Reason: reason,
RetryAfterSeconds: retryAfterSeconds,
CommitSha: string.IsNullOrWhiteSpace(_applicationOptions.CommitSha)
? null
: _applicationOptions.CommitSha),
occurredAt: occurredAt,
payloadTypeInfo: RandomSteamGameJsonContext.Default.LibraryExportRejectedEvent,
correlationId: correlationId,
cancellationToken: CancellationToken.None);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to publish library-export rejection event {CorrelationId}.",
correlationId);
}
}
private async Task PublishLibraryExportCompletedEventAsync(
string provider,
int gameCount,
long durationMilliseconds,
int verifiedCount,
int playableCount,
int unsupportedCount,
int unknownCount,
DateTimeOffset occurredAt,
string correlationId)
{
try
{
await _missionControlClient.TryPublishAsync(
eventType: RandomSteamGameEventTypes.LibraryExportCompleted,
payload: new LibraryExportCompletedEvent(
VisitorId: GetVisitorIdForTelemetry(),
Provider: provider,
IngressNetwork: IngressNetworkClassifier.FromHost(HttpContext.Request.Host.Host),
GameCount: gameCount,
DurationMilliseconds: durationMilliseconds,
VerifiedCount: verifiedCount,
PlayableCount: playableCount,
UnsupportedCount: unsupportedCount,
UnknownCount: unknownCount,
CommitSha: string.IsNullOrWhiteSpace(_applicationOptions.CommitSha)
? null
: _applicationOptions.CommitSha),
occurredAt: occurredAt,
payloadTypeInfo: RandomSteamGameJsonContext.Default.LibraryExportCompletedEvent,
correlationId: correlationId,
cancellationToken: CancellationToken.None);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to publish library-export event {CorrelationId}.",
correlationId);
}
}
private async Task PublishGamePickEventAsync(
string provider,
RandomGamePickAttempt? telemetry,
bool unplayedOnly,
Stopwatch stopwatch,
string outcome,
bool succeeded,
DateTimeOffset occurredAt,
string correlationId,
long identifierResolutionMilliseconds)
{
stopwatch.Stop();
try
{
await _missionControlClient.TryPublishAsync(
eventType:
RandomSteamGameEventTypes.GamePickCompleted,
payload: new GamePickCompletedEvent(
VisitorId: GetVisitorIdForTelemetry(),
Provider: provider,
IngressNetwork: IngressNetworkClassifier.FromHost(HttpContext.Request.Host.Host),
AppId: telemetry?.Game?.Id,
// Display metadata only. Use AppId for stable joins, grouping, and identity.
GameName: GamePickTelemetryName.Sanitize(telemetry?.Game?.Name),
UnplayedOnly: unplayedOnly,
DurationMilliseconds: stopwatch.ElapsedMilliseconds,
CacheStatus: telemetry?.Cache.StatusName ?? OwnedGamesCacheInfo.Unknown.StatusName,
CacheAgeSeconds: telemetry?.Cache.AgeSeconds,
EligibleGameCount: telemetry?.EligibleGameCount,
LibrarySizeBucket: telemetry is null
? null
: telemetry.LibraryGameCount is null
? null
: LibrarySizeBuckets.FromCount(telemetry.LibraryGameCount.Value),
Timings: telemetry is null
? new GamePickTimings(identifierResolutionMilliseconds, 0, 0)
: telemetry.Timings with
{
IdentifierResolutionMilliseconds = identifierResolutionMilliseconds
},
CommitSha: string.IsNullOrWhiteSpace(_applicationOptions.CommitSha)
? null
: _applicationOptions.CommitSha,
Outcome: outcome,
Succeeded: succeeded),
occurredAt: occurredAt,
payloadTypeInfo: RandomSteamGameJsonContext.Default.GamePickCompletedEvent,
correlationId: correlationId,
cancellationToken: CancellationToken.None);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to publish game-pick event {CorrelationId}.",
correlationId);
}
}
/// <summary>
/// Utility: Resolves a vanity URL to a Steam ID.
/// GET /api/steam/resolve/{vanityUrl}
/// </summary>
[HttpGet("resolve/{vanityUrl}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(long))]
public async Task<IActionResult> ResolveVanity(string provider, string vanityUrl)
{
if (!TryGetProvider(provider, out var service))
{
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
if (!IsValidVanityUrl(vanityUrl))
{
return Problem([Errors.Steam.InvalidVanityUrl]);
}
var result = await service.ResolveIdentifierAsync(vanityUrl);
return result.Match(
result => Ok(result),
errors => Problem(errors));
}
private bool TryGetProvider(
string provider,
[NotNullWhen(true)] out IGameProvider? service)
{
return _factory.TryGetProvider(provider, out service);
}
private static Error? ValidateIdentifier(long? userId, string? vanityUrl)
{
var hasUserId = userId.HasValue;
var hasVanityUrl = !string.IsNullOrWhiteSpace(vanityUrl);
if (!hasUserId && !hasVanityUrl)
{
return Errors.Steam.IdentifierRequired;
}
if (hasUserId && hasVanityUrl)
{
return Errors.Steam.AmbiguousIdentifier;
}
if (hasUserId && !IsValidSteamId(userId!.Value))
{
return Errors.Steam.InvalidSteamId;
}
if (hasVanityUrl && !IsValidVanityUrl(vanityUrl!))
{
return Errors.Steam.InvalidVanityUrl;
}
return null;
}
private static bool IsValidSteamId(long steamId)
{
return steamId is >= MinSteamId and <= MaxSteamId;
}
private static bool IsValidVanityUrl(string vanityUrl)
{
return SteamVanityUrlHelper.TryNormalize(vanityUrl, out _);
}
private static async Task<ErrorOr<long>> ResolveIdentifier(
IGameProvider service,
long? userId,
string? vanityUrl)
{
if (!string.IsNullOrWhiteSpace(vanityUrl))
{
return await service.ResolveIdentifierAsync(vanityUrl);
}
if (userId.HasValue)
{
return userId.Value;
}
return Errors.Steam.IdentifierRequired;
}
private static string GetOutcome(IReadOnlyList<Error> errors)
{
var first = errors.FirstOrDefault();
return first.Code switch
{
"Steam.EmptyLibrary" => GamePickOutcome.EmptyLibrary,
"Steam.NoSelectableGamesAfterExclusions" => GamePickOutcome.NoEligibleGames,
"Steam.ApiFailed" => GamePickOutcome.LibraryLoadFailed,
"Steam.VanityResolutionFailed" => GamePickOutcome.IdentifierResolutionFailed,
_ => GamePickOutcome.SelectionFailed
};
}
private async Task TrackRandomGameGeneratedAsync()
{
try
{
await _appStatsService.IncrementRandomGamesGeneratedAsync();
}
catch (Exception ex)
{
// This should never block game generation.
_logger.LogWarning(ex, "Failed to increment random games generated counter.");
}
}
private async Task TrackLibraryExportedAsync()
{
try
{
await _appStatsService.IncrementLibrariesExportedAsync();
}
catch (Exception exception)
{
// Stats must never prevent a successful export.
_logger.LogWarning(exception, "Failed to increment libraries exported counter.");
}
}
private string? GetVisitorIdForTelemetry()
{
try
{
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
return string.IsNullOrWhiteSpace(ip)
? null
: _visitorIdProvider.GetVisitorId(ip);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to generate visitor ID for game-pick telemetry.");
return null;
}
}
}