Programmable stream subscribe API
Problem Space
Currently in Orleans streaming space, there’s two subscribe models supported. One is ImplicitSubscribe, which define the subscription map for orleans streaming infrastructure in compile time. Another one is ExplicitSubscribe, which rely on the consumer grain to be activated to Subscribe and attach its observer to streaming infrastructure. These two model serves great so far and covers most of the use cases in Orleans streaming. But we recently got a new use case, which is the drive for this new feature in Orleans streaming. The new use case is:
- I want to dynamically configure consumer’s subscribe/unsubscribe in runtime
- I don’t want to use ExplicitSubscribe model, which requires application to activate the consumer grains to build the subscription map. I want to be able to define the subscription map outside grain context(without async grain call), for efficiency concern. For example, when application boostraping.
EDIT: About case (3. Since my consumers and producers exists in the same silo, I want they to use local streaming infra, for efficiency concern. ), it is a new scenario essentially which is not related to the subscribing problems currently in the system. This case is more about performance improvement on streaming, but with certain constraints and complications. We want to tinker more on it. So remove this case from this issue for now.
For this new use case, neither of orleans streaming system’s current subscribe models can support it. This drove us to design this new feature for streaming. As follows it the design for this feature.
New Component
• IStreamSubscriptionManager: the public interface which application use to configure subscription programmablly. User can access StreamSubscriptionManager through stream provider. It will not support adding or removing implicit subscriptions. Those subscriptions will be query only.
New Pattern
- Application configure subscription map using
IStreamSubscriptionManager2. Consumer grain attach its observer usingResumeAsyncin its grain logic.
Common Questions
1 What would a quick remove/re-add pair do to an active grain? Would it just stop receiving events and then start receiving them again? In the current design, it would simply stop delivering events to the consumer, then resume delivering events. The effects of this ‘interruption’ would depend on the stream provider implementation. For SMS, any messages sent between the remove/add, could be lost. For recoverable stream providers like EventHub, when the re-added subscription is being established the handshake with the grain will inform the streaming system where to start delivering from, and if the data is still in the cache no data loss should occur.
API Design
IStreamSubscriptionManager
public interface IStreamSubscriptionManager
{
Task<StreamSubscription> AddSubscription(IStreamIdentity streamId, GrainReference grainRef);
Task RemoveSubscription(Guid subscriptionId);
Task<IEnumerable<StreamSubscription>> GetSubscriptions(IStreamIdentity StreamId);
}
StreamSubscription
public class StreamSubscription
{
StreamSubscription(Guid subscriptionId, string streamProviderName, IStreamIdentity streamId, IGrainIdentity grainId)
{
this.SubscriptionId = subscriptionId;
this.StreamProviderName = streamProviderName;
this.StreamId = streamId;
this.GrainId = grainId;
}
public Guid SubscriptionId;
public string StreamProviderName;
public IStreamIdentity StreamId;
public IGrainIdentity GrainId;
}
IStreamProvider A property will be added to a stream provider for users to access it’s subscription manager.
public interface IStreamProvider
{
string Name { get; }
IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace);
bool IsRewindable { get; }
IStreamSubscriptionManager SubscriptionManager { get; }
}
StreamSubscriptionManagerExtensions
public static class StreamSubscriptionManagerExtensions
{
public static Task<StreamSubscription> AddSubscription<TGrainInterface>(
this IStreamSubscriptionManager manager,
IStreamIdentity streamId,
Guid primaryKey,
string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidKey
{
// placeholder
return Task.FromResult<StreamSubscription>(null);
}
public static Task<StreamSubscription> AddSubscription<TGrainInterface>(
this IStreamSubscriptionManager manager,
IStreamIdentity streamId,
long primaryKey,
string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerKey
{
// placeholder
return Task.FromResult<StreamSubscription>(null);
}
public static Task<StreamSubscription> AddSubscription<TGrainInterface>(
this IStreamSubscriptionManager manager,
IStreamIdentity streamId,
string primaryKey,
string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithStringKey
{
// placeholder
return Task.FromResult<StreamSubscription>(null);
}
public static Task<StreamSubscription> AddSubscription<TGrainInterface>(
this IStreamSubscriptionManager manager,
IStreamIdentity streamId,
Guid primaryKey,
string keyExtension,
string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidCompoundKey
{
// placeholder
return Task.FromResult<StreamSubscription>(null);
}
public static Task<StreamSubscription> AddSubscription<TGrainInterface>(
this IStreamSubscriptionManager manager,
IStreamIdentity streamId,
long primaryKey,
string keyExtension,
string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerCompoundKey
{
// placeholder
return Task.FromResult<StreamSubscription>(null);
}
}
Implementation details
StreamSubscriptionManager An internal StreamSubscriptionManager will be developed that is constructed with the IStreamPubSub configured for the stream provider.
EDIT: Remove the implementation for MemoryPubSub for same reasons described on EDIT above Remove (MemoryPubSub We’ll add an implementation of IStreamPubSub that keeps subscription information in local memory.) From this issue
An example usage could be a bootstrap provider which used configuration settings to create stream subscriptions at silo startup.
To create a stream subscription for a grain with id grainId, and a stream with id streamId
Guid grainId = Guid.NewGuid();
IStreamIdentity streamId = new StreamIdentity(Guid.NewGuid(), "MyStreamNamespace");
One could create a subscription using the grain reference obtained from a grain factory
IMyGrain myGrain = grainFactory.GetGrain<IMyGrain>(grainId);
StreamSubscription subscription = await streamProvider.SubscriptionManager.AddSubscription(streamId, myGrain.AsWeaklyTypedReference());
or by using the utility functions that mirror the grain factory pattern.
StreamSubscription subscription = await streamProvider.SubscriptionManager.AddSubscription<IMyGrain>(streamId, grainId);
Either approach will create a subscription just as if the grain created it by calling SubscribeAsync, and the next event delivered on the stream will be routed to the grain, activating the grain if it is not yet active.
tagging @gabikliot
Interesting... I would allow not just bootstrap provider but GrainServices as well. I have a case here where I wan't to publish messages to streams from it, but it isn't allowed...
Can you help me understand why it is not allowed?
As far as I know, you can access IServiceProvider in GrainService, and then you can get IStreamProviderManager from ISP, which can help you accesss the streamProvider you want. This streamProvider can help you get SubscriptionManager and AddSubscription.
And what's the use case you want to build the subscription map using GrainService?
@jdom @sergeybykov I know you guys want to know
suggest
public interface IStreamSubscriptionManager
{
Task<StreamSubscription> AddSubscription(IStreamIdentity streamId, GrainReference grainRef);
Task RemoveSubscription(Guid subscriptionId); => Task RemoveSubscription(StreamSubscription subscription);
Task<IEnumerable<StreamSubscription>> GetSubscriptions(IStreamIdentity StreamId);
}
because of current IStreamPubSub design and RemoveSubscription method need to call IStreamPubSub to remove the subscription, with subscriptionId and streamId, instead of just subscriptionId
Maybe Task RemoveSubscription(IStreamIdentity streamId, Guid subscriptionId)? We can add an extension function for Task RemoveSubscription(StreamSubscription subscription) but I don't think we should be passing in more info than is needed.
@xiazen maybe it is allowed by other stream providers (idk), but SMS one it isn't.
The reason os probably because SMS will end up doing a grain method call, and the grain service isn't allowed to do that because it doesn't have activation context.
To simulate the failure, try create a grain service, inject IStreamProviderManager at the ctor, and then call this code in any method of the service:
try
{
var streamP = sprovider.GetStreamProvider("SMSProvider");
var stream = streamP.GetStream<EngineStatus>(Guid.Empty, "mystream");
await stream.OnNextAsync(new EngineStatus
{
Node = Silo.ToString(),
Status = DockerEngineStatus.Starting
});
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
That will print Attempting to GetCurrentActivationData when not in an activation scope.
To clarify. This issue originally mixed two unrelated concerns: 1) API for managing stream subscriptions on behalf of grains without the need to activate them; and 2) per-silo in-memory streaming pub-sub. I suggested to limit this issue to 1), and that's why @xiazen updated the description. 2) might get brought back up as a separate issue.
Over the last week, we made some API changes and also add new feature to Programmatic Subscribing, for reasons we think would make programmatic subscribing great again! Summary below:
API change: First, We decided to provide access of IStreamSubscriptionManager through DI, and one StreamProvider extension method, instead of through IStreamProvider interface. The main reason behind this change is to prevent unnecessary coupling between IStreamProvider and IStreamSubscriptionManager. So the API would be updated as follows:
public interface IStreamSubscriptionManager
{
Task<StreamSubscription> AddSubscription(IStreamIdentity streamId, GrainReference grainRef);
Task RemoveSubscription(IStreamIdentity streamId, Guid subscriptionId);
Task<IEnumerable<StreamSubscription>> GetSubscriptions(IStreamIdentity StreamId);
}
public interface IStreamSubscriptionManagerAdmin
{
IStreamSubscriptionManager GetStreamSubscriptionManager(string name);
}
This is similar pattern with StreamProviderManager.GetStreamProvider(string name); For now, the name in GetStreamSubscriptionManager(string name) is streamProviderName, but in the future , it DOES NOT have to be. So this decouples the concept of IStreamSubscriptionManager with IStreamProvider. But for better user experience, we provide an extension method for the IStreamProvider to retrieve its associated StreamSubscriptionManager, if it is associated with one. Otherwise the method returns false. So in API design aspect, it implies not all StreamProvider has one StreamSubscriptionManager associated. This two concepts are still decoupled.
public static class StreamSubscriptionManagerExtension
{
static bool TryGetStreamSubscrptionManager(this IStreamProvider streamProvider, out IStreamSubscriptionManager manager);
}
So the application layer can access IStreamSubscriptionManager through DI and the extension method.
Second, to support the ability of notifying an activated consumer grain about its new subscription made by IStreamSubscriptionMangaer, we added a new method OnSubscriptionChange on IStreamProvider.
public interface IStreamProvider
{
string Name { get; }
IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace);
bool IsRewindable { get; }
void SetOnSubscriptionChangeAction<T>(Func<StreamSubscriptionHandle<T>, Task> onAdd);
}
Example code: Programmatic managing subscription:
var subManager = this.ServiceProvider.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManger(providerName);
await subManager.Add(streamId, grainRef);
or
IStreamSubscriptionManager subManager;
bool re = this.ServiceProvider.Get<IStreamSubscriptionManager>().GetStreamProvider(providerName).TryGetStreamSubscriptionManager(out subManager);
if(re)
{
await subManager.Add(streamId, grainRef);
}
Grain code:
public class ExampleGrain : Grain, IExampleGrain
{
void async onAdd<T>(StreamSubscriptionHandle<T> handle)
{
await handle.ResumeAsync(new SampleObserver());
}
public override async Task OnActivateAsync()
{
IStreamProvider streamProvider = base.GetStreamProvider(streamId.ProviderName);
await streamProvider.SetOnSubscriptionChangeAction<int>(onAdd<int>);
}
}
this feature has been added to the master branch. close this issue
Reopen this issue for reasons:
- there's update on the public API
- there's no documentation about Programmatic Subscribe , this issue is the closest text to a documentation. So I plan to keep it open until this feature has proper documentation
Updated API:
Compared to last post, the changes here is we added param string streamProviderName to IStreamSubscriptionManager 's methods. Main reason behind it is to decouple subscription setup with StreamProvider set up (#2881). Subscription set up does not rely on a stream provider finishing configuring. It can be set up before or after the stream provider.
public interface IStreamSubscriptionManager
{
Task<StreamSubscription> AddSubscription(string streamProviderName, IStreamIdentity streamId, GrainReference grainRef);
Task RemoveSubscription(string streamProviderName, IStreamIdentity streamId, Guid subscriptionId);
Task<IEnumerable<StreamSubscription>> GetSubscriptions(string streamProviderName, IStreamIdentity StreamId);
}
Second, we introduced StreamSubscriptionManagerType in the IStreamSubscriptionManagerAdmin. Currently we only have ExplicitSubscribeOnly type, which means Programmatic Subscribe (StreamSubscriptionManager) currently play wells with explicit subscribe style consumer grains, not play well with Implicit subscribe style consumer grain.
public interface IStreamSubscriptionManagerAdmin
{
IStreamSubscriptionManager GetStreamSubscriptionManager(string managerType);
}
public static class StreamSubscriptionManagerType
{
public readonly static string ExplicitSubscribeOnly = "ExplicitSubscribeOnly";
}
This is similar pattern with StreamProviderManager.GetStreamProvider(string name). So you can retrieve StreamSubscriptionManager like this:
var subManager = this.ServiceProvider.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManager(StreamSubscriptionManagerType.ExplicitSubscribeOnly);
But for better user experience, we provide an extension method for the IStreamProvider to retrieve its associated StreamSubscriptionManager, if it is associated with one. Only stream provider configured with StreamPubSubType of ExplicitGrainBasedOnly or ExplicitGrainBasedAndImplicit will have an associated StreamSubscriptionManager. Otherwise the method returns false. So in API design aspect, it implies not all StreamProvider has one StreamSubscriptionManager associated. This two concepts are still decoupled.
public static class StreamSubscriptionManagerExtension
{
public static bool TryGetStreamSubscrptionManager(this IStreamProvider streamProvider, out IStreamSubscriptionManager manager)
}
So the application layer can access IStreamSubscriptionManagerAdmin through DI and get the correct StreamSubscriptionManager from there, or use the extension method.
Thirdly, to support the ability of notifying an activated consumer grain about its new subscription made by IStreamSubscriptionMangaer, we added a new method SetOnSubscriptionChangeAction on IStreamProvider.
If a consumer grain calls this method in its OnActivateAsync, it will hand a onAddAction handle to streaming infra. So when an subscription is added on behalf of the grain, and the first new item in this newly subscribed stream is about to arrive to the consumer grain, the stream infra will activate the grain -> grain OnActivateAsync logic give the streaming infra onAddAction handle -> streaming infra use this onAddAction handle to determine what to do with the newly arrived item, if there's no observer attached to the subscription for this grain yet. Most of the case, in the onAddAction, users will do ResumeAsync() on the parsed in StreamSubscriptionHandle param.
public interface IStreamProvider
{
string Name { get; }
IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace);
bool IsRewindable { get; }
Task SetOnSubscriptionChangeAction<T>(Func<StreamSubscriptionHandle<T>, Task> onAddAction);
}
Example code: Programmatic managing subscription:
var subManager = this.ServiceProvider.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManger(StreamSubscriptionManagerType.ExplicitSubscribeOnly);
await subManager..AddSubscription(providerName, streamId, grainRef);
or
IStreamSubscriptionManager subManager;
bool re = this.ServiceProvider.Get<IStreamSubscriptionManager>().GetStreamProvider(providerName).TryGetStreamSubscriptionManager(out subManager);
if(re)
{
await subManager..AddSubscription(providerName, streamId, grainRef);
}
Grain code:
public class ExampleConsumerGrain : Grain, IExampleGrain
{
public override async Task OnActivateAsync()
{
streamProvider = base.GetStreamProvider("SMSProvider2");
await streamProvider.SetOnSubscriptionChangeAction<int>(this.OnAdd);
}
private async Task OnAdd(StreamSubscriptionHandle<int> handle)
{
var observer = new ConsumerObserver<int>(this.logger);
await handle.ResumeAsync(observer);
}
}
Good example code to refer to when you try to figure out how to use this feature exactly !
ProgrammaticSubscribeTests (https://github.com/dotnet/orleans/tree/master/test/Tester/StreamingTests/ProgrammaticSubscribeTests)
Currently we are thinking about doing another refactoring on the API, to IStreamProvider method Task SetOnSubscriptionChangeAction<T>(Func<StreamSubscriptionHandle<T>, Task> onAddAction); specifically.
This API is misleading because SetOnSubscriptionChangeAction shouldn't be coupled with a stream provider, it can be set up with or without the stream provider.
We are currently thinking about this alternative:
If a consumer grain wants to use the SetOnSubscriptionChangeAction feature, instead of calling SetOnSubscriptionChangeAction method on a stream provider and give the streaming infra an onAddAction handle, it implements a interface instead: (names are not final)
public interface IStreamSubscriptionObserver
{
Task OnAdd<T>(StreamSubscriptionHandle<T> handle);
}
In this way, set up OnSubscriptionChange actions will be decoupled with stream provider.
One task in triage, do we want to add onRemove(StreamIdentity streamId, string providerName) to IStreamSubscriptionObserver ?
@xiazen, I think an OnRemoved makes sense, but as we've not figured out how to actually wire that up, I think we should leave it off for now. I think it can be added in a future pass.
I probably should open a issue to discuss this. But I figured post it here may bring more context to the question.
One concern with OnRemove, it is a little redundant. The expected behavior of OnRemove wakes up the grain and notify it that one of its subscription being removed. But the grain can also call a its own method to remove the subscription and handle the removed subscription from there.
Programmatic subscribe came from the request/benefits of setting up subscription without waking up the consumer grain. But since OnRemove activates the grain anyways, where's the gain?
I would argue that an OnRemove call should not be made to a grain if the grain is not setup to handle the call, so it could wake up grains that inherit from IStreamSubscriptionObserver, but not other streaming grains.
I'd also argue that the OnRemove call should not be called when a grain unsubscribed, only when something else removes the subscription, as a way of notifying the grain of the subscription change.
As for the utility of this call, I agree it is of limited utility, but if subscriptions can be added/removed for a grain, a grain should have some way of knowing about these changes.
Consider a diagnostic stream processing grain that can be subscribed to a stream and collect statistics. A user may want to subscribe the grain for a while, then unsubscribe the grain and get the resulting statistics. The grain would need to know when it's unsubscribed to generate the report. I'm not saying this is a core scenario, nor that this couldn't be done without the OnRemoved, this is just an example of where knowing that a grain is no longer subscribed to a stream could be valuable.
The limited utility of the feature, combined with the unclear means of implementing it, are why I'm advocating for revisiting the issue at a later point, when there is a clearer need.
U r a good candidate that you are interested. He suggested if there's people interested then we implement it.
Xiao
Get Outlook for Androidhttps://aka.ms/ghei36
From: Jason Bragg [email protected] Sent: Wednesday, April 5, 2017 2:54:15 PM To: dotnet/orleans Cc: Xiao Zeng; Mention Subject: Re: [dotnet/orleans] Programmable stream subscribe API (#2741)
I would argue that an OnRemove call should not be made to a grain if the grain is not setup to handle the call, so it could wake up grains that inherit from IStreamSubscriptionObserver, but not other streaming grains.
I'd also argue that the OnRemove call should not be called when a grain unsubscribed, only when something else removes the subscription, as a way of notifying the grain of the subscription change.
As for the utility of this call, I agree it is of limited utility, but if subscriptions can be added/removed for a grain, a grain should have some way of knowing about these changes.
Consider a diagnostic stream processing grain that can be subscribed to a stream and collect statistics. A user may want to subscribe the grain for a while, then unsubscribe the grain and get the resulting statistics. The grain would need to know when it's unsubscribed to generate the report. I'm not saying this is a core scenario, nor that this couldn't be done without the OnRemoved, this is just an example of where knowing that a grain is no longer subscribed to a stream could be valuable.
The limited utility of the feature, combined with the unclear means of implementing it, are why I'm advocating for revisiting the issue at a later point, when there is a clearer need.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fdotnet%2Forleans%2Fissues%2F2741%23issuecomment-292008646&data=02%7C01%7Cxiazen%40microsoft.com%7C67ffd898f15f48a25d5b08d47c6e4e16%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C636270260579328130&sdata=y7X2uB2wNMuNKyNGfjGXuV7wfCeezD%2FrMIxF7uh9XAA%3D&reserved=0, or mute the threadhttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FAT1w2bLO5Uv3b8emijR5Of4v2CGcetokks5rtA2HgaJpZM4ME702&data=02%7C01%7Cxiazen%40microsoft.com%7C67ffd898f15f48a25d5b08d47c6e4e16%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C636270260579328130&sdata=XLBslHGi7I%2B5iktrcYk8qpG5XExe2ORHfbFx7jcLqJU%3D&reserved=0.
Resolved via #2796.