ServerDbManagerExt.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Text.Json;
  2. using Robust.Shared.Asynchronous;
  3. namespace Content.Server.Database;
  4. public static class ServerDbManagerExt
  5. {
  6. /// <summary>
  7. /// Subscribe to a database notification on a specific channel, formatted as JSON.
  8. /// </summary>
  9. /// <param name="dbManager">The database manager to subscribe on.</param>
  10. /// <param name="taskManager">The task manager used to run the main callback on the main thread.</param>
  11. /// <param name="sawmill">Sawmill to log any errors to.</param>
  12. /// <param name="channel">
  13. /// The notification channel to listen on. Only notifications on this channel will be handled.
  14. /// </param>
  15. /// <param name="action">
  16. /// The action to run on the notification data.
  17. /// This runs on the main thread.
  18. /// </param>
  19. /// <param name="earlyFilter">
  20. /// An early filter callback that runs before the JSON message is deserialized.
  21. /// Return false to not handle the notification.
  22. /// This does not run on the main thread.
  23. /// </param>
  24. /// <param name="filter">
  25. /// A filter callback that runs after the JSON message is deserialized.
  26. /// Return false to not handle the notification.
  27. /// This does not run on the main thread.
  28. /// </param>
  29. /// <typeparam name="TData">The type of JSON data to deserialize.</typeparam>
  30. public static void SubscribeToJsonNotification<TData>(
  31. this IServerDbManager dbManager,
  32. ITaskManager taskManager,
  33. ISawmill sawmill,
  34. string channel,
  35. Action<TData> action,
  36. Func<bool>? earlyFilter = null,
  37. Func<TData, bool>? filter = null)
  38. {
  39. dbManager.SubscribeToNotifications(notification =>
  40. {
  41. if (notification.Channel != channel)
  42. return;
  43. if (notification.Payload == null)
  44. {
  45. sawmill.Error($"Got {channel} notification with null payload!");
  46. return;
  47. }
  48. if (earlyFilter != null && !earlyFilter())
  49. return;
  50. TData data;
  51. try
  52. {
  53. data = JsonSerializer.Deserialize<TData>(notification.Payload)
  54. ?? throw new JsonException("Content is null");
  55. }
  56. catch (JsonException e)
  57. {
  58. sawmill.Error($"Got invalid JSON in {channel} notification: {e}");
  59. return;
  60. }
  61. if (filter != null && !filter(data))
  62. return;
  63. taskManager.RunOnMainThread(() =>
  64. {
  65. action(data);
  66. });
  67. });
  68. }
  69. }