using System.Text.Json; using Robust.Shared.Asynchronous; namespace Content.Server.Database; public static class ServerDbManagerExt { /// /// Subscribe to a database notification on a specific channel, formatted as JSON. /// /// The database manager to subscribe on. /// The task manager used to run the main callback on the main thread. /// Sawmill to log any errors to. /// /// The notification channel to listen on. Only notifications on this channel will be handled. /// /// /// The action to run on the notification data. /// This runs on the main thread. /// /// /// An early filter callback that runs before the JSON message is deserialized. /// Return false to not handle the notification. /// This does not run on the main thread. /// /// /// A filter callback that runs after the JSON message is deserialized. /// Return false to not handle the notification. /// This does not run on the main thread. /// /// The type of JSON data to deserialize. public static void SubscribeToJsonNotification( this IServerDbManager dbManager, ITaskManager taskManager, ISawmill sawmill, string channel, Action action, Func? earlyFilter = null, Func? filter = null) { dbManager.SubscribeToNotifications(notification => { if (notification.Channel != channel) return; if (notification.Payload == null) { sawmill.Error($"Got {channel} notification with null payload!"); return; } if (earlyFilter != null && !earlyFilter()) return; TData data; try { data = JsonSerializer.Deserialize(notification.Payload) ?? throw new JsonException("Content is null"); } catch (JsonException e) { sawmill.Error($"Got invalid JSON in {channel} notification: {e}"); return; } if (filter != null && !filter(data)) return; taskManager.RunOnMainThread(() => { action(data); }); }); } }