示例#1
0
        public OrniscientObserver()
        {
            var streamprovider = GrainClient.GetStreamProvider(StreamKeys.StreamProvider);

            _stream = streamprovider.GetStream <DiffModel>(Guid.Empty, StreamKeys.OrniscientClient);
            _stream.SubscribeAsync(this);
        }
        private async Task ConnectToClusterAsync()
        {
            await EnsureOrleansClusterConnection();

            OrleansLog.Subscribing(_logger, _id);

            var provider = _clusterClient.GetStreamProvider(Constants.STREAM_PROVIDER);

            _clientMessageStream = provider.GetStream <ClientInvocationMessage>(_id, Constants.CLIENT_MESSAGE_STREAM_NAMESPACE);
            await _clientMessageStream.SubscribeAsync(async (message, token) => await OnReceivedClientMessageAsync(message));

            _allMessageStream = provider.GetStream <AllInvocationMessage>(_hubTypeId, Constants.HUB_MESSAGE_STREAM_NAMESPACE);
            await _allMessageStream.SubscribeAsync(async (message, token) => await OnReceivedAllMessageAsync(message));

            try
            {
                await _clusterClient.GetHubLifetimeManagerGrain(_id, _hubTypeId).OnInitializeAsync(_options.TimeoutInterval ?? TimeSpan.FromSeconds(30));

                // Tick heartbeat
                heartbeatDisposable = Observable.Interval(TimeSpan.FromSeconds(1))
                                      .Subscribe(async value =>
                {
                    await _clusterClient.GetHubLifetimeManagerGrain(_id, _hubTypeId).OnHeartbeatAsync();
                });
            }
            catch (Exception e)
            {
                OrleansLog.InternalMessageFailed(_logger, e);
            }
        }
示例#3
0
        public override async Task OnActivateAsync()
        {
            logger = base.GetLogger("MultipleImplicitSubscriptionGrain " + base.IdentityString);
            logger.Info("OnActivateAsync");

            var streamProvider = GetStreamProvider("SMSProvider");

            redStream  = streamProvider.GetStream <int>(this.GetPrimaryKey(), "red");
            blueStream = streamProvider.GetStream <int>(this.GetPrimaryKey(), "blue");

            await redStream.SubscribeAsync(
                (e, t) =>
            {
                logger.Info("Received a red event {0}", e);
                redCounter++;
                return(Task.CompletedTask);
            });

            await blueStream.SubscribeAsync(
                (e, t) =>
            {
                logger.Info("Received a blue event {0}", e);
                blueCounter++;
                return(Task.CompletedTask);
            });
        }
示例#4
0
        public async Task StreamingPubSubStoreTest()
        {
            var strmId = Guid.NewGuid();

            var providers = this.HostedCluster.ClientConfiguration.GetAllProviderConfigurations();
            var sms       = from x in providers
                            where
                            x.Name.Equals(StreamProviderName)
                            select x;

            Assert.True(sms.Count() == 1);


            try
            {
                var streamProv            = GrainClient.GetStreamProvider(StreamProviderName);
                IAsyncStream <int> stream = streamProv.GetStream <int>(strmId, "test1");

                StreamSubscriptionHandle <int> handle = await stream.SubscribeAsync(
                    (e, t) => { return(TaskDone.Done); },
                    e => { return(TaskDone.Done); });
            }
            catch (Exception ex)
            {
                this.output.WriteLine(ex.ToString());
                throw;
            }
        }
示例#5
0
        public override async Task OnConnectAsync(WebSocket webSocket, RouteValueDictionary values)
        {
            var room           = Convert.ToInt64(values["room"]);
            var streamProvider = client.GetStreamProvider(Constants.StreamProviders.ChatRooms);
            var chat           = client.GetGrain <IChatRoom>(room);
            var streamId       = await chat.JoinAsync();

            roomId = room;
            stream = streamProvider.GetStream <ChatMessage>(streamId, Constants.Streams.Namespaces.Chats);

            var handlers = await stream.GetAllSubscriptionHandles();

            if (null == handlers || 0 == handlers.Count)
            {
                subscription = await stream.SubscribeAsync(OnStreamMessage);
            }
            else
            {
                foreach (var handler in handlers)
                {
                    subscription = await handler.ResumeAsync(OnStreamMessage);
                }
            }

            registry[room].Add(webSocket);
        }
