Skip to content

Commit

Permalink
[Fix] concurrent connections issue (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevensJourney authored Mar 21, 2024
1 parent c30e308 commit 37e266d
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/lemon-zoos-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@journeyapps/powersync-sdk-web': patch
---

Added some serialization checks for broadcasted logs from shared web worker. Unserializable items will return a warning.
5 changes: 5 additions & 0 deletions .changeset/lucky-planes-prove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@journeyapps/powersync-sdk-common': patch
---

Fixed issue where sync stream exceptions would not close previous streaming connections.
5 changes: 5 additions & 0 deletions .changeset/modern-terms-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@journeyapps/powersync-sdk-web': patch
---

Fixed issue where SyncBucketStorage logs would not be broadcasted from the shared sync worker to individual tabs.
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,10 @@ export abstract class AbstractStreamingSyncImplementation
}
}

connect() {
async connect() {
if (this.abortController) {
await this.disconnect();
}
this.abortController = new AbortController();
this.streamingSync(this.abortController.signal);
return this.waitForStatus({ connected: true });
Expand All @@ -231,6 +234,8 @@ export abstract class AbstractStreamingSyncImplementation
throw new Error('Disconnect not possible');
}
this.abortController.abort('Disconnected');
this.abortController = null;
this.updateSyncStatus({ connected: false });
}

/**
Expand All @@ -249,7 +254,14 @@ export abstract class AbstractStreamingSyncImplementation
crudUpdate: () => this.triggerCrudUpload()
});

/**
* Create a new abort controller which aborts items downstream.
* This is needed to close any previous connections on exception.
*/
let nestedAbortController = new AbortController();

signal.addEventListener('abort', () => {
nestedAbortController.abort();
this.crudUpdateListener?.();
this.crudUpdateListener = undefined;
this.updateSyncStatus({
Expand All @@ -265,7 +277,10 @@ export abstract class AbstractStreamingSyncImplementation
if (signal?.aborted) {
break;
}
await this.streamingSyncIteration(signal);
const { retry } = await this.streamingSyncIteration(nestedAbortController.signal);
if (!retry) {
break;
}
// Continue immediately
} catch (ex) {
this.logger.error(ex);
Expand All @@ -274,8 +289,17 @@ export abstract class AbstractStreamingSyncImplementation
});
// On error, wait a little before retrying
await this.delayRetry();
} finally {
// Abort any open network requests. Create a new nested controller for retry.
nestedAbortController.abort();
nestedAbortController = new AbortController();
}
}

// Mark as disconnected if here
if (this.abortController) {
await this.disconnect();
}
}

protected async streamingSyncIteration(signal: AbortSignal, progress?: () => void): Promise<{ retry?: boolean }> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,6 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
data: {}
};

(localStorage as any).setItem('posting close' + Math.random(), `$}`);

this.messagePort.postMessage(closeMessagePayload);

// Release the proxy
Expand Down
24 changes: 21 additions & 3 deletions packages/powersync-sdk-web/src/worker/sync/BroadcastLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,17 @@ export class BroadcastLogger implements ILogger {

log(...x: any[]): void {
console.log(...x);
this.clients.forEach((p) => p.clientProvider.log(...x));
this.sanitizeArgs(x, (params) => this.clients.forEach((p) => p.clientProvider.log(...params)));
}

warn(...x: any[]): void {
console.warn(...x);
this.clients.forEach((p) => p.clientProvider.warn(...x));
this.sanitizeArgs(x, (params) => this.clients.forEach((p) => p.clientProvider.warn(...params)));
}

error(...x: any[]): void {
console.error(...x);
this.clients.forEach((p) => p.clientProvider.error(...x));
this.sanitizeArgs(x, (params) => this.clients.forEach((p) => p.clientProvider.error(...params)));
}

time(label: string): void {
Expand All @@ -76,4 +76,22 @@ export class BroadcastLogger implements ILogger {
// Levels are not adjustable on this level.
return true;
}

/**
* Guards against any logging errors.
* We don't want a logging exception to cause further issues upstream
*/
private sanitizeArgs(x: any[], handler: (...params: any[]) => void) {
const sanitizedParams = x.map((param) => {
try {
// Try and clone here first. If it fails it won't be passable over a MessagePort
return structuredClone(x);
} catch (ex) {
console.error(ex);
return 'Could not serialize log params. Check shared worker logs for more details.';
}
});

return handler(...sanitizedParams);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ export class SharedSyncImplementation
flags: { enableMultiTabs: true },
logger: this.broadCastLogger
}),
new Mutex()
new Mutex(),
this.broadCastLogger
),
remote: new WebRemote({
fetchCredentials: async () => {
Expand Down

0 comments on commit 37e266d

Please sign in to comment.