Exemple #1
0
    /// <summary>
    /// Creates a re-entrant function that waits for sync points in sequence.
    /// </summary>
    /// <param name="count">The number of sync points to expect</param>
    /// <param name="syncPoints">The <see cref="SyncPoint"/> objects that can be used to coordinate the sync point</param>
    /// <returns></returns>
    public static Func <Task> Create(int count, out SyncPoint[] syncPoints, bool runContinuationsAsynchronously = true)
    {
        // Need to use a local so the closure can capture it. You can't use out vars in a closure.
        var localSyncPoints = new SyncPoint[count];

        for (var i = 0; i < count; i += 1)
        {
            localSyncPoints[i] = new SyncPoint(runContinuationsAsynchronously);
        }

        syncPoints = localSyncPoints;

        var counter = 0;

        return(() =>
        {
            if (counter >= localSyncPoints.Length)
            {
                return Task.CompletedTask;
            }
            else
            {
                var syncPoint = localSyncPoints[counter];

                counter += 1;
                return syncPoint.WaitToContinue();
            }
        });
    }
Exemple #2
0
        private ArrayList GetOutOfRangeIntervals()
        {
            Ui.View.Subtitles subtitles = Base.Document.Subtitles;
            ArrayList         intervals = new ArrayList();

            if (syncPoints.Collection.Count == 0)
            {
                return(intervals);
            }

            SyncPoint first = syncPoints.Collection.Get(0);

            if (first.SubtitleNumber > 0)
            {
                string firstInterval = "1" + (first.SubtitleNumber > 1 ? "-" + first.SubtitleNumber : String.Empty);
                intervals.Add(firstInterval);
            }

            SyncPoint last = syncPoints.Collection.Get(syncPoints.Collection.Count - 1);
            int       lastSubtitleNumber = subtitles.Count - 1;

            if (last.SubtitleNumber < lastSubtitleNumber)
            {
                string lastInterval = (last.SubtitleNumber < lastSubtitleNumber - 1 ? (last.SubtitleNumber + 2) + "-" : String.Empty) + (lastSubtitleNumber + 1);
                intervals.Add(lastInterval);
            }

            return(intervals);
        }
Exemple #3
0
        public async Task QueuedRequestsContinueWhenSpaceBecomesAvailible()
        {
            var blocker      = new SyncPoint();
            var firstRequest = true;

            var middleware = TestUtils.CreateTestMiddleware(
                maxConcurrentRequests: 1,
                next: httpContext =>
            {
                if (firstRequest)
                {
                    firstRequest = false;
                    return(blocker.WaitToContinue());
                }
                return(Task.CompletedTask);
            });

            // t1 (as the first request) is blocked by the tcs blocker
            var t1 = middleware.Invoke(new DefaultHttpContext());

            Assert.Equal(1, middleware.ActiveRequestCount);

            // t2 is blocked from entering the server since t1 already exists there
            // note: increasing MaxConcurrentRequests would allow t2 through while t1 is blocked
            var t2 = middleware.Invoke(new DefaultHttpContext());

            Assert.Equal(2, middleware.ActiveRequestCount);

            // unblock the first task, and the second should follow
            blocker.Continue();
            await t1.OrTimeout();

            await t2.OrTimeout();
        }
Exemple #4
0
    public static Func <Task> Create(out SyncPoint syncPoint, bool runContinuationsAsynchronously = true)
    {
        var handler = Create(1, out var syncPoints, runContinuationsAsynchronously);

        syncPoint = syncPoints[0];
        return(handler);
    }
