public async Task ConnectAsync(string url) { _url = url; while (!IsConnectionFinished()) { // Wait until current connection ends. _wrapperAdapter.TaskDelay(1000).Wait(); } await ConnectAsync(); }
public void Start() { //Delay first execution until expected time has passed _wrappedAdapter.TaskDelay(_interval * 1000).Wait(); var schedulerTask = PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds: _interval * 1000, cancelToken: _cancelTokenSource.Token); }
private async Task BuildJsonAndPost(List <Event> events, Util.SplitStopwatch clock) { var eventsJson = JsonConvert.SerializeObject(events, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); for (int i = 0; i < MaxAttempts; i++) { if (i > 0) { _wrapperAdapter.TaskDelay(500).Wait(); } var response = await ExecutePost(EventsUrlTemplate, eventsJson); RecordTelemetry(nameof(SendBulkEventsTask), (int)response.statusCode, response.content, ResourceEnum.EventSync, clock); if (response.statusCode >= System.Net.HttpStatusCode.OK && response.statusCode < System.Net.HttpStatusCode.Ambiguous) { _log.Debug($"Post bulk events success in {i} attempts."); return; } } _log.Debug($"Post bulk events fail after {MaxAttempts} attempts."); }
public void Start() { lock (_lock) { if (_running || _statusManager.IsDestroyed()) { return; } _running = true; _cancelTokenSource = new CancellationTokenSource(); _tasksManager.Start(() => { //Delay first execution until expected time has passed var intervalInMilliseconds = _interval * 1000; _wrappedAdapter.TaskDelay(intervalInMilliseconds).Wait(); if (_running) { _tasksManager.Start(() => _worker.ExecuteTasks(_cancelTokenSource.Token), _cancelTokenSource, "Segments Fetcher Worker."); _tasksManager.StartPeriodic(() => AddSegmentsToQueue(), intervalInMilliseconds, _cancelTokenSource, "Segmennnnts Fetcher Add to Queue."); } }, _cancelTokenSource, "Main Segments Fetcher."); } }
public void Start() { _wrapperAdapter .TaskDelay(_firstPushWindow * 1000) .ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, _interval * 1000, _cancellationTokenSource.Token); }); }
public void Start() { Task.Factory.StartNew(() => { while (true) { if (_gates.IsSDKReady(0)) { //Delay first execution until expected time has passed var intervalInMilliseconds = _interval * 1000; _wrappedAdapter.TaskDelay(intervalInMilliseconds).Wait(); PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds, _cancelTokenSource.Token); break; } _wrappedAdapter.TaskDelay(500).Wait(); } }); }
private async Task <SyncResult> AttempSegmentSync(string name, long targetChangeNumber, FetchOptions fetchOptions, int maxRetries, int?retryDelayMs, bool withBackoff) { try { var remainingAttempts = maxRetries; if (withBackoff) { _backOffSplits.Reset(); } while (true) { remainingAttempts--; await _segmentFetcher.Fetch(name, fetchOptions); if (targetChangeNumber <= _segmentCache.GetChangeNumber(name)) { return(new SyncResult(true, remainingAttempts)); } else if (remainingAttempts <= 0) { return(new SyncResult(false, remainingAttempts)); } var delay = withBackoff ? _backOffSplits.GetInterval(inMiliseconds: true) : retryDelayMs.Value; _wrapperAdapter.TaskDelay((int)delay).Wait(); } } catch (Exception ex) { _log.Debug("Exception while AttempSplitsSync.", ex); } return(new SyncResult(false, 0)); }
public void Start() { lock (_lock) { if (_running) { return; } _running = true; _tasksManager.Start(() => { _wrapperAdapter.TaskDelay(_firstPushWindow * 1000).Wait(); _tasksManager.StartPeriodic(() => SendBulkEvents(), _interval * 1000, _cancellationTokenSource, "Send Bulk Events."); }, new CancellationTokenSource(), "Main Events Log."); } }
private void ScheduleNextTokenRefresh(double time) { try { var sleepTime = Convert.ToInt32(time) * 1000; _log.Debug($"ScheduleNextTokenRefresh sleep time : {sleepTime} miliseconds."); _wrapperAdapter .TaskDelay(sleepTime) .ContinueWith((t) => { _log.Debug("Starting ScheduleNextTokenRefresh ..."); StopSse(); StartSse(); }); } catch (Exception ex) { _log.Error($"ScheduleNextTokenRefresh: {ex.Message}"); } }
public void Start() { lock (_lock) { if (_running) { return; } _running = true; _tasksManager.Start(() => { //Delay first execution until expected time has passed var intervalInMilliseconds = _configurationOptions.TelemetryRefreshRate * 1000; _wrapperAdapter.TaskDelay(intervalInMilliseconds).Wait(); _tasksManager.StartPeriodic(() => RecordStats(), intervalInMilliseconds, _cancellationTokenSource, "Telemetry Stats."); }, _cancellationTokenSource, "Main Telemetry."); } }
public void Start() { _tasksManager.Start(() => { try { while (!_synchronizer.SyncAll(_shutdownCancellationTokenSource, asynchronous: false)) { _wrapperAdapter.TaskDelay(500).Wait(); } _statusManager.SetReady(); _telemetrySyncTask.RecordConfigInit(); _synchronizer.StartPeriodicDataRecording(); if (_streamingEnabled) { _log.Debug("Starting streaming mode..."); var connected = _pushManager.StartSse().Result; if (connected) { return; } } _log.Debug("Starting polling mode ..."); _synchronizer.StartPeriodicFetching(); _telemetryRuntimeProducer.RecordStreamingEvent(new StreamingEvent(EventTypeEnum.SyncMode, (int)SyncModeEnum.Polling)); } catch (Exception ex) { _log.Debug("Exception initialization SDK.", ex); } }, _shutdownCancellationTokenSource, "SDK Initialization"); }
private async Task BuildJsonAndPost(List <KeyImpression> impressions, Util.SplitStopwatch clock) { var impressionsJson = ConvertToJson(impressions); for (int i = 0; i < MaxAttempts; i++) { if (i > 0) { _wrapperAdapter.TaskDelay(500).Wait(); } var response = await ExecutePost(TestImpressionsUrlTemplate, impressionsJson); RecordTelemetry(nameof(SendBulkImpressions), (int)response.statusCode, response.content, ResourceEnum.ImpressionSync, clock); if (response.statusCode >= System.Net.HttpStatusCode.OK && response.statusCode < System.Net.HttpStatusCode.Ambiguous) { _log.Debug($"Post bulk impressions success in {i} attempts."); return; } } _log.Debug($"Post bulk impressions fail after {MaxAttempts} attempts."); }
private void ScheduleNextTokenRefresh(double time) { try { ForceCancellationToken(); _cancellationTokenSourceRefreshToken = new CancellationTokenSource(); var sleepTime = Convert.ToInt32(time) * 1000; _log.Debug($"ScheduleNextTokenRefresh sleep time : {sleepTime} miliseconds."); _refreshTokenTask = _wrapperAdapter .TaskDelay(sleepTime) .ContinueWith((t) => { _log.Debug("Starting ScheduleNextTokenRefresh ..."); StopSse(); StartSse(); }, _cancellationTokenSourceRefreshToken.Token); } catch (Exception ex) { _log.Error($"ScheduleNextTokenRefresh: {ex.Message}"); } }
private async Task ReadStreamAsync(Stream stream, CancellationToken cancellationToken) { _log.Debug($"Reading stream ...."); try { while (!cancellationToken.IsCancellationRequested && (IsConnected() || _firstEvent)) { if (stream.CanRead && (IsConnected() || _firstEvent)) { Array.Clear(_buffer, 0, BufferSize); var timeoutToken = new CancellationTokenSource(); var timeoutTask = _wrapperAdapter.TaskDelay(ReadTimeoutMs, timeoutToken.Token); var streamReadTask = stream.ReadAsync(_buffer, 0, BufferSize, cancellationToken); // Creates a task that will complete when any of the supplied tasks have completed. // Returns: A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed. var finishedTask = await _wrapperAdapter.WhenAny(streamReadTask, timeoutTask); try { if (finishedTask == timeoutTask) { throw new ReadStreamException(SSEClientActions.RETRYABLE_ERROR, $"Streaming read time out after {ReadTimeoutMs} seconds."); } int len = streamReadTask.Result; if (len == 0) { throw new ReadStreamException(SSEClientActions.RETRYABLE_ERROR, "Streaming end of the file."); } var notificationString = _encoder.GetString(_buffer, 0, len); _log.Debug($"Read stream encoder buffer: {notificationString}"); if (_firstEvent) { ProcessFirtsEvent(notificationString); } if (notificationString != KeepAliveResponse && IsConnected()) { var lines = notificationString.Split(_notificationSplitArray, StringSplitOptions.None); foreach (var line in lines) { if (!string.IsNullOrEmpty(line)) { var eventData = _notificationParser.Parse(line); if (eventData != null) { if (eventData.Type == NotificationType.ERROR) { var notificationError = (NotificationError)eventData; ProcessErrorNotification(notificationError); } else { DispatchEvent(eventData); } } } } } } finally { _log.Debug("Disposing Stream Read Task..."); timeoutToken.Cancel(); timeoutToken.Dispose(); _wrapperAdapter.TaskWaitAndDispose(timeoutTask, streamReadTask, finishedTask); } } } } catch (ReadStreamException ex) { _log.Debug("ReadStreamException", ex); throw ex; } catch (Exception ex) { if (!cancellationToken.IsCancellationRequested) { _log.Debug("Stream ended abruptly, proceeding to reconnect.", ex); throw new ReadStreamException(SSEClientActions.RETRYABLE_ERROR, ex.Message); } _log.Debug("Stream Token cancelled.", ex); } finally { _log.Debug($"Stop read stream"); } }