示例#1
0
        private static void PrintHints()
        {
            var menuColor = ConsoleColor.Magenta;

            PrettyConsole.Line("Type '/start to start with default topology", menuColor);
            PrettyConsole.Line("Type '<any text>' to send a message", menuColor);
        }
示例#2
0
        private static async Task LeaveChannel(IClusterClient client)
        {
            if (!EnsureChannelMembership())
            {
                return;
            }

            PrettyConsole.Line($"Leaving channel {_joinedChannel}");

            var room   = client.GetGrain <IChannel>(_joinedChannel);
            var roomId = await room.GetId();

            var stream = client.GetStreamProvider(Constants.ChatRoomStreamProvider).GetStream <ChatMsg>(roomId, Constants.CharRoomStreamNameSpace);

            //unsubscribe from the channel/stream since client left, so that client won't
            //receive future messages from this channel/stream
            var subscriptionHandles = await stream.GetAllSubscriptionHandles();

            foreach (var handle in subscriptionHandles)
            {
                await handle.UnsubscribeAsync();
            }

            await room.Leave(_userName);

            _joinedChannel = null;
        }
示例#3
0
        private static async Task JoinChannel(IClusterClient client, string channelName)
        {
            if (_joinedChannel == channelName)
            {
                PrettyConsole.Line($"You already joined channel {channelName}. Double joining a channel, which is implemented as a stream, would result in double subscription to the same stream, " +
                                   $"which would result in receiving duplicated messages. For more information, please refer to Orleans streaming documentation.");
                return;
            }

            PrettyConsole.Line($"Joining to channel {channelName}");

            var room   = client.GetGrain <IChannel>(channelName);
            var roomId = await room.GetId();

            var stream = client.GetStreamProvider(Constants.ChatRoomStreamProvider).GetStream <ChatMsg>(roomId, Constants.CharRoomStreamNameSpace);

            var logger = client.ServiceProvider.GetService <ILoggerFactory>().CreateLogger($"{channelName} channel");

            //subscribe to the stream to receiver farther messages sent to the chatroom
            await stream.SubscribeAsync(new StreamObserver(logger));

            await room.Join(_userName);

            _joinedChannel = channelName;
        }
示例#4
0
        private static bool EnsureChannelMembership()
        {
            if (string.IsNullOrEmpty(_joinedChannel))
            {
                PrettyConsole.Line($"You're not a member of a channel");
                return(false);
            }

            return(true);
        }
示例#5
0
        private static async Task JoinChannel(IClusterClient client, string channelName)
        {
            PrettyConsole.Line($"Joining to channel {channelName}");
            _joinedChannel = channelName;
            var room = client.GetGrain <IChatRoom>(_joinedChannel);
            await room.Join("Alexey");


            await ShowCurrentChannelHistory(client);
        }
示例#6
0
        private static async Task ShowCurrentChannelHistory(IClusterClient client)
        {
            var room    = client.GetGrain <IChannel>(_joinedChannel);
            var history = await room.ReadHistory(1000);

            PrettyConsole.Line($"====== History for '{_joinedChannel}' Channel ======", ConsoleColor.DarkGreen);
            foreach (var msg in history)
            {
                PrettyConsole.Line($" ({msg.Created:g}) {msg.Author}> {msg.Text}", ConsoleColor.DarkGreen);
            }
        }
示例#7
0
        public static void Main()
        {
            var clientInstance = InitializeClient().GetAwaiter().GetResult();

            PrettyConsole.Line("==== CLIENT: Initialized ====", ConsoleColor.Cyan);
            PrettyConsole.Line("CLIENT: Write commands:", ConsoleColor.Cyan);

            Menu(clientInstance).GetAwaiter().GetResult();

            PrettyConsole.Line("==== CLIENT: Shutting down ====", ConsoleColor.DarkRed);
        }