Exemple #5
0
        public async Task AsyncUnaryCall_SuccessAfterRetry_AccessResponseHeaders_SuccessfullyResponseHeadersReturned()
        {
            // Arrange
            HttpContent?content   = null;
            var         syncPoint = new SyncPoint(runContinuationsAsynchronously: true);

            var callCount  = 0;
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                callCount++;
                content = request.Content !;

                if (callCount == 1)
                {
                    await content.CopyToAsync(new MemoryStream());

                    await syncPoint.WaitForSyncPoint();

                    return(ResponseUtils.CreateHeadersOnlyResponse(
                               HttpStatusCode.OK,
                               StatusCode.Unavailable,
                               customHeaders: new Dictionary <string, string> {
                        ["call-count"] = callCount.ToString()
                    }));
                }

                syncPoint.Continue();

                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(
                           HttpStatusCode.OK,
                           streamContent,
                           customHeaders: new Dictionary <string, string> {
                    ["call-count"] = callCount.ToString()
                }));
            });
            var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig();
            var invoker       = HttpClientCallInvokerFactory.Create(httpClient, serviceConfig: serviceConfig);

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest {
                Name = "World"
            });
            var headersTask = call.ResponseHeadersAsync;

            // Wait until the first call has failed and the second is on the server
            await syncPoint.WaitToContinue().DefaultTimeout();

            // Assert
            Assert.AreEqual(2, callCount);
            Assert.AreEqual("Hello world", (await call.ResponseAsync.DefaultTimeout()).Message);

            var headers = await headersTask.DefaultTimeout();

            Assert.AreEqual("2", headers.GetValue("call-count"));
        }
 public WebSocketChannel(ChannelReader <WebSocketMessage> input, ChannelWriter <WebSocketMessage> output, SyncPoint sync = null)
 {
     _input  = input;
     _output = output;
     _sync   = sync;
     _state  = WebSocketState.Open;
 }
Exemple #7
0
        private void Replace(int index, SyncPoint syncPoint)
        {
            TreeIter iter;

            model.GetIterFromString(out iter, index.ToString());
            model.SetValue(iter, 0, syncPoint);
        }
        public async Task AsyncUnaryCall_AuthInterceptorSuccess_ResponseHeadersPopulated()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                var response      = ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent);
                response.Headers.Add("custom", "ABC");
                return(response);
            });
            var credentialsSyncPoint = new SyncPoint(runContinuationsAsynchronously: true);
            var credentials          = CallCredentials.FromInterceptor(async(context, metadata) =>
            {
                await credentialsSyncPoint.WaitToContinue();
                metadata.Add("Authorization", $"Bearer TEST");
            });

            var invoker = HttpClientCallInvokerFactory.Create(httpClient, configure: options => options.Credentials = ChannelCredentials.Create(new SslCredentials(), credentials));

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var responseHeadersTask = call.ResponseHeadersAsync;

            await credentialsSyncPoint.WaitForSyncPoint().DefaultTimeout();

            credentialsSyncPoint.Continue();

            var responseHeaders = await responseHeadersTask.DefaultTimeout();

            // Assert
            Assert.AreEqual("ABC", responseHeaders.GetValue("custom"));
        }
Exemple #9
0
    public async Task GlobalFiltersRunBeforeHubSpecificFilters()
    {
        using (StartVerifiableLog())
        {
            var syncPoint1      = SyncPoint.Create(3, out var syncPoints1);
            var syncPoint2      = SyncPoint.Create(3, out var syncPoints2);
            var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services =>
            {
                services.AddSignalR(options =>
                {
                    options.AddFilter(new SyncPointFilter(syncPoints1));
                })
                .AddHubOptions <MethodHub>(options =>
                {
                    options.AddFilter(new SyncPointFilter(syncPoints2));
                });
            }, LoggerFactory);

            var connectionHandler = serviceProvider.GetService <HubConnectionHandler <MethodHub> >();

            using (var client = new TestClient())
            {
                var connectionHandlerTask = await client.ConnectAsync(connectionHandler);

                await syncPoints1[0].WaitForSyncPoint().DefaultTimeout();
                // Second filter wont run yet because first filter is waiting on SyncPoint
                Assert.False(syncPoints2[0].WaitForSyncPoint().IsCompleted);
                syncPoints1[0].Continue();

                await syncPoints2[0].WaitForSyncPoint().DefaultTimeout();
                syncPoints2[0].Continue();
                await client.Connected.DefaultTimeout();

                var invokeTask = client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!");

                await syncPoints1[1].WaitForSyncPoint().DefaultTimeout();
                // Second filter wont run yet because first filter is waiting on SyncPoint
                Assert.False(syncPoints2[1].WaitForSyncPoint().IsCompleted);
                syncPoints1[1].Continue();

                await syncPoints2[1].WaitForSyncPoint().DefaultTimeout();
                syncPoints2[1].Continue();
                var message = await invokeTask.DefaultTimeout();

                Assert.Null(message.Error);

                client.Dispose();

                await syncPoints1[2].WaitForSyncPoint().DefaultTimeout();
                // Second filter wont run yet because first filter is waiting on SyncPoint
                Assert.False(syncPoints2[2].WaitForSyncPoint().IsCompleted);
                syncPoints1[2].Continue();

                await syncPoints2[2].WaitForSyncPoint().DefaultTimeout();
                syncPoints2[2].Continue();

                await connectionHandlerTask.DefaultTimeout();
            }
        }
    }