示例#6
0
        public static async Task <StreamSubscriptionHandle <T> > ResumeOrSubscribeAsync <T>(this IAsyncStream <T> stream, IAsyncObserver <T> observer)
        {
            if (stream is null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var handles = await stream.GetAllSubscriptionHandles();

            // resume or subscribe to the stream
            if (handles.Count > 0)
            {
                // resume the first subscription
                var handle = await handles[0].ResumeAsync(observer);

                // cleanup any accidental duplicates
                for (var i = 1; i < handles.Count; ++i)
                {
                    await handles[i].UnsubscribeAsync();
                }

                return(handle);
            }
            else
            {
                return(await stream.SubscribeAsync(observer));
            }
        }
示例#7
0
        private async Task SubscribeAndProcess(IAsyncStream <IDomainEvent> eventStream, bool isSync)
        {
            //Подписываемся на события
            await eventStream.SubscribeAsync(async (data, _) =>
            {
                Logger.LogInformation($"(Saga Manager [{GetSagaName()}] received event {data.GetPrettyName()}.");

                //Определяем ID саги
                var prefix          = GetSagaPrefix();
                var correlatedSagas = GetCorrelatedSagas(prefix, data.Metadata.CorrelationIds);

                if (!correlatedSagas.Any())
                {
                    correlatedSagas.Add($"{prefix}-{Guid.NewGuid()})");
                }

                foreach (var sagaId in correlatedSagas)
                {
                    var saga = GrainFactory.GetGrain <ISaga>(sagaId, GetType().FullName);

                    Logger.LogInformation(
                        $"(Saga Manager [{GetSagaName()}] send event to Saga {data.GetPrettyName()}.");
                    //Вызываем сагу для обработки события
                    if (isSync)
                    {
                        await saga.ProcessEvent(data).ConfigureAwait(false);
                    }
                    else
                    {
                        var __ = saga.ProcessEvent(data).ConfigureAwait(false);
                    }
                }
            });
        }
示例#8
0
文件: Account.cs 项目: malevy/Barker
        public override async Task OnActivateAsync()
        {
            _receivedMessages = new Queue<Message>();

            // acquire the message stream so that messages can be published
            _streamProvider = GetStreamProvider("DefaultProvider");
            _publicStream = _streamProvider.GetStream<Message>(PublicStreamId, "MessageStreams");

            if (null == State.StreamSubscriptionHandle)
            {
                // create the subscription and hook up a handler for receiving messages
                State.StreamSubscriptionHandle =
                    await _publicStream.SubscribeAsync((message, seq) => this.MessagePublished(message));
            }
            else
            {
                // the subscription already exists so just hook up a handler for receiving messages 
                State.StreamSubscriptionHandle = await State.StreamSubscriptionHandle.ResumeAsync((message, seq) => this.MessagePublished(message));
            }
            await this.WriteStateAsync();

            _clientStream = _streamProvider.GetStream<MessageBatch>(this.GetPrimaryKey(), "AccountSteams");

            // this timer is used to send received messages to the client
            this.RegisterTimer(UpdateSubscribers, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));

            await base.OnActivateAsync();
        }
        public async Task StartSubscribe()
        {
            var streamProvider = GetStreamProvider("SMSProvider");

            Stream = streamProvider.GetStream <string>(StreamIdGenerator.StreamId, "ACCOUNTID");
            await Stream.SubscribeAsync(async (a, token) => await NewAccount(a));
        }
