| | | 1 | | using Microsoft.Extensions.Configuration; |
| | | 2 | | using Newtonsoft.Json; |
| | | 3 | | using Newtonsoft.Json.Linq; |
| | | 4 | | |
| | | 5 | | namespace Services.EmailRoutingServices; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Путь к overlay-файлу настроек (writable в Docker). Основной appsettings.json в образе read-only. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class AppRuntimeSettingsPaths |
| | | 11 | | { |
| | | 12 | | public const string DefaultRelativePath = "data/appsettings.runtime.json"; |
| | | 13 | | public const string ConfigKey = "RuntimeSettings:FilePath"; |
| | | 14 | | public const string EnvVar = "ST2_RUNTIME_SETTINGS_PATH"; |
| | | 15 | | |
| | | 16 | | public static string ResolvePath(string contentRootPath, IConfiguration configuration) |
| | | 17 | | { |
| | 4 | 18 | | var configured = configuration[ConfigKey]; |
| | 4 | 19 | | if (string.IsNullOrWhiteSpace(configured)) |
| | 4 | 20 | | configured = Environment.GetEnvironmentVariable(EnvVar); |
| | | 21 | | |
| | 4 | 22 | | if (!string.IsNullOrWhiteSpace(configured)) |
| | | 23 | | { |
| | 0 | 24 | | return Path.IsPathRooted(configured) |
| | 0 | 25 | | ? configured |
| | 0 | 26 | | : Path.Combine(contentRootPath, configured); |
| | | 27 | | } |
| | | 28 | | |
| | 4 | 29 | | return Path.Combine(contentRootPath, DefaultRelativePath); |
| | | 30 | | } |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | public static class AppRuntimeSettingsWriter |
| | | 34 | | { |
| | | 35 | | public static async Task SaveAsync( |
| | | 36 | | string contentRootPath, |
| | | 37 | | IConfiguration configuration, |
| | | 38 | | Action<JObject> mutate, |
| | | 39 | | CancellationToken cancellationToken = default) |
| | | 40 | | { |
| | | 41 | | var path = AppRuntimeSettingsPaths.ResolvePath(contentRootPath, configuration); |
| | | 42 | | var directory = Path.GetDirectoryName(path); |
| | | 43 | | if (!string.IsNullOrEmpty(directory)) |
| | | 44 | | Directory.CreateDirectory(directory); |
| | | 45 | | |
| | | 46 | | JObject root; |
| | | 47 | | if (File.Exists(path)) |
| | | 48 | | root = JObject.Parse(await File.ReadAllTextAsync(path, cancellationToken)); |
| | | 49 | | else |
| | | 50 | | root = new JObject(); |
| | | 51 | | |
| | | 52 | | mutate(root); |
| | | 53 | | |
| | | 54 | | await File.WriteAllTextAsync(path, root.ToString(Formatting.Indented), cancellationToken); |
| | | 55 | | } |
| | | 56 | | } |