Exemple #10
0
        public async Task ClientStreaming_ResponseCompletesWithoutReadingRequest()
        {
            // Arrange
            var requestStreamTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
            var responseEndingSyncPoint = new SyncPoint();

            RequestDelegate appDelegate = async ctx =>
            {
                await ctx.Response.WriteAsync("POST Response");
                await responseEndingSyncPoint.WaitToContinue();
            };

            Stream requestStream = null;

            var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
            var server = new TestServer(builder);
            var client = server.CreateClient();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
            httpRequest.Version = new Version(2, 0);
            httpRequest.Content = new PushContent(async stream =>
            {
                requestStream = stream;
                await requestStreamTcs.Task;
            });

            // Act
            var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();

            var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            // Assert

            // Read response
            byte[] buffer = new byte[1024];
            var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
            Assert.Equal("POST Response", Encoding.UTF8.GetString(buffer, 0, length));

            // Send large content and block on back pressure
            var writeTask = Task.Run(async () =>
            {
                try
                {
                    await requestStream.WriteAsync(Encoding.UTF8.GetBytes(new string('!', 1024 * 1024 * 50))).AsTask().DefaultTimeout();
                    requestStreamTcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    requestStreamTcs.SetException(ex);
                }
            });

            responseEndingSyncPoint.Continue();

            // No more response content
            length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
            Assert.Equal(0, length);

            await writeTask;
        }
Exemple #11
0
        private void OnAdd(object o, EventArgs args)
        {
            /* Check if document and video are loaded */
            if (!(Base.IsDocumentLoaded && Base.Ui.Video.IsLoaded))
            {
                return;
            }

            /* Get selected subtitle */
            TreePath path = Base.Ui.View.Selection.Path;

            if (path == null)
            {
                return;
            }

            int      subtitleNumber = Core.Util.PathToInt(path);
            Subtitle subtitle       = Base.Ui.View.Selection.Subtitle;

            /* Get current start */
            Timing currentTiming = new Timing(subtitle.Frames.Start, subtitle.Times.Start);

            /* Get correct start from video */
            Timing correctTiming = new Timing(Base.Ui.Video.Position.CurrentFrames, Base.Ui.Video.Position.CurrentTime);

            /* Create and add the sync point */
            SyncPoint syncPoint      = new SyncPoint(subtitleNumber, currentTiming, correctTiming);
            int       syncPointIndex = syncPoints.Add(syncPoint);
            TreePath  syncPointPath  = Core.Util.IntToPath(syncPointIndex);

            SelectPath(syncPointPath);

            UpdateFromSyncPointCountChanged();
        }
Exemple #12
0
        public async Task Resolver_SubchannelTransientFailure_ResolverRefreshed()
        {
            // Ignore errors
            SetExpectedErrorsFilter(writeContext =>
            {
                return(true);
            });

            string?host = null;

            Task <HelloReply> UnaryMethod(HelloRequest request, ServerCallContext context)
            {
                host = context.Host;
                return(Task.FromResult(new HelloReply {
                    Message = request.Name
                }));
            }

            // Arrange
            using var endpoint1 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50051, UnaryMethod, nameof(UnaryMethod));
            using var endpoint2 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50052, UnaryMethod, nameof(UnaryMethod));

            SyncPoint?syncPoint = new SyncPoint(runContinuationsAsynchronously: true);

            syncPoint.Continue();

            var resolver = new TestResolver(async() =>
            {
                await syncPoint.WaitToContinue().DefaultTimeout();
                syncPoint = new SyncPoint(runContinuationsAsynchronously: true);
            });

            resolver.UpdateAddresses(new List <BalancerAddress>
            {
                new BalancerAddress(endpoint1.Address.Host, endpoint1.Address.Port),
                new BalancerAddress(endpoint2.Address.Host, endpoint2.Address.Port)
            });

            var channel = await BalancerHelpers.CreateChannel(LoggerFactory, new RoundRobinConfig(), resolver, connect : true);

            await BalancerHelpers.WaitForSubChannelsToBeReadyAsync(Logger, channel, 2).DefaultTimeout();

            var client = TestClientFactory.Create(channel, endpoint1.Method);

            var waitForRefreshTask = syncPoint.WaitForSyncPoint();

            endpoint1.Dispose();

            await waitForRefreshTask.DefaultTimeout();

            resolver.UpdateAddresses(new List <BalancerAddress>
            {
                new BalancerAddress(endpoint2.Address.Host, endpoint2.Address.Port)
            });

            syncPoint.Continue();

            await BalancerHelpers.WaitForSubChannelsToBeReadyAsync(Logger, channel, 1).DefaultTimeout();
        }
