コード例 #1
0
        public async Task OnNextAsync(DiffModel item, StreamSequenceToken token = null)
        {
            _logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");
            var newGrains = await ApplyFilter(item.NewGrains);

            CurrentStats?.AddRange(newGrains);

            if (InSummaryMode)
            {
                await _dashboardInstanceStream.OnNextAsync(new DiffModel
                {
                    SummaryView      = InSummaryMode,
                    TypeCounts       = item.TypeCounts,
                    NewGrains        = GetGrainSummaries(),
                    SummaryViewLinks = GetGrainSummaryLinks(),
                    SessionId        = SessionId
                });
            }
            else
            {
                item.NewGrains = newGrains;
                _logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");

                if (item.NewGrains != null && (item.NewGrains.Any() || item.RemovedGrains.Any()))
                {
                    item.SummaryView = InSummaryMode;
                    item.SessionId   = SessionId;
                    await _dashboardInstanceStream.OnNextAsync(item);
                }
            }
        }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task <long> RegisterRoomAsync(string name)
        {
            if (State.Rooms.ContainsValue(name))
            {
                throw new DuplicateNameException();
            }

            var idManager = GrainFactory.GetGrain <IRoomIdManager>(RoomIdManager.DefaultId);
            var id        = await idManager.GenerateIdAsync();

            //var room = GrainFactory.GetGrain<IChatRoom>(id);

            State.Rooms.Add(id, name);

            await Task.WhenAll(
                WriteStateAsync(),
                actions.OnNextAsync(new RoomActionMessage
            {
                Action = RoomAction.Registered,
                RoomId = id
            })
                );

            return(id);
        }
コード例 #3
0
        public override Task SendAllAsync(string methodName, object?[]?args,
                                          CancellationToken cancellationToken = new CancellationToken())
        {
            var message = new InvocationMessage(methodName, args);

            return(_allStream.OnNextAsync(new AllMessage(message)));
        }
コード例 #4
0
ファイル: Channel.cs プロジェクト: raidnav/orleans-chat
        public async Task <Guid> Join(string nickname)
        {
            _onlineMembers.Add(nickname);
            await _stream.OnNextAsync(new Message("System", $"{nickname} join the chat '{this.GetPrimaryKeyString()}' ..."));

            return(_stream.Guid);
        }
コード例 #5
0
        public async Task <Guid> Join(string nickname)
        {
            _onlineMembers.Add(nickname);

            await _stream.OnNextAsync(new Message($"{nickname} has joined the channel"));

            return(_stream.Guid);
        }
コード例 #6
0
        private async Task TickTock(object arg)
        {
            var e = new GameAreaEvent {
                TimelineMessage = $"The clock ticks. The time is now _{DateTime.Now}_"
            };

            logger.LogInformation("Sending event: {e}", e);
            await areaEventStream.OnNextAsync(e);
        }
コード例 #7
0
ファイル: UserSession.cs プロジェクト: lulzzz/origine
        public virtual Task Send <T>(short packetId, T obj = default)
        {
            var packet = new TPacket
            {
                Command = packetId,
                Data    = obj != null?Serialize(obj) : default
            };

            return(asyncStream.OnNextAsync(packet));
        }
コード例 #8
0
        public async Task PlayerMove(GameMessage message)
        {
            MoveMessage moveMsg = message as MoveMessage;

            if (moveMsg == null)
            {
                throw new Exception($"Player move recieved a message that was not of type {typeof(MoveMessage)} but was {message.GetType()}");
            }

            logger.LogInformation($"Player {moveMsg.PlayerId} moved in direction {moveMsg.Direction}");

            await stream.OnNextAsync(message);
        }
コード例 #9
0
 public void SendBatchedMessages(string senderIdentifier)
 {
     while (true)
     {
         PayloadMessage message = MakeBatchedMessage(senderIdentifier, sequenceNumber);
         if (message == null)
         {
             break;
         }
         ++sequenceNumber;
         stream.OnNextAsync(message.AsImmutable());
     }
 }
コード例 #10
0
        public async Task Deposit(double a)
        {
            this.State.Balance += a;
            await this.WriteStateAsync();

            await _stream.OnNextAsync(new TransactionEvent
            {
                Amount = a,
                Type   = TransactionType.Credit,
                Data   = new Dictionary <string, string> {
                    { "key", "hello" }
                }
            });
        }
