|
| 1 | +using System.Buffers; |
| 2 | +using System.Text.Json; |
| 3 | + |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.Extensions.Logging.Abstractions; |
| 6 | +using Microsoft.Extensions.Options; |
| 7 | + |
| 8 | +using NATS.Client.Core; |
| 9 | + |
| 10 | +using ZiggyCreatures.Caching.Fusion.Internals; |
| 11 | + |
| 12 | +namespace ZiggyCreatures.Caching.Fusion.Backplane.NATS; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// A Redis based implementation of a FusionCache backplane. |
| 16 | +/// </summary> |
| 17 | +public partial class NatsBackplane |
| 18 | + : IFusionCacheBackplane |
| 19 | +{ |
| 20 | + private BackplaneSubscriptionOptions? _subscriptionOptions; |
| 21 | + private readonly ILogger? _logger; |
| 22 | + private INatsConnection _connection; |
| 23 | + private string _channelName = ""; |
| 24 | + private Func<BackplaneMessage, ValueTask>? _incomingMessageHandlerAsync; |
| 25 | + private INatsSub<NatsMemoryOwner<byte>>? _subscription; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Initializes a new instance of the RedisBackplane class. |
| 29 | + /// </summary> |
| 30 | + /// <param name="natsConnection">The NATS connection instance to use.</param> |
| 31 | + /// <param name="logger">The <see cref="ILogger{TCategoryName}"/> instance to use. If null, logging will be completely disabled.</param> |
| 32 | + public NatsBackplane(INatsConnection? natsConnection, ILogger<NatsBackplane>? logger = null) |
| 33 | + { |
| 34 | + _connection = natsConnection ?? throw new ArgumentNullException(nameof(natsConnection)); |
| 35 | + |
| 36 | + // LOGGING |
| 37 | + if (logger is NullLogger<NatsBackplane>) |
| 38 | + { |
| 39 | + // IGNORE NULL LOGGER (FOR BETTER PERF) |
| 40 | + _logger = null; |
| 41 | + } |
| 42 | + else |
| 43 | + { |
| 44 | + _logger = logger; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /// <inheritdoc/> |
| 49 | + public async ValueTask SubscribeAsync(BackplaneSubscriptionOptions subscriptionOptions) |
| 50 | + { |
| 51 | + if (subscriptionOptions is null) |
| 52 | + throw new ArgumentNullException(nameof(subscriptionOptions)); |
| 53 | + |
| 54 | + if (subscriptionOptions.ChannelName is null) |
| 55 | + throw new NullReferenceException("The BackplaneSubscriptionOptions.ChannelName cannot be null"); |
| 56 | + |
| 57 | + if (subscriptionOptions.IncomingMessageHandler is null) |
| 58 | + throw new NullReferenceException("The BackplaneSubscriptionOptions.IncomingMessageHandler cannot be null"); |
| 59 | + |
| 60 | + if (subscriptionOptions.ConnectHandler is null) |
| 61 | + throw new NullReferenceException("The BackplaneSubscriptionOptions.ConnectHandler cannot be null"); |
| 62 | + |
| 63 | + if (subscriptionOptions.IncomingMessageHandlerAsync is null) |
| 64 | + throw new NullReferenceException("The BackplaneSubscriptionOptions.IncomingMessageHandlerAsync cannot be null"); |
| 65 | + |
| 66 | + if (subscriptionOptions.ConnectHandlerAsync is null) |
| 67 | + throw new NullReferenceException("The BackplaneSubscriptionOptions.ConnectHandlerAsync cannot be null"); |
| 68 | + |
| 69 | + _subscriptionOptions = subscriptionOptions; |
| 70 | + |
| 71 | + _channelName = _subscriptionOptions.ChannelName; |
| 72 | + if (string.IsNullOrEmpty(_channelName)) |
| 73 | + throw new NullReferenceException("The backplane channel name must have a value"); |
| 74 | + |
| 75 | + _incomingMessageHandlerAsync = _subscriptionOptions.IncomingMessageHandlerAsync; |
| 76 | + _subscription = await _connection.SubscribeCoreAsync<NatsMemoryOwner<byte>>(_channelName); |
| 77 | + _ = Task.Run(async () => |
| 78 | + { |
| 79 | + while (await _subscription.Msgs.WaitToReadAsync().ConfigureAwait(false)) |
| 80 | + { |
| 81 | + while (_subscription.Msgs.TryRead(out var msg)) |
| 82 | + { |
| 83 | + using (msg.Data) |
| 84 | + { |
| 85 | + var message = BackplaneMessage.FromByteArray(msg.Data.Memory.ToArray()); |
| 86 | + await OnMessageAsync(message).ConfigureAwait(false); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | + /// <inheritdoc/> |
| 95 | + public void Subscribe(BackplaneSubscriptionOptions options) |
| 96 | + { |
| 97 | + SubscribeAsync(options).AsTask().Wait(); |
| 98 | + } |
| 99 | + |
| 100 | + /// <inheritdoc/> |
| 101 | + public async ValueTask UnsubscribeAsync() |
| 102 | + { |
| 103 | + if (_subscription is not null) |
| 104 | + { |
| 105 | + await _subscription.UnsubscribeAsync().ConfigureAwait(false); |
| 106 | + await _subscription.Msgs.Completion; |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + /// <inheritdoc/> |
| 111 | + public void Unsubscribe() |
| 112 | + { |
| 113 | + UnsubscribeAsync().AsTask().Wait(); |
| 114 | + } |
| 115 | + |
| 116 | + /// <inheritdoc/> |
| 117 | + public async ValueTask PublishAsync(BackplaneMessage message, FusionCacheEntryOptions options, CancellationToken token = default) |
| 118 | + { |
| 119 | + var writer = new NatsBufferWriter<byte>(); |
| 120 | + writer.Write(BackplaneMessage.ToByteArray(message)); |
| 121 | + await _connection.PublishAsync(_channelName, writer).ConfigureAwait(false); |
| 122 | + } |
| 123 | + |
| 124 | + /// <inheritdoc/> |
| 125 | + public void Publish(BackplaneMessage message, FusionCacheEntryOptions options, CancellationToken token = default) |
| 126 | + { |
| 127 | + PublishAsync(message, options, token).AsTask().Wait(); |
| 128 | + } |
| 129 | + |
| 130 | + internal async ValueTask OnMessageAsync(BackplaneMessage message) |
| 131 | + { |
| 132 | + var tmp = _incomingMessageHandlerAsync; |
| 133 | + if (tmp is null) |
| 134 | + { |
| 135 | + if (_logger?.IsEnabled(LogLevel.Trace) ?? false) |
| 136 | + _logger.Log(LogLevel.Trace, "FUSION [N={CacheName} I={CacheInstanceId}]: [BP] incoming message handler was null", _subscriptionOptions?.CacheName, _subscriptionOptions?.CacheInstanceId); |
| 137 | + return; |
| 138 | + } |
| 139 | + |
| 140 | + await tmp(message).ConfigureAwait(false); |
| 141 | + } |
| 142 | +} |
0 commit comments