Exemple #13
0
        public async Task ServerStreaming_WriteAfterMethodComplete_Error(bool writeBeforeExit)
        {
            var tcs       = new TaskCompletionSource <object?>(TaskCreationOptions.RunContinuationsAsynchronously);
            var writeTcs  = new TaskCompletionSource <Task>(TaskCreationOptions.RunContinuationsAsynchronously);
            var syncPoint = new SyncPoint(runContinuationsAsynchronously: true);

            async Task ServerStreamingWithTrailers(DataMessage request, IServerStreamWriter <DataMessage> responseStream, ServerCallContext context)
            {
                var writeTask = Task.Run(async() =>
                {
                    if (writeBeforeExit)
                    {
                        await responseStream.WriteAsync(new DataMessage());
                    }

                    await syncPoint.WaitToContinue();

                    await responseStream.WriteAsync(new DataMessage());
                });

                writeTcs.SetResult(writeTask);

                await tcs.Task;
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddServerStreamingMethod <DataMessage, DataMessage>(ServerStreamingWithTrailers);

            var channel = CreateChannel();

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.ServerStreamingCall(new DataMessage());

            await syncPoint.WaitForSyncPoint().DefaultTimeout();

            tcs.SetResult(null);

            // Assert
            if (writeBeforeExit)
            {
                Assert.IsTrue(await call.ResponseStream.MoveNext().DefaultTimeout());
            }

            Assert.IsFalse(await call.ResponseStream.MoveNext().DefaultTimeout());
            Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);

            syncPoint.Continue();

            var writeTask = await writeTcs.Task.DefaultTimeout();

            var ex = await ExceptionAssert.ThrowsAsync <InvalidOperationException>(() => writeTask).DefaultTimeout();

            Assert.AreEqual("Can't write the message because the request is complete.", ex.Message);

            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
 public void Update()
 {
     if (pendingSyncPoint != null)
     {
         SetArSessionOriginPositionAndOrientation(pendingSyncPoint.X, pendingSyncPoint.Z,
                                                  pendingSyncPoint.Orientation);
         pendingSyncPoint = null;
     }
 }
	/* Private members */

	private SyncPoints AdaptForOperation (SyncPoints syncPoints, bool toSyncAll) {
		if ((syncPoints == null) || (!toSyncAll) || (toSyncAll && (syncPoints.Count < 2)))
			return syncPoints;

		SyncPoints adapted = syncPoints.Clone();

		/* Add the first subtitle if possible */
		int firstSubtitleNumber = 0;
		if ((subtitles.Collection.Count > 1) && (!adapted.Contains(firstSubtitleNumber))) {

			/* Calculate sync shift and factor using the last 2 sync points */
			SyncPoint firstSyncPoint = adapted[0];
			SyncPoint secondSyncPoint = adapted[1];
			Subtitle firstSyncPointSubtitle = subtitles.Collection[firstSyncPoint.SubtitleNumber];
			Subtitle secondSyncPointSubtitle = subtitles.Collection[secondSyncPoint.SubtitleNumber];
			TimeSpan shift = firstSyncPoint.Correct.Time - firstSyncPointSubtitle.Times.PreciseStart;
			double factor = (secondSyncPoint.Correct.Time - firstSyncPoint.Correct.Time).TotalMilliseconds / (secondSyncPointSubtitle.Times.PreciseStart - firstSyncPointSubtitle.Times.PreciseStart).TotalMilliseconds;

			/* Calculate new time */
			Subtitle firstSubtitle = subtitles.Collection[firstSubtitleNumber];
			TimeSpan firstSubtitleNewTime = firstSubtitle.Times.Start + shift; //Apply shift
			firstSubtitleNewTime = SyncUtil.Scale(firstSubtitleNewTime, TimeSpan.Zero, factor);
			if (firstSubtitleNewTime < TimeSpan.Zero) { //Can't have negative start
				firstSubtitleNewTime = TimeSpan.Zero;
			}
			int firstSubtitleNewFrame = (int)TimingUtil.TimeToFrames(firstSubtitleNewTime, subtitles.Properties.CurrentFrameRate);
			Domain.Timing firstSubtitleNewTiming = new Domain.Timing(firstSubtitleNewFrame, firstSubtitleNewTime);
			Domain.Timing firstSubtitleCurrentTiming = new Domain.Timing(firstSubtitle.Frames.Start, firstSubtitle.Times.Start);
			SyncPoint newFirstSyncPoint = new SyncPoint(firstSubtitleNumber, firstSubtitleCurrentTiming, firstSubtitleNewTiming);
			adapted.Add(newFirstSyncPoint);
		}

		/* Add last subtitle if possible */
		int lastSubtitleNumber = subtitles.Collection.Count - 1;
		if ((subtitles.Collection.Count > 1) && (!adapted.Contains(lastSubtitleNumber))) {

			/* Calculate sync shift and factor using the last 2 sync points */
			SyncPoint penultSyncPoint = adapted[adapted.Count - 2];
			SyncPoint lastSyncPoint = adapted[adapted.Count - 1];
			Subtitle penultSyncPointSubtitle = subtitles.Collection[penultSyncPoint.SubtitleNumber];
			Subtitle lastSyncPointSubtitle = subtitles.Collection[lastSyncPoint.SubtitleNumber];
			TimeSpan shift = penultSyncPoint.Correct.Time - penultSyncPointSubtitle.Times.PreciseStart;
			double factor = (lastSyncPoint.Correct.Time - penultSyncPoint.Correct.Time).TotalMilliseconds / (lastSyncPointSubtitle.Times.PreciseStart - penultSyncPointSubtitle.Times.PreciseStart).TotalMilliseconds;

			/* Calculate new time */
			Subtitle lastSubtitle = subtitles.Collection[lastSubtitleNumber];
			TimeSpan lastSubtitleNewTime = lastSubtitle.Times.Start + shift; //Apply shift
			lastSubtitleNewTime = SyncUtil.Scale(lastSubtitleNewTime, penultSyncPoint.Correct.Time, factor);
			int lastSubtitleNewFrame = (int)TimingUtil.TimeToFrames(lastSubtitleNewTime, subtitles.Properties.CurrentFrameRate);
			Domain.Timing lastSubtitleNewTiming = new Domain.Timing(lastSubtitleNewFrame, lastSubtitleNewTime);
			Domain.Timing lastSubtitleCurrentTiming = new Domain.Timing(lastSubtitle.Frames.Start, lastSubtitle.Times.Start);
			SyncPoint newLastSyncPoint = new SyncPoint(lastSubtitleNumber, lastSubtitleCurrentTiming, lastSubtitleNewTiming);
			adapted.Add(newLastSyncPoint);
		}

		return adapted;
	}
Exemple #16
0
        public ViewModel(string name, SyncPoint point)
        {
            this.point = point;
            this.Name  = name;

            point.Blocked  += OnBlocked;
            point.Released += OnReleased;

            this.IsActivated = point.IsActivated;
        }
Exemple #17
0
        public async Task AsyncUnaryCall_AuthInteceptorDispose_Error()
        {
            // Arrange
            var testSink = new TestSink();
            var services = new ServiceCollection();

            services.AddLogging(b =>
            {
                b.AddProvider(new TestLoggerProvider(testSink));
            });
            services.AddNUnitLogger();
            var provider = services.BuildServiceProvider();

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var serviceConfig        = ServiceConfigHelpers.CreateRetryServiceConfig();
            var credentialsSyncPoint = new SyncPoint(runContinuationsAsynchronously: true);
            var credentials          = CallCredentials.FromInterceptor(async(context, metadata) =>
            {
                await credentialsSyncPoint.WaitToContinue();
                metadata.Add("Authorization", $"Bearer TEST");
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory: provider.GetRequiredService <ILoggerFactory>(), serviceConfig: serviceConfig, configure: options => options.Credentials = ChannelCredentials.Create(new SslCredentials(), credentials));

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest {
                Name = "World"
            });
            var responseTask        = call.ResponseAsync;
            var responseHeadersTask = call.ResponseHeadersAsync;

            await credentialsSyncPoint.WaitForSyncPoint().DefaultTimeout();

            call.Dispose();

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);

            ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseHeadersTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);

            var write = testSink.Writes.Single(w => w.EventId.Name == "CallCommited");

            Assert.AreEqual("Call commited. Reason: Canceled", write.State.ToString());
        }
