Skip to content

Commit

Permalink
Don't reuse steam client
Browse files Browse the repository at this point in the history
  • Loading branch information
Equinox- committed Oct 18, 2024
1 parent 4b6c605 commit 14a9c92
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
# Restore game cache keys.
- name: Generate game cache key
id: game_cache_key
run: powershell -Command echo "key=game-cache-v3-$(Get-Date -Format yyyy-MM)" >> $env:GITHUB_OUTPUT
run: powershell -Command echo "key=game-cache-v4-$(Get-Date -Format yyyy-MM)" >> $env:GITHUB_OUTPUT
- name: Cache Game Binaries
uses: actions/cache@v3
with:
Expand Down
51 changes: 31 additions & 20 deletions SchemaBuilder/GameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,17 @@ namespace SchemaBuilder
{
public class GameManager : IHostedService
{
// Data files required for definition loading.
private static readonly string[] DataFileExtensions = { ".mwm", ".sbc", ".resx", ".xml" };

private static bool IsDataFile(string path)
{
foreach (var ext in DataFileExtensions)
if (path.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}

private const bool Skip = false;

private readonly SteamDownloader _steamInternal;
private readonly Func<SteamDownloader> _steamFactory;
private SteamDownloader _steamInternal;
private readonly ILogger<GameManager> _log;

private readonly string _rootDir;

public GameManager(SteamDownloader steam, ILogger<GameManager> log)
public GameManager(Func<SteamDownloader> steamFactory, ILogger<GameManager> log)
{
_steamInternal = steam;
_steamFactory = steamFactory;
_log = log;
_rootDir = Path.GetFullPath("./");
}
Expand All @@ -49,7 +39,7 @@ public async Task<GameInstall> RestoreGame(Game game, string branch)
var installDir = Path.Combine(_rootDir, "game", game.ToString(), branch);
if (!Skip)
await RunWithRetry(steam => steam.InstallAppAsync(info.SteamDedicatedAppId, info.SteamDedicatedDepotId, branch, installDir,
path => path.StartsWith(BinariesDir) || IsDataFile(path), game.ToString()));
path => path.StartsWith(BinariesDir), game.ToString()));

return new GameInstall(this, _log, game, Path.Combine(installDir, ContentDir), Path.Combine(installDir, BinariesDir));
}
Expand Down Expand Up @@ -121,8 +111,7 @@ public async Task<string> RestoreMod(Game game, PublishedFileDetails details)
if (!Skip)
await RunWithRetry(steam => steam.InstallModAsync(info.SteamGameAppId, details.publishedfileid, installDir,
path => path.IndexOf("Data/Scripts", StringComparison.OrdinalIgnoreCase) >= 0
|| path.IndexOf("Data\\Scripts", StringComparison.OrdinalIgnoreCase) >= 0
|| IsDataFile(path),
|| path.IndexOf("Data\\Scripts", StringComparison.OrdinalIgnoreCase) >= 0,
$"{game}-{details.publishedfileid}-{details.title}"));
return installDir;
}
Expand All @@ -134,18 +123,40 @@ private async Task<T> RunWithRetry<T>(Func<SteamDownloader, Task<T>> action)
{
try
{
if (_steamInternal == null)
{
_steamInternal = _steamFactory();
await _steamInternal.LoginAsync();
}
return await action(_steamInternal);
}
catch
catch (Exception ex)
{
_log.LogInformation(ex, "Failed to run task");
if (attempt >= 5) throw;
await Task.Delay(TimeSpan.FromSeconds(10 * Math.Pow(2, attempt)));
// await Task.Delay(TimeSpan.FromSeconds(10 * Math.Pow(2, attempt)));
attempt++;
}
finally
{
if (_steamInternal is { IsLoggedIn: false })
{
try
{
await _steamInternal.LogoutAsync();
}
catch (Exception e)
{
_log.LogWarning(e, $"Failed to logout");
}

_steamInternal = null;
}
}
}
}

public Task StartAsync(CancellationToken cancellationToken) => RunWithRetry(steam => steam.LoginAsync());
public Task StartAsync(CancellationToken cancellationToken) => RunWithRetry(_ => Task.FromResult(0));

