Skip to content

Commit c1f8bbc

Browse files
committed
Added a timeout to the post stream. Fixes cases where disconnect wasn't noticed.
1 parent 2728eab commit c1f8bbc

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

PowerSync/PowerSync.Common/Client/Sync/Stream/Remote.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ public class RequestDetails
3030

3131
public class Remote
3232
{
33+
34+
private const int STREAMING_POST_TIMEOUT_MS = 30_000;
35+
3336
private readonly HttpClient httpClient;
3437
protected IPowerSyncBackendConnector connector;
3538

@@ -148,12 +151,22 @@ public async Task<T> Get<T>(string path, Dictionary<string, string>? headers = n
148151
using var reader = new StreamReader(stream, Encoding.UTF8);
149152
string? line;
150153

154+
using var timeoutCts = new CancellationTokenSource();
155+
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(options.CancellationToken, timeoutCts.Token);
156+
157+
linkedCts.Token.Register(() =>
158+
{
159+
stream.Close();
160+
});
161+
151162
while ((line = await reader.ReadLineAsync()) != null)
152163
{
164+
timeoutCts.CancelAfter(TimeSpan.FromMilliseconds(STREAMING_POST_TIMEOUT_MS));
153165
yield return ParseStreamingSyncLine(JObject.Parse(line));
154166
}
155167
}
156168

169+
157170
public static StreamingSyncLine? ParseStreamingSyncLine(JObject json)
158171
{
159172
// Determine the type based on available keys

PowerSync/PowerSync.Common/Client/Sync/Stream/StreamingSyncImplementation.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace PowerSync.Common.Client.Sync.Stream;
22

3+
using System.Net.Sockets;
34
using Microsoft.Extensions.Logging;
45
using Microsoft.Extensions.Logging.Abstractions;
56

@@ -285,7 +286,14 @@ protected async Task StreamingSync(CancellationToken? signal, PowerSyncConnectio
285286
}
286287
catch (Exception ex)
287288
{
288-
logger.LogError("Caught exception in streaming sync: {message}", ex.Message);
289+
var exMessage = ex.Message;
290+
if (ex.InnerException != null && (ex.InnerException is ObjectDisposedException || ex.InnerException is SocketException))
291+
{
292+
exMessage = "Stream closed or timed out -" + ex.InnerException.Message;
293+
}
294+
295+
296+
logger.LogError("Caught exception in streaming sync: {message}", exMessage);
289297

290298
// Either:
291299
// - A network request failed with a failed connection or not OKAY response code.

0 commit comments

Comments
 (0)