diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-11-22 18:36:31 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-11-22 18:36:31 -0600 |
| commit | 47490e366b5bc4b2a1679fba50655697afbe7137 (patch) | |
| tree | ae98bb4fb66d20e5fecd69267bcbb17d80c4986b /src/slskd/Program.cs | |
| parent | 2e073014a003fc4e972a9a2677fccd3d30074cd2 (diff) | |
| parent | 6ba7311d48b95ca75f49b3b28c1a8db810f87fe1 (diff) | |
| download | slskd-47490e366b5bc4b2a1679fba50655697afbe7137.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/axios-0.30.2
Diffstat (limited to 'src/slskd/Program.cs')
| -rw-r--r-- | src/slskd/Program.cs | 82 |
1 files changed, 78 insertions, 4 deletions
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0d879d0c..07d08fca 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,6 +23,8 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using System.IO; using System.Linq; using System.Net; @@ -236,6 +238,7 @@ namespace slskd private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + private static IDisposable DotNetRuntimeStats { get; set; } [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -590,7 +593,9 @@ namespace slskd new SoulseekClient(options: new SoulseekClientOptions( maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>()))); + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(), + maximumConcurrentSearches: 2, + raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can // access instance methods @@ -605,9 +610,12 @@ namespace slskd var connectionStringDictionary = new ConnectionStringDictionary(Database.List .Select(database => { + var caching = OptionsAtStartup.Flags.NoSqliteCacheSharing ? "Private" : "Shared"; + var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing + var connStr = OptionsAtStartup.Flags.Volatile - ? $"Data Source=file:{database}?mode=memory;Cache=shared;Pooling=True;" - : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache=shared;Pooling=True;"; + ? $"Data Source=file:{database}?mode=memory;Cache={caching};Pooling={pooling};" + : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache={caching};Pooling={pooling}"; return new KeyValuePair<Database, ConnectionString>(database, connStr); }) @@ -702,8 +710,10 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); + // note: don't dispose this (or let it be disposed) or some of the stats, like those related + // to the thread pool won't work + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddSystemMetrics(); - using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); @@ -1132,6 +1142,30 @@ namespace slskd } })) .CreateLogger(); + + if (OptionsAtStartup.Flags.LogUnobservedExceptions) + { + // log Exceptions raised on fired-and-forgotten tasks, which adds very little value but might help debug someday + TaskScheduler.UnobservedTaskException += (sender, e) => + { + Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + e.SetObserved(); + }; + } + + AppDomain.CurrentDomain.UnhandledException += (sender, e) => + { + var exception = e.ExceptionObject as Exception; + + if (e.IsTerminating) + { + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + } + else + { + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + } + }; } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) @@ -1178,6 +1212,7 @@ namespace slskd services.AddDbContextFactory<T>(options => { options.UseSqlite(connectionString); + options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { @@ -1185,11 +1220,50 @@ namespace slskd } }); + /* + instantiate the DbContext and make sure it is created + */ using var ctx = services .BuildServiceProvider() .GetRequiredService<IDbContextFactory<T>>() .CreateDbContext(); + Log.Debug("Ensuring {Contex} is created", typeof(T).Name); + ctx.Database.EnsureCreated(); + + /* + set (and validate) our desired PRAGMAs + + synchronous mode is also set upon every connection via SqliteConnectionOpenedInterceptor. + */ + ctx.Database.OpenConnection(); + var conn = ctx.Database.GetDbConnection(); + + Log.Debug("Setting PRAGMAs for {Contex}", typeof(T).Name); + using var initCommand = conn.CreateCommand(); + initCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=1; PRAGMA optimize;"; + initCommand.ExecuteNonQuery(); + + using var journalCmd = conn.CreateCommand(); + journalCmd.CommandText = "PRAGMA journal_mode;"; + var journalMode = journalCmd.ExecuteScalar()?.ToString(); + + if (!journalMode.Equals("WAL", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} journal_mode PRAGMA to WAL; performance may be reduced", typeof(T).Name); + } + + using var syncCmd = conn.CreateCommand(); + syncCmd.CommandText = "PRAGMA synchronous;"; + var sync = syncCmd.ExecuteScalar()?.ToString(); + + if (!sync.Equals("1", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} synchronous PRAGMA to 1; performance may be reduced", typeof(T).Name); + } + + Log.Debug("PRAGMAs for {Context}: journal_mode={JournalMode}, synchronous={Synchronous}", typeof(T).Name, journalMode, sync); + return services; } catch (Exception ex) |