示例#8
0
        private static void PrintHints()
        {
            var menuColor = ConsoleColor.Magenta;

            PrettyConsole.Line("Type '/r' to run task", menuColor);
            PrettyConsole.Line("Type '/j <channel>' to join specific channel", menuColor);
            PrettyConsole.Line("Type '/l <channel>' to leave specific channel", menuColor);
            PrettyConsole.Line("Type '<any text>' to send a message", menuColor);
            PrettyConsole.Line("Type '/h' to re-read channel history", menuColor);
            PrettyConsole.Line("Type '/exit' to exit client.", menuColor);
        }
示例#9
0
        private static void PrintHints()
        {
            var menuColor = ConsoleColor.Magenta;

            PrettyConsole.Line("Type '/j <channel>' to join specific channel", menuColor);
            PrettyConsole.Line("Type '/n <username>' to set your user name", menuColor);
            PrettyConsole.Line("Type '/l' to leave specific channel", menuColor);
            PrettyConsole.Line("Type '<any text>' to send a message", menuColor);
            PrettyConsole.Line("Type '/h' to re-read channel history", menuColor);
            PrettyConsole.Line("Type '/m' to query members in the channel", menuColor);
            PrettyConsole.Line("Type '/exit' to exit client.", menuColor);
        }
示例#10
0
        private static async Task ShowChannelMembers(IClusterClient client)
        {
            var room    = client.GetGrain <IChannel>(_joinedChannel);
            var members = await room.GetMembers();

            PrettyConsole.Line($"====== Members for '{_joinedChannel}' Channel ======", ConsoleColor.DarkGreen);
            foreach (var member in members)
            {
                PrettyConsole.Line(member, ConsoleColor.DarkGreen);
            }
            PrettyConsole.Line("============", ConsoleColor.DarkGreen);
        }
示例#11
0
        private static async Task <IClusterClient> InitializeClient(string[] args)
        {
            int initializeCounter = 0;

            var initSucceed = false;

            while (!initSucceed)
            {
                try
                {
                    var client = new ClientBuilder().Configure <ClusterOptions>(options =>
                    {
                        options.ClusterId = Constants.ClusterId;
                        options.ServiceId = Constants.ServiceId;
                    })
                                 //.UseLocalhostClustering()
                                 .UseConsulClustering(options =>
                    {
                        options.Address      = new Uri("http://127.0.0.1:8500");
                        options.KvRootFolder = "test";
                    })
                                 .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IChannel).Assembly).WithReferences())
                                 .ConfigureLogging(logging => logging.AddConsole())
                                 //Depends on your application requirements, you can configure your client with other stream providers, which can provide other features,
                                 //such as persistence or recoverability. For more information, please see http://dotnet.github.io/orleans/Documentation/Orleans-Streams/Stream-Providers.html
                                 .AddSimpleMessageStreamProvider(Constants.ChatRoomStreamProvider)
                                 .Build();
                    await client.Connect();

                    initSucceed = client.IsInitialized;

                    if (initSucceed)
                    {
                        return(client);
                    }
                }
                catch (Exception exc)
                {
                    PrettyConsole.Line(exc.Message, ConsoleColor.Cyan);
                    initSucceed = false;
                }

                if (initializeCounter++ > 10)
                {
                    return(null);
                }

                PrettyConsole.Line("Client Init Failed. Sleeping 5s...", ConsoleColor.Red);
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }

            return(null);
        }
示例#12
0
        private static async Task Main(string[] args)
        {
            var clientInstance = await InitializeClient(args);

            PrettyConsole.Line("==== CLIENT: Initialized ====", ConsoleColor.Cyan);
            PrettyConsole.Line("CLIENT: Write commands:", ConsoleColor.Cyan);

            PrintHints();
            await JoinChannel(clientInstance, DefaultChannel);
            await Interact(clientInstance);
            await LeaveChannel(clientInstance);

            PrettyConsole.Line("==== CLIENT: Shutting down ====", ConsoleColor.DarkRed);
        }
