Пример #1
0
        public async Task CustomProcessTestAsync()
        {
            await TaskEx.YieldToThreadPool();

            ThreadPool.SetMaxThreads(128, 128);

            var cohortCount = 4;
            var cluster     = await TestUtils.CreateCluster <int, SetBox <int> >(cohortCount).ConfigureAwait(false);

            var workerCount = 100;
            var sync        = new AsyncCountdownLatch(workerCount);
            var tasks       = Util.Generate(
                workerCount,
                value => ChannelsExtensions.Go(async() => {
                sync.Signal();
                await sync.WaitAsync().ConfigureAwait(false);

                var node   = cluster[value % cohortCount];
                var result = await node.UserCache.ProcessAsync(0, SetAddEntryOperation <int, int> .Create(value)).ConfigureAwait(false);
                AssertTrue(result);
            }));

            try {
                await Task.WhenAll(tasks).ConfigureAwait(false);

                Console.WriteLine("Validating set contents");
                var result = await cluster[0].UserCache.GetAsync(0).ConfigureAwait(false);
                AssertCollectionDeepEquals(new HashSet <int>(Enumerable.Range(0, 100)), result.Value.Set);
            } catch (Exception e) {
                Console.Error.WriteLine("Test threw " + e);
                throw;
            }
        }