Exemple #18
0
        public async Task AsyncServerStreamingCall_SuccessAfterRetry_RequestContentSent()
        {
            // Arrange
            var          syncPoint      = new SyncPoint(runContinuationsAsynchronously: true);
            MemoryStream?requestContent = null;

            var callCount  = 0;
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                Interlocked.Increment(ref callCount);

                var s  = await request.Content !.ReadAsStreamAsync();
                var ms = new MemoryStream();
                await s.CopyToAsync(ms);

                if (callCount == 1)
                {
                    await syncPoint.WaitForSyncPoint();

                    await request.Content !.CopyToAsync(new MemoryStream());
                    return(ResponseUtils.CreateHeadersOnlyResponse(HttpStatusCode.OK, StatusCode.Unavailable));
                }

                syncPoint.Continue();

                requestContent = ms;

                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var serviceConfig = ServiceConfigHelpers.CreateHedgingServiceConfig(maxAttempts: 2, hedgingDelay: TimeSpan.FromMilliseconds(50));
            var invoker       = HttpClientCallInvokerFactory.Create(httpClient, serviceConfig: serviceConfig);

            // Act
            var call = invoker.AsyncServerStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.GetServiceMethod(MethodType.ServerStreaming), string.Empty, new CallOptions(), new HelloRequest {
                Name = "World"
            });
            var moveNextTask = call.ResponseStream.MoveNext(CancellationToken.None);

            // Wait until the first call has failed and the second is on the server
            await syncPoint.WaitToContinue().DefaultTimeout();

            // Assert
            Assert.IsTrue(await moveNextTask);
            Assert.AreEqual("Hello world", call.ResponseStream.Current.Message);

            requestContent !.Seek(0, SeekOrigin.Begin);
            var requestMessage = await ReadRequestMessage(requestContent).DefaultTimeout();

            Assert.AreEqual("World", requestMessage !.Name);
        }