示例#13
0
        private static async Task LeaveChannel(IClusterClient client)
        {
            PrettyConsole.Line($"Leaving channel {_joinedChannel}");
            var room     = client.GetGrain <IChannel>(_joinedChannel);
            var streamId = await room.Leave(_userName);

            var stream = client.GetStreamProvider(Constants.ChatRoomStreamNameProvider)
                         .GetStream <Message>(streamId, Constants.ChatRoomStreamNamespace);
            var subscriptionsHandles = await stream.GetAllSubscriptionHandles();

            foreach (var streamSubscriptionHandle in subscriptionsHandles)
            {
                await streamSubscriptionHandle.UnsubscribeAsync();
            }
        }
示例#14
0
        private static async Task RunTask(IClusterClient client)
        {
            var tick = client.GetGrain <ITicker>(Guid.Empty);

            foreach (var item in Enumerable.Range(1, 100))
            {
                try
                {
                    var res = await tick.Tick(10);
                }
                catch (Exception e)
                {
                    PrettyConsole.Line($"Exception {e.Message}");
                }
            }
        }
示例#15
0
        private static async Task ShowChannelMembers(IGrainFactory client)
        {
            if (!EnsureChannelMembership())
            {
                return;
            }

            var room    = client.GetGrain <IChannel>(_joinedChannel);
            var members = await room.GetMembers();

            PrettyConsole.Line($"====== Members for '{_joinedChannel}' Channel ======", ConsoleColor.DarkGreen);
            foreach (var member in members)
            {
                PrettyConsole.Line(member, ConsoleColor.DarkGreen);
            }

            PrettyConsole.Line("============", ConsoleColor.DarkGreen);
        }
示例#16
0
        private static async Task ShowCurrentChannelHistory(IGrainFactory client)
        {
            if (!EnsureChannelMembership())
            {
                return;
            }

            var room    = client.GetGrain <IChannel>(_joinedChannel);
            var history = await room.ReadHistory(1000);

            PrettyConsole.Line($"====== History for '{_joinedChannel}' Channel ======", ConsoleColor.DarkGreen);
            foreach (var chatMsg in history)
            {
                PrettyConsole.Line($" ({chatMsg.Created:g}) {chatMsg.Author}> {chatMsg.Text}", ConsoleColor.DarkGreen);
            }

            PrettyConsole.Line("============", ConsoleColor.DarkGreen);
        }
示例#17
0
        private static async Task RenameMember(IGrainFactory client, string nickname)
        {
            if (!EnsureChannelMembership())
            {
                return;
            }

            var room = client.GetGrain <IChannel>(_joinedChannel);

            if (await room.RenameMember(_userName, nickname))
            {
                _userName = nickname;
                PrettyConsole.Line($"Your user name is set to be {_userName}", ConsoleColor.DarkGreen);
            }
            else
            {
                PrettyConsole.Line($"Something went wrong during the renaming", ConsoleColor.DarkRed);
            }
        }
示例#18
0
        private static async Task Menu(IClusterClient client)
        {
            string input;

            PrintHints();

            do
            {
                input = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(input))
                {
                    continue;
                }

                if (input.StartsWith("/j"))
                {
                    await JoinChannel(client, input.Replace("/j", "").Trim());
                }
                else if (input.StartsWith("/n"))
                {
                    userName = input.Replace("/n", "").Trim();
                    PrettyConsole.Line($"Your user name is set to be {userName}", ConsoleColor.DarkGreen);
                }
                else if (input.StartsWith("/l"))
                {
                    await LeaveChannel(client);
                }
                else if (input.StartsWith("/h"))
                {
                    await ShowCurrentChannelHistory(client);
                }
                else if (input.StartsWith("/m"))
                {
                    await ShowChannelMembers(client);
                }
                else if (!input.StartsWith("/exit"))
                {
                    await SendMessage(client, input);
                }
            } while (input != "/exit");
        }