示例#10
0
        public async Task SerializationExceptionFromClassUsedInStreamsAndAlsoStateTestTest()
        {
            Guid facilityGuid = Guid.NewGuid();

            MessageContract messageReceivedFromStream = null;

            #region Stream setup spy
            IStreamProvider callpointStreamProvider        = _fixture.HostedCluster.StreamProviderManager.GetStreamProvider("StreamProvider");
            IAsyncStream <MessageContract> callpointStream = callpointStreamProvider.GetStream <MessageContract>(facilityGuid, "Namespace");
            var subHandle = callpointStream.SubscribeAsync((message, token) =>
            {
                messageReceivedFromStream = message;
                return(TaskDone.Done);
            });


            IStreamProvider streamProvider = _fixture.HostedCluster.StreamProviderManager.GetStreamProvider("StreamProviderOther");
            IAsyncStream <SomeOtherMessage> messageStream = streamProvider.GetStream <SomeOtherMessage>(facilityGuid, "NamespaceOther");

            #endregion

            var aceMessage = new SomeOtherMessage
            {
                MyProp = "MyProp"
            };
            await messageStream.OnNextAsync(aceMessage);

            await Task.Delay(TimeSpan.FromMilliseconds(1000));

            Assert.NotNull(messageReceivedFromStream);
            Assert.IsType <MessageContract>(messageReceivedFromStream);
        }
示例#11
0
        public static async Task <StreamSubscriptionHandle <TEvent> > EnsureIsSubscribedOnce <T, TEvent>(this T handler,
                                                                                                         IAsyncStream <TEvent> stream)
            where T : Grain, IEventHandler
            where TEvent : IEvent
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            var eventTypes = GetSupportedEventTypes(handler);

            if (eventTypes.Count == 0)
            {
                throw new ArgumentException($"No events could be handled by {handler.GetType().Name}.");
            }
            var handles = await stream.GetAllSubscriptionHandles();

            var observer = new EventObserver <T, TEvent>(handler, eventTypes);

            if (handles.Count > 0)
            {
                await handles[0].ResumeAsync(observer);
                return(handles[0]);
            }
            // Filter event types on subscription level
            var handle = await stream.SubscribeAsync(observer);

            return(handle);
        }
示例#12
0
        public override async Task OnActivateAsync()
        {
            logger.Info("OnActivateAsync");

            var streamProvider = this.GetStreamProvider("SMSProvider");

            redStream  = streamProvider.GetStream <int>(this.GetPrimaryKey(), "red");
            blueStream = streamProvider.GetStream <int>(this.GetPrimaryKey(), "blue");

            await redStream.SubscribeAsync(
                (e, t) =>
            {
                logger.Info("Received a red event {0}", e);
                redCounter++;
                return(Task.CompletedTask);
            });

            await blueStream.SubscribeAsync(
                (e, t) =>
            {
                logger.Info("Received a blue event {0}", e);
                blueCounter++;
                return(Task.CompletedTask);
            });
        }
        public override async Task OnActivateAsync()
        {
            logger = base.GetLogger("MultipleImplicitSubscriptionGrain " + base.IdentityString);
            logger.Info("OnActivateAsync");

            var streamProvider = GetStreamProvider("SMSProvider");
            redStream = streamProvider.GetStream<int>(this.GetPrimaryKey(), "red");
            blueStream = streamProvider.GetStream<int>(this.GetPrimaryKey(), "blue");

            await redStream.SubscribeAsync(
                (e, t) =>
                {
                    logger.Info("Received a red event {0}", e);
                    redCounter++;
                    return TaskDone.Done;
                });

            await blueStream.SubscribeAsync(
                (e, t) =>
                {
                    logger.Info("Received a blue event {0}", e);
                    blueCounter++;
                    return TaskDone.Done;
                });
        }
示例#14
0
            public async override Task OnActivateAsync()
            {
                _streamProvider = this.GetStreamProvider(euroDolStream);

                _euroDolStream = _streamProvider.GetStream <IEventWithVersionId>(Guid.Empty, euroDolStream);

                var subscription = await _euroDolStream.SubscribeAsync(this);
            }
示例#15
0
        public override async Task OnActivateAsync()
        {
            _streamProvider = GetStreamProvider(Constants.StreamProviderName);
            _incomingStream = _streamProvider.GetStream <MockCommand>(this.GetPrimaryKey(), MockCommand.MockCommandNamespace);
            await _incomingStream.SubscribeAsync(OnNextAsync);

            await base.OnActivateAsync();
        }
