ServiceCollectionExtensions.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Jellyfin.Database.Implementations;
  7. using Jellyfin.Database.Implementations.DbConfiguration;
  8. using Jellyfin.Database.Implementations.Locking;
  9. using Jellyfin.Database.Providers.Sqlite;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Controller.Configuration;
  12. using Microsoft.EntityFrameworkCore;
  13. using Microsoft.Extensions.Configuration;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using JellyfinDbProviderFactory = System.Func<System.IServiceProvider, Jellyfin.Database.Implementations.IJellyfinDatabaseProvider>;
  16. namespace Jellyfin.Server.Implementations.Extensions;
  17. /// <summary>
  18. /// Extensions for the <see cref="IServiceCollection"/> interface.
  19. /// </summary>
  20. public static class ServiceCollectionExtensions
  21. {
  22. private static IEnumerable<Type> DatabaseProviderTypes()
  23. {
  24. yield return typeof(SqliteDatabaseProvider);
  25. }
  26. private static IDictionary<string, JellyfinDbProviderFactory> GetSupportedDbProviders()
  27. {
  28. var items = new Dictionary<string, JellyfinDbProviderFactory>(StringComparer.InvariantCultureIgnoreCase);
  29. foreach (var providerType in DatabaseProviderTypes())
  30. {
  31. var keyAttribute = providerType.GetCustomAttribute<JellyfinDatabaseProviderKeyAttribute>();
  32. if (keyAttribute is null || string.IsNullOrWhiteSpace(keyAttribute.DatabaseProviderKey))
  33. {
  34. continue;
  35. }
  36. var provider = providerType;
  37. items[keyAttribute.DatabaseProviderKey] = (services) => (IJellyfinDatabaseProvider)ActivatorUtilities.CreateInstance(services, providerType);
  38. }
  39. return items;
  40. }
  41. private static JellyfinDbProviderFactory? LoadDatabasePlugin(CustomDatabaseOptions customProviderOptions, IApplicationPaths applicationPaths)
  42. {
  43. var plugin = Directory.EnumerateDirectories(applicationPaths.PluginsPath)
  44. .Where(e => Path.GetFileName(e)!.StartsWith(customProviderOptions.PluginName, StringComparison.OrdinalIgnoreCase))
  45. .Order()
  46. .FirstOrDefault()
  47. ?? throw new InvalidOperationException($"The requested custom database plugin with the name '{customProviderOptions.PluginName}' could not been found in '{applicationPaths.PluginsPath}'");
  48. var dbProviderAssembly = Path.Combine(plugin, Path.ChangeExtension(customProviderOptions.PluginAssembly, "dll"));
  49. if (!File.Exists(dbProviderAssembly))
  50. {
  51. throw new InvalidOperationException($"Could not find the requested assembly at '{dbProviderAssembly}'");
  52. }
  53. // we have to load the assembly without proxy to ensure maximum performance for this.
  54. var assembly = Assembly.LoadFrom(dbProviderAssembly);
  55. var dbProviderType = assembly.GetExportedTypes().FirstOrDefault(f => f.IsAssignableTo(typeof(IJellyfinDatabaseProvider)))
  56. ?? throw new InvalidOperationException($"Could not find any type implementing the '{nameof(IJellyfinDatabaseProvider)}' interface.");
  57. return (services) => (IJellyfinDatabaseProvider)ActivatorUtilities.CreateInstance(services, dbProviderType);
  58. }
  59. /// <summary>
  60. /// Adds the <see cref="IDbContextFactory{TContext}"/> interface to the service collection with second level caching enabled.
  61. /// </summary>
  62. /// <param name="serviceCollection">An instance of the <see cref="IServiceCollection"/> interface.</param>
  63. /// <param name="configurationManager">The server configuration manager.</param>
  64. /// <param name="configuration">The startup Configuration.</param>
  65. /// <returns>The updated service collection.</returns>
  66. public static IServiceCollection AddJellyfinDbContext(
  67. this IServiceCollection serviceCollection,
  68. IServerConfigurationManager configurationManager,
  69. IConfiguration configuration)
  70. {
  71. var efCoreConfiguration = configurationManager.GetConfiguration<DatabaseConfigurationOptions>("database");
  72. JellyfinDbProviderFactory? providerFactory = null;
  73. if (efCoreConfiguration?.DatabaseType is null)
  74. {
  75. var cmdMigrationArgument = configuration.GetValue<string>("migration-provider");
  76. if (!string.IsNullOrWhiteSpace(cmdMigrationArgument))
  77. {
  78. efCoreConfiguration = new DatabaseConfigurationOptions()
  79. {
  80. DatabaseType = cmdMigrationArgument,
  81. };
  82. }
  83. else
  84. {
  85. // when nothing is setup via new Database configuration, fallback to SQLite with default settings.
  86. efCoreConfiguration = new DatabaseConfigurationOptions()
  87. {
  88. DatabaseType = "Jellyfin-SQLite",
  89. LockingBehavior = DatabaseLockingBehaviorTypes.NoLock
  90. };
  91. configurationManager.SaveConfiguration("database", efCoreConfiguration);
  92. }
  93. }
  94. if (efCoreConfiguration.DatabaseType.Equals("PLUGIN_PROVIDER", StringComparison.OrdinalIgnoreCase))
  95. {
  96. if (efCoreConfiguration.CustomProviderOptions is null)
  97. {
  98. throw new InvalidOperationException("The custom database provider must declare the custom provider options to work");
  99. }
  100. providerFactory = LoadDatabasePlugin(efCoreConfiguration.CustomProviderOptions, configurationManager.ApplicationPaths);
  101. }
  102. else
  103. {
  104. var providers = GetSupportedDbProviders();
  105. if (!providers.TryGetValue(efCoreConfiguration.DatabaseType.ToUpperInvariant(), out providerFactory!))
  106. {
  107. throw new InvalidOperationException($"Jellyfin cannot find the database provider of type '{efCoreConfiguration.DatabaseType}'. Supported types are {string.Join(", ", providers.Keys)}");
  108. }
  109. }
  110. serviceCollection.AddSingleton<IJellyfinDatabaseProvider>(providerFactory!);
  111. switch (efCoreConfiguration.LockingBehavior)
  112. {
  113. case DatabaseLockingBehaviorTypes.NoLock:
  114. serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, NoLockBehavior>();
  115. break;
  116. case DatabaseLockingBehaviorTypes.Pessimistic:
  117. serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, PessimisticLockBehavior>();
  118. break;
  119. case DatabaseLockingBehaviorTypes.Optimistic:
  120. serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, OptimisticLockBehavior>();
  121. break;
  122. }
  123. serviceCollection.AddPooledDbContextFactory<JellyfinDbContext>((serviceProvider, opt) =>
  124. {
  125. var provider = serviceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  126. provider.Initialise(opt);
  127. var lockingBehavior = serviceProvider.GetRequiredService<IEntityFrameworkCoreLockingBehavior>();
  128. lockingBehavior.Initialise(opt);
  129. });
  130. return serviceCollection;
  131. }
  132. }