Пример #2
0
            public async Task <bool> TryHandshakeAsync(double minTimeoutSeconds)
            {
                try {
                    using (await synchronization.LockAsync().ConfigureAwait(false)) {
                        Console.WriteLine("Attempting to connect to ID " + AdapterId + " AKA " + string.Join(" ", AdapterId.ToByteArray()));

                        bluetoothClient = new BluetoothClient();
                        bluetoothClient.Authenticate = false;
                        bluetoothClient.Encrypt      = false;

                        await bluetoothClient.ConnectAsync(address, CAMPFIRE_NET_SERVICE_CLASS).ConfigureAwait(false);

                        disconnectedChannel.SetIsClosed(false);

                        Console.WriteLine("Connected. Their Adapter ID is " + AdapterId + " AKA " + string.Join(" ", AdapterId.ToByteArray()));

                        ChannelsExtensions.Go(async() => {
                            Console.WriteLine("Entered BT Reader Task");
                            var networkStream = bluetoothClient.GetStream();
                            try {
                                while (!disconnectedChannel.IsClosed)
                                {
                                    Console.WriteLine("Reading BT Frame");
                                    var dataLengthBuffer = await ReadBytesAsync(networkStream, 4).ConfigureAwait(false);
                                    var dataLength       = BitConverter.ToInt32(dataLengthBuffer, 0);
                                    Console.WriteLine("Got BT Frame Length: " + dataLength);
                                    var data = await ReadBytesAsync(networkStream, dataLength).ConfigureAwait(false);
                                    await inboundChannel.WriteAsync(data).ConfigureAwait(false);
                                }
                            } catch (Exception e) {
                                Console.WriteLine(e);
                                Teardown();
                            }
                        }).Forget();
                        return(true);
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to connect to ID " + AdapterId + " AKA " + string.Join(" ", AdapterId.ToByteArray()));
                    Console.WriteLine(e.GetType().FullName);
                    return(false);
                }
            }
Пример #3
0
        public async Task RunAsync()
        {
            await TaskEx.YieldToThreadPool();

            ThreadPool.SetMaxThreads(128, 128);

            var cohortCount = 4;
            var cluster     = await TestUtils.CreateCluster <int, string>(cohortCount).ConfigureAwait(false);

            var workerCount = 100;
            var sync        = new AsyncCountdownLatch(workerCount);
            var tasks       = Util.Generate(
                workerCount,
                key => ChannelsExtensions.Go(async() => {
                try {
                    Console.WriteLine("Entered thread for worker of key " + key);

                    sync.Signal();
                    await sync.WaitAsync().ConfigureAwait(false);

                    const int kReadCount = 10;
                    for (var i = 0; i < kReadCount; i++)
                    {
                        var node  = cluster[i % cohortCount];
                        var entry = await node.UserCache.GetAsync(key).ConfigureAwait(false);
                        AssertEquals(key, entry.Key);
                        AssertEquals(null, entry.Value);
                        AssertFalse(entry.Exists);
                    }
                } catch (Exception e) {
                    Console.Error.WriteLine("Worker on key " + key + " threw " + e);
                    throw;
                }
            }));

            try {
                await Task.WhenAll(tasks).ConfigureAwait(false);
            } catch (Exception e) {
                Console.Error.WriteLine("Test threw " + e);
                throw;
            }
        }
Пример #4
0
            private async Task HandshakeAsync(double minTimeoutSeconds)
            {
                using (await synchronization.LockAsync().ConfigureAwait(false)) {
                    var isServer = androidBluetoothAdapter.AdapterId.CompareTo(AdapterId) > 0;

                    // Michael's laptop is always the client as windows client doesn't understand being a server.
                    if (Name?.Contains("DESKTOP") ?? false)
                    {
                        isServer = true;
                    }

                    if (isServer)
                    {
                        socket = await inboundBluetoothSocketTable.TakeAsyncOrTimeout(device).ConfigureAwait(false);
                    }
                    else
                    {
                        var socketBox = new AsyncBox <BluetoothSocket>();
                        new Thread(() => {
                            try {
                                socketBox.SetResult(device.CreateInsecureRfcommSocketToServiceRecord(CampfireNetBluetoothConstants.APP_UUID));
                            } catch (Exception e) {
                                socketBox.SetException(e);
                            }
                        }).Start();

                        socket = await socketBox.GetResultAsync().ConfigureAwait(false);

                        var connectedChannel = ChannelFactory.Nonblocking <bool>();

                        Go(async() => {
                            await socket.ConnectAsync().ConfigureAwait(false);
                            await ChannelsExtensions.WriteAsync(connectedChannel, true);
                        }).Forget();

                        bool isTimeout = false;
                        await new Select {
                            Case(ChannelFactory.Timer(TimeSpan.FromSeconds(minTimeoutSeconds)), () => {
                                socket.Dispose();
                                isTimeout = true;
                            }),
                            Case(connectedChannel, () => {
                                // whee!
                            })
                        }.ConfigureAwait(false);
                        if (isTimeout)
                        {
                            throw new TimeoutException();
                        }
                    }
                    disconnectedChannel.SetIsClosed(false);

                    ChannelsExtensions.Go(async() => {
                        Console.WriteLine("Entered BT Reader Task");
                        var networkStream = socket.InputStream;
                        try {
                            while (!disconnectedChannel.IsClosed)
                            {
                                Console.WriteLine("Reading BT Frame");
                                var dataLengthBuffer = await ReadBytesAsync(networkStream, 4).ConfigureAwait(false);
                                var dataLength       = BitConverter.ToInt32(dataLengthBuffer, 0);
                                var data             = await ReadBytesAsync(networkStream, dataLength).ConfigureAwait(false);
                                await ChannelsExtensions.WriteAsync(inboundChannel, data).ConfigureAwait(false);
                            }
                        } catch (Exception e) {
                            Console.WriteLine(e);
                            Teardown();
                        }
                    }).Forget();
                }
            }
Пример #5
0
        public async Task DiscoverAsync()
        {
            var rateLimit = ChannelFactory.Timer(1000); // 5000, 5000);
            var connectedNeighborContextsByAdapterId = new ConcurrentDictionary <Guid, NeighborConnectionContext>();

            while (true)
            {
                Debug("Starting discovery round!");
                var discoveryStartTime = DateTime.Now;
                var neighbors          = await bluetoothAdapter.DiscoverAsync().ConfigureAwait(false);

                var discoveryDurationSeconds = Math.Max(10, 3 * (DateTime.Now - discoveryStartTime).TotalSeconds);
                try {
                    var neighborsToConnectTo = new List <IBluetoothNeighbor>();
                    foreach (var neighbor in neighbors)
                    {
                        if (neighbor.IsConnected)
                        {
                            Debug("Connection Candidate: {0} already connected.", neighbor.AdapterId);
                            continue;
                        }

                        if (connectedNeighborContextsByAdapterId.ContainsKey(neighbor.AdapterId))
                        {
                            Debug("Connection Candidate: {0} already has connected context.", neighbor.AdapterId);
                            continue;
                        }

                        Debug("Connection Candidate: {0} looks like a go.", neighbor.AdapterId);
                        neighborsToConnectTo.Add(neighbor);
                    }
                    await Task.WhenAll(
                        neighborsToConnectTo.Select(neighbor => ChannelsExtensions.Go(async() => {
                        Debug("Attempt to connect to: {0}", neighbor.AdapterId);
                        var connected = await neighbor.TryHandshakeAsync(discoveryDurationSeconds).ConfigureAwait(false);
                        if (!connected)
                        {
                            Debug("Failed to connect to: {0}", neighbor.AdapterId);
                            return;
                        }
                        Debug("Successfully connected to: {0}", neighbor.AdapterId);

                        //                           Console.WriteLine("Discovered neighbor: " + neighbor.AdapterId);
                        var remoteMerkleTree  = merkleTreeFactory.CreateForNeighbor(neighbor.AdapterId.ToString("N"));
                        var connectionContext = new NeighborConnectionContext(identity, bluetoothAdapter, neighbor, broadcastMessageSerializer, localMerkleTree, remoteMerkleTree);
                        connectedNeighborContextsByAdapterId.AddOrThrow(neighbor.AdapterId, connectionContext);
                        connectionContext.BroadcastReceived += HandleBroadcastReceived;
                        connectionContext.Start(() => {
                            Debug("Connection Context Torn Down: {0}", neighbor.AdapterId);

                            connectionContext.BroadcastReceived -= HandleBroadcastReceived;
                            connectedNeighborContextsByAdapterId.RemoveOrThrow(neighbor.AdapterId);
                            neighbor.Disconnect();
                        });
                    }))
                        )
                    .ConfigureAwait(false);
                } catch (Exception e) {
                    Debug("Discovery threw!");
                    Debug(e.ToString());
                }
                Debug("Ending discovery round!");
                await ChannelsExtensions.ReadAsync(rateLimit).ConfigureAwait(false);
            }
        }