예제 #1
0
 void Start()
 {
     Debug.Log("GameStateManager started");
     pss = new PubSubService();
     InitializeTransitionArray();
     currentState = UpdateGameState(GameState.JOIN, null);
 }
예제 #2
0
        public async Task SubscribedPeers_AllTopics()
        {
            var topic1 = Guid.NewGuid().ToString();
            var topic2 = Guid.NewGuid().ToString();
            var ns     = new PubSubService {
                LocalPeer = self
            };
            var router = new FloodRouter {
                SwarmService = new SwarmService()
            };

            router.RemoteTopics.AddInterest(topic1, other1);
            router.RemoteTopics.AddInterest(topic2, other2);
            ns.Routers.Add(router);
            await ns.StartAsync();

            try
            {
                var peers = (await ns.PeersAsync()).ToArray();
                Assert.AreEqual(2, peers.Length);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
예제 #3
0
        public async Task Subscribe_HandlerExceptionIsIgnored()
        {
            var ns = new PubSubService {
                LocalPeer = self
            };
            await ns.StartAsync();

            try
            {
                var topic        = Guid.NewGuid().ToString();
                var cs           = new CancellationTokenSource();
                var messageCount = 0;
                await ns.SubscribeAsync(topic, msg =>
                {
                    ++messageCount;
                    throw new Exception();
                }, cs.Token);

                await ns.PublishAsync(topic, "", cs.Token);

                Assert.AreEqual(1, messageCount);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
예제 #4
0
        public async Task DuplicateMessagesAreIgnored()
        {
            var ns = new PubSubService {
                LocalPeer = self
            };

            ns.Routers.Add(new LoopbackRouter());
            await ns.StartAsync();

            try
            {
                var topic        = Guid.NewGuid().ToString();
                var cs           = new CancellationTokenSource();
                var messageCount = 0;
                await ns.SubscribeAsync(topic, msg => { ++messageCount; }, cs.Token);

                await ns.PublishAsync(topic, "", cs.Token);

                Assert.AreEqual(1, messageCount);
                Assert.AreEqual(2ul, ns.MesssagesReceived);
                Assert.AreEqual(1ul, ns.DuplicateMesssagesReceived);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
        public void AddSubscriberTest()
        {
            PubSubService  ps = new PubSubService();
            NewsSubscriber ns = new NewsSubscriber();

            ps.AddSubscriber("Topic", ns);
            Assert.IsTrue(ps.subscribersTopicMap["Topic"].Contains(ns));
        }
        public void AddMessageToQueueTest()
        {
            PubSubService ps = new PubSubService();

            ps.AddMessageToQueue(new Message("Data", "Scince"));
            Assert.AreEqual(ps.messagesQueue.Count, 1);
            ps.messagesQueue.Dequeue();
            Assert.AreEqual(ps.messagesQueue.Count, 0);
        }
예제 #7
0
        public DfsService(IBitSwapApi bitSwapApi,
                          BitSwapService bitSwapService,
                          IBlockApi blockApi,
                          IBlockRepositoryApi blockRepositoryApi,
                          IBootstrapApi bootstrapApi,
                          IConfigApi configApi,
                          IDagApi dagApi,
                          IDhtApi dhtApi,
                          IDnsApi dnsApi,
                          KatDhtService dhtService,
                          IUnixFsApi unixFsApi,
                          IKeyApi keyApi,
                          INameApi nameApi,
                          IObjectApi objectApi,
                          IPinApi pinApi,
                          Ping1 pingService,
                          IPubSubApi pubSubApi,
                          PubSubService pubSubService,
                          IStatsApi statsApi,
                          ISwarmApi swarmApi,
                          SwarmService swarmService,
                          DfsOptions dfsOptions,
                          IHashProvider hashProvider,
                          DfsState dfsState,
                          IPasswordManager passwordManager,
                          IMigrationManager migrationManager,
                          Peer localPeer)
        {
            BitSwapApi         = bitSwapApi;
            BitSwapService     = bitSwapService;
            BlockApi           = blockApi;
            BlockRepositoryApi = blockRepositoryApi;
            BootstrapApi       = bootstrapApi;
            ConfigApi          = configApi;
            DagApi             = dagApi;
            DhtApi             = dhtApi;
            DhtService         = dhtService;
            UnixFsApi          = unixFsApi;
            KeyApi             = keyApi;
            NameApi            = nameApi;
            ObjectApi          = objectApi;
            PinApi             = pinApi;
            PingService        = pingService;
            PubSubApi          = pubSubApi;
            PubSubService      = pubSubService;
            StatsApi           = statsApi;
            SwarmApi           = swarmApi;
            SwarmService       = swarmService;
            Options            = dfsOptions;
            _hashProvider      = hashProvider;
            _dfsState          = dfsState;
            DnsApi             = dnsApi;
            MigrationManager   = migrationManager;
            LocalPeer          = localPeer;

            InitAsync().Wait();
        }
예제 #8
0
        public void UnSubscribeTest()
        {
            NewsSubscriber ns = new NewsSubscriber();
            PubSubService  ps = new PubSubService();

            ns.AddSubscriber("Topic", ps);
            ns.UnSubscribe("Topic", ps);
            Assert.IsFalse(ps.subscribersTopicMap["Topic"].Contains(ns));
        }
        void Start()
        {
            if (Vision != null)
            {
                Vision.VisionOwner        = gameObject;
                Vision.transform.position = VisionPlaceholder.position;
            }

            PubSubService.RegisterListener <TargetSpottedEvent>(OnTargetSpotted);
            PubSubService.RegisterListener <TargetLostEvent>(OnTargetLost);
        }
예제 #10
0
        public void Start()
        {
            GrpcEnvironment.SetLogger(new ConsoleLogger());

            _server = new Grpc.Core.Server();
            _server.Ports.Add("127.0.0.1", 51000, ServerCredentials.Insecure);
            Log.Information("Starting gRPC server: {Host}:{Port}", _server.Ports.Single().Host, _server.Ports.Single().Port);
            _server.Services.Add(DataAccessService.BindService(new DataAccessServiceImpl()));
            _server.Services.Add(PubSubService.BindService(new PubSubServiceImpl()));
            _server.Start();
        }
예제 #11
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            var pubsubService = new PubSubService();

            pubsubService.CreateTopic();
        }
예제 #12
0
        /// <summary>
        /// Handles the use case for adding a new user.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>If the user is created succesfully.</returns>
        public async Task <bool> Handle(AddUser request, CancellationToken cancellationToken)
        {
            var(username, email, password) = request;

            if (await this.userManager.FindByEmailAsync(email) != null)
            {
                throw new EmailAlreadyTakenException();
            }

            if (await this.userManager.FindByNameAsync(username) != null)
            {
                throw new UsernameAlreadyTakenException();
            }

            var user = new KwetterUser
            {
                Id       = Guid.NewGuid(),
                Email    = email,
                UserName = username,
            };

            var result = await this.userManager.CreateAsync(user, password);

            if (!result.Succeeded)
            {
                throw new Exception(result.Errors.First().Description);
            }

            var userRole = await this.roleManager.FindByNameAsync("user");

            if (userRole == null)
            {
                await this.roleManager.CreateAsync(new KwetterRole()
                {
                    Name = "user", Description = "The user role."
                });
            }

            await this.userManager.AddToRoleAsync(user, "user");

            await PubSubService.Publish("user-created", new
            {
                UserId   = user.Id,
                Username = user.UserName,
                Email    = user.Email,
            });

            return(result.Succeeded);
        }
예제 #13
0
        public PublishSubscribe(
            IPEndPoint serverEndPoint,
            IObservable <IEnumerable <DnsEndPoint> > seedsEndpointObservable,
            ILoggerFactory loggerFactory,
            ISerializer <byte[]> serializer,
            ChannelCredentials channelCredentials = null)
        {
            _serializer = serializer;

            PublishSubscribeServerRouter publishSubscribeServerRouter = new PublishSubscribeServerRouter(loggerFactory, topic => new DefaultTopicFilter(topic));

            RegisterDisposable(publishSubscribeServerRouter);
            Server server = new Server
            {
                Services = { PubSubService.BindService(publishSubscribeServerRouter) },
                Ports    = { new ServerPort(serverEndPoint.Address.ToString(), serverEndPoint.Port, ServerCredentials.Insecure) }
            };

            server.Start();

            seedsEndpointObservable
            .Select(seedEndPoints => seedEndPoints
                    .Select(dnsEndPoint => new Channel(dnsEndPoint.Host, dnsEndPoint.Port, channelCredentials ?? ChannelCredentials.Insecure))
                    .Select(channel => new PubSubService.PubSubServiceClient(channel)))
            .Subscribe(_clientsSource, CancellationToken);

            ILogger <PublishSubscribe> logger = loggerFactory.CreateLogger <PublishSubscribe>();

            _clientsSource
            .SelectMany(clients => clients.Select(client => client.Publish().RequestStream))
            .CombineLatest(_publishSubject, (streamWriter, message) =>
            {
                try
                {
                    streamWriter.WriteAsync(message).GetAwaiter().GetResult();
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Error while sending message");
                }

                return(Unit.Default);
            })
            .Subscribe(CancellationToken);
        }
예제 #14
0
        void Start()
        {
            CurrentTarget = null;
            agent.speed   = enemy.EnemyStats.MovementSpeed;

            //stateMachine.ChangeState(new EnemyIdleState(animation, new AnimationClip[1],  agent));

            // Setup vision parameters and subscribe to events;
            if (Vision != null)
            {
                Vision.VisionOwner        = gameObject;
                Vision.transform.position = VisionPlaceholder.position;
                Vision.transform.parent   = VisionPlaceholder;
            }

            PubSubService.RegisterListener <TargetSpottedEvent>(OnTargetSpotted);
            PubSubService.RegisterListener <TargetLostEvent>(OnTargetLost);
        }
예제 #15
0
        public async Task MessageID_Increments()
        {
            var ns = new PubSubService {
                LocalPeer = self
            };
            await ns.StartAsync();

            try
            {
                var a = ns.CreateMessage("topic", new byte[0]);
                var b = ns.CreateMessage("topic", new byte[0]);
                Assert.IsTrue(string.Compare(b.MessageId, a.MessageId, StringComparison.Ordinal) > 0);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
        /// <summary>
        /// Configures the specified application.
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">The environment.</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceScopeFactory scopeFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseCors(x => x.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod());
            }

            app.UsePathBase(new PathString("/api/profile"));
            app.UseHealthChecks("/api/profile/health");
            app.UseHealthChecks("/health");
            app.UseRouting();
            app.UseCors(x => x.WithOrigins("https://kwetter.org", "https://www.kwetter.org").AllowAnyHeader().AllowAnyMethod());
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

            PubSubService.Subscribe("profileservice--user-created", scopeFactory);
            PubSubService.Subscribe("profileservice--user-deleted", scopeFactory);
        }
예제 #17
0
        /// <summary>
        /// Handles the use case for deleteing an existing user.
        /// Handles the use case for deleteing an existing user.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>If the user is created succesfully.</returns>
        public async Task <bool> Handle(DeleteUser request, CancellationToken cancellationToken)
        {
            var foundUser = await this.userManager.FindByIdAsync(request.UserId.ToString());

            if (foundUser == null)
            {
                throw new UserNotFoundException();
            }

            var deleteResult = await this.userManager.DeleteAsync(foundUser);

            await PubSubService.Publish("user-deleted", new
            {
                UserId   = foundUser.Id,
                Username = foundUser.UserName,
                Email    = foundUser.Email,
            });

            return(deleteResult.Succeeded);
        }
예제 #18
0
 public NodeAgentService(
     IDbContextFactory <SuperComposeContext> ctxFactory,
     ConnectionService connService,
     CryptoService cryptoService,
     ILogger <NodeAgentService> logger,
     PubSubService pubSub,
     ConnectionLogService connectionLog,
     ProxyClient proxyClient,
     NodeService nodeService
     )
 {
     this.ctxFactory    = ctxFactory;
     this.connService   = connService;
     this.cryptoService = cryptoService;
     this.logger        = logger;
     this.pubSub        = pubSub;
     this.connectionLog = connectionLog;
     this.proxyClient   = proxyClient;
     this.nodeService   = nodeService;
 }
예제 #19
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var pubsubService = new PubSubService();

            pubsubService.CreateTopic();
            pubsubService.CreateSubscription();

            var simpleSubscriber = SubscriberClient.CreateAsync(PubSubService.SubscriptionName).Result;

            simpleSubscriber.StartAsync((msg, cancellationToken) =>
            {
                Console.WriteLine("{0}: Received new message: {1}", DateTime.Now.ToString("o"), msg.Data.ToStringUtf8());

                return(Task.FromResult(SubscriberClient.Reply.Ack));
            });
        }
예제 #20
0
        public async Task Topics()
        {
            var ns = new PubSubService {
                LocalPeer = self
            };
            await ns.StartAsync();

            try
            {
                var topicA = Guid.NewGuid().ToString();
                var topicB = Guid.NewGuid().ToString();
                var csA    = new CancellationTokenSource();
                var csB    = new CancellationTokenSource();

                await ns.SubscribeAsync(topicA, msg => { }, csA.Token);

                await ns.SubscribeAsync(topicA, msg => { }, csA.Token);

                await ns.SubscribeAsync(topicB, msg => { }, csB.Token);

                var topics = (await ns.SubscribedTopicsAsync(csA.Token)).ToArray();
                Assert.AreEqual(2, topics.Length);
                CollectionAssert.Contains(topics, topicA);
                CollectionAssert.Contains(topics, topicB);

                csA.Cancel();
                topics = (await ns.SubscribedTopicsAsync(csA.Token)).ToArray();
                Assert.AreEqual(1, topics.Length);
                CollectionAssert.Contains(topics, topicB);

                csB.Cancel();
                topics = (await ns.SubscribedTopicsAsync(csA.Token)).ToArray();
                Assert.AreEqual(0, topics.Length);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
예제 #21
0
        public async Task Publish()
        {
            var ns = new PubSubService {
                LocalPeer = self
            };
            await ns.StartAsync();

            try
            {
                await ns.PublishAsync("topic", "foo");

                await ns.PublishAsync("topic", new byte[] { 1, 2, 3 });

                await ns.PublishAsync("topic", new MemoryStream(new byte[] { 1, 2, 3 }));

                Assert.AreEqual(3ul, ns.MesssagesPublished);
                Assert.AreEqual(3ul, ns.MesssagesReceived);
            }
            finally
            {
                await ns.StopAsync();
            }
        }
예제 #22
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                var options = CommandLine.Parser.Default.ParseArguments <PubSubOptions>(args);
                options.WithParsed <PubSubOptions>(o => {
                    PubSubService2.Properties.Settings.Default.PublishAsync = !o.PublishSync;
                    PubSubService2.Properties.Settings.Default.WritePublicationsToConsole = !o.WritePublicationsToConsole;
                });
                options.WithNotParsed <PubSubOptions>(e =>
                {
                    Console.WriteLine("No arguments for console. Using settings file options.");
                });
            }
            var svc = new PubSubService();

            svc.Start();
            Console.WriteLine("Running pub sub service in console.");
            Console.WriteLine($" >> Publish {(PubSubService2.Properties.Settings.Default.PublishAsync ? "asynchronously.  (use -s on console to publish synchronously)" : "synchronously" )}.");
            Console.WriteLine($" >> Print publication(s) to console{(PubSubService2.Properties.Settings.Default.WritePublicationsToConsole ? "." : " is suppressed. (use '-p' on console to print.)")}");
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            svc.Stop();
        }
        IEnumerator SearchForTargets(float delay)
        {
            while (true)
            {
                Collider[] targets = Physics.OverlapSphere(transform.position, ViewRadius, TargetMask);

                var lostTargets = targets
                                  .Select(t => t.GetComponent <Collider>())
                                  .Where(t => !visibleTargets.Contains(t.transform));

                lostTargets.ToList().ForEach(col => PubSubService.Publish(new TargetLostEvent(col)));

                visibleTargets.Clear();

                foreach (Collider target in targets)
                {
                    Vector3 directionToTarget = (target.transform.position - transform.position).normalized;

                    // CurrentTarget is within view angle
                    if (Vector3.Angle(transform.forward, directionToTarget) < ViewAngle / 2f)
                    {
                        float distanceToTarget = Vector3.Distance(transform.position, target.transform.position);

                        // check for obstacles in a way
                        if (!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, ObstacleMask))
                        {
                            visibleTargets.Add(target.transform);

                            PubSubService.Publish(new TargetSpottedEvent(target, VisionOwner.transform));
                        }
                    }
                }

                yield return(new WaitForSeconds(delay));
            }
        }
예제 #24
0
 public Subscription(SuperComposeContext ctx, PubSubService pubSub)
 {
     this.ctx    = ctx;
     this.pubSub = pubSub;
 }
예제 #25
0
        /// <summary>
        ///   Starts the network services.
        /// </summary>
        /// <returns>
        ///   A task that represents the asynchronous operation.
        /// </returns>
        /// <remarks>
        ///   Starts the various IPFS and PeerTalk network services.  This should
        ///   be called after any configuration changes.
        /// </remarks>
        /// <exception cref="Exception">
        ///   When the engine is already started.
        /// </exception>
        public async Task StartAsync()
        {
            if (stopTasks.Count > 0)
            {
                throw new Exception("IPFS engine is already started.");
            }

            var localPeer = await LocalPeer.ConfigureAwait(false);

            log.Debug("starting " + localPeer.Id);

            // Everybody needs the swarm.
            var swarm = await SwarmService.ConfigureAwait(false);

            stopTasks.Add(async() =>
            {
                await swarm.StopAsync().ConfigureAwait(false);
            });
            await swarm.StartAsync().ConfigureAwait(false);

            // Start the primary services.
            var tasks = new List <Func <Task> >
            {
                async() =>
                {
                    var bitswap = await BitswapService.ConfigureAwait(false);

                    stopTasks.Add(async() => await bitswap.StopAsync().ConfigureAwait(false));
                    await bitswap.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    var dht = await DhtService.ConfigureAwait(false);

                    stopTasks.Add(async() => await dht.StopAsync().ConfigureAwait(false));
                    await dht.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    var pubsub = await PubSubService.ConfigureAwait(false);

                    stopTasks.Add(async() => await pubsub.StopAsync().ConfigureAwait(false));
                    await pubsub.StartAsync().ConfigureAwait(false);
                },
            };

            log.Debug("waiting for services to start");
            await Task.WhenAll(tasks.Select(t => t())).ConfigureAwait(false);

            // Starting listening to the swarm.
            var json = await Config.GetAsync("Addresses.Swarm").ConfigureAwait(false);

            var numberListeners = 0;

            foreach (string a in json)
            {
                try
                {
                    await swarm.StartListeningAsync(a).ConfigureAwait(false);

                    ++numberListeners;
                }
                catch (Exception e)
                {
                    log.Warn($"Listener failure for '{a}'", e);
                    // eat the exception
                }
            }
            if (numberListeners == 0)
            {
                log.Error("No listeners were created.");
            }

            // Now that the listener addresses are established, the discovery
            // services can begin.
            MulticastService multicast = null;

            if (!Options.Discovery.DisableMdns)
            {
                multicast = new MulticastService();
#pragma warning disable CS1998
                stopTasks.Add(async() => multicast.Dispose());
#pragma warning restore CS1998
            }

            var autodialer = new AutoDialer(swarm)
            {
                MinConnections = Options.Swarm.MinConnections
            };
#pragma warning disable CS1998
            stopTasks.Add(async() => autodialer.Dispose());
#pragma warning restore CS1998

            tasks = new List <Func <Task> >
            {
                // Bootstrap discovery
                async() =>
                {
                    var bootstrap = new PeerTalk.Discovery.Bootstrap
                    {
                        Addresses = await this.Bootstrap.ListAsync()
                    };
                    bootstrap.PeerDiscovered += OnPeerDiscovered;
                    stopTasks.Add(async() => await bootstrap.StopAsync().ConfigureAwait(false));
                    await bootstrap.StartAsync().ConfigureAwait(false);
                },
                // New multicast DNS discovery
                async() =>
                {
                    if (Options.Discovery.DisableMdns)
                    {
                        return;
                    }
                    var mdns = new PeerTalk.Discovery.MdnsNext
                    {
                        LocalPeer        = localPeer,
                        MulticastService = multicast
                    };
                    if (Options.Swarm.PrivateNetworkKey != null)
                    {
                        mdns.ServiceName = $"_p2p-{Options.Swarm.PrivateNetworkKey.Fingerprint().ToHexString()}._udp";
                    }
                    mdns.PeerDiscovered += OnPeerDiscovered;
                    stopTasks.Add(async() => await mdns.StopAsync().ConfigureAwait(false));
                    await mdns.StartAsync().ConfigureAwait(false);
                },
                // Old style JS multicast DNS discovery
                async() =>
                {
                    if (Options.Discovery.DisableMdns || Options.Swarm.PrivateNetworkKey != null)
                    {
                        return;
                    }
                    var mdns = new PeerTalk.Discovery.MdnsJs
                    {
                        LocalPeer        = localPeer,
                        MulticastService = multicast
                    };
                    mdns.PeerDiscovered += OnPeerDiscovered;
                    stopTasks.Add(async() => await mdns.StopAsync().ConfigureAwait(false));
                    await mdns.StartAsync().ConfigureAwait(false);
                },
                // Old style GO multicast DNS discovery
                async() =>
                {
                    if (Options.Discovery.DisableMdns || Options.Swarm.PrivateNetworkKey != null)
                    {
                        return;
                    }
                    var mdns = new PeerTalk.Discovery.MdnsGo
                    {
                        LocalPeer        = localPeer,
                        MulticastService = multicast
                    };
                    mdns.PeerDiscovered += OnPeerDiscovered;
                    stopTasks.Add(async() => await mdns.StopAsync().ConfigureAwait(false));
                    await mdns.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    if (Options.Discovery.DisableRandomWalk)
                    {
                        return;
                    }
                    var randomWalk = new RandomWalk {
                        Dht = Dht
                    };
                    stopTasks.Add(async() => await randomWalk.StopAsync().ConfigureAwait(false));
                    await randomWalk.StartAsync().ConfigureAwait(false);
                }
            };
            log.Debug("waiting for discovery services to start");
            await Task.WhenAll(tasks.Select(t => t())).ConfigureAwait(false);

            multicast?.Start();

            log.Debug("started");
        }
예제 #26
0
        public async Task Sends_Hello_OnConnect()
        {
            var topic = Guid.NewGuid().ToString();

            var swarm1 = new SwarmService {
                LocalPeer = self
            };
            var router1 = new FloodRouter {
                SwarmService = swarm1
            };
            var ns1 = new PubSubService {
                LocalPeer = self
            };

            ns1.Routers.Add(router1);
            await swarm1.StartAsync();

            await ns1.StartAsync();

            var swarm2 = new SwarmService {
                LocalPeer = other
            };
            var router2 = new FloodRouter {
                SwarmService = swarm2
            };
            var ns2 = new PubSubService {
                LocalPeer = other
            };

            ns2.Routers.Add(router2);
            await swarm2.StartAsync();

            await ns2.StartAsync();

            try
            {
                await swarm1.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                await swarm2.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                var cs = new CancellationTokenSource();
                await ns1.SubscribeAsync(topic, msg => { }, cs.Token);

                await swarm1.ConnectAsync(other, cs.Token);

                var peers   = new Peer[0];
                var endTime = DateTime.Now.AddSeconds(3);
                while (peers.Length == 0)
                {
                    if (DateTime.Now > endTime)
                    {
                        Assert.Fail("timeout");
                    }

                    await Task.Delay(100, cs.Token);

                    peers = (await ns2.PeersAsync(topic, cs.Token)).ToArray();
                }

                CollectionAssert.Contains(peers, self);
            }
            finally
            {
                await swarm1.StopAsync();

                await ns1.StopAsync();

                await swarm2.StopAsync();

                await ns2.StopAsync();
            }
        }
예제 #27
0
        public async Task Relays_PublishedMessage()
        {
            var topic = Guid.NewGuid().ToString();

            var swarm1 = new SwarmService {
                LocalPeer = self
            };
            var router1 = new FloodRouter {
                SwarmService = swarm1
            };
            var ns1 = new PubSubService {
                LocalPeer = self
            };

            ns1.Routers.Add(router1);
            await swarm1.StartAsync();

            await ns1.StartAsync();

            var swarm2 = new SwarmService {
                LocalPeer = other
            };
            var router2 = new FloodRouter {
                SwarmService = swarm2
            };
            var ns2 = new PubSubService {
                LocalPeer = other
            };

            ns2.Routers.Add(router2);
            await swarm2.StartAsync();

            await ns2.StartAsync();

            var swarm3 = new SwarmService {
                LocalPeer = other1
            };
            var router3 = new FloodRouter {
                SwarmService = swarm3
            };
            var ns3 = new PubSubService {
                LocalPeer = other1
            };

            ns3.Routers.Add(router3);
            await swarm3.StartAsync();

            await ns3.StartAsync();

            try
            {
                IPublishedMessage lastMessage2 = null;
                IPublishedMessage lastMessage3 = null;
                await swarm1.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                await swarm2.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                await swarm3.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                var cs = new CancellationTokenSource();
                await ns2.SubscribeAsync(topic, msg => lastMessage2 = msg, cs.Token);

                await ns3.SubscribeAsync(topic, msg => lastMessage3 = msg, cs.Token);

                await swarm1.ConnectAsync(other, cs.Token);

                await swarm3.ConnectAsync(other, cs.Token);

                var peers   = new Peer[0];
                var endTime = DateTime.Now.AddSeconds(3);
                while (peers.Length == 0)
                {
                    if (DateTime.Now > endTime)
                    {
                        Assert.Fail("timeout");
                    }

                    await Task.Delay(100, cs.Token);

                    peers = (await ns2.PeersAsync(topic, cs.Token)).ToArray();
                }

                CollectionAssert.Contains(peers, other1);

                await ns1.PublishAsync(topic, new byte[] { 1 }, cs.Token);

                endTime = DateTime.Now.AddSeconds(3);
                while (lastMessage2 == null || lastMessage3 == null)
                {
                    if (DateTime.Now > endTime)
                    {
                        Assert.Fail("timeout");
                    }

                    await Task.Delay(100, cs.Token);
                }

                Assert.IsNotNull(lastMessage2);
                Assert.AreEqual(self, lastMessage2.Sender);
                CollectionAssert.AreEqual(new byte[] { 1 }, lastMessage2.DataBytes);
                CollectionAssert.Contains(lastMessage2.Topics.ToArray(), topic);

                Assert.IsNotNull(lastMessage3);
                Assert.AreEqual(self, lastMessage3.Sender);
                CollectionAssert.AreEqual(new byte[] { 1 }, lastMessage3.DataBytes);
                CollectionAssert.Contains(lastMessage3.Topics.ToArray(), topic);
            }
            finally
            {
                await swarm1.StopAsync();

                await ns1.StopAsync();

                await swarm2.StopAsync();

                await ns2.StopAsync();

                await swarm3.StopAsync();

                await ns3.StopAsync();
            }
        }
예제 #28
0
 public void SetPubSubService(PubSubService pss)
 {
     this.pss = pss;
 }
예제 #29
0
        /// <summary>
        ///     Starts the network services.
        /// </summary>
        /// <returns>
        ///     A task that represents the asynchronous operation.
        /// </returns>
        /// <remarks>
        ///     Starts the various IPFS and Lib.P2P network services.  This should
        ///     be called after any configuration changes.
        /// </remarks>
        /// <exception cref="Exception">
        ///     When the engine is already started.
        /// </exception>
        public async Task StartAsync()
        {
            _dfsState.IsStarted = true;
            if (_stopTasks.Count > 0)
            {
                throw new Exception("IPFS engine is already started.");
            }

            // Repository must be at the correct version.
            await MigrationManager.MirgrateToVersionAsync(MigrationManager.LatestVersion).ConfigureAwait(false);

            Log.Debug("starting " + LocalPeer.Id);

            // Everybody needs the swarm.
            _stopTasks.Add(async() => { await SwarmService.StopAsync().ConfigureAwait(false); });
            await SwarmService.StartAsync().ConfigureAwait(false);

            var peerManager = new PeerManager
            {
                SwarmService = SwarmService
            };
            await peerManager.StartAsync().ConfigureAwait(false);

            _stopTasks.Add(async() => { await peerManager.StopAsync().ConfigureAwait(false); });

            // Start the primary services.
            var tasks = new List <Func <Task> >
            {
                async() =>
                {
                    _stopTasks.Add(async() => await BitSwapService.StopAsync().ConfigureAwait(false));
                    await BitSwapService.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    _stopTasks.Add(async() => await DhtService.StopAsync().ConfigureAwait(false));
                    await DhtService.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    _stopTasks.Add(async() => await PingService.StopAsync().ConfigureAwait(false));
                    await PingService.StartAsync().ConfigureAwait(false);
                },
                async() =>
                {
                    _stopTasks.Add(async() => await PubSubService.StopAsync().ConfigureAwait(false));
                    await PubSubService.StartAsync().ConfigureAwait(false);
                }
            };

            Log.Debug("waiting for services to start");
            await Task.WhenAll(tasks.Select(t => t())).ConfigureAwait(false);

            // Starting listening to the swarm.
            var json = await ConfigApi.GetAsync("Addresses.Swarm").ConfigureAwait(false);

            var numberListeners = 0;

            foreach (string a in json)
            {
                try
                {
                    await SwarmService.StartListeningAsync(a).ConfigureAwait(false);

                    ++numberListeners;
                }
                catch (Exception e)
                {
                    Log.Warning($"Listener failure for '{a}'", e);
                }
            }

            if (numberListeners == 0)
            {
                Log.Error("No listeners were created.");
            }

            // Now that the listener addresses are established, the discovery
            // services can begin.
            MulticastService multicast = null;

            if (!Options.Discovery.DisableMdns)
            {
                multicast = new MulticastService();
#pragma warning disable CS1998
                _stopTasks.Add(async() => multicast.Dispose());
#pragma warning restore CS1998
            }

            var autodialer = new AutoDialer(SwarmService)
            {
                MinConnections = Options.Swarm.MinConnections
            };
#pragma warning disable CS1998
            _stopTasks.Add(async() => autodialer.Dispose());
#pragma warning restore CS1998

            tasks = new List <Func <Task> >
            {
                // Bootstrap discovery
                async() =>
                {
                    var bootstrap = new Bootstrap
                    {
                        Addresses = await BootstrapApi.ListAsync()
                    };
                    bootstrap.PeerDiscovered += OnPeerDiscovered;
                    _stopTasks.Add(async() => await bootstrap.StopAsync().ConfigureAwait(false));
                    await bootstrap.StartAsync().ConfigureAwait(false);
                },

                async() =>
                {
                    if (Options.Discovery.DisableRandomWalk)
                    {
                        return;
                    }
                    var randomWalk = new RandomWalk {
                        Dht = DhtApi
                    };
                    _stopTasks.Add(async() => await randomWalk.StopAsync().ConfigureAwait(false));
                    await randomWalk.StartAsync().ConfigureAwait(false);
                }
            };
            Log.Debug("waiting for discovery services to start");
            await Task.WhenAll(tasks.Select(t => t())).ConfigureAwait(false);

            multicast?.Start();

            Log.Debug("started");
        }
예제 #30
0
 public PubSubApi(PubSubService pubSubService)
 {
     _pubSubService = pubSubService;
 }