diff --git a/CHANGELOG.md b/CHANGELOG.md index b359d92cc..da2ef3289 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ # Changelog +## [1.0.8-rc37] - unstable + +* [PostIt] Telemetry + ## [1.0.8-rc36] - unstable ### Added diff --git a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs index ddefc4cf3..c2288fd0c 100644 --- a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs +++ b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs @@ -87,6 +87,7 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService { Cancel(epoch); Log.Error("PostIt.Chat", ex.ToString()); + api.QueueExceptionReport(ex, "PostIt.Android.Chat"); try { await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error)) diff --git a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs index c38d46c0f..7adf97c54 100644 --- a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs +++ b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs @@ -34,8 +34,11 @@ public sealed class ChatBootReceiver : BroadcastReceiver { Log.Error("PostIt.Chat", "Boot restart rejected: " + ex); if (api is not null) + { + api.QueueExceptionReport(ex, "PostIt.Android.Chat"); AndroidSettings.ReportError(api.Settings, "Android a refuse le redemarrage de la messagerie : " + ex.Message); + } } finally { pending?.Finish(); } }); diff --git a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs index f887a7d31..7de2f38b1 100644 --- a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs +++ b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs @@ -253,6 +253,7 @@ public sealed class ChatConnectionService : Service private void ReportError(Exception ex) { Log.Error("PostIt.Chat", ex.ToString()); + _api?.QueueExceptionReport(ex, "PostIt.Android.Chat"); if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message); } diff --git a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs index 5f3bd765d..415d256fe 100644 --- a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs +++ b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs @@ -175,6 +175,20 @@ public class SettingsLoadTests Assert.Equal("bonjour", roundTrip.SearchText); } + [Fact] + public void Exception_reports_are_disabled_by_default_and_persist_when_enabled() + { + var defaults = new PostIt.ViewModels.Settings(); + Assert.False(defaults.ShareExceptionReports); + + defaults.ShareExceptionReports = true; + var roundTrip = JsonSerializer.Deserialize( + JsonSerializer.Serialize(defaults)); + + Assert.NotNull(roundTrip); + Assert.True(roundTrip.ShareExceptionReports); + } + /// /// First-start regression guard: older settings payloads can /// still contain ActionStatus from a previous write. This diff --git a/src/PostIt/PostIt.Tests/YavscApiClientTests.cs b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs index 2fba36b43..e0beb915e 100644 --- a/src/PostIt/PostIt.Tests/YavscApiClientTests.cs +++ b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs @@ -19,6 +19,51 @@ namespace PostIt.Tests; [Trait("Category", "non-reg")] public class YavscApiClientTests { + [Fact] + public async Task Exception_reports_are_sent_only_after_local_opt_in() + { + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var tokensPath = TokensPath(); + try + { + var settings = new Settings + { + ApiUrl = apiServer.BaseUrl + "/api/v1/", + ShareExceptionReports = true, + Authentication = new AuthenticationSettings + { + Authority = "https://example.test/" + } + }; + settings.Load(); + var store = new TokenStore(tokensPath); + store.Save(new RefreshTokenRecord( + "access", "refresh", DateTimeOffset.UtcNow.AddMinutes(5))); + await using var client = new YavscApiClient(settings, store); + Assert.True(settings.ShareExceptionReports); + Assert.True(client.HasValidSession); + + var reportWasSent = await client.ReportExceptionAsync( + new InvalidOperationException("Messaging service unavailable"), + "PostIt.Android.Chat", + TestContext.Current.CancellationToken); + Assert.True(reportWasSent, $"share={settings.ShareExceptionReports}; session={client.HasValidSession}"); + Assert.Equal(1, apiServer.RequestCount); + + settings.ShareExceptionReports = false; + Assert.False(await client.ReportExceptionAsync( + new InvalidOperationException("Do not send"), + "PostIt.Android.Chat", + TestContext.Current.CancellationToken)); + Assert.Equal(1, apiServer.RequestCount); + } + finally + { + if (File.Exists(tokensPath)) File.Delete(tokensPath); + } + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs index 1e970c2ba..68e50a581 100644 --- a/src/PostIt/PostIt/App.axaml.cs +++ b/src/PostIt/PostIt/App.axaml.cs @@ -23,6 +23,7 @@ namespace PostIt; public partial class App : Application, ILiveView, IVMPusherApp { public static bool LiveMode { get; private set; } + private static bool _exceptionHandlersRegistered; private Task? _bootTask; private bool _sessionNavigationConfigured; public static string? CliConfigFileSpecification { get; private set; } @@ -52,7 +53,14 @@ public partial class App : Application, ILiveView, IVMPusherApp this.ServiceProvider = Platform.CreateServiceProvider?.Invoke() ?? new ServiceCollection().BuildPostItServices(); var settings = ServiceProvider.GetRequiredService(); - ServiceProvider.GetRequiredService().StartSessionMaintenance(); + var api = ServiceProvider.GetRequiredService(); + api.StartSessionMaintenance(); + if (!_exceptionHandlersRegistered) + { + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; + _exceptionHandlersRegistered = true; + } if (!LiveMode) { @@ -115,6 +123,20 @@ public partial class App : Application, ILiveView, IVMPusherApp base.OnFrameworkInitializationCompleted(); } + private static void OnUnhandledException(object? sender, UnhandledExceptionEventArgs args) + { + if (args.ExceptionObject is Exception exception && Current is App app) + app.ServiceProvider?.GetService() + ?.QueueExceptionReport(exception, "PostIt"); + } + + private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args) + { + if (Current is App app) + app.ServiceProvider?.GetService() + ?.QueueExceptionReport(args.Exception, "PostIt"); + } + private bool IsProduction() { #if DEBUG diff --git a/src/PostIt/PostIt/Services/YavscApiClient.cs b/src/PostIt/PostIt/Services/YavscApiClient.cs index 0917f46a2..433a15db9 100644 --- a/src/PostIt/PostIt/Services/YavscApiClient.cs +++ b/src/PostIt/PostIt/Services/YavscApiClient.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using IdentityModel.OidcClient; using PostIt.ViewModels; +using Yavsc.ApiControllers; using Yavsc.Api.Client; namespace PostIt.Services; @@ -110,6 +111,55 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable /// The current OIDC id_token, or null. public string? CurrentIdToken => _tokens?.IdToken; + public async Task ReportExceptionAsync( + Exception exception, + string component, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(exception); + ArgumentException.ThrowIfNullOrWhiteSpace(component); + + if (!Settings.ShareExceptionReports || !HasValidSession) + return false; + + var exceptionType = exception.GetType().FullName ?? exception.GetType().Name; + var exceptionDetails = exception.ToString(); + var exceptionJson = SerializeExceptionDetails(exceptionType, exceptionDetails); + while (exceptionJson.Length > 10240 && exceptionDetails.Length > 0) + { + exceptionDetails = exceptionDetails[..(exceptionDetails.Length / 2)]; + exceptionJson = SerializeExceptionDetails(exceptionType, exceptionDetails); + } + + var apiRoot = new Uri(Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute); + var endpoint = new Uri(apiRoot, "/api/bug/signal"); + var report = new BugReport + { + Component = component, + FeatureShortName = "PostIt", + ExceptionObjectJson = exceptionJson + }; + await CallAsync(HttpMethod.Post, endpoint.ToString(), report, ct).ConfigureAwait(false); + return true; + } + + public void QueueExceptionReport(Exception exception, string component) + { + if (!Settings.ShareExceptionReports || !HasValidSession) + return; + + var report = ReportExceptionAsync(exception, component); + _ = report.ContinueWith( + failed => Console.Error.WriteLine( + $"Exception report failed: {failed.Exception?.GetBaseException()}"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + + private static string SerializeExceptionDetails(string exceptionType, string details) => + JsonSerializer.Serialize(new { ExceptionType = exceptionType, Details = details }); + public void StartSessionMaintenance() { lock (_maintenanceGate) diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 430419483..3ad9ddf46 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -67,6 +67,8 @@ public partial class Settings : ViewModelBase [ObservableProperty] public partial bool AndroidKeepChatConnected { get; set; } [ObservableProperty] + public partial bool ShareExceptionReports { get; set; } + [ObservableProperty] public partial Dictionary ChatRoomsByAccount { get; set; } = new(); [JsonIgnore] public bool SupportsBackgroundChatService => OperatingSystem.IsAndroid(); @@ -174,6 +176,7 @@ public partial class Settings : ViewModelBase partial void OnPodcastBlurBackgroundChanged(bool value) => MarkDirty(); partial void OnLanCallAddressChanged(string? value) => MarkDirty(); partial void OnAndroidKeepChatConnectedChanged(bool value) => MarkDirty(); + partial void OnShareExceptionReportsChanged(bool value) => MarkDirty(); partial void OnChatRoomsByAccountChanged(Dictionary value) => MarkDirty(); /// @@ -441,6 +444,7 @@ public partial class Settings : ViewModelBase PodcastBlurBackground = settings.PodcastBlurBackground; LanCallAddress = settings.LanCallAddress; AndroidKeepChatConnected = settings.AndroidKeepChatConnected; + ShareExceptionReports = settings.ShareExceptionReports; ChatRoomsByAccount = settings.ChatRoomsByAccount ?? new(); if (!(settings.Authentication is null)) { @@ -521,6 +525,7 @@ public partial class Settings : ViewModelBase this.ApiUrl = "https://api.pschneider.fr/api/v1/"; this.SearchText = string.Empty; this.ProviderOngoingRequestsSortOption = string.Empty; + this.ShareExceptionReports = false; } /// diff --git a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml index f0865fd70..160c185ac 100644 --- a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml @@ -55,6 +55,10 @@ + + diff --git a/src/Yavsc.Abstract/IT/BugReport.cs b/src/Yavsc.Abstract/IT/BugReport.cs index 3c04d5a93..a876666a7 100644 --- a/src/Yavsc.Abstract/IT/BugReport.cs +++ b/src/Yavsc.Abstract/IT/BugReport.cs @@ -4,12 +4,11 @@ using Yavsc.Attributes.Validation; namespace Yavsc.ApiControllers { public class BugReport { - [Required,YaStringLength(1024)] - public string ApiKey { get ; set; } [Required,YaStringLength(512)] public string Component { get ; set; } [Required][YaStringLength(10240)] public string ExceptionObjectJson { get ; set; } + [YaStringLength(256)] + public string FeatureShortName { get ; set; } } } - diff --git a/src/Yavsc.Api/Controllers/Survey/BugApiController.cs b/src/Yavsc.Api/Controllers/Survey/BugApiController.cs index a28ed8df3..6c3a2454c 100644 --- a/src/Yavsc.Api/Controllers/Survey/BugApiController.cs +++ b/src/Yavsc.Api/Controllers/Survey/BugApiController.cs @@ -1,4 +1,3 @@ -using Newtonsoft.Json; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Yavsc.Models; @@ -22,22 +21,26 @@ namespace Yavsc.ApiControllers [HttpPost("signal")] [Authorize] - public IActionResult Signal([FromBody] BugReport report) + public async Task Signal([FromBody] BugReport report) { - _logger.LogWarning("bug reported : "+report.ExceptionObjectJson); if (report.ExceptionObjectJson!=null) if (report.ExceptionObjectJson.Length > 10240) report.ExceptionObjectJson = report.ExceptionObjectJson.Substring(0,10240); if (!ModelState.IsValid) - { - _logger.LogError("Bag request :"); - _logger.LogError(JsonConvert.SerializeObject(ModelState)); + _logger.LogError("Invalid bug report request."); return new BadRequestObjectResult(ModelState); } - var existent = _context.Bug.FirstOrDefault( b => + _logger.LogWarning("Bug report received for component {Component}.", report.Component); + var feature = string.IsNullOrWhiteSpace(report.FeatureShortName) + ? null + : await _context.Feature.FirstOrDefaultAsync( + f => f.ShortName == report.FeatureShortName); + long? featureId = feature?.Id; + var existent = await _context.Bug.FirstOrDefaultAsync(b => b.Description == report.ExceptionObjectJson && b.Title == report.Component && + b.FeatureId == featureId && b.Status != BugStatus.Rejected ); if (existent != null) @@ -48,10 +51,11 @@ namespace Yavsc.ApiControllers _logger.LogInformation("Filling a new bug report"); var bug = new Bug { Title = report.Component, - Description = report.ExceptionObjectJson + Description = report.ExceptionObjectJson, + FeatureId = featureId }; _context.Bug.Add(bug); - _context.SaveChanges(); + await _context.SaveChangesAsync(); return CreatedAtRoute("GetBug", new { id = bug.Id }, bug); }