示例#16
0
 public async Task OnConnect(Guid serverId)
 {
     State.ServerId                  = serverId;
     _serverStream                   = _streamProvider.GetStream <ClientMessage>(State.ServerId, Constants.SERVERS_STREAM);
     _serverDisconnectedStream       = _streamProvider.GetStream <Guid>(State.ServerId, Constants.SERVER_DISCONNECTED);
     _serverDisconnectedSubscription = await _serverDisconnectedStream.SubscribeAsync(async _ => await OnDisconnect("server-disconnected"));
     await WriteStateAsync();
 }
示例#17
0
        public async Task OnConnect(Guid serverId)
        {
            State.ServerId = serverId;
            SetupStreams();
            await _serverDisconnectedStream.SubscribeAsync(async (connId, _) => await OnDisconnect(ClientDisconnectReasons.ServerDisconnected));

            await WriteStateAsync();
        }
            List <IClusterTestListener> listeners = new List <IClusterTestListener>(); // keep them from being GCed

            // stream-based notification
            public void SubscribeStream(int i, IAsyncObserver <int> listener)
            {
                IStreamProvider    streamProvider = this.Client.GetStreamProvider("SMSProvider");
                Guid               guid           = new Guid(i, 0, 0, new byte[8]);
                IAsyncStream <int> stream         = streamProvider.GetStream <int>(guid, "notificationtest");

                handle = stream.SubscribeAsync(listener).GetResult();
            }
示例#19
0
        public async Task RenewConsumer(ILogger logger, IStreamProvider streamProvider)
        {
            _logger = logger;
            _logger.LogInformation("RenewConsumer");
            IAsyncStream <StreamItem> stream = streamProvider.GetStream <StreamItem>(_streamId, _streamNamespace);

            _subscription = await stream.SubscribeAsync(this);
        }
示例#20
0
        static async Task SubscribeToStream()
        {
            StreamProvider        = GrainClient.GetStreamProvider("SimpleStreamProvider");
            ClusterSnapshotStream = StreamProvider
                                    .GetStream <MetricsSnapshot>(Guid.Empty, "ClusterMetricSnapshots");

            await ClusterSnapshotStream.SubscribeAsync(OnNewMetricSnapshot);
        }
示例#21
0
        public async Task Initialize(Guid cmdStreamId, Guid ackStreamId)
        {
            Logger.Output.WriteLine($"Slave({myId}): Initialize");

            cmdStream = cmdStreamProvider.GetStream <Cmd>(cmdStreamId, Constants.CmdStreamNamespace);
            ackStream = ackStreamProvider.GetStream <Ack>(ackStreamId, Constants.AckStreamNamespace);

            cmdHandle = await cmdStream.SubscribeAsync(OnCmd);
        }
示例#22
0
        public override async Task OnActivateAsync()
        {
            IAsyncStream <Post> stream = this.GetStreamProvider("SMSProvider").GetStream <Post>(Guid.Empty, "questions");
            await stream.SubscribeAsync(this);

            _questions = await _dbContext.Questions.Where(p => p.PostId == 1).ToListAsync();

            _replies = await _dbContext.Replies.Where(p => p.QuestionId == 1).ToListAsync();
        }
示例#23
0
        public async Task SubscribeAsync(IAsyncStream <ChatMessage> stream)
        {
            if (null == stream)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            subscription = await stream.SubscribeAsync(this);
        }
示例#24
0
        public override async Task OnActivateAsync()
        {
            logger = GetLogger("SampleStreaming_ConsumerGrain " + IdentityString);
            logger.Info("OnActivateAsync");

            IStreamProvider    streamProvider = GetStreamProvider("KafkaProvider");
            IAsyncStream <int> stream         = streamProvider.GetStream <int>(this.GetPrimaryKey(), StreamNamespace);

            consumerHandle = await stream.SubscribeAsync(this, lastToken);
        }
