orleans icon indicating copy to clipboard operation
orleans copied to clipboard

Namespace property removed from ImplicitStreamSubscriptionAttribute in 1.5

Open centur opened this issue 8 years ago • 45 comments

From gitter chat here

We started to migrate 1.4 -> 1.5 (2.0 deemed too big rework and too many breaking changes) and discovered that we need to make some changes in our code base. They are more or less reasonable like DI for constructors and some removed defaults. There is one change in 1.5 that looks strange and unreasonable and I'd like to understand what was the reasoning behind it:

Previously (in 1.4) ImplicitStreamSubscriptionAttribute has a public Namespace property on it and it was quite nice way to use subscription attribute itself to subscribe instance of the class to streams: we are using reflection to create shared code in BaseStreamListener class which simply reflected over attributes and produced the list of "namespaces" to subscribe - thus we have centralized way to subscribe to the stream in base class - reusable piece of logic. in 1.5. Namespace property was replaced by Predicate and for simple scenario like ours - all what we need is to pass namespace string in ctor, which then will be converted to ExactMatchStreamNamespacePredicate (which design is also leaves question as it's internal and doesn't expose any helpful information to subscribe to streams in the stream listening classes).

From my understanding - we still need to subscribe instance to the stream in runtime, and call something like this:

foreach(var streamNamespace in allNamespaces)
  var inputStream = StreamFactory.GetStream<TMessageType>(primaryKey, streamProvider, streamNamespace);
   var handle = await inputStream.SubscribeAsync(ReceiveCommand, OnCommandError, OnCommandCompleted);
  _streams.Add(inputStream);
  _handles.Add(handle);
}

At least this is how we are working with streams in 1.4.

In raw Orleans 1.5 we need to add ImplicitStreamSubscription("fooNamespace") attribute to the class but ALSO to keep a separate collection of namespaces to subscribe in runtime like in above example. It feels that this is not a well-thought decision and some practical functionality was removed without adding any obvious way to achieve the same results.

In 1.4. we don't need to maintain any separate collection - it was beautifully simple to scrap all string values from attributes on the class:

    protected virtual IEnumerable<string> getNamespacesFromAttributes()
    {
            var allNamespaces = this.GetType()
                .GetCustomAttributes(typeof(ImplicitStreamSubscriptionAttribute), false)
                .Select(attrib => ((ImplicitStreamSubscriptionAttribute) attrib).Namespace)
                .ToList();

            return allNamespaces;
    }

and the attributes on top of the class were a single source of truth for namespaces this stream is subscribed to.

We can simply add back this functionality by creating

/// <summary>
	/// The reason why this class exists is that between 1.4 and 1.5 ImplicitStreamSubscriptionAttribute lost it's property "Namespace" that we were using in getNamespacesFromAttributes method of BaseListenerGrain.
	/// This class simply returns it back.
	/// </summary>
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class DrawboardImplicitStreamSubscriptionAttribute : ImplicitStreamSubscriptionAttribute
	{
		/// <summary>
		/// Legacy compartible property Namespace to make subscription easier
		/// </summary>
		public string  Namespace { get; }

		/// <summary>Used to subscribe to all stream namespaces.</summary>
		public DrawboardImplicitStreamSubscriptionAttribute() : base()
		{
			this.Namespace = string.Empty;
		}

		/// <summary>Used to subscribe to the specified stream namespace.</summary>
		/// <param name="streamNamespace">The stream namespace to subscribe.</param>
		public DrawboardImplicitStreamSubscriptionAttribute(string streamNamespace) : base(streamNamespace)
		{
			this.Namespace = streamNamespace;
		}

	}

And ditch all ImplicitStreamSubscriptionAttribute in favour of our own one, and this is what we are doing now. For me it's a code smell to introduce your own attributes to solve the problem that was perfectly solved in older versions of framework.

But the question is - what was the reason behind this breaking change ? It feels that it doesn't affect anything, but was simply to break public contract that was in use (across multiple 1.x version) without any obvious alternative or any afterthoughts of how this is going to affect existing deployments.

Also, If there is a better way to implement this in non 2.0 world - keen to hear in comments.

centur avatar Aug 09 '18 22:08 centur

For implicit subscriptions, the subscriptions always exist, and the grain is always subscribed to them, it's just a question of attaching the observable to the stream. For that, one needs to know which stream the grain is subscribed to. To make this cleaner, we added a new capability. One needs only have their grain implement the IStreamSubscriptionObserver interface.

Something like

    public async Task OnSubscribed(IStreamSubscriptionHandleFactory handleFactory)
    {
        await handleFactory.Create<IFruit>().ResumeAsync(OnNext);
    }