Exemple #19
0
        private void OnRowActivated(object o, RowActivatedArgs args)
        {
            SyncPoint syncPoint      = syncPoints[args.Path];
            int       subtitleNumber = syncPoint.SubtitleNumber;

            if (subtitleNumber < Base.Document.Subtitles.Count)
            {
                Base.Ui.View.Selection.Select(Core.Util.IntToPath(syncPoint.SubtitleNumber), true, true);
                Base.Ui.Video.Seek(syncPoint.Correct.Time);
            }
        }
        public void OnButtonClick_WillScheduleSyncOnArCalibrationBehaviour()
        {
            var syncPoint = new SyncPoint("Lone Cowboy", 10, 10, 84);

            Repositories.SyncPointRepository.Save(new[] { syncPoint });

            _selectorBehaviour.Start();

            _selectorBehaviour.scrollContent.transform.GetChild(0).GetComponent <Button>().onClick.Invoke();

            Assert.AreEqual(syncPoint, _selectorBehaviour.calibrationBehaviour.pendingSyncPoint);
        }
        public void Start_WillCreateScrollViewItemOnScrollView()
        {
            var syncPoint = new SyncPoint("Lone Cowboy", 10, 10, 84);

            Repositories.SyncPointRepository.Save(new[] { syncPoint });

            _selectorBehaviour.Start();

            var content = _selectorBehaviour.scrollContent;

            Assert.AreEqual(1, content.transform.childCount);
        }
Exemple #22
0
        public void Save_ASavedSyncPointCanBeRetrieved()
        {
            var syncPoint = new SyncPoint("test", 2, 2, 0);

            _inMemorySyncPointRepository.Save(new[] { syncPoint });

            var result = _inMemorySyncPointRepository.Get();

            Assert.AreEqual(1, result.Length);
            Assert.AreEqual(2, result[0].X);
            Assert.AreEqual(2, result[0].Z);
        }