示例#25
0
        public override async Task OnActivateAsync()
        {
            var streamProvider = GetStreamProvider(ChunklerConstants.SimpleChunkStreamProvider);

            _chunkUpdateEventStream = streamProvider.GetStream <ChunkUpdate>(_chunkKey, ChunklerConstants.ChunkOutcomingUpdate);
            _chunkActionEventStream = streamProvider.GetStream <ChunkAction>(_chunkKey, ChunklerConstants.ChunkIncomingAction);
            await _chunkActionEventStream.SubscribeAsync(this);

            await base.OnActivateAsync();
        }
示例#26
0
        public override Task OnActivateAsync()
        {
            var streamProvider = GetStreamProvider(Consts.FilesStreamProvider);

            _streamIds   = streamProvider.GetStream <string>(Consts.StreamIdsGuid, Consts.FilesStreamNameSpace);
            _streamFiles = streamProvider.GetStream <byte[]>(Consts.StreamFilesGuid, Consts.FilesStreamNameSpace);
            _streamIds.SubscribeAsync(async(id, token) => { await GetFileId(id); });
            _streamFiles.SubscribeAsync(async(file, token) => { await GetFile(file); });
            return(base.OnActivateAsync());
        }
        public async Task StreamingPubSubStoreTest()
        {
            var strmId = Guid.NewGuid();

            var streamProv            = GrainClient.GetStreamProvider("SMSProvider");
            IAsyncStream <int> stream = streamProv.GetStream <int>(strmId, "test1");

            StreamSubscriptionHandle <int> handle = await stream.SubscribeAsync(
                (e, t) => { return(TaskDone.Done); },
                e => { return(TaskDone.Done); });
        }
示例#28
0
        public override Task OnActivateAsync()
        {
            var streamProvider = this.GetStreamProvider("SMSProvider");
            var primaryKey     = this.GetPrimaryKey();

            _deviceEventStream = streamProvider.GetStream <DeviceEvent>(primaryKey, "DeviceEvent");
            _deviceEventStream.SubscribeAsync(async(deviceEvent, token) => await this.AddEventHistory(deviceEvent));

            _deviceEventStream.OnCompletedAsync();
            return(base.OnActivateAsync());
        }
示例#29
0
        public override async Task OnActivateAsync()
        {
            logger = this.GetLogger("GeneratedEvenCollectorGrain " + base.IdentityString);
            logger.Info("OnActivateAsync");

            var streamProvider = GetStreamProvider(GeneratedStreamTestConstants.StreamProviderName);

            stream = streamProvider.GetStream <GeneratedEvent>(this.GetPrimaryKey(), StreamNamespace);

            await stream.SubscribeAsync(OnNextAsync);
        }
        public async Task Connect()
        {
            if (null == _subscription)
            {
                _streamProvider = base.GetStreamProvider("EUR/USD");

                _euroDolStream = _streamProvider.GetStream <IEvent>(Guid.Empty, "EUR/USD");

                _subscription = await _euroDolStream.SubscribeAsync(this);
            }
        }
示例#31
0
        /// <inheritdoc />
        public async Task SubscribeAsync()
        {
            if (_successStream != null)
            {
                _successStreamHandle = await _successStream.SubscribeAsync(SuccessHandler);
            }

            if (_failureStream != null)
            {
                _failureStreamHandle = await _failureStream.SubscribeAsync(FailureHandler);
            }
        }
        public override async Task OnActivateAsync()
        {
            logger = base.GetLogger("GeneratedEvenCollectorGrain " + base.IdentityString);
            logger.Info("OnActivateAsync");

            var streamProvider = GetStreamProvider(StreamProviderName);
            stream = streamProvider.GetStream<GeneratedEvent>(this.GetPrimaryKey(), StreamNamespace);

            await stream.SubscribeAsync(
                (e, t) =>
                {
                    counter++;
                    logger.Info("Received a generated event {0}, of {1} events", e, counter);
                    if (e.EventType == GeneratedEvent.GeneratedEventType.Fill)
                    {
                        return TaskDone.Done;
                    }
                    var reporter = this.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(ReporterId);
                    return reporter.ReportResult(this.GetPrimaryKey(), StreamProviderName, StreamNamespace, counter);
                });
        }