The system will now tell the grain about it's subscriptions by calling the OnSubscribed for each stream attempting to deliver events to the grain. If you want to know more about the stream prior to connecting the observer, the IStreamSubscriptionHandleFactory has information in it, like stream id and provider name.

Comparable code to what you have should be something like:

public async Task OnSubscribed(IStreamSubscriptionHandleFactory handleFactory)
{
    var handle = await handleFactory.Create<TMessageType>().ResumeAsync(
        ReceiveCommand, OnCommandError, OnCommandCompleted);
    _handles.Add(handle);
}

if you want to cache that actual stream (for some reason) you can add

var inputStream = StreamFactory.GetStream<TMessageType>(handleFactory.StreamId.Guid,
    handleFactory.ProviderName, handleFactory.StreamId.Namespace);
_streams.Add(inputStream);

jason-bragg avatar Aug 10 '18 00:08 jason-bragg

Thanks @jason-bragg 👍 , this looks clean. 1.5.4. implementation passes a bit different object than in your example - an actual handle, not factory, which looks even better:

                public async Task OnSubscribed(StreamSubscriptionHandle<TMessageType> handle)
		{
			await handle.ResumeAsync(ReceiveCommand, OnCommandError, OnCommandCompleted);
			_handles.Add(handle);
		}

On caching actual stream - I think it was done before we realised that for a proper Unsubscribe we don't need an actual IAsyncStream<TMessageType> object, but only a handle. We can cache handle in the existing interface which is using to unsubscribe \close websocket clients on deactivation.

One thing that I don't 100% understand - with this new code - how runtime selects which stream to chose by name? Previously it was in the code of obtaining stream reference e.g.:

var streamProviderName = "EventhubStreamProvider1";
var inputStream = StreamFactory.GetStream<TMessageType>(primaryKey, streamProviderName, streamNamespace);

But how it works with this IStreamSubscriptionObserver - how Orleans infers which specific stream implementation (out of all registered ones ) to use for this subscription?

centur avatar Aug 10 '18 03:08 centur

Hmm.. this isn't good news.. The original implementation that returned a handle had a bug in it. The changes to the public surface were there to address that. I thought we'd pushed the fix in a 1.5.x release, but I'm not confident.

@xiazen, do you recall what we fixed and in what release?

jason-bragg avatar Aug 10 '18 16:08 jason-bragg

Umm @jason-bragg does it means that 1.5 doesn't work well with streams or it's just your solution that would not work ?

centur avatar Aug 12 '18 22:08 centur

Seems that this is what I guessed - I tried to debug streams locally - proposed solution does not work. reverted to previous idea with our own custom attribute and old subscription code in OnActivateAsync(). I recon this is quite an issue...

centur avatar Aug 13 '18 04:08 centur

