-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Broadcast channel to replace SMS #7735
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
src/Orleans.BroadcastChannel/BroadcastChannelConsumerExtension.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
using System; | ||
using System.Collections.Concurrent; | ||
using System.Threading.Tasks; | ||
using Orleans.Runtime; | ||
|
||
namespace Orleans.BroadcastChannel | ||
{ | ||
internal interface IBroadcastChannelConsumerExtension : IGrainExtension | ||
{ | ||
Task OnError(InternalChannelId streamId, Exception exception); | ||
Task OnPublished(InternalChannelId streamId, object item); | ||
} | ||
|
||
internal class BroadcastChannelConsumerExtension : IBroadcastChannelConsumerExtension | ||
{ | ||
private readonly ConcurrentDictionary<InternalChannelId, ICallback> _handlers = new(); | ||
private readonly IOnBroadcastChannelSubscribed _subscriptionObserver; | ||
private AsyncLock _lock = new AsyncLock(); | ||
|
||
private interface ICallback | ||
{ | ||
Task OnError(Exception exception); | ||
|
||
Task OnPublished(object item); | ||
} | ||
|
||
private class Callback<T> : ICallback | ||
{ | ||
private readonly Func<T, Task> _onPublished; | ||
private readonly Func<Exception, Task> _onError; | ||
|
||
private static Task NoOp(Exception _) => Task.CompletedTask; | ||
|
||
public Callback(Func<T, Task> onPublished, Func<Exception, Task> onError) | ||
{ | ||
_onPublished = onPublished; | ||
_onError = onError ?? NoOp; | ||
} | ||
|
||
public Task OnError(Exception exception) => _onError(exception); | ||
|
||
public Task OnPublished(object item) | ||
{ | ||
return item is T typedItem | ||
? _onPublished(typedItem) | ||
: _onError(new InvalidCastException($"Received an item of type {item.GetType().Name}, expected {typeof(T).FullName}")); | ||
} | ||
} | ||
|
||
public BroadcastChannelConsumerExtension(IGrainContextAccessor grainContextAccessor) | ||
{ | ||
_subscriptionObserver = grainContextAccessor.GrainContext?.GrainInstance as IOnBroadcastChannelSubscribed; | ||
if (_subscriptionObserver == null) | ||
{ | ||
throw new ArgumentException($"The grain doesn't implement interface {nameof(IOnBroadcastChannelSubscribed)}"); | ||
} | ||
} | ||
|
||
public async Task OnError(InternalChannelId streamId, Exception exception) | ||
{ | ||
var callback = await GetStreamCallback(streamId); | ||
if (callback != default) | ||
{ | ||
await callback.OnError(exception); | ||
} | ||
} | ||
|
||
public async Task OnPublished(InternalChannelId streamId, object item) | ||
{ | ||
var callback = await GetStreamCallback(streamId); | ||
if (callback != default) | ||
{ | ||
await callback.OnPublished(item); | ||
} | ||
} | ||
|
||
public void Attach<T>(InternalChannelId streamId, Func<T, Task> onPublished, Func<Exception, Task> onError) | ||
{ | ||
_handlers.TryAdd(streamId, new Callback<T>(onPublished, onError)); | ||
} | ||
|
||
private async ValueTask<ICallback> GetStreamCallback(InternalChannelId streamId) | ||
{ | ||
ICallback callback; | ||
if (_handlers.TryGetValue(streamId, out callback)) | ||
{ | ||
return callback; | ||
} | ||
using (await _lock.LockAsync()) | ||
{ | ||
if (_handlers.TryGetValue(streamId, out callback)) | ||
{ | ||
return callback; | ||
} | ||
// Give a chance to the grain to attach a handler for this streamId | ||
var subscription = new BroadcastChannelSubscription(this, streamId); | ||
await _subscriptionObserver.OnSubscribed(subscription); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The reason this works ( |
||
} | ||
_handlers.TryGetValue(streamId, out callback); | ||
return callback; | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
namespace Orleans.BroadcastChannel | ||
{ | ||
public class BroadcastChannelOptions | ||
{ | ||
public bool FireAndForgetDelivery { get; set; } = true; | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
using System; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using Orleans.BroadcastChannel.SubscriberTable; | ||
using Orleans.Providers; | ||
using Orleans.Runtime; | ||
|
||
namespace Orleans.BroadcastChannel | ||
{ | ||
public interface IBroadcastChannelProvider | ||
{ | ||
IBroadcastChannelWriter<T> GetChannelWriter<T>(ChannelId streamId); | ||
} | ||
|
||
internal class BroadcastChannelProvider : IBroadcastChannelProvider | ||
{ | ||
private readonly string _providerName; | ||
private readonly BroadcastChannelOptions _options; | ||
private readonly IGrainFactory _grainFactory; | ||
private readonly ImplicitChannelSubscriberTable _subscriberTable; | ||
private readonly ILoggerFactory _loggerFactory; | ||
|
||
public BroadcastChannelProvider( | ||
string providerName, | ||
BroadcastChannelOptions options, | ||
IGrainFactory grainFactory, | ||
ImplicitChannelSubscriberTable subscriberTable, | ||
ILoggerFactory loggerFactory) | ||
{ | ||
_providerName = providerName; | ||
_options = options; | ||
_grainFactory = grainFactory; | ||
_subscriberTable = subscriberTable; | ||
_loggerFactory = loggerFactory; | ||
} | ||
|
||
public IBroadcastChannelWriter<T> GetChannelWriter<T>(ChannelId streamId) | ||
{ | ||
return new BroadcastChannelWriter<T>( | ||
new InternalChannelId(_providerName, streamId), | ||
_grainFactory, | ||
_subscriberTable, | ||
_options.FireAndForgetDelivery, | ||
_loggerFactory); | ||
} | ||
|
||
public static IBroadcastChannelProvider Create(IServiceProvider sp, string name) | ||
{ | ||
var opt = sp.GetOptionsByName<BroadcastChannelOptions>(name); | ||
return ActivatorUtilities.CreateInstance<BroadcastChannelProvider>(sp, name, sp.GetOptionsByName<BroadcastChannelOptions>(name)); | ||
} | ||
} | ||
} | ||
|
43 changes: 43 additions & 0 deletions
43
src/Orleans.BroadcastChannel/BroadcastChannelSubscription.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
using System; | ||
using System.Threading.Tasks; | ||
using Orleans.Runtime; | ||
|
||
namespace Orleans.BroadcastChannel | ||
{ | ||
public interface IBroadcastChannelSubscription | ||
{ | ||
public ChannelId ChannelId { get; } | ||
|
||
public string ProviderName { get; } | ||
|
||
Task Attach<T>(Func<T, Task> onPublished, Func<Exception, Task> onError = null); | ||
} | ||
|
||
public interface IOnBroadcastChannelSubscribed | ||
{ | ||
public Task OnSubscribed(IBroadcastChannelSubscription streamSubscription); | ||
} | ||
|
||
internal class BroadcastChannelSubscription : IBroadcastChannelSubscription | ||
{ | ||
private readonly BroadcastChannelConsumerExtension _consumerExtension; | ||
private readonly InternalChannelId _streamId; | ||
|
||
public ChannelId ChannelId => _streamId.ChannelId; | ||
|
||
public string ProviderName => _streamId.ProviderName; | ||
|
||
public BroadcastChannelSubscription(BroadcastChannelConsumerExtension consumerExtension, InternalChannelId streamId) | ||
{ | ||
_consumerExtension = consumerExtension; | ||
_streamId = streamId; | ||
} | ||
|
||
public Task Attach<T>(Func<T, Task> onPublished, Func<Exception, Task> onError = null) | ||
{ | ||
_consumerExtension.Attach(_streamId, onPublished, onError); | ||
return Task.CompletedTask; | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.Logging; | ||
using Orleans.BroadcastChannel.SubscriberTable; | ||
using Orleans.Providers; | ||
using Orleans.Runtime; | ||
|
||
namespace Orleans.BroadcastChannel | ||
{ | ||
public interface IBroadcastChannelWriter<T> | ||
{ | ||
Task Publish(T item); | ||
} | ||
|
||
internal class BroadcastChannelWriter<T> : IBroadcastChannelWriter<T> | ||
{ | ||
private static readonly string LoggingCategory = typeof(BroadcastChannelWriter<>).FullName; | ||
|
||
private readonly InternalChannelId _channelId; | ||
private readonly IGrainFactory _grainFactory; | ||
private readonly ImplicitChannelSubscriberTable _subscriberTable; | ||
private readonly bool _fireAndForgetDelivery; | ||
private readonly ILogger _logger; | ||
|
||
public BroadcastChannelWriter( | ||
InternalChannelId channelId, | ||
IGrainFactory grainFactory, | ||
ImplicitChannelSubscriberTable subscriberTable, | ||
bool fireAndForgetDelivery, | ||
ILoggerFactory loggerFactory) | ||
{ | ||
_channelId = channelId; | ||
_grainFactory = grainFactory; | ||
_subscriberTable = subscriberTable; | ||
_fireAndForgetDelivery = fireAndForgetDelivery; | ||
_logger = loggerFactory.CreateLogger(LoggingCategory); | ||
} | ||
|
||
public async Task Publish(T item) | ||
{ | ||
var subscribers = _subscriberTable.GetImplicitSubscribers(_channelId, _grainFactory); | ||
|
||
if (subscribers.Count == 0) | ||
{ | ||
if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug("No consumer found for {Item}", item); | ||
return; | ||
} | ||
|
||
if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug("Publishing item {Item} to {ConsumerCount} consumers", item, subscribers.Count); | ||
|
||
if (_fireAndForgetDelivery) | ||
{ | ||
foreach (var sub in subscribers) | ||
{ | ||
PublishToSubscriber(sub.Value, item).Ignore(); | ||
} | ||
} | ||
else | ||
{ | ||
var tasks = new List<Task>(); | ||
foreach (var sub in subscribers) | ||
{ | ||
tasks.Add(PublishToSubscriber(sub.Value, item)); | ||
} | ||
try | ||
{ | ||
await Task.WhenAll(tasks); | ||
} | ||
catch (Exception) | ||
{ | ||
throw new AggregateException(tasks.Select(t => t.Exception).Where(ex => ex != null)); | ||
} | ||
} | ||
} | ||
|
||
private async Task PublishToSubscriber(IBroadcastChannelConsumerExtension consumer, T item) | ||
{ | ||
try | ||
{ | ||
await consumer.OnPublished(_channelId, item); | ||
} | ||
catch (Exception ex) | ||
{ | ||
_logger.LogError(ex, "Exception when sending item to {GrainId}", consumer.GetGrainId()); | ||
if (!_fireAndForgetDelivery) | ||
{ | ||
throw; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems like this is not nullable: it's accessed unconditionally further down.
In that case, perhaps a direct cast would be more appropriate.