示例#19
0
        private static async Task TestCustomTopology(IClusterClient client)
        {
            var topologyManager = client.GetGrain <ITopology>(Constants.Topology_Manager);
            //Get and add source
            var sources = await topologyManager.GetRandomSources(1);

            var source = sources[0];

            joinedChannel = source.GetPrimaryKey();
            //Get and add stateless to sources
            var statelessOps = await topologyManager.GetRandomStatelessOperators(3);

            await topologyManager.AddCustomeOperatorsToSources(sources, statelessOps);

            //Get and Add stateful to stateless
            var statefulOps = await topologyManager.GetRandomStatefulOperators(2);

            await topologyManager.AddCustomeOperatorsToNonSourceOperators(statelessOps, statefulOps);

            PrettyConsole.Line("Stateless: " + statelessOps.Count + " StatefulOps: " + statefulOps.Count);
            //Start Timer
            var coordinator = client.GetGrain <IBatchCoordinator>(Constants.Coordinator);
            await coordinator.StartBarrierTimer();

            await source.RegisterTimerForSources();

            //Start Error Detector
            var detector = client.GetGrain <IErrorDetector>(Constants.Error_Detector);
            await detector.RegisterTimerToDetectFailures();

            //var room2 = client.GetGrain<IStreamSource>("new");
            var streamId = await source.Join(userName);

            //var streamId2 = await room2.Join(userName);
            var stream = client.GetStreamProvider(Constants.FaultTolerantStreamProvider)
                         .GetStream <StreamMessage>(streamId, Constants.FaultTolerantStreamNameSpace);
            //subscribe to the stream to receiver furthur messages sent to the chatroom
            StatefulStreamObserver observer = new StatefulStreamObserver(client.ServiceProvider.GetService <ILoggerFactory>()
                                                                         .CreateLogger($"{joinedChannel} channel"));

            await stream.SubscribeAsync(observer);
        }
示例#20
0
        static async Task <IClusterClient> InitializeClient(string[] args)
        {
            int initializeCounter = 0;
            var config            = ClientConfiguration.LocalhostSilo()
                                    .SimpleMessageStreamProvider(FluentConfig.AltNetStream);

            config.DefaultTraceLevel = Severity.Error;

            var initSucceed = false;

            while (!initSucceed)
            {
                try
                {
                    var client = new ClientBuilder().UseConfiguration(config).Build();
                    await client.Connect();

                    initSucceed = client.IsInitialized;

                    if (initSucceed)
                    {
                        return(client);
                    }
                }
                catch (Exception exc)
                {
                    PrettyConsole.Line(exc.Message, ConsoleColor.Cyan);
                    initSucceed = false;
                }

                if (initializeCounter++ > 10)
                {
                    return(null);
                }

                PrettyConsole.Line("Client Init Failed. Sleeping 5s...", ConsoleColor.Red);
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }

            return(null);
        }
示例#21
0
        private static async Task <IClusterClient> InitializeClient()
        {
            int initializeCounter = 0;

            while (true)
            {
                try {
                    var client = new ClientBuilder()
                                 .Configure <ClusterOptions>(options => {
                        options.ClusterId = Constants.ClusterId;
                        options.ServiceId = Constants.ServiceId;
                    })
                                 .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IChannel).Assembly).WithReferences())
                                 .ConfigureLogging(logging => logging.AddConsole())
                                 .AddSimpleMessageStreamProvider(Constants.ChatRoomStreamNameProvider)
                                 .Build();

                    await client.Connect();

                    if (client.IsInitialized)
                    {
                        return(client);
                    }
                }
                catch (Exception e) {
                    PrettyConsole.Line(e.Message, ConsoleColor.Cyan);
                }

                if (initializeCounter++ > 10)
                {
                    return(null);
                }

                PrettyConsole.Line("Client Init Failed. Sleeping 5s...", ConsoleColor.Red);
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
        }
 public Task OnNextAsync(StreamMessage msg, StreamSequenceToken token = null)
 {
     PrettyConsole.Line("Receive Message, Key: " + msg.Key + " Value: " + msg.Value);
     return(Task.CompletedTask);
 }
示例#23
0
 private static async Task LeaveChannel(IClusterClient client, string channelName)
 {
     PrettyConsole.Line($"Leaving to channel {channelName}");
     var room = client.GetGrain <IChatRoom>(_joinedChannel);
     await room.Leave("Alexey");
 }