工单增加连接失败日志

This commit is contained in:
chfei committed 2026-10-19 14:53:47 +08:00
1 parent 8e0cc20649
commit 1b0aa81263
1 file changed
+161 -159
@@ -1,3 +1,4 @@
using AllBase;
using LaunchDarkly.EventSource; using LaunchDarkly.EventSource;
using Newtonsoft.Json; using Newtonsoft.Json;
using OrderSupportTicket.Models; using OrderSupportTicket.Models;
@@ -14,186 +15,187 @@ namespace OrderSupportTicket.Services;
/// </summary> /// </summary>
public sealed class EventSourceTicketRealtimeService public sealed class EventSourceTicketRealtimeService
{ {
private const string EventsPath = "/api/open/v2/customer-work-orders/events"; private const string EventsPath = "/api/open/v2/customer-work-orders/events";
private readonly object _sync = new object(); private readonly object _sync = new object();
private EventSource _eventSource; private EventSource _eventSource;
private bool _running; private bool _running;
private bool _disposed; private bool _disposed;
public event EventHandler<TicketRealtimeNotificationEventArgs> NotificationReceived; public event EventHandler<TicketRealtimeNotificationEventArgs> NotificationReceived;
public event EventHandler<TicketRealtimeStateChangedEventArgs> StateChanged; public event EventHandler<TicketRealtimeStateChangedEventArgs> StateChanged;
/// <summary> /// <summary>
/// 当前 SSE 连接状态。 /// 当前 SSE 连接状态。
/// </summary> /// </summary>
public TicketRealtimeState State { get; private set; } = TicketRealtimeState.Disconnected; public TicketRealtimeState State { get; private set; } = TicketRealtimeState.Disconnected;
public void Start(TicketClientOptions options) public void Start(TicketClientOptions options)
{ {
if (_disposed) if (_disposed)
throw new ObjectDisposedException(nameof(EventSourceTicketRealtimeService)); throw new ObjectDisposedException(nameof(EventSourceTicketRealtimeService));
if (options == null) if (options == null)
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
TicketApiService.ValidateOptions(options); TicketApiService.ValidateOptions(options);
StopCore(); StopCore();
var uri = BuildEventsUri(options); var uri = BuildEventsUri(options);
var source = new EventSource(uri); var source = new EventSource(uri);
source.Opened += OnOpened; source.Opened += OnOpened;
source.Closed += OnClosed; source.Closed += OnClosed;
source.MessageReceived += OnMessageReceived; source.MessageReceived += OnMessageReceived;
source.Error += OnError; source.Error += OnError;
lock (_sync) lock (_sync)
{ {
_running = true; _running = true;
_eventSource = source; _eventSource = source;
} }
SetState(TicketRealtimeState.Connecting, "连接中…"); SetState(TicketRealtimeState.Connecting, "连接中…");
_ = RunAsync(source); _ = RunAsync(source);
} }
public Task StopAsync() public Task StopAsync()
{ {
StopCore(); StopCore();
SetState(TicketRealtimeState.Disconnected, "已断开"); SetState(TicketRealtimeState.Disconnected, "已断开");
return Task.FromResult(0); return Task.FromResult(0);
} }
public void Dispose() public void Dispose()
{ {
if (_disposed) if (_disposed)
return; return;
StopCore(); StopCore();
_disposed = true; _disposed = true;
} }
private async Task RunAsync(EventSource source) private async Task RunAsync(EventSource source)
{ {
try try
{ {
await source.StartAsync(); await source.StartAsync();
lock (_sync) lock (_sync)
{ {
if (!_running || !ReferenceEquals(_eventSource, source)) if (!_running || !ReferenceEquals(_eventSource, source))
return; return;
} }
SetState(TicketRealtimeState.Reconnecting, "连接已关闭,等待重连…"); SetState(TicketRealtimeState.Reconnecting, "连接已关闭,等待重连…");
} }
catch (Exception ex) catch (Exception ex)
{ {
lock (_sync) LogSave.Add("工单服务连接失败:" + ex.Message);
{ lock (_sync)
if (!_running || !ReferenceEquals(_eventSource, source)) {
return; if (!_running || !ReferenceEquals(_eventSource, source))
} return;
SetState(TicketRealtimeState.Reconnecting, "连接失败:" + ex.Message); }
} SetState(TicketRealtimeState.Reconnecting, "连接失败:" + ex.Message);
} }
}
private void OnOpened(object sender, StateChangedEventArgs args) private void OnOpened(object sender, StateChangedEventArgs args)
{ {
SetState(TicketRealtimeState.Connected, "已连接"); SetState(TicketRealtimeState.Connected, "已连接");
} }
private void OnClosed(object sender, StateChangedEventArgs args) private void OnClosed(object sender, StateChangedEventArgs args)
{ {
lock (_sync) lock (_sync)
{ {
if (!_running || !ReferenceEquals(_eventSource, sender)) if (!_running || !ReferenceEquals(_eventSource, sender))
return; return;
} }
SetState(TicketRealtimeState.Reconnecting, "连接断开,重连中…"); SetState(TicketRealtimeState.Reconnecting, "连接断开,重连中…");
} }
private void OnError(object sender, ExceptionEventArgs args) private void OnError(object sender, ExceptionEventArgs args)
{ {
lock (_sync) lock (_sync)
{ {
if (!_running || !ReferenceEquals(_eventSource, sender)) if (!_running || !ReferenceEquals(_eventSource, sender))
return; return;
} }
SetState( SetState(
TicketRealtimeState.Reconnecting, TicketRealtimeState.Reconnecting,
"连接异常,重连中:" + (args.Exception?.Message ?? "未知错误")); "连接异常,重连中:" + (args.Exception?.Message ?? "未知错误"));
} }
private void OnMessageReceived(object sender, MessageReceivedEventArgs args) private void OnMessageReceived(object sender, MessageReceivedEventArgs args)
{ {
if (args == null) if (args == null)
return; return;
var data = args.Message.Data; var data = args.Message.Data;
if (string.IsNullOrWhiteSpace(data)) if (string.IsNullOrWhiteSpace(data))
return; return;
TicketRealtimeNotification notification; TicketRealtimeNotification notification;
try try
{ {
notification = JsonConvert.DeserializeObject<TicketRealtimeNotification>(data, TicketApiService.JsonSettings); notification = JsonConvert.DeserializeObject<TicketRealtimeNotification>(data, TicketApiService.JsonSettings);
} }
catch (JsonException) catch (JsonException)
{ {
return; return;
} }
if (notification == null) if (notification == null)
return; return;
if (string.IsNullOrWhiteSpace(notification.EventId)) if (string.IsNullOrWhiteSpace(notification.EventId))
notification.EventId = args.Message.LastEventId; notification.EventId = args.Message.LastEventId;
if (string.IsNullOrWhiteSpace(notification.Type)) if (string.IsNullOrWhiteSpace(notification.Type))
notification.Type = args.EventName; notification.Type = args.EventName;
NotificationReceived?.Invoke( NotificationReceived?.Invoke(
this, this,
new TicketRealtimeNotificationEventArgs(notification)); new TicketRealtimeNotificationEventArgs(notification));
} }
private void StopCore() private void StopCore()
{ {
EventSource source; EventSource source;
lock (_sync) lock (_sync)
{ {
_running = false; _running = false;
source = _eventSource; source = _eventSource;
_eventSource = null; _eventSource = null;
} }
if (source == null) if (source == null)
return; return;
source.Opened -= OnOpened; source.Opened -= OnOpened;
source.Closed -= OnClosed; source.Closed -= OnClosed;
source.MessageReceived -= OnMessageReceived; source.MessageReceived -= OnMessageReceived;
source.Error -= OnError; source.Error -= OnError;
source.Close(); source.Close();
} }
private void SetState(TicketRealtimeState state, string message) private void SetState(TicketRealtimeState state, string message)
{ {
State = state; State = state;
StateChanged?.Invoke( StateChanged?.Invoke(
this, this,
new TicketRealtimeStateChangedEventArgs(state, message)); new TicketRealtimeStateChangedEventArgs(state, message));
} }
private static Uri BuildEventsUri(TicketClientOptions options) private static Uri BuildEventsUri(TicketClientOptions options)
{ {
var appIds = options.AppIds var appIds = options.AppIds
.Where(a => !string.IsNullOrWhiteSpace(a)) .Where(a => !string.IsNullOrWhiteSpace(a))
.Distinct(StringComparer.Ordinal) .Distinct(StringComparer.Ordinal)
.Select(a => "appId=" + Uri.EscapeDataString(a.Trim())); .Select(a => "appId=" + Uri.EscapeDataString(a.Trim()));
var query = new[] var query = new[]
{ {
"purchaseAccount=" + Uri.EscapeDataString(options.UserName) "purchaseAccount=" + Uri.EscapeDataString(options.UserName)
}.Concat(appIds); }.Concat(appIds);
return new Uri( return new Uri(
TicketApiService.ServerUrl TicketApiService.ServerUrl
+ EventsPath + EventsPath
+ "?" + "?"
+ string.Join("&", query), + string.Join("&", query),
UriKind.Absolute); UriKind.Absolute);
} }
} }