@centur, 1.5.x works with streams, but, due to a bug, the IStreamSubscriptionObserver abstraction only works for sms. :( I think your original work around is probably the best solution until you move to 2.0, unfortunately.. :/

jason-bragg avatar Aug 13 '18 17:08 jason-bragg

the IStreamSubscriptionObserver bug fix change is included in 2.0 I think. But not 1.5.x

xiazen avatar Aug 13 '18 18:08 xiazen

Would it make sense to release 1.5.5 with the fix?

sergeybykov avatar Aug 13 '18 18:08 sergeybykov

if we can. I don't see why not. Ideally it should, since the feature and the bug is released within 1.5.0. So in theory the fix should be included in 1.5.x

xiazen avatar Aug 13 '18 21:08 xiazen

@jason-bragg that may not happen very soon (migration to 2.0). I tried to do it in a separate branch - changes are quite painful and very broad, we haven't got to 1.5.4 yet (battling with DI currently) so having this fix in 1.5.5 would be nice.

centur avatar Aug 14 '18 04:08 centur

We're looking at a 1.5.5 release. If we go forward with it, this will definitely be included.

jason-bragg avatar Aug 14 '18 17:08 jason-bragg

@xiazen @jason-bragg What commit from master do we need to backport to 1.5.5 for this?

sergeybykov avatar Aug 31 '18 00:08 sergeybykov

@centur We ported the relevant PRs (#3843 and #3851) to https://github.com/dotnet/orleans/tree/1.5.5. Can you pull, build, and try it to confirm that this will resolve the issue for you?

sergeybykov avatar Sep 05 '18 21:09 sergeybykov

@centur We just published 1.5.5. I think we can close this now. Please reopen if that's not the case.

sergeybykov avatar Sep 08 '18 00:09 sergeybykov

Sorry just get a chance to get to it, really, last week was a bit packed. First outcome - Cloud service silo does not start with this error 👍

[WaWorkerHost.exe] Starting Orleans.Runtime.Host.AzureSilo v1.5.5.0 (Release).
[WaWorkerHost.exe] [2018-09-11 02:03:00.398 GMT    12	ERROR  	100105	OrleansSiloHost	]	!!!!!!!!!! ERROR starting Orleans silo name=AzureCloudServiceHost.DBCloud.ActorsHost_IN_0 Exception=
Exc level 0: System.TypeLoadException: Could not load type 'Orleans.Streams.Core.IStreamSubscriptionObserver`1' from assembly 'Orleans, Version=1.5.5.0, Culture=neutral, PublicKeyToken=null'.
   at Orleans.Runtime.Silo..ctor(SiloInitializationParameters initializationParams)
   at Orleans.Runtime.Host.SiloHost.InitializeOrleansSilo()	
Exc level 0: System.TypeLoadException: Could not load type 'Orleans.Streams.Core.IStreamSubscriptionObserver`1' from assembly 'Orleans, Version=1.5.5.0, Culture=neutral, PublicKeyToken=null'.
   at Orleans.Runtime.Silo..ctor(SiloInitializationParameters initializationParams)
   at Orleans.Runtime.Host.SiloHost.InitializeOrleansSilo()
[WaWorkerHost.exe] [2018-09-11 02:03:00.421 GMT    12	ERROR  	100105	OrleansSiloHost	]	!!!!!!!!!! ERROR starting Orleans silo name=AzureCloudServiceHost.DBCloud.ActorsHost_IN_0 Exception=
Exc level 0: System.InvalidOperationException: Cannot start silo AzureCloudServiceHost.DBCloud.ActorsHost_IN_0 due to prior initialization error
   at Orleans.Runtime.Host.SiloHost.StartOrleansSilo(Boolean catchExceptions)	
Exc level 0: System.InvalidOperationException: Cannot start silo AzureCloudServiceHost.DBCloud.ActorsHost_IN_0 due to prior initialization error
   at Orleans.Runtime.Host.SiloHost.StartOrleansSilo(Boolean catchExceptions)
[WaWorkerHost.exe] [2018-09-11 02:03:00.438 GMT    12	ERROR  	100285	OrleansAzureSilo	]	!!!!!!!!!! Failed to start Orleans silo 'AzureCloudServiceHost.DBCloud.ActorsHost_IN_0' as a Secondary node.	
[runtime] Unhandled Exception:
System.Exception: Silo failed to start correctly - aborting
   at Orleans.Runtime.Host.AzureSilo.RunImpl(Nullable`1 cancellationToken)
   at Orleans.Runtime.Host.AzureSilo.Run(CancellationToken cancellationToken)
   at DBCloud.ActorsHost.WorkerRole.Run() in C:\Projects\bullclip-backend\DBCloud.ActorsHost\WorkerRole.cs:line 85
   at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.StartRoleInternal()
   at Microsoft.WindowsAzure.ServiceRuntime.Implementation.Loader.RoleRuntimeBridge.<StartRole>b__2()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Orleans.dll version in the package looks valid (old Cloud services still require us to have valid <assemblyBinding><dependentAssembly>.... setup, so it always a check for me) image

So we are staying on 1.5.4 for now, it's in production already.

But I still can't understand how it supposed to work (again :( ) in new model:

1.5.4 has generic interface IStreamSubscriptionObserver<TMessageType> in 1.5.5 it's non-generic IStreamSubscriptionObserver - is this an accidental or intentional breaking change ? I understand that it's quite unlikely anyone used it as it was not working properly. Generic version of interface kinda makes sense - in pre 1.5.x it was StreamFactory.GetStream<TMessageType>(primaryKey, streamProvider, streamNamespace); . And in our code I have that generic TMessageType available ( in all our classes that are implicitly subscribing to streams) so I can re-subscribe as @jason-bragg posted above - var handle = await handleFactory.Create<TMessageType>().ResumeAsync(ReceiveCommand, OnCommandError, OnCommandCompleted); . I remember it was invoked for every attribute instance on the class.

But what I can't understand - how this factory resolves which exact stream provider to use? In 1.4 it was an explicit parameter in this code:

var inputStream = StreamFactory.GetStream<TMessageType>(primaryKey, streamProvider, streamNamespace);
var handle = await inputStream.SubscribeAsync(ReceiveCommand, OnCommandError, OnCommandCompleted);

Right there, first line, streamProvider - name of the provider from config. No magic, if one has 10 Azure queue-backed provider instances registered - he must call these 2 lines for each of 10 provider.

From everything I saw so far in 1.5.x, new streaming has no way to resolve provider by name. There is no such parameters in the interface and class itself is not setting it anywhere. Can someone points me to that magic in the code which is used to select a specific events stream for subscription (if we are implementation-specific - specific set of azure queues)

centur avatar Sep 11 '18 02:09 centur

@sergeybykov I can't reopen this issue. only team members can.

centur avatar Sep 11 '18 02:09 centur

1.5.4 has generic interface IStreamSubscriptionObserver in 1.5.5 it's non-generic IStreamSubscriptionObserver - is this an accidental or intentional breaking change ? I understand that it's quite unlikely anyone used it as it was not working properly.

Yes it is a breaking change, because 1.5.4 IStreamSubscriptionObserver<TMessageType> has a bug so this feature doesn't work. We fixed it by introducing the factory in 1.5.5. The reason for the change is, if I remember correctly, IStreamSubscriptionObserver<TMessageType> has trouble handle the case where TMessageType is a base class or an interface, but the message sent is a child class of the base class or an interface implementation. The streaming infra has difficulty figure out the correct IStreamSubscriptionObserver<TMessageType> to use, since at this point it only knows the message's concrete type. Ofc we can use reflection to figure out interfaces this class implements, but we have no way to know which one. So we introduced the factory pattern in 1.5.5, hand this job to application code, since application would know which TMessageType it is expecting. Hence this breaking change. Does this make sense?

how this factory resolves which exact stream provider to use?

The IStreamSubscriptionHandleFactory has a getter for stream provider name, so the consumer grain will know which stream provider and which stream it is dealing with, when OnSubscribed called.

From everything I saw so far in 1.5.x, new streaming has no way to resolve provider by name.

In 1.5, it has ways to resolve provider by name, for stream provider specificly, I believe you can call GetStreamProvider method on Grains and cluster client

As for the assembly loading bug... hmm.... is it happening with OrleansSiloHost?

xiazen avatar Sep 11 '18 20:09 xiazen

Sorry for the lack of documentation on IStreamSubscriptionObserver<TMessageType> feature, and probably some docs missing in 1.5. streaming. Did you guys successfully migrated to 1.5.4?

xiazen avatar Sep 11 '18 20:09 xiazen

@xiazen Assembly loading bug - from stack trace above I would assume so

System.TypeLoadException: Could not load type 'Orleans.Streams.Core.IStreamSubscriptionObserver`1' from assembly 'Orleans, Version=1.5.5.0, Culture=neutral, PublicKeyToken=null'.
   at Orleans.Runtime.Silo..ctor(SiloInitializationParameters initializationParams)
   at Orleans.Runtime.Host.SiloHost.InitializeOrleansSilo()	

this not even getting into our code, it's at the point of constructing silo host in the role.

On others - this still does not clarify anything with regards to my question - how this interface figures out, which exact named stream to use in subscription. if the syntax of new re-subscribing in this issue is correct - name is currently removed from the process flow. And it breaks model in my head. To illustrate this with a bit more specific context: We have multiple (5 different) Azure Queue backed streams with different queue names and polling frequencies. Call it AQ_1_Provider to AQ_5_Provider. In some cases we are sending same message, say UserCreated class instance into multiple streams. Now for each of those streams we have multiple listeners (grains which have been implicitly subscribed to a stream and specific namespace). In listeners we usually subscribed to streams by provider name - e.g. AQ_3 and AQ_5 and name of the message (which is usually a message type name, in the case above, Namespace on attribute was assigned to nameof(UserCreated) )

So with this general setup - I understand that to subscribe to UserCreated messages (read namespace) from AQ_3 stream - I need both values in 1.4.x How come it to some magical resolution that in 1.5 and new system we don't use name of a stream provider AQ_3 anymore. How that even works ? There is no named registration or named DI injection in our grains. How it picks correct Stream provider registration ?

centur avatar Sep 12 '18 00:09 centur

How come it to some magical resolution that in 1.5 and new system we don't use name of a stream provider AQ_3 anymore.

Sorry for confused you somehow, but I never said we doesn't need a stream provider name to begin within 1.5. When you set up the subscription usingStreamSubscriptionManager on behalf of the grain, you will need go give streaming infra the stream provider name, stream id and grain ref . This is how stream infra knows what stream provider name to set on the IStreamSubscriptionHandleFactory when it sees a message sent to the consumer grain. Does this answer your question, or you are confused about something else?

xiazen avatar Sep 18 '18 14:09 xiazen