Add opt-in PostIt exception reporting
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
0ac6970e9d
commit
6839d9cac9
12 changed files with 165 additions and 13 deletions
|
|
@ -2,6 +2,10 @@
|
|||
# Changelog
|
||||
|
||||
|
||||
## [1.0.8-rc37] - unstable
|
||||
|
||||
* [PostIt] Telemetry
|
||||
|
||||
## [1.0.8-rc36] - unstable
|
||||
|
||||
### Added
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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(); }
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<PostIt.ViewModels.Settings>(
|
||||
JsonSerializer.Serialize(defaults));
|
||||
|
||||
Assert.NotNull(roundTrip);
|
||||
Assert.True(roundTrip.ShareExceptionReports);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First-start regression guard: older settings payloads can
|
||||
/// still contain <c>ActionStatus</c> from a previous write. This
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
|
|
|
|||
|
|
@ -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<Settings>();
|
||||
ServiceProvider.GetRequiredService<YavscApiClient>().StartSessionMaintenance();
|
||||
var api = ServiceProvider.GetRequiredService<YavscApiClient>();
|
||||
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<YavscApiClient>()
|
||||
?.QueueExceptionReport(exception, "PostIt");
|
||||
}
|
||||
|
||||
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
|
||||
{
|
||||
if (Current is App app)
|
||||
app.ServiceProvider?.GetService<YavscApiClient>()
|
||||
?.QueueExceptionReport(args.Exception, "PostIt");
|
||||
}
|
||||
|
||||
private bool IsProduction()
|
||||
{
|
||||
#if DEBUG
|
||||
|
|
|
|||
|
|
@ -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
|
|||
/// <summary>The current OIDC id_token, or null.</summary>
|
||||
public string? CurrentIdToken => _tokens?.IdToken;
|
||||
|
||||
public async Task<bool> 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)
|
||||
|
|
|
|||
|
|
@ -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<string, string[]> 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<string, string[]> value) => MarkDirty();
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -55,6 +55,10 @@
|
|||
<TextBlock Text="SignalR uniquement, sans notification permanente. Les alertes s'affichent seulement a reception d'un message ou evenement. Sauver avec cette option active demande l'exemption batterie Android seulement si PostIt n'est pas deja exempte. Vous restez libre de refuser. Autorisez aussi les donnees en arriere-plan dans Android. Ces reglages ne garantissent pas la survie du service ni sa reprise au demarrage. Sans cette option, la connexion dure pendant la vie du processus PostIt."
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<CheckBox Content="Partager les exceptions techniques avec Yavsc"
|
||||
IsChecked="{Binding ShareExceptionReports, Mode=TwoWay}" />
|
||||
<TextBlock Text="Desactive par defaut. Si vous activez cette option, PostIt transmet le type, le message et la trace technique des exceptions signalees pour aider au diagnostic. Ces details peuvent contenir des informations issues de l'environnement de l'application."
|
||||
TextWrapping="Wrap" />
|
||||
<TextBlock Text="Avatar: PNG, JPG/JPEG, WEBP, GIF. Taille max 2 MB."
|
||||
Opacity="0.8"
|
||||
TextWrapping="Wrap" />
|
||||
|
|
|
|||
|
|
@ -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; }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<IActionResult> 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);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue