public async Task <IActionResult> SignatureHelp( [FromBody] WorkspaceRequest request, [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "15000") { if (Debugger.IsAttached && !(Clock.Current is VirtualClock)) { _disposables.Add(VirtualClock.Start()); } using (var operation = Log.OnEnterAndConfirmOnExit()) { operation.Info("Processing workspaceType {workspaceType}", request.Workspace.WorkspaceType); if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs)) { return(BadRequest()); } var runTimeout = TimeSpan.FromMilliseconds(timeoutMs); var budget = new TimeBudget(runTimeout); var server = GetServerForWorkspace(request.Workspace); var result = await server.GetSignatureHelp(request, budget); budget.RecordEntry(); operation.Succeed(); return(Ok(result)); } }
public async Task <IActionResult> Compile( [FromBody] WorkspaceRequest request, [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "45000") { using (var operation = Log.OnEnterAndConfirmOnExit()) { var workspaceType = request.Workspace.WorkspaceType; operation.Info("Compiling workspaceType {workspaceType}", workspaceType); if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs)) { return(BadRequest()); } if (string.Equals(workspaceType, "script", StringComparison.OrdinalIgnoreCase)) { return(BadRequest()); } var runTimeout = TimeSpan.FromMilliseconds(timeoutMs); var budget = new TimeBudget(runTimeout); var result = await _workspaceServer.Compile(request, budget); budget.RecordEntry(); operation.Succeed(); return(Ok(result)); } }
public static async Task KillSession(long sessionId, byte[] sessionPassword, IObservable <ConnectionState> onConnectionStateChanged, string connectionString, TimeSpan timeout) { var zooKeeper = new ZooKeeperNetExClient(connectionString, 5000, null, sessionId, sessionPassword); try { var budged = TimeBudget.StartNew(timeout); var observer = new WaitStateObserver(ConnectionState.Expired); onConnectionStateChanged.Subscribe(observer); while (!budged.HasExpired) { if (zooKeeper.getState().Equals(ZooKeeperNetExClient.States.CONNECTED)) { break; } Thread.Sleep(100); } await zooKeeper.closeAsync().ConfigureAwait(false); if (await observer.Signal.Task.TryWaitAsync(budged.Remaining).ConfigureAwait(false)) { return; } throw new TimeoutException($"Expected to kill session within {timeout}, but failed to do so."); } finally { await zooKeeper.closeAsync().ConfigureAwait(false); } }
public HostingShutdown( ApplicationShutdown appShutdown, IServiceBeacon serviceBeacon, IServiceLocator serviceLocator, IVostokApplicationIdentity identity, IMetricContext instanceMetrics, ILog log, CancellationToken token, TimeSpan totalTimeout, TimeSpan beaconTimeout, bool beaconWaitEnabled, bool sendAnnotation) { this.appShutdown = appShutdown; this.serviceBeacon = serviceBeacon; this.serviceLocator = serviceLocator; this.identity = identity; this.instanceMetrics = instanceMetrics; this.log = log.ForContext <HostingShutdown>(); this.totalTimeout = totalTimeout; this.beaconTimeout = beaconTimeout; this.beaconWaitEnabled = beaconWaitEnabled; this.sendAnnotation = sendAnnotation; hostShutdownBudget = TimeBudget.CreateNew(totalTimeout); tokenRegistration = token.Register(OnHostShutdownTriggered); }
private async Task BeaconTask() { var observer = new AdHocConnectionStateObserver(OnConnectionStateChanged, OnCompleted); using (zooKeeperClient.OnConnectionStateChanged.Subscribe(observer)) { log.Info( "Registering an instance of application '{Application}' in environment '{Environment}' with id = '{Instance}'.", replicaInfo.Application, replicaInfo.Environment, replicaInfo.Replica); while (isRunning) { var budget = TimeBudget.StartNew(settings.MinimumTimeBetweenIterations); await BeaconTaskIteration().ConfigureAwait(false); if (!budget.HasExpired) { await Task.Delay(budget.Remaining, stopCancellationToken.Token).SilentlyContinue().ConfigureAwait(false); } } } }
private async Task WaitForBeaconShutdownAsync(TimeBudget budget) { try { log.Info("Service beacon graceful deregistration has been initiated (up to {ServiceBeaconWaitTime}).", budget.Remaining); var replicaInfo = serviceBeacon.ReplicaInfo; var elapsedBefore = budget.Elapsed; while (!budget.HasExpired) { var topology = serviceLocator.Locate(replicaInfo.Environment, replicaInfo.Application); var replica = topology?.Replicas.FirstOrDefault(r => r.ToString().Equals(replicaInfo.Replica, StringComparison.OrdinalIgnoreCase)); if (replica == null) { log.Info("Service replica has disappeared from topology according to local service locator in {ServiceBeaconWaitDuration}.", budget.Elapsed - elapsedBefore); break; } await Task.Delay(TimeSpanArithmetics.Min(budget.Remaining, 100.Milliseconds())).ConfigureAwait(false); } // (iloktionov): The rest of the wait is a safety net (other applications may receive SD notifications significantly later). await Task.Delay(budget.Remaining).ConfigureAwait(false); } catch (Exception error) { log.Error(error, "Failed to wait gracefully for service beacon deregistration."); } }
private bool StopServiceBeacon(TimeBudget budget) { if (serviceBeacon is DevNullServiceBeacon) { return(true); } var elapsedBefore = budget.Elapsed; log.Info("Stopping service beacon.."); try { serviceBeacon.Stop(); log.Info("Stopped service beacon in {ServiceBeaconStopTime}.", budget.Elapsed - elapsedBefore); return(true); } catch (Exception error) { log.Error(error, "Failed to stop service beacon."); return(false); } }
public async Task <ReplicaResult> SendToReplicaAsync( ITransport transport, IReplicaOrdering replicaOrdering, Uri replica, Request request, int connectionAttempts, TimeSpan?connectionTimeout, TimeSpan timeout, CancellationToken cancellationToken) { if (configuration.Logging.LogReplicaRequests) { LogRequest(replica, timeout); } var timeBudget = TimeBudget.StartNew(timeout, TimeSpan.FromMilliseconds(1)); var absoluteRequest = requestConverter.TryConvertToAbsolute(request, replica); var response = await SendRequestAsync(transport, absoluteRequest, timeBudget, connectionAttempts, connectionTimeout, cancellationToken).ConfigureAwait(false); var responseVerdict = responseClassifier.Decide(response, configuration.ResponseCriteria); var result = new ReplicaResult(replica, response, responseVerdict, timeBudget.Elapsed); if (configuration.Logging.LogReplicaResults) { LogResult(result); } replicaOrdering.Learn(result, storageProvider); return(result); }
public GameState() { UUIDGenerator.SetUUID(0); EntityHashSet = new Dictionary <int, IEntity>(); teams = new RTSTeam[MAX_PLAYERS]; activeTeams = new IndexedTeam[0]; Regions = new List <ImpactRegion>(); // No Data Yet Available VoxState = new VoxState(); VoxState.World.worldMin = Point.Zero; Scripts = new Dictionary <string, ReflectedScript>(); grid = new LevelGrid(); //grid.L0 = null; grid.L1 = null; grid.L2 = null; curFrame = 0; timePlayed = 0f; tbMemBuildings = new TimeBudget(BUILDING_MEMORIZATION_LATENCY); lckParticles = new object(); particles = new List <Particle>(); tmpParticles = new List <Particle>(); }
public async Task <ZooKeeperNetExClient> GetConnectedClient() { var budget = TimeBudget.StartNew(settings.Timeout); while (!budget.HasExpired) { if (!ResetClientIfNeeded(state)) { return(null); } var currentState = state; if (currentState == null) { return(null); } if (currentState.IsConnected) { return(currentState.Client); } if (!await currentState.NextState.Task.WaitAsync(budget.Remaining).ConfigureAwait(false)) { return(null); } } return(null); }
public void TimeBudget_allows_cancellation() { var budget = new TimeBudget(30.Seconds()); budget.Cancel(); budget.IsExceeded.Should().BeTrue(); }
public async Task TimeBudget_IsExceeded_returnes_true_after_budget_duration_has_passed() { var budget = new TimeBudget(5.Seconds()); await Clock.Current.Wait(6.Seconds()); budget.IsExceeded.Should().BeTrue(); }
public async Task The_remaining_duration_can_be_checked() { var budget = new TimeBudget(5.Seconds()); await Clock.Current.Wait(3.Seconds()); budget.RemainingDuration.Should().BeCloseTo(2.Seconds()); }
public async Task When_TimeBudget_is_exceeded_then_RemainingDuration_is_zero() { var budget = new TimeBudget(5.Seconds()); await Clock.Current.Wait(20.Seconds()); budget.RemainingDuration.Should().Be(TimeSpan.Zero); }
public RequestInfo(TimeSpan requestTimeout, RequestPriority requestPriority, string clientApplicationIdentity, IPAddress clientIpAddress) { Timeout = requestTimeout; Budget = TimeBudget.StartNew(Timeout.Cut(100.Milliseconds(), 0.05)); Priority = requestPriority; ClientApplicationIdentity = clientApplicationIdentity; ClientIpAddress = clientIpAddress; }
public async Task TimeBudget_IsExceeded_returnes_false_before_budget_duration_has_passed() { var budget = new TimeBudget(5.Seconds()); await Clock.Current.Wait(2.Seconds()); budget.IsExceeded.Should().BeFalse(); }
public GameplayController() { commands = new Queue <DevCommand>(); tbSquadDecisions = new TimeBudget(SQUAD_BUDGET_BINS); tbEntityDecisions = new TimeBudget(ENTITY_BUDGET_BINS); tbFOWCalculations = new TimeBudget(FOW_BUDGET_BINS); }
public async Task CancelIfExceeds_T_returns_the_expected_value_if_task_time_does_not_exceed_budget() { var budget = new TimeBudget(1.Seconds(), clock); var result = await Task.Run(async() => "not cancelled") .CancelIfExceeds(budget, ifCancelled: () => "cancelled"); result.Should().Be("not cancelled"); }
public ClientHolderState WithConnectionState(ConnectionState newConnectionState, ZooKeeperClientSettings settings) => new ClientHolderState( IsSuspended, newConnectionState.IsConnected(settings.CanBeReadOnly), lazyClient, ConnectionWatcher, newConnectionState, ConnectionString, TimeBudget.StartNew(settings.Timeout));
public static ClientHolderState CreateSuspended(TimeBudget suspendedFor) => new ClientHolderState( true, false, null, null, ConnectionState.Disconnected, null, suspendedFor);
public void StartNew_should_produce_a_budget_that_will_eventually_expire() { var budget = TimeBudget.StartNew(250.Milliseconds()); budget.HasExpired.Should().BeFalse(); new Action(() => budget.HasExpired.Should().BeFalse()) .ShouldPassIn(10.Seconds()); }
public void StartNew_should_produce_a_running_budget() { var budget = TimeBudget.StartNew(10.Seconds()); var remainingBefore = budget.Remaining; Thread.Sleep(1); budget.Remaining.Should().BeLessThan(remainingBefore); }
public async Task When_the_clock_is_advanced_then_start_time_does_not_change() { var startTime = Clock.Now(); var budget = new TimeBudget(5.Seconds()); await Clock.Current.Wait(5.Minutes()); budget.StartTime.Should().Be(startTime); }
public void CancelIfExceeds_throws_if_task_time_exceeds_budget() { clock.Schedule(c => { }, 500.Milliseconds()); var budget = new TimeBudget(1.Seconds(), clock); Func <Task> timeout = () => clock.Wait(10.Seconds()) .CancelIfExceeds(budget); timeout.Should().Throw <BudgetExceededException>(); }
public ScheduledActionContext( DateTimeOffset timestamp, TimeBudget budget, IScheduler scheduler, CancellationToken cancellationToken) { Timestamp = timestamp; this.budget = budget; Scheduler = scheduler; CancellationToken = cancellationToken; }
public async Task When_a_time_budget_is_canceled_before_expiration_then_the_elapsed_duration_at_cancellation_is_captured() { var budget = new TimeBudget(3.Seconds()); await Clock.Current.Wait(2.Seconds()); budget.Cancel(); await Clock.Current.Wait(2.Seconds()); budget.ElapsedDurationAtCancellation.Should().Be(2.Seconds()); }
private async Task <Response> SendRequestAsync( ITransport transport, [CanBeNull] Request request, TimeBudget timeBudget, int connectionAttempts, TimeSpan?connectionTimeout, CancellationToken cancellationToken) { if (request == null) { return(Responses.Unknown); } try { for (var attempt = 1; attempt <= connectionAttempts; ++attempt) { var connectionAttemptTimeout = connectionTimeout == null || timeBudget.Remaining < connectionTimeout ? (TimeSpan?)null : connectionTimeout.Value; var response = await transport.SendAsync(request, connectionAttemptTimeout, timeBudget.Remaining, cancellationToken).ConfigureAwait(false); if (response.Code == ResponseCode.Canceled) { throw new OperationCanceledException(); } if (response.Code == ResponseCode.ConnectFailure) { continue; } return(response); } return(Responses.ConnectFailure); } catch (OperationCanceledException) { throw; } catch (StreamAlreadyUsedException) { LogStreamReuseFailure(); return(Responses.StreamReuseFailure); } catch (Exception error) { LogTransportException(error); return(Responses.UnknownFailure); } }
private Task ShutdownBeaconAsync(TimeSpan timeout) { var budget = TimeBudget.StartNew(timeout); // (iloktionov): No reason to wait for deregistration if serviceBeacon.Stop() call has failed. if (!StopServiceBeacon(budget)) { return(Task.CompletedTask); } return(beaconWaitEnabled ? WaitForBeaconShutdownAsync(budget) : Task.CompletedTask); }
public async Task When_a_time_budget_is_canceled_then_the_remaining_duration_is_zero() { var budget = new TimeBudget(3.Seconds()); await Clock.Current.Wait(2.Seconds()); budget.Cancel(); await Clock.Current.Wait(2.Seconds()); budget.RemainingDuration.Should().Be(TimeSpan.Zero); }
public void Initiate(TimeSpan remainingTotalBudget) { log.Info("Application shutdown has been initiated. Timeout = {ApplicationShutdownTimeout}.", remainingTotalBudget.ToPrettyString()); // (iloktionov): Start the shutdown budget so that ShutdownTimeout property will return actual remaining time from here on. Interlocked.Exchange(ref budget, TimeBudget.StartNew(remainingTotalBudget)); // (iloktionov): Complete the task to notify VostokHost without relying on ShutdownToken callbacks. taskSource.TrySetResult(true); // (iloktionov): Protect against synchronous execution of arbitrary user callbacks. Task.Run(() => tokenSource.Cancel()); }