-
-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathApp.axaml.cs
1096 lines (946 loc) · 37.9 KB
/
App.axaml.cs
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Input.Platform;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Platform.Storage;
using Avalonia.Styling;
using Avalonia.Threading;
using FluentAvalonia.Interop;
using FluentAvalonia.UI.Controls;
using MessagePipe;
using MessagePipe.Interprocess.Workers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Config;
using NLog.Extensions.Logging;
using NLog.Targets;
using Octokit;
using Polly;
using Polly.Contrib.WaitAndRetry;
using Polly.Extensions.Http;
using Polly.Timeout;
using Refit;
using Sentry;
using StabilityMatrix.Avalonia.Behaviors;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Progress;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Core.Api;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Converters.Json;
using StabilityMatrix.Core.Database;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Helper.Analytics;
using StabilityMatrix.Core.Models.Api;
using StabilityMatrix.Core.Models.Configs;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Settings;
using StabilityMatrix.Core.Services;
using StabilityMatrix.Core.Updater;
using Application = Avalonia.Application;
using Logger = NLog.Logger;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
#if DEBUG
using StabilityMatrix.Avalonia.Diagnostics.LogViewer;
using StabilityMatrix.Avalonia.Diagnostics.LogViewer.Extensions;
#endif
namespace StabilityMatrix.Avalonia;
public sealed class App : Application
{
private static readonly Lazy<Logger> LoggerLazy = new(LogManager.GetCurrentClassLogger);
private static Logger Logger => LoggerLazy.Value;
private readonly SemaphoreSlim onExitSemaphore = new(1, 1);
/// <summary>
/// True if <see cref="OnShutdownRequested"/> has started async dispose of services.
/// </summary>
private bool isAsyncDisposeStarted;
/// <summary>
/// True if <see cref="OnShutdownRequested"/> has completed async dispose of services.
/// </summary>
private bool isAsyncDisposeComplete;
private bool isOnExitComplete;
private ServiceProvider? serviceProvider;
[NotNull]
public static Visual? VisualRoot { get; internal set; }
public static TopLevel TopLevel => TopLevel.GetTopLevel(VisualRoot).Unwrap();
public static IStorageProvider StorageProvider => TopLevel.StorageProvider;
public static IClipboard? Clipboard => TopLevel.Clipboard;
// ReSharper disable once MemberCanBePrivate.Global
[NotNull]
public static IConfiguration? Config { get; private set; }
#if DEBUG
// ReSharper disable twice LocalizableElement
// ReSharper disable once ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
public static string LykosAuthApiBaseUrl => Config?["LykosAuthApiBaseUrl"] ?? "https://auth.lykos.ai";
#else
public const string LykosAuthApiBaseUrl = "https://auth.lykos.ai";
#endif
#if DEBUG
// ReSharper disable twice LocalizableElement
// ReSharper disable once ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
public static string LykosAnalyticsApiBaseUrl =>
Config?["LykosAnalyticsApiBaseUrl"] ?? "https://analytics.lykos.ai";
#else
public const string LykosAnalyticsApiBaseUrl = "https://analytics.lykos.ai";
#endif
// ReSharper disable once MemberCanBePrivate.Global
public IClassicDesktopStyleApplicationLifetime? DesktopLifetime =>
ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
public static new App? Current => (App?)Application.Current;
[NotNull]
public static IServiceProvider? Services =>
Design.IsDesignMode ? DesignData.DesignData.Services : Current?.serviceProvider;
internal static bool IsHeadlessMode =>
TopLevel.TryGetPlatformHandle()?.HandleDescriptor is null or "STUB";
/// <summary>
/// Called before <see cref="Services"/> is built.
/// Can be used by UI tests to override services.
/// </summary>
internal static event EventHandler<IServiceCollection>? BeforeBuildServiceProvider;
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
SetFontFamily(GetPlatformDefaultFontFamily());
// Set design theme
if (Design.IsDesignMode)
{
RequestedThemeVariant = ThemeVariant.Dark;
}
}
public override void OnFrameworkInitializationCompleted()
{
// Remove DataAnnotations validation plugin since we're using INotifyDataErrorInfo from MvvmToolkit
var dataValidationPluginsToRemove = BindingPlugins
.DataValidators.OfType<DataAnnotationsValidationPlugin>()
.ToArray();
foreach (var plugin in dataValidationPluginsToRemove)
{
BindingPlugins.DataValidators.Remove(plugin);
}
base.OnFrameworkInitializationCompleted();
if (Design.IsDesignMode)
{
DesignData.DesignData.Initialize();
// serviceProvider = (ServiceProvider?) DesignData.DesignData.Services;
}
else
{
ConfigureServiceProvider();
}
if (DesktopLifetime is not null)
{
DesktopLifetime.ShutdownMode = ShutdownMode.OnExplicitShutdown;
Setup();
// First time setup if needed
var settingsManager = Services.GetRequiredService<ISettingsManager>();
if (!settingsManager.IsEulaAccepted())
{
var setupWindow = Services.GetRequiredService<FirstLaunchSetupWindow>();
var setupViewModel = Services.GetRequiredService<FirstLaunchSetupViewModel>();
setupWindow.DataContext = setupViewModel;
setupWindow.ShowAsDialog = true;
setupWindow.ShowActivated = true;
setupWindow.ShowAsyncCts = new CancellationTokenSource();
setupWindow.ExtendClientAreaChromeHints = Program.Args.NoWindowChromeEffects
? ExtendClientAreaChromeHints.NoChrome
: ExtendClientAreaChromeHints.PreferSystemChrome;
DesktopLifetime.MainWindow = setupWindow;
setupWindow.ShowAsyncCts.Token.Register(() =>
{
if (setupWindow.Result == ContentDialogResult.Primary)
{
settingsManager.SetEulaAccepted();
ShowMainWindow();
DesktopLifetime.MainWindow.Show();
}
else
{
Shutdown();
}
});
}
else
{
ShowMainWindow();
}
}
}
/// <summary>
/// Set the default font family for the application.
/// </summary>
private void SetFontFamily(FontFamily fontFamily)
{
Resources["ContentControlThemeFontFamily"] = fontFamily;
}
/// <summary>
/// Get the default font family for the current platform and language.
/// </summary>
public FontFamily GetPlatformDefaultFontFamily()
{
try
{
var fonts = new List<string>();
if (Cultures.Current?.Name == "ja-JP")
{
return Resources["NotoSansJP"] as FontFamily
?? throw new ApplicationException("Font NotoSansJP not found");
}
if (Compat.IsWindows)
{
fonts.Add(OSVersionHelper.IsWindows11() ? "Segoe UI Variable Text" : "Segoe UI");
}
else if (Compat.IsMacOS)
{
// Use Segoe fonts if installed, but we can't distribute them
fonts.Add("Segoe UI Variable");
fonts.Add("Segoe UI");
fonts.Add("San Francisco");
fonts.Add("Helvetica Neue");
fonts.Add("Helvetica");
}
else
{
return FontFamily.Default;
}
return new FontFamily(string.Join(",", fonts));
}
catch (Exception e)
{
Logger.Error(e);
return FontFamily.Default;
}
}
/// <summary>
/// Setup tasks to be run shortly before any window is shown
/// </summary>
private void Setup()
{
using var _ = CodeTimer.StartNew();
// Setup uri handler for `stabilitymatrix://` protocol
Program.UriHandler.RegisterUriScheme();
// Setup activation protocol handlers (uri handler on macOS)
if (Compat.IsMacOS && this.TryGetFeature<IActivatableLifetime>() is { } activatableLifetime)
{
Logger.Debug("ActivatableLifetime available, setting up activation protocol handlers");
activatableLifetime.Activated += OnActivated;
}
}
private void ShowMainWindow()
{
if (DesktopLifetime is null)
return;
var mainWindow = Services.GetRequiredService<MainWindow>();
VisualRoot = mainWindow;
DesktopLifetime.MainWindow = mainWindow;
DesktopLifetime.Exit += OnApplicationLifetimeExit;
DesktopLifetime.ShutdownRequested += OnShutdownRequested;
AppDomain.CurrentDomain.ProcessExit += OnExit;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
// Since we're manually shutting down NLog in OnExit
LogManager.AutoShutdown = false;
}
[MemberNotNull(nameof(serviceProvider))]
private void ConfigureServiceProvider()
{
var services = ConfigureServices();
BeforeBuildServiceProvider?.Invoke(null, services);
serviceProvider = services.BuildServiceProvider();
var settingsManager = Services.GetRequiredService<ISettingsManager>();
if (Program.Args.DataDirectoryOverride is not null)
{
var normalizedDataDirPath = Path.GetFullPath(Program.Args.DataDirectoryOverride);
if (Compat.IsWindows)
{
// ReSharper disable twice LocalizableElement
normalizedDataDirPath = normalizedDataDirPath.Replace("\\\\", "\\");
}
settingsManager.SetLibraryDirOverride(normalizedDataDirPath);
}
if (settingsManager.TryFindLibrary())
{
Cultures.SetSupportedCultureOrDefault(
settingsManager.Settings.Language,
settingsManager.Settings.NumberFormatMode
);
}
else
{
Cultures.TrySetSupportedCulture(Settings.GetDefaultCulture());
}
Services.GetRequiredService<ProgressManagerViewModel>().StartEventListener();
}
internal static void ConfigurePageViewModels(IServiceCollection services)
{
services.AddSingleton<MainWindowViewModel>(
provider =>
new MainWindowViewModel(
provider.GetRequiredService<ISettingsManager>(),
provider.GetRequiredService<IDiscordRichPresenceService>(),
provider.GetRequiredService<ServiceManager<ViewModelBase>>(),
provider.GetRequiredService<ITrackedDownloadService>(),
provider.GetRequiredService<IModelIndexService>(),
provider.GetRequiredService<Lazy<IModelDownloadLinkHandler>>(),
provider.GetRequiredService<INotificationService>(),
provider.GetRequiredService<IAnalyticsHelper>(),
provider.GetRequiredService<IUpdateHelper>()
)
{
Pages =
{
provider.GetRequiredService<PackageManagerViewModel>(),
provider.GetRequiredService<InferenceViewModel>(),
provider.GetRequiredService<CheckpointsPageViewModel>(),
provider.GetRequiredService<CheckpointBrowserViewModel>(),
provider.GetRequiredService<OutputsPageViewModel>(),
provider.GetRequiredService<WorkflowsPageViewModel>()
},
FooterPages = { provider.GetRequiredService<SettingsViewModel>() }
}
);
}
internal static IServiceCollection ConfigureServices()
{
var services = new ServiceCollection();
services.AddMemoryCache();
services.AddLazyInstance();
// Named pipe interprocess communication on Windows and Linux for uri handling
if (Compat.IsWindows || Compat.IsLinux)
{
services.AddMessagePipe().AddNamedPipeInterprocess("StabilityMatrix");
}
else
{
// Use activation events on macOS, so just in-memory message pipe
services.AddMessagePipe().AddInMemoryDistributedMessageBroker();
}
// Register services by attributes
services.AddServicesByAttributes();
ConfigurePageViewModels(services);
services.AddServiceManagerWithCurrentCollectionServices<ViewModelBase>(
s => s.ServiceType.GetCustomAttributes<ManagedServiceAttribute>().Any()
);
// Other services
services.AddSingleton<ITrackedDownloadService, TrackedDownloadService>();
services.AddSingleton<IDisposable>(
provider => (IDisposable)provider.GetRequiredService<ITrackedDownloadService>()
);
// Rich presence
services.AddSingleton<IDiscordRichPresenceService, DiscordRichPresenceService>();
services.AddSingleton<IDisposable>(
provider => provider.GetRequiredService<IDiscordRichPresenceService>()
);
Config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
services.Configure<DebugOptions>(Config.GetSection(nameof(DebugOptions)));
if (Compat.IsWindows)
{
services.AddSingleton<IPrerequisiteHelper, WindowsPrerequisiteHelper>();
}
else if (Compat.IsLinux || Compat.IsMacOS)
{
services.AddSingleton<IPrerequisiteHelper, UnixPrerequisiteHelper>();
}
if (!Design.IsDesignMode)
{
services.AddSingleton<ILiteDbContext, LiteDbContext>();
services.AddSingleton<IDisposable>(p => p.GetRequiredService<ILiteDbContext>());
}
services.AddTransient<IGitHubClient, GitHubClient>(_ =>
{
var client = new GitHubClient(new ProductHeaderValue("StabilityMatrix"));
// var githubApiKey = Config["GithubApiKey"];
// if (string.IsNullOrWhiteSpace(githubApiKey))
// return client;
//
// client.Credentials = new Credentials(
// ""
// );
return client;
});
// Configure Refit and Polly
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
jsonSerializerOptions.Converters.Add(new ObjectToInferredTypesConverter());
jsonSerializerOptions.Converters.Add(new DefaultUnknownEnumConverter<CivitFileType>());
jsonSerializerOptions.Converters.Add(new DefaultUnknownEnumConverter<CivitModelType>());
jsonSerializerOptions.Converters.Add(new DefaultUnknownEnumConverter<CivitModelFormat>());
jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
jsonSerializerOptions.Converters.Add(new AnalyticsRequestConverter());
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
var defaultRefitSettings = new RefitSettings
{
ContentSerializer = new SystemTextJsonContentSerializer(jsonSerializerOptions)
};
// Refit settings for IApiFactory
var defaultSystemTextJsonSettings = SystemTextJsonContentSerializer.GetDefaultJsonSerializerOptions();
defaultSystemTextJsonSettings.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
var apiFactoryRefitSettings = new RefitSettings
{
ContentSerializer = new SystemTextJsonContentSerializer(defaultSystemTextJsonSettings),
};
// HTTP Policies
var retryStatusCodes = new[]
{
HttpStatusCode.RequestTimeout, // 408
HttpStatusCode.InternalServerError, // 500
HttpStatusCode.BadGateway, // 502
HttpStatusCode.ServiceUnavailable, // 503
HttpStatusCode.GatewayTimeout // 504
};
// Default retry policy: ~30s max
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.OrResult(r => retryStatusCodes.Contains(r.StatusCode))
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(750),
retryCount: 6
),
onRetry: (result, timeSpan, retryCount, _) =>
{
if (retryCount > 3)
{
Logger.Info(
"Retry attempt {Count}/{Max} after {Seconds:N2}s due to {Exception}",
retryCount,
6,
timeSpan.TotalSeconds,
result.Exception?.ToString()
);
}
}
)
// 10s timeout for each attempt
.WrapAsync(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(60)));
// Longer retry policy: ~60s max
var retryPolicyLonger = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.OrResult(r => retryStatusCodes.Contains(r.StatusCode))
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(1000),
retryCount: 7
),
onRetry: (result, timeSpan, retryCount, _) =>
{
if (retryCount > 4)
{
Logger.Info(
"Retry attempt {Count}/{Max} after {Seconds:N2}s due to {Exception}",
retryCount,
7,
timeSpan.TotalSeconds,
result.Exception?.ToString()
);
}
}
)
// 30s timeout for each attempt
.WrapAsync(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(120)));
// Shorter local retry policy: ~5s total
var localRetryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.OrResult(r => retryStatusCodes.Contains(r.StatusCode))
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(320),
retryCount: 5
)
)
// 3s timeout for each attempt
.WrapAsync(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(3)));
// named client for update
services.AddHttpClient("UpdateClient").AddPolicyHandler(retryPolicy);
// Add Refit clients
// Note: HttpClient.Timeout should be high to allow Polly to handle timeouts instead
services
.AddRefitClient<ICivitApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://civitai.com");
c.Timeout = TimeSpan.FromHours(1);
})
.AddPolicyHandler(retryPolicyLonger);
services
.AddRefitClient<ICivitTRPCApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://civitai.com");
c.Timeout = TimeSpan.FromHours(1);
})
.AddPolicyHandler(retryPolicyLonger);
services
.AddRefitClient<IPyPiApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://pypi.org");
c.Timeout = TimeSpan.FromHours(1);
})
.AddPolicyHandler(retryPolicyLonger);
services
.AddRefitClient<ILykosAuthApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri(LykosAuthApiBaseUrl);
c.Timeout = TimeSpan.FromHours(1);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false })
.AddPolicyHandler(retryPolicy)
.AddHttpMessageHandler(
serviceProvider =>
new TokenAuthHeaderHandler(serviceProvider.GetRequiredService<LykosAuthTokenProvider>())
);
services
.AddRefitClient<ILykosAnalyticsApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri(LykosAnalyticsApiBaseUrl);
c.Timeout = TimeSpan.FromMinutes(5);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false })
.AddPolicyHandler(retryPolicy);
services
.AddRefitClient<IOpenArtApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://openart.ai/api/public/workflows");
c.Timeout = TimeSpan.FromHours(1);
})
.AddPolicyHandler(retryPolicy);
// Add Refit client managers
services.AddHttpClient("A3Client").AddPolicyHandler(localRetryPolicy);
services
.AddHttpClient("DontFollowRedirects")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false })
.AddPolicyHandler(retryPolicy);
// Add Refit client factory
services.AddSingleton<IApiFactory, ApiFactory>(
provider =>
new ApiFactory(provider.GetRequiredService<IHttpClientFactory>())
{
RefitSettings = apiFactoryRefitSettings,
}
);
ConditionalAddLogViewer(services);
var logConfig = ConfigureLogging();
// Add logging
services.AddLogging(builder =>
{
builder.ClearProviders();
builder
.AddFilter("Microsoft.Extensions.Http", LogLevel.Warning)
.AddFilter("Microsoft.Extensions.Http.DefaultHttpClientFactory", LogLevel.Warning)
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning);
builder.SetMinimumLevel(LogLevel.Trace);
#if DEBUG
builder.AddNLog(
logConfig,
new NLogProviderOptions
{
IgnoreEmptyEventId = false,
CaptureEventId = EventIdCaptureType.Legacy
}
);
#else
builder.AddNLog(logConfig);
#endif
});
return services;
}
/// <summary>
/// Requests shutdown of the Current Application.
/// </summary>
/// <remarks>This returns asynchronously *without waiting* for Shutdown</remarks>
/// <param name="exitCode">Exit code for the application.</param>
/// <exception cref="NullReferenceException">If Application.Current is null</exception>
public static void Shutdown(int exitCode = 0)
{
if (Current is null)
throw new NullReferenceException("Current Application was null when Shutdown called");
if (Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
{
try
{
var result = lifetime.TryShutdown(exitCode);
Debug.WriteLine($"Shutdown: {result}");
if (result)
{
Environment.Exit(exitCode);
}
}
catch (InvalidOperationException)
{
// Ignore in case already shutting down
}
}
else
{
Environment.Exit(exitCode);
}
}
private void OnShutdownRequested(object? sender, ShutdownRequestedEventArgs e)
{
Logger.Trace("Start OnShutdownRequested");
if (e.Cancel)
return;
// Skip if Async Dispose already started, shutdown will be handled by it
if (isAsyncDisposeStarted)
return;
// Cancel shutdown for now to dispose
e.Cancel = true;
isAsyncDisposeStarted = true;
Logger.Trace("OnShutdownRequested Canceled: Disposing IAsyncDisposables");
Dispatcher
.UIThread.InvokeAsync(async () =>
{
if (serviceProvider is null)
{
Logger.Warn("Service Provider is null, skipping Async Dispose");
return;
}
var settingsManager = Services.GetRequiredService<ISettingsManager>();
Logger.Debug("Disposing App Services");
try
{
OnServiceProviderDisposing(serviceProvider);
await serviceProvider.DisposeAsync();
isAsyncDisposeComplete = true;
}
catch (Exception disposeEx)
{
Logger.Error(disposeEx, "Failed to dispose ServerProvider");
}
Logger.Debug("Flushing SettingsManager");
try
{
var cts = new CancellationTokenSource(5000);
await settingsManager.FlushAsync(cts.Token);
}
catch (OperationCanceledException)
{
Logger.Error("Timeout Flushing SettingsManager");
}
})
.ContinueWith(_ =>
{
// Shutdown again
Logger.Debug("Finished async shutdown tasks, shutting down");
if (Dispatcher.UIThread.SupportsRunLoops)
{
Dispatcher.UIThread.Invoke(() => Shutdown());
}
Environment.Exit(0);
})
.SafeFireAndForget();
}
private void OnApplicationLifetimeExit(object? sender, ControlledApplicationLifetimeExitEventArgs args)
{
Logger.Debug("OnApplicationLifetimeExit: {@Args}", args);
OnExit(sender, args);
}
private void OnExit(object? sender, EventArgs _)
{
// Skip if already run
if (isOnExitComplete)
{
return;
}
// Skip if another OnExit is running
if (!onExitSemaphore.Wait(0))
{
// Block until the other OnExit is done to delay shutdown
onExitSemaphore.Wait();
onExitSemaphore.Release();
return;
}
try
{
if (serviceProvider is null)
{
Logger.Warn("Service Provider is null, skipping OnExit");
return;
}
// Dispose services only if async dispose has not completed
if (!isAsyncDisposeComplete)
{
Logger.Debug("OnExit: Disposing App Services");
OnServiceProviderDisposing(serviceProvider);
serviceProvider.Dispose();
}
Logger.Debug("OnExit: Finished");
}
finally
{
isOnExitComplete = true;
onExitSemaphore.Release();
LogManager.Shutdown();
}
}
private static void OnServiceProviderDisposing(ServiceProvider serviceProvider)
{
// Force materialize SharedFolders so its DisposeAsync is called
// since it's not used by anything at the moment
_ = serviceProvider.GetService<ISharedFolders>();
// Remove the NamedPipeWorker disposable if present
// causes crash on avalonia dispatcher thread for some reason
// https://github.com/dotnet/runtime/issues/39902
var disposables = serviceProvider.GetDisposables();
disposables.RemoveAll(d => d is NamedPipeWorker);
Logger.Trace("Disposing {Count} Disposables", disposables.Count);
}
private static void TaskScheduler_UnobservedTaskException(
object? sender,
UnobservedTaskExceptionEventArgs e
)
{
if (e.Observed || e.Exception is not Exception unobservedEx)
return;
try
{
var notificationService = Services.GetRequiredService<INotificationService>();
Dispatcher.UIThread.Invoke(() =>
{
var originException = unobservedEx.InnerException ?? unobservedEx;
notificationService.ShowPersistent(
$"Unobserved Task Exception - {originException.GetType().Name}",
originException.Message
);
});
// Consider the exception observed if we were able to show a notification
e.SetObserved();
}
catch (Exception ex)
{
Logger.Error(ex, "Failed to show Unobserved Task Exception notification");
}
}
private static async void OnActivated(object? sender, ActivatedEventArgs args)
{
if (args is not ProtocolActivatedEventArgs protocolArgs)
{
Logger.Warn("Activated with unknown args: {Args}", args);
return;
}
if (protocolArgs.Kind is ActivationKind.OpenUri)
{
Logger.Info("Activated with Protocol OpenUri: {Uri}", protocolArgs.Uri);
// Ensure the uri scheme is our custom scheme
if (
!protocolArgs.Uri.Scheme.Equals(Program.UriHandler.Scheme, StringComparison.OrdinalIgnoreCase)
)
{
Logger.Warn("Unknown scheme for OpenUri: {Uri}", protocolArgs.Uri);
return;
}
var publisher = Services.GetRequiredService<IDistributedPublisher<string, Uri>>();
await publisher.PublishAsync(UriHandler.IpcKeySend, protocolArgs.Uri);
}
}
private static LoggingConfiguration ConfigureLogging()
{
var setupBuilder = LogManager.Setup();
ConditionalAddLogViewerNLog(setupBuilder);
setupBuilder.LoadConfiguration(builder =>
{
// Filter some sources to be warn levels or above only
builder.ForLogger("System.*").WriteToNil(NLog.LogLevel.Warn);
builder.ForLogger("Microsoft.*").WriteToNil(NLog.LogLevel.Warn);
builder.ForLogger("Microsoft.Extensions.Http.*").WriteToNil(NLog.LogLevel.Warn);
// Disable some trace logging by default, unless overriden by app settings
var typesToDisableTrace = new[]
{
typeof(ConsoleViewModel),
typeof(LoadableViewModelBase),
typeof(TextEditorCompletionBehavior)
};
foreach (var type in typesToDisableTrace)
{
// Skip if app settings already set a level for this type
if (
Config[$"Logging:LogLevel:{type.FullName}"] is { } levelStr
&& Enum.TryParse<LogLevel>(levelStr, true, out _)
)
{
continue;
}
// Set minimum level to Debug for these types
builder.ForLogger(type.FullName).WriteToNil(NLog.LogLevel.Debug);
}
// Debug console logging
/*if (Debugger.IsAttached)
{
builder
.ForLogger()
.FilterMinLevel(NLog.LogLevel.Trace)
.WriteTo(
new DebuggerTarget("debugger")
{
Layout = "[${level:uppercase=true}]\t${logger:shortName=true}\t${message}"
}
)
.WithAsync();
}*/
// Console logging
builder
.ForLogger()
.FilterMinLevel(NLog.LogLevel.Trace)
.WriteTo(
new ConsoleTarget("console")
{
Layout = "[${level:uppercase=true}]\t${logger:shortName=true}\t${message}",
DetectConsoleAvailable = true
}
)
.WithAsync();
// File logging
builder
.ForLogger()
.FilterMinLevel(NLog.LogLevel.Debug)
.WriteTo(
new FileTarget("logfile")
{
Layout =
"${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}",
FileName = "${specialfolder:folder=ApplicationData}/StabilityMatrix/Logs/app.log",
ArchiveOldFileOnStartup = true,
ArchiveFileName =
"${specialfolder:folder=ApplicationData}/StabilityMatrix/Logs/app.{#}.log",
ArchiveDateFormat = "yyyy-MM-dd HH_mm_ss",
ArchiveNumbering = ArchiveNumberingMode.Date,
MaxArchiveFiles = 9
}
)
.WithAsync();
#if DEBUG
// LogViewer target when debug mode
builder
.ForLogger()
.FilterMinLevel(NLog.LogLevel.Trace)
.WriteTo(new DataStoreLoggerTarget { Layout = "${message}" });
#endif
});
// Sentry
if (SentrySdk.IsEnabled)
{
LogManager.Configuration.AddSentry(o =>
{
o.InitializeSdk = false;
o.Layout = "${message}";