コード例 #11
0
        public async Task OnNextAsync(UserRegisteredEvent item, StreamSequenceToken token = null)
        {
            var @event = new UserVerificationEvent()
            {
                Email  = item.Email,
                Status = UserVerificationStatusEnum.Verified
            };

            if (_verificationState.State.IsAlreadyVerified)
            {
                @event.Status = UserVerificationStatusEnum.Duplicate;
            }

            if (_blacklistedEmails.Get().Contains(item.Email))
            {
                @event.Status = UserVerificationStatusEnum.Blocked;

                _logger.LogWarning("Blacklisted user {email}", item.Email);
            }

            await _userVerificationStream.OnNextAsync(@event);

            _verificationState.State.IsAlreadyVerified = true;
            await _verificationState.WriteStateAsync();
        }
コード例 #12
0
ファイル: DataDriver.cs プロジェクト: lulzzz/BDS-2019-2020
        public async Task Run()
        {
            string line;
            Random random = new Random();
            int    count  = rate / 2 + random.Next(rate + 1);

            for (int i = 0; i < count; ++i)
            {
                line = photoFile.ReadLine();
                if (line == null)
                {
                    break;
                }
                long ts = DataDriver.getCurrentTimestamp() + random.Next(2 * randSpan + 1) - randSpan;
                line = line + " " + ts;
                await photoStream.OnNextAsync(line);

                int pid;
                if (!Int32.TryParse(line.Split(" ")[0], out pid))
                {
                    continue;
                }
                if (tags.ContainsKey(pid))
                {
                    foreach (int uid in tags[pid])
                    {
                        string tagLine = pid + " " + uid + " " + ts;
                        await tagStream.OnNextAsync(tagLine);
                    }
                }
            }
        }
コード例 #13
0
        private Task HandleMatchEvent(MatchEventDto matchEventDto)
        {
            switch ((MatchEventType)matchEventDto.MatchEventType)
            {
            case MatchEventType.None:
                break;

            case MatchEventType.Goal:
                State.Apply(matchEventDto.ToGoalEvent());
                break;

            case MatchEventType.YellowCard:
                State.Apply(matchEventDto.ToYellowCardEvent());
                break;

            case MatchEventType.RedCard:
                State.Apply(matchEventDto.ToRedCardEvent());
                break;

            case MatchEventType.Substitution:
                State.Apply(matchEventDto.ToSubstitutionEvent());
                break;

            case MatchEventType.Time:
                State.Apply(matchEventDto.ToTimeEvent());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(_stream.OnNextAsync(matchEventDto));
        }
        public async Task ReportSiloStatistics(MetricsSnapshot snapshot)
        {
            try
            {
                // add or replace the snapshot for the silo this came from
                if (!SiloSnapshots.ContainsKey(snapshot.Source))
                {
                    SiloSnapshots.Add(snapshot.Source, snapshot);
                }
                else
                {
                    SiloSnapshots[snapshot.Source] = snapshot;
                }

                if (SiloSnapshotStream != null)
                {
                    await SiloSnapshotStream.OnNextAsync(snapshot);
                }

                // recalculate cluster metrics snapshot
                // any time a silo snapshot is added or updated
                ClusterSnapshot = CalculateClusterMetrics(SiloSnapshots.Values.ToList());

                //if (ClusterSnapshotStream != null)
                //    await ClusterSnapshotStream.OnNextAsync(ClusterSnapshot);

                logger.IncrementMetric("SiloMetricsReported");
            }
            catch (Exception ex)
            {
                logger.TrackException(ex);
                throw;
            }
        }
コード例 #15
0
        private static async void SendMessage()
        {
            await Task.Run(async() =>
            {
                try
                {
                    //HEY! this will throw an exception if the Orleans.GrainClient hasn't initialized yet...
                    IStreamProvider streamProvider             = Orleans.GrainClient.GetStreamProvider("StreamProviding");
                    IAsyncStream <SimpleMessage> messageStream = streamProvider.GetStream <SimpleMessage>(Guid.Empty, "test");
                    if (messageStream == null)
                    {
                        Console.WriteLine("MessagesToTcpClientSender.SendMessageFromBrcAsync got a null messageStream trying to send!?!?!?");
                    }

                    SimpleMessage message = new SimpleMessage()
                    {
                        SimpleText = "Hello World"
                    };

                    await messageStream.OnNextAsync(message);
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Orleans call MessagesToTcpClientSender.SendMessageAsync has failed, I am going to throw exception: " + exc.Message);
                    Console.WriteLine(exc.Message);
                    throw;
                }
            });
        }
コード例 #16
0
 private Task Fire([CallerMemberName] string caller = null)
 {
     numProducedItems++;
     logger.Info("{0} (item={1})", caller, numProducedItems);
     RequestContext.Set(RequestContextKey, RequestContextValue);
     return(producer.OnNextAsync(numProducedItems));
 }
コード例 #17
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);
        }
