-
Notifications
You must be signed in to change notification settings - Fork 8
chore: Add FDv2 Polling Data Source #190
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
db1b38a
feat: Add support for transactional data stores.
kinyoklion 1757212
chore: Add changeset sorting.
kinyoklion 5c499c9
Remove version collapsing.
kinyoklion d73c5f9
Change data to property
kinyoklion 9ffcf50
chore: Add support for transactional data source updates.
kinyoklion edde5c3
Merge branch 'rlamb/add-changeset-sorting' into rlamb/sdk-1583/transa…
kinyoklion 8805426
Basic transactional apply routing.
kinyoklion 9c37607
Support non-transactional data stores.
kinyoklion 5d16f31
Organize code by region.
kinyoklion 94184a3
Only find environment ID once per connection.
kinyoklion 94cdabf
chore: Add FDv2 polling data source.
kinyoklion 8c14faa
Error handling improvements.
kinyoklion 5b2e4d3
Merge branch 'rlamb/sdk-1583/transactional-data-source-updates' into …
kinyoklion 90e87a0
Error handling improvements.
kinyoklion 9655e3a
Merge branch 'rlamb/sdk-1583/transactional-data-source-updates' into …
kinyoklion 5844a66
Refactor application to transactional versus non-transactional stores.
kinyoklion 891ad0a
Sort and add comments.
kinyoklion ff7c34d
Merge branch 'rlamb/sdk-1583/transactional-data-source-updates' into …
kinyoklion aee3377
Merge branch 'main' into rlamb/sdk-1584/fdv2-polling-data-source
kinyoklion 30bec0e
More robust JSON parsing.
kinyoklion 6c5765a
Better 304 handling.
kinyoklion 69b18d1
More JSON error handling.
kinyoklion File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
238 changes: 238 additions & 0 deletions
238
pkgs/sdk/server/src/Internal/FDv2DataSources/FDv2PollingDataSource.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| using System; | ||
| using System.Linq; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using LaunchDarkly.Logging; | ||
| using LaunchDarkly.Sdk.Internal; | ||
| using LaunchDarkly.Sdk.Internal.Concurrent; | ||
| using LaunchDarkly.Sdk.Internal.Http; | ||
| using LaunchDarkly.Sdk.Server.Interfaces; | ||
| using LaunchDarkly.Sdk.Server.Subsystems; | ||
|
|
||
| namespace LaunchDarkly.Sdk.Server.Internal.FDv2DataSources | ||
| { | ||
| internal sealed class FDv2PollingDataSource : IDataSource | ||
| { | ||
| internal delegate Selector SelectorSource(); | ||
|
|
||
| private readonly IFDv2PollingRequestor _requestor; | ||
| private readonly IDataSourceUpdates _dataSourceUpdates; | ||
| private readonly TaskExecutor _taskExecutor; | ||
| private readonly TimeSpan _pollInterval; | ||
| private readonly AtomicBoolean _initialized = new AtomicBoolean(false); | ||
| private readonly TaskCompletionSource<bool> _initTask; | ||
| private readonly Logger _log; | ||
| private readonly FDv2ProtocolHandler _protocolHandler = new FDv2ProtocolHandler(); | ||
| private readonly object _protocolLock = new object(); | ||
| private readonly SelectorSource _selectorSource; | ||
|
|
||
| private CancellationTokenSource _canceler; | ||
| private string _environmentId; | ||
|
|
||
| internal FDv2PollingDataSource( | ||
| LdClientContext context, | ||
| IDataSourceUpdates dataSourceUpdates, | ||
| IFDv2PollingRequestor requestor, | ||
| TimeSpan pollInterval, | ||
| SelectorSource selectorSource | ||
| ) | ||
| { | ||
| _requestor = requestor; | ||
| _dataSourceUpdates = dataSourceUpdates; | ||
| _taskExecutor = context.TaskExecutor; | ||
| _pollInterval = pollInterval; | ||
| _selectorSource = selectorSource; | ||
| _initTask = new TaskCompletionSource<bool>(); | ||
| _log = context.Logger.SubLogger(LogNames.FDv2DataSourceSubLog); | ||
|
|
||
| _log.Debug("Created LaunchDarkly FDv2 polling data source"); | ||
| } | ||
|
|
||
| public bool Initialized => _initialized.Get(); | ||
|
|
||
| public Task<bool> Start() | ||
| { | ||
| lock (this) | ||
| { | ||
| // If we have a canceler, then the source has already been started. | ||
| if (_canceler != null) return _initTask.Task; | ||
|
|
||
| _log.Info("Starting LaunchDarkly FDv2 polling with interval: {0} milliseconds", | ||
| _pollInterval.TotalMilliseconds); | ||
| _canceler = _taskExecutor.StartRepeatingTask(TimeSpan.Zero, | ||
| _pollInterval, UpdateTaskAsync); | ||
| } | ||
|
|
||
| return _initTask.Task; | ||
| } | ||
|
|
||
| private async Task UpdateTaskAsync() | ||
| { | ||
| _log.Debug("Polling LaunchDarkly for feature flag updates"); | ||
| try | ||
| { | ||
| var selector = _selectorSource(); | ||
| var response = await _requestor.PollingRequestAsync(selector); | ||
|
|
||
| if (response == null) | ||
| { | ||
| // This means we got a cached response (304), so we are valid. | ||
| // We could have previously been interrupted, so we need to return to valid even | ||
| // if there are no changes. | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Valid, null); | ||
| return; | ||
| } | ||
kinyoklion marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (response.Value.Headers != null) | ||
| { | ||
| _environmentId = response.Value.Headers.FirstOrDefault(item => | ||
| item.Key.ToLower() == HeaderConstants.EnvironmentId).Value | ||
| ?.FirstOrDefault(); | ||
| } | ||
|
|
||
| ProcessPollingResponse(response.Value); | ||
| } | ||
| catch (UnsuccessfulResponseException ex) | ||
| { | ||
| var errorInfo = DataSourceStatus.ErrorInfo.FromHttpError(ex.StatusCode); | ||
|
|
||
| if (HttpErrors.IsRecoverable(ex.StatusCode)) | ||
| { | ||
| _log.Warn(HttpErrors.ErrorMessage(ex.StatusCode, "polling request", "will retry")); | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Interrupted, errorInfo); | ||
| } | ||
| else | ||
| { | ||
| _log.Error(HttpErrors.ErrorMessage(ex.StatusCode, "polling request", "")); | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Off, errorInfo); | ||
| try | ||
| { | ||
| _initTask.SetResult(true); | ||
| } | ||
| catch (InvalidOperationException) | ||
| { | ||
| // the task was already set - nothing more to do | ||
| } | ||
|
|
||
| ((IDisposable)this).Dispose(); | ||
| } | ||
| } | ||
| catch (JsonException ex) | ||
| { | ||
| _log.Error("Polling request received malformed data: {0}", LogValues.ExceptionSummary(ex)); | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Interrupted, | ||
| new DataSourceStatus.ErrorInfo | ||
| { | ||
| Kind = DataSourceStatus.ErrorKind.InvalidData, | ||
| Time = DateTime.Now | ||
| }); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| var realEx = (ex is AggregateException ae) ? ae.Flatten() : ex; | ||
| _log.Warn("Polling for feature flag updates failed: {0}", LogValues.ExceptionSummary(ex)); | ||
| _log.Debug(LogValues.ExceptionTrace(ex)); | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Interrupted, | ||
| DataSourceStatus.ErrorInfo.FromException(realEx)); | ||
| } | ||
| } | ||
|
|
||
| private void ProcessPollingResponse(FDv2PollingResponse response) | ||
| { | ||
| lock (_protocolLock) | ||
| { | ||
| _protocolHandler.Reset(); | ||
|
|
||
| foreach (var evt in response.Events) | ||
| { | ||
| var action = _protocolHandler.HandleEvent(evt); | ||
| ProcessProtocolAction(action); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void HandleJsonError(string message) | ||
| { | ||
| _log.Error("LaunchDarkly polling request received invalid data: {0}", message); | ||
|
|
||
| var errorInfo = new DataSourceStatus.ErrorInfo | ||
| { | ||
| Kind = DataSourceStatus.ErrorKind.InvalidData, | ||
| Message = message, | ||
| Time = DateTime.Now | ||
| }; | ||
| _dataSourceUpdates.UpdateStatus(DataSourceState.Interrupted, errorInfo); | ||
| } | ||
|
|
||
| private void ProcessProtocolAction(IFDv2ProtocolAction action) | ||
| { | ||
| switch (action) | ||
| { | ||
| case FDv2ActionChangeset changesetAction: | ||
| ProcessChangeSet(changesetAction.Changeset); | ||
| break; | ||
| case FDv2ActionError errorAction: | ||
| _log.Error("FDv2 error event: {0} - {1}", errorAction.Id, errorAction.Reason); | ||
| break; | ||
| case FDv2ActionGoodbye goodbyeAction: | ||
| _log.Info("FDv2 server disconnecting: {0}", goodbyeAction.Reason); | ||
| break; | ||
| case FDv2ActionInternalError internalErrorAction: | ||
| _log.Error("FDv2 protocol error ({0}): {1}", internalErrorAction.ErrorType, | ||
| internalErrorAction.Message); | ||
| // Handle JsonError by updating status to Interrupted with InvalidData error kind | ||
| if (internalErrorAction.ErrorType == FDv2ProtocolErrorType.JsonError) | ||
| { | ||
| HandleJsonError(internalErrorAction.Message); | ||
| } | ||
| break; | ||
kinyoklion marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| case FDv2ActionNone _: | ||
| // No action needed | ||
| break; | ||
| default: | ||
| // Represents an implementation error. Actions expanded without the handling | ||
| // being expanded. | ||
| _log.Error("Unhandled FDv2 Protocol Action."); | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| private void ProcessChangeSet(FDv2ChangeSet fdv2ChangeSet) | ||
| { | ||
| if (!(_dataSourceUpdates is ITransactionalDataSourceUpdates transactionalDataSourceUpdates)) | ||
| throw new InvalidOperationException("Cannot apply updates to non-transactional data source"); | ||
|
|
||
| var dataStoreChangeSet = FDv2ChangeSetTranslator.ToChangeSet(fdv2ChangeSet, _log, _environmentId); | ||
|
|
||
| // If the update fails, then we wait until the next poll and try again. | ||
| // This is different from a streaming data source, which will need to re-start to get an initial | ||
| // payload. | ||
| if (!transactionalDataSourceUpdates.Apply(dataStoreChangeSet)) return; | ||
|
|
||
| // Only mark as initialized after successfully applying a changeset | ||
| if (_initialized.GetAndSet(true)) return; | ||
| _initTask.SetResult(true); | ||
| _log.Info("First polling request successful"); | ||
| } | ||
|
|
||
| void IDisposable.Dispose() | ||
| { | ||
| Dispose(true); | ||
| GC.SuppressFinalize(this); | ||
| } | ||
|
|
||
| private void Dispose(bool disposing) | ||
| { | ||
| if (!disposing) return; | ||
|
|
||
| Shutdown(); | ||
| } | ||
|
|
||
| private void Shutdown() | ||
| { | ||
| _canceler?.Cancel(); | ||
| _requestor.Dispose(); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I removed this comment because it was blatantly wrong. A 304 is a success, and this code doesn't even run when there is a 304 because we return above. (I looked back through the history and it has been incorrect since addition 9 years ago.)