Exemple #23
0
        public async Task GET_ServerAbort_ClientReceivesAbort(HttpProtocols protocol)
        {
            // Arrange
            var syncPoint      = new SyncPoint();
            var cancelledTcs   = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
            var writeAsyncTask = new TaskCompletionSource <Task>(TaskCreationOptions.RunContinuationsAsynchronously);

            var builder = CreateHostBuilder(async context =>
            {
                context.RequestAborted.Register(() => cancelledTcs.SetResult());

                context.Abort();

                // Sync with client
                await syncPoint.WaitToContinue();

                writeAsyncTask.SetResult(context.Response.Body.WriteAsync(TestData).AsTask());
            }, protocol: protocol);

            using (var host = builder.Build())
                using (var client = CreateClient())
                {
                    await host.StartAsync().DefaultTimeout();

                    var request = new HttpRequestMessage(HttpMethod.Get, $"https://127.0.0.1:{host.GetPort()}/");
                    request.Version       = GetProtocol(protocol);
                    request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;

                    // Act
                    var ex = await Assert.ThrowsAnyAsync <HttpRequestException>(() => client.SendAsync(request, CancellationToken.None)).DefaultTimeout();

                    // Assert
                    if (protocol == HttpProtocols.Http3)
                    {
                        var innerEx = Assert.IsType <QuicStreamAbortedException>(ex.InnerException);
                        Assert.Equal(258, innerEx.ErrorCode);
                    }

                    await cancelledTcs.Task.DefaultTimeout();

                    // Sync with server to ensure RequestDelegate is still running
                    await syncPoint.WaitForSyncPoint().DefaultTimeout();

                    syncPoint.Continue();

                    var serverWriteTask = await writeAsyncTask.Task.DefaultTimeout();

                    await serverWriteTask.DefaultTimeout();

                    await host.StopAsync().DefaultTimeout();
                }
        }
        /// <summary>
        /// Updates a syncpoint.
        /// </summary>
        /// <param name="syncpoint">The syncpoint to update.</param>
        /// <param name="include">The include param.</param>
        /// <returns>The object of updates syncpoint.</returns>
        public static SyncPoint PutSyncpoint(SyncPoint syncpoint, Include include = Include.None)
        {
            var url = string.Format(SyncpointUrl, syncpoint.Id);

            var includeStr = FormatInclude(include);

            if (!string.IsNullOrWhiteSpace(includeStr))
            {
                url += $"?include={includeStr}";
            }

            return(HttpPut(url, syncpoint));
        }
        public async Task ClientStreaming_ServerAbort()
        {
            // Arrange
            var requestStreamSyncPoint  = new SyncPoint();
            var responseEndingSyncPoint = new SyncPoint();

            RequestDelegate appDelegate = async ctx =>
            {
                // Send headers
                await ctx.Response.BodyWriter.FlushAsync();

                ctx.Abort();
                await responseEndingSyncPoint.WaitToContinue();
            };

            Stream requestStream = null;

            var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
            var server  = new TestServer(builder);
            var client  = server.CreateClient();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");

            httpRequest.Version = new Version(2, 0);
            httpRequest.Content = new PushContent(async stream =>
            {
                requestStream = stream;
                await requestStreamSyncPoint.WaitToContinue();
            });

            // Act
            var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).WithTimeout();

            var responseContent = await response.Content.ReadAsStreamAsync().WithTimeout();

            // Assert

            // Ensure server has aborted
            await responseEndingSyncPoint.WaitForSyncPoint();

            // Ensure request stream has started
            await requestStreamSyncPoint.WaitForSyncPoint();

            // Send content and finish request body
            await ExceptionAssert.ThrowsAsync <OperationCanceledException>(
                () => requestStream.WriteAsync(Encoding.UTF8.GetBytes("Hello world")).AsTask(),
                "Flush was canceled on underlying PipeWriter.").WithTimeout();

            responseEndingSyncPoint.Continue();
            requestStreamSyncPoint.Continue();
        }