public Task StopAsync(CancellationToken cancellationToken) => RunWithRetry(async steam =>
{
Expand Down
3 changes: 2 additions & 1 deletion SchemaBuilder/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using SchemaBuilder.Schema;
using SchemaService.SteamUtils;
using SteamKit2;
using SteamKit2.Discovery;

namespace SchemaBuilder
{
Expand All @@ -14,7 +15,7 @@ public static async Task Main(string[] args)
using var host = new HostBuilder()
.ConfigureServices(svc =>
{
svc.AddSteamDownloader(SteamConfiguration.Create(x => { }));
svc.AddSteamDownloader(SteamConfiguration.Create(x => x.WithServerListProvider(new MemoryServerListProvider())));
svc.AddSingleton<GameManager>();
svc.AddHostedService<GameManager>();
svc.AddSingleton<SchemaGenerator>();
Expand Down
35 changes: 22 additions & 13 deletions SteamUtils/SteamDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ namespace SchemaService.SteamUtils
{
public static class SteamDownloaderFactory
{
public static void AddSteamDownloader(this IServiceCollection collection, SteamConfiguration config)
private class SteamDebugLogSetup
{
var categoryCleaner = new Regex("^[0-9a-f]+/");
collection.AddSingleton(svc =>
public SteamDebugLogSetup(ILoggerFactory logFactory)
{
var logFactory = svc.GetRequiredService<ILoggerFactory>();
var categoryCleaner = new Regex("^[0-9a-f]+/");
DebugLog.ClearListeners();
DebugLog.AddListener((category, msg) =>
{
Expand All @@ -40,10 +39,20 @@ public static void AddSteamDownloader(this IServiceCollection collection, SteamC
}
});
DebugLog.Enabled = true;
return new SteamClient(config);
}
}

public static void AddSteamDownloader(this IServiceCollection collection, SteamConfiguration config)
{
collection.AddSingleton<SteamDebugLogSetup>();
collection.AddSingleton(config);
collection.AddSingleton<Func<SteamDownloader>>(svc =>
{
var log = svc.GetRequiredService<ILoggerFactory>();
var cfg = svc.GetRequiredService<SteamConfiguration>();
svc.GetRequiredService<SteamDebugLogSetup>();
return () => new SteamDownloader(log, cfg);
});
collection.AddSingleton<CdnPool>();
collection.AddSingleton<SteamDownloader>();
}
}

Expand Down Expand Up @@ -72,20 +81,20 @@ public class SteamDownloader

private readonly ILogger<SteamDownloader> _log;

private bool IsLoggedIn => _loginDetails != null;
public bool IsLoggedIn => _loginDetails != null;
public CdnPool CdnPool { get; }

public SteamDownloader(ILogger<SteamDownloader> log, SteamClient client, CdnPool cdnPool)
public SteamDownloader(ILoggerFactory log, SteamConfiguration config)
{
_log = log;
_client = client;
_log = log.CreateLogger<SteamDownloader>();
_client = new SteamClient(config);
_user = _client.GetHandler<SteamUser>();
_apps = _client.GetHandler<SteamApps>();
_cloud = _client.GetHandler<SteamCloud>();
_content = _client.GetHandler<SteamContent>();
_unifiedMessages = _client.GetHandler<SteamUnifiedMessages>();
_publishedFiles = _unifiedMessages.CreateService<IPublishedFile>();
CdnPool = cdnPool;
CdnPool = new CdnPool(log.CreateLogger<CdnPool>(), _client);


_callbacks = new CallbackPump(_client);
Expand Down Expand Up @@ -193,7 +202,7 @@ public async Task<LoggedOnCallback> LoginAsync(LogOnDetails details = default)
.WaitForAsync(x => x is ConnectedCallback || x is DisconnectedCallback);

if (connectResult is DisconnectedCallback)
throw new Exception("Failed to connect to Steam.");
throw new Exception("Failed to connect to Steam");

if (details == null)
_user.LogOnAnonymous();
Expand Down

0 comments on commit 14a9c92

Please sign in to comment.