コード例 #18
0
ファイル: RoomGrain.cs プロジェクト: wincc0823/MO.Framework
 public Task RoomNotify(MOMsg msg)
 {
     if (_players.Count == 0)
     {
         return(Task.CompletedTask);
     }
     return(_stream.OnNextAsync(msg));
 }
コード例 #19
0
ファイル: BlockChainExtractor.cs プロジェクト: lulzzz/scynet
        public override Task OnActivateAsync()
        {
            var streamProvider = this.GetStreamProvider("SMSProvider");

            _stream = streamProvider.GetStream <byte[]>(Guid.Parse("db260371-c425-41df-b729-f530c2367bb5"), "hello");

            return(_stream.OnNextAsync(new byte[] { 0xFF, 0xDE, 0xAD, 0xBE, 0xEF }));
        }
コード例 #20
0
        public async Task HandleEvent(DeviceEvent deviceEvent)
        {
            this.RaiseEvent(deviceEvent);

            await ConfirmEvents();

            await _deviceEventStream.OnNextAsync(deviceEvent);
        }
コード例 #21
0
        public async Task UpdatePlayerAsync(string name)
        {
            State.Name = name;

            await WriteStateAsync();

            await _stream.OnNextAsync(new PlayerUpdated(name));
        }
コード例 #22
0
        private async Task Fire([CallerMemberName] string caller = null)
        {
            RequestContext.Set(RequestContextKey, RequestContextValue);
            await producer.OnNextAsync(numProducedItems);

            numProducedItems++;
            logger.LogInformation("{Caller} (item count={Count})", caller, numProducedItems);
        }
コード例 #23
0
        private async Task <bool> SaveFile(byte[] file)
        {
            State.Files.Add(file);
            await WriteStateAsync();

            await _streamFiles.OnNextAsync(file);

            return(true);
        }
コード例 #24
0
        async Task <string> IEmailSender.SendEmailAsync(string message)
        {
            IAsyncStream <string> stream = this.GetStreamProvider("SMSProvider").GetStream <string>(Guid.Empty, "chat");
            await stream.OnNextAsync($"{this.GetPrimaryKeyString()} - {message}");


            logger.LogInformation($"\n Message received: greeting = '{message}'");
            return($"\n Client said: '{message}'!");
        }
コード例 #25
0
        async Task <string> IHello.SayHello(string greeting)
        {
            IAsyncStream <string> stream = this.GetStreamProvider("SMSProvider").GetStream <string>(Guid.Empty, "chat");
            await stream.OnNextAsync($"{this.GetPrimaryKeyString()} - {greeting}");


            logger.LogInformation($"\n SayHello message received: greeting = '{greeting}'");
            return($"\n Client said: '{greeting}', so HelloGrain says: Hello!");
        }
コード例 #26
0
 public async Task Notify(string msg, NotifyType type = NotifyType.Message)
 {
     PlayerNotifyMsg notify = new PlayerNotifyMsg()
     {
         Message = msg,
         Type    = type
     };
     await stream.OnNextAsync(notify);
 }
コード例 #27
0
        public async Task <int> ProcessActionAsync(ChunkAction action)
        {
            State.ChangeIndex++;
            _pixelsCache[action.XIndex + action.YIndex * _chunkWidth].Rgba = action.Color;
            State.Image = _imageProcessor.GetBytesFromPixels(_pixelsCache, _chunkHeight, _chunkWidth);

            await WriteStateAsync();

            await _chunkUpdateEventStream.OnNextAsync(new ChunkUpdate
            {
                ChangeIndex = State.ChangeIndex,
                Color       = action.Color,
                XIndex      = action.XIndex,
                YIndex      = action.YIndex
            });

            return(State.ChangeIndex);
        }
コード例 #28
0
        private async Task <bool> SaveFileId(string fileId)
        {
            State.Messages.Add(fileId);
            await WriteStateAsync();

            await _streamIds.OnNextAsync(fileId);

            return(true);
        }
コード例 #29
0
        public async Task <int> SendItems(IEnumerable <T> items, bool useTransaction = true, int?transactionId = null)
        {
            var curTransactionId = transactionId ?? ++_lastTransactionId;

            if (useTransaction)
            {
                await StartTransaction(curTransactionId);
            }
            var message = new ItemMessage <T>(items);
            await ActorModel.WhenAll(_messageStream.OnNextAsync(message));

            if (useTransaction)
            {
                await EndTransaction(curTransactionId);
            }

            return(curTransactionId);
        }
コード例 #30
0
        public async Task Handle(string @event)
        {
            this.Events.Add(@event);
            this.HandledEvents++;

            await Task.Delay(50);

            await _asyncStream.OnNextAsync(new OrderEvent(this.GetPrimaryKeyString(), Event.Updated));
        }