Exemple #26
0
        public async Task Unary_RetryThrottlingBecomesActive_HasDelay_Failure()
        {
            var callCount = 0;
            var syncPoint = new SyncPoint(runContinuationsAsynchronously: true);

            async Task <DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                Interlocked.Increment(ref callCount);
                await syncPoint.WaitToContinue();

                return(request);
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod <DataMessage, DataMessage>(UnaryFailure);

            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateHedgingServiceConfig(
                                            hedgingDelay: TimeSpan.FromMilliseconds(100),
                                            retryThrottling: new RetryThrottlingPolicy
            {
                MaxTokens  = 5,
                TokenRatio = 0.1
            }));

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            await syncPoint.WaitForSyncPoint().DefaultTimeout();

            // Manually trigger retry throttling
            Debug.Assert(channel.RetryThrottling != null);
            channel.RetryThrottling.CallFailure();
            channel.RetryThrottling.CallFailure();
            channel.RetryThrottling.CallFailure();
            Debug.Assert(channel.RetryThrottling.IsRetryThrottlingActive());

            // Assert
            await TestHelpers.AssertIsTrueRetryAsync(() => HasLog(LogLevel.Debug, "AdditionalCallsBlockedByRetryThrottling", "Additional calls blocked by retry throttling."), "Check for expected log.");

            Assert.AreEqual(1, callCount);
            syncPoint.Continue();

            await call.ResponseAsync.DefaultTimeout();

            Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);

            AssertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: ResponseHeadersReceived");
        }
	private bool AreSyncArgsValid (SyncPoints syncPoints) {
		if ((syncPoints == null) || (syncPoints.Count < 2) || (syncPoints[syncPoints.Count - 1].SubtitleNumber > subtitles.Collection.Count))
			return false;

		SyncPoint previous = syncPoints[0];
		for (int index = 1 ; index < syncPoints.Count ; index++) {
			SyncPoint current = syncPoints[index];
			if (!SyncUtil.AreSyncPointsValid(subtitles, previous, current))
				return false;

			previous = current;
		}
		return true;
	}
Exemple #28
0
        public IEnumerator OnStartCameraViewsLocationMarker()
        {
            var syncPoint = new SyncPoint("test", 10, 10, 0);

            Repositories.SyncPointRepository.Save(new [] { syncPoint });
            yield return(LoadScene());

            var cameraPos = _mainCamera.transform.position;

            yield return(null);

            Assert.AreEqual(syncPoint.X, cameraPos.x);
            Assert.AreEqual(syncPoint.Z, cameraPos.z);
        }
    public async Task HandleCallAsync_WriteMultipleMessages_Returned()
    {
        // Arrange
        var syncPoint = new SyncPoint();

        ServerStreamingServerMethod <JsonTranscodingGreeterService, HelloRequest, HelloReply> invoker = async(s, r, w, c) =>
        {
            await w.WriteAsync(new HelloReply { Message = $"Hello {r.Name} 1" });

            await syncPoint.WaitToContinue();

            await w.WriteAsync(new HelloReply { Message = $"Hello {r.Name} 2" });
        };

        var pipe = new Pipe();

        var routeParameterDescriptors = new Dictionary <string, List <FieldDescriptor> >
        {
            ["name"] = new List <FieldDescriptor>(new[] { HelloRequest.Descriptor.FindFieldByNumber(HelloRequest.NameFieldNumber) })
        };
        var descriptorInfo = TestHelpers.CreateDescriptorInfo(routeParameterDescriptors: routeParameterDescriptors);
        var callHandler    = CreateCallHandler(invoker, descriptorInfo: descriptorInfo);
        var httpContext    = TestHelpers.CreateHttpContext(bodyStream: pipe.Writer.AsStream());

        httpContext.Request.RouteValues["name"] = "TestName!";

        // Act
        var callTask = callHandler.HandleCallAsync(httpContext);

        // Assert
        Assert.Equal(200, httpContext.Response.StatusCode);
        Assert.Equal("application/json; charset=utf-8", httpContext.Response.ContentType);

        var line1 = await ReadLineAsync(pipe.Reader).DefaultTimeout();

        using var responseJson1 = JsonDocument.Parse(line1 !);
        Assert.Equal("Hello TestName! 1", responseJson1.RootElement.GetProperty("message").GetString());

        await syncPoint.WaitForSyncPoint().DefaultTimeout();

        syncPoint.Continue();

        var line2 = await ReadLineAsync(pipe.Reader).DefaultTimeout();

        using var responseJson2 = JsonDocument.Parse(line2 !);
        Assert.Equal("Hello TestName! 2", responseJson2.RootElement.GetProperty("message").GetString());

        await callTask.DefaultTimeout();
    }
Exemple #30
0
        public void Save_CanSaveMultipleSyncPoints()
        {
            var syncPoint1 = new SyncPoint("test", 1, 1, 0);
            var syncPoint2 = new SyncPoint("test2", 2, 2, 0);

            _inMemorySyncPointRepository.Save(new[] { syncPoint1, syncPoint2 });

            var result = _inMemorySyncPointRepository.Get();

            Assert.AreEqual(2, result.Length);
            Assert.AreEqual(1, result[0].X);
            Assert.AreEqual(1, result[0].Z);
            Assert.AreEqual(2, result[1].X);
            Assert.AreEqual(2, result[1].Z);
        }