-
Notifications
You must be signed in to change notification settings - Fork 1
monitor datastream connection and fallback to api flag check if not c… #72
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
cbrady
merged 6 commits into
main
from
chris/sch-3923-fallback-to-api-flag-check-if-datastream-not-connected
Jul 22, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
07ad888
monitor datastream connection and fallback to api flag check if not c…
cbrady 7a23db9
fix gihub org script
cbrady 8e419b0
address PR feedback
cbrady 45b221a
refactor datastream reconnection logic and implement better connectio…
cbrady b4d550e
git example program
cbrady 1e57b37
Update .github/workflows/claude-code.yml
cbrady 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
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
Empty file.
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
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 | ||||
|---|---|---|---|---|---|---|
|
|
@@ -19,11 +19,11 @@ public class DatastreamClient : IDisposable | |||||
| private readonly string _apiKey; | ||||||
| private readonly Uri _baseUrl; | ||||||
| private readonly TimeSpan _cacheTtl; | ||||||
| private readonly TaskCompletionSource<bool> _monitorSource; | ||||||
|
|
||||||
| private readonly Action<bool> _connectionStateCallback; | ||||||
| private IWebSocketClient _webSocket; | ||||||
| private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); | ||||||
| private readonly SemaphoreSlim _reconnectSemaphore = new SemaphoreSlim(1, 1); | ||||||
| private CancellationTokenSource _readCancellationSource = new CancellationTokenSource(); | ||||||
|
|
||||||
| // Cache providers | ||||||
| private readonly ICacheProvider<Flag> _flagsCache; | ||||||
|
|
@@ -58,16 +58,16 @@ public DatastreamClient( | |||||
| string baseUrl, | ||||||
| ISchematicLogger logger, | ||||||
| string apiKey, | ||||||
| TaskCompletionSource<bool> monitorSource, | ||||||
| Action<bool> connectionStateCallback, | ||||||
| TimeSpan? cacheTtl = null, | ||||||
| IWebSocketClient? webSocket = null, | ||||||
| DatastreamOptions? options = null | ||||||
| ) | ||||||
| { | ||||||
| _logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||||||
| _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey)); | ||||||
| _monitorSource = monitorSource ?? throw new ArgumentNullException(nameof(monitorSource)); | ||||||
| _connectionStateCallback = connectionStateCallback ?? throw new ArgumentNullException(nameof(connectionStateCallback)); | ||||||
|
|
||||||
| // Use options if provided, otherwise use default values | ||||||
| options ??= new DatastreamOptions(); | ||||||
| _cacheTtl = cacheTtl ?? options.CacheTTL ?? TimeSpan.FromHours(24); | ||||||
|
|
@@ -80,12 +80,12 @@ public DatastreamClient( | |||||
| _baseUrl = GetBaseUrl(baseUrl); | ||||||
|
|
||||||
| // Initialize cache providers | ||||||
|
|
||||||
| // Flags always use LocalCache with unlimited TTL regardless of configuration | ||||||
| _flagsCache = new LocalCache<Flag>(options.LocalCacheCapacity, TimeSpan.MaxValue); // Flags don't expire | ||||||
|
|
||||||
| // Company and User caches use the configured provider type | ||||||
| if (options.CacheProviderType == DatastreamCacheProviderType.Redis && | ||||||
| if (options.CacheProviderType == DatastreamCacheProviderType.Redis && | ||||||
| options.RedisConfig != null) | ||||||
| { | ||||||
| try | ||||||
|
|
@@ -141,17 +141,23 @@ private async Task ConnectAndReadAsync() | |||||
| try | ||||||
| { | ||||||
| await _reconnectSemaphore.WaitAsync(); | ||||||
| if (_readCancellationSource.IsCancellationRequested) | ||||||
| { | ||||||
| _readCancellationSource.Dispose(); | ||||||
| _readCancellationSource = new CancellationTokenSource(); | ||||||
| } | ||||||
| _webSocket.Options.SetRequestHeader("X-Schematic-Api-Key", _apiKey); | ||||||
| _webSocket.Options.KeepAliveInterval = PingPeriod; // Set keep-alive interval | ||||||
|
|
||||||
| try | ||||||
| { | ||||||
| _webSocket.Options.SetRequestHeader("X-Schematic-Api-Key", _apiKey); | ||||||
| _webSocket.Options.KeepAliveInterval = PingPeriod; // Set keep-alive interval | ||||||
|
|
||||||
| await _webSocket.ConnectAsync(_baseUrl, _cancellationTokenSource.Token); | ||||||
| _logger.Info("Connected to Schematic WebSocket"); | ||||||
| attempts = 0; | ||||||
|
|
||||||
| // Signal monitor that we're connected | ||||||
| _monitorSource.TrySetResult(true); | ||||||
| // Signal connection state | ||||||
| _connectionStateCallback(true); | ||||||
|
|
||||||
| // Start reading messages | ||||||
| var readTask = ReadMessagesAsync(); | ||||||
|
|
@@ -169,21 +175,53 @@ private async Task ConnectAndReadAsync() | |||||
|
|
||||||
| // Wait for the read task to complete, which happens on disconnection | ||||||
| await readTask; | ||||||
|
|
||||||
| _readCancellationSource.Token.ThrowIfCancellationRequested(); | ||||||
| } | ||||||
| catch (Exception connectEx) | ||||||
| { | ||||||
| // Handle connection errors specifically | ||||||
| _logger.Error("Failed to connect to WebSocket: {0}", connectEx.Message); | ||||||
| // Don't rethrow - allow the outer exception handler to handle retries | ||||||
| throw; | ||||||
| } | ||||||
| finally | ||||||
| { | ||||||
| _reconnectSemaphore.Release(); | ||||||
| // Ensure connection is closed before reconnecting | ||||||
| if (_webSocket.State == WebSocketState.Open) | ||||||
| { | ||||||
| try | ||||||
| { | ||||||
| await _webSocket.CloseAsync( | ||||||
| WebSocketCloseStatus.NormalClosure, | ||||||
| "Reconnecting", | ||||||
| CancellationToken.None | ||||||
| ); | ||||||
| } | ||||||
| catch (Exception ex) | ||||||
| { | ||||||
| _logger.Error("Error closing WebSocket: {0}", ex.Message); | ||||||
| _webSocket.Abort(); | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
| catch (Exception ex) | ||||||
| catch (Exception connectionEx) | ||||||
| { | ||||||
| _logger.Error("WebSocket connection error: {Message}", ex.Message); | ||||||
| _reconnectSemaphore.Release(); | ||||||
| _logger.Error("WebSocket connection error: {0}", connectionEx.Message); | ||||||
| attempts++; | ||||||
| _monitorSource.TrySetResult(false); | ||||||
| _connectionStateCallback(false); | ||||||
|
|
||||||
| if (_webSocket != null) | ||||||
| { | ||||||
| try { _webSocket.Dispose(); } catch { /* ignore */ } | ||||||
|
||||||
| try { _webSocket.Dispose(); } catch { /* ignore */ } | |
| try { _webSocket.Dispose(); } catch (Exception disposeEx) { _logger.Error("Error disposing WebSocket: {0}", disposeEx.Message); } |
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.
The semaphore is acquired but the corresponding Release() call is moved to a catch block far below. This makes the resource management pattern hard to follow and error-prone. Consider using a using statement or try-finally block immediately after acquisition.