Skip to content
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

Refactor streams to ensure they only have a single subscription #6713

Merged
merged 7 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
}

function loadActivity() {
client.messageActivityFeed().subscribe((resp, final) => {
client.subscribeToMessageActivityFeed((resp, final) => {
activityEvents.set(resp.events);
if ($activityEvents.length > 0 && final) {
client.markActivityFeedRead($activityEvents[0].timestamp);
Expand Down
71 changes: 39 additions & 32 deletions frontend/openchat-client/src/openchat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,6 @@ import type {
PaymentGateApproval,
PaymentGateApprovals,
MessageActivityFeedResponse,
Stream,
} from "openchat-shared";
import {
AuthProvider,
Expand Down Expand Up @@ -1357,19 +1356,23 @@ export class OpenChat extends OpenChatAgentWorker {
});
}

messageActivityFeed(): Stream<MessageActivityFeedResponse> {
return this.sendStreamRequest({
subscribeToMessageActivityFeed(
subscribeFn: (value: MessageActivityFeedResponse, final: boolean) => void,
) {
this.sendStreamRequest({
kind: "messageActivityFeed",
since: this._liveState.globalState.messageActivitySummary.readUpToTimestamp,
}).subscribe((response) => {
const userIds = new Set<string>();
for (const event of response.events) {
if (event.userId !== undefined) {
userIds.add(event.userId);
}).subscribe({
onResult: (response, final) => {
const userIds = new Set<string>();
for (const event of response.events) {
if (event.userId !== undefined) {
userIds.add(event.userId);
}
}
}
this.getMissingUsers(userIds);
return response;
this.getMissingUsers(userIds);
subscribeFn(response, final);
},
});
}

Expand Down Expand Up @@ -3553,8 +3556,8 @@ export class OpenChat extends OpenChatAgentWorker {
},
undefined,
isCryptoMessage ? 2 * DEFAULT_WORKER_TIMEOUT : undefined,
)
.subscribe((response) => {
).subscribe({
onResult: (response) => {
if (response === "accepted") {
unconfirmed.markAccepted(messageContext, eventWrapper.event.messageId);
return;
Expand Down Expand Up @@ -3613,8 +3616,8 @@ export class OpenChat extends OpenChatAgentWorker {
}

resolve(resp);
})
.catch(() => {
},
onError: () => {
this.onSendMessageFailure(
chatId,
eventWrapper.event.messageId,
Expand All @@ -3625,7 +3628,8 @@ export class OpenChat extends OpenChatAgentWorker {
);

return resolve(CommonResponses.failure());
});
},
});
});
}

Expand Down Expand Up @@ -4587,8 +4591,8 @@ export class OpenChat extends OpenChatAgentWorker {
getCurrentUser(): Promise<CurrentUserResponse> {
return new Promise((resolve, reject) => {
let resolved = false;
this.sendStreamRequest({ kind: "getCurrentUser" })
.subscribe((user) => {
this.sendStreamRequest({ kind: "getCurrentUser" }).subscribe({
onResult: (user) => {
if (user.kind === "created_user") {
userCreatedStore.set(true);
currentUser.set(user);
Expand All @@ -4600,8 +4604,9 @@ export class OpenChat extends OpenChatAgentWorker {
resolve(user);
resolved = true;
}
})
.catch(reject);
},
onError: reject,
});
});
}

Expand Down Expand Up @@ -5746,22 +5751,23 @@ export class OpenChat extends OpenChatAgentWorker {
this.sendStreamRequest({
kind: "getUpdates",
initialLoad,
})
.subscribe(async (resp) => {
}).subscribe({
onResult: async (resp) => {
await this.handleChatsResponse(
updateRegistryTask,
!this._liveState.chatsInitialised,
resp as UpdatesResult,
);
chatsLoading.set(!this._liveState.chatsInitialised);
})
.catch((err) => {
},
onError: (err) => {
console.warn("getUpdates threw an error: ", err);
resolve();
})
.finally(() => {
},
onEnd: () => {
resolve();
});
},
});
});
}

Expand Down Expand Up @@ -6275,8 +6281,8 @@ export class OpenChat extends OpenChatAgentWorker {
return new Promise((resolve) => {
this.sendStreamRequest({
kind: "updateRegistry",
})
.subscribe(([registry, updated]) => {
}).subscribe({
onResult: ([registry, updated]) => {
if (updated || Object.keys(get(cryptoLookup)).length === 0) {
this.currentAirdropChannel = registry.currentAirdropChannel;
const cryptoRecord = toRecord(registry.tokenDetails, (t) => t.ledger);
Expand Down Expand Up @@ -6311,11 +6317,12 @@ export class OpenChat extends OpenChatAgentWorker {
resolved = true;
resolve();
}
})
.catch((err) => {
},
onError: (err) => {
console.warn(`Failed to update the registry: ${err}`);
resolve();
});
},
});
});
}

Expand Down
28 changes: 15 additions & 13 deletions frontend/openchat-shared/src/domain/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,20 @@ type OnStreamResult<T> = (result: T, final: boolean) => void;
type OnStreamError = (reason?: unknown) => void;
type OnStreamEnd = () => void;

type Subscription<T> = {
onResult?: OnStreamResult<T>;
onError?: OnStreamError;
onEnd?: OnStreamEnd;
};

/**
* This class offers a Promise-like interface but replaces `then` with `subscribe`.
* The function passed into subscribe will then be called each time new data is available.
* The onResult fn will also be given a `final` param in case the calling code needs to know
* if the final chunk of data has been received.
*/
export class Stream<T> {
private subscribed = false;
private onResult?: OnStreamResult<T>;
private onError?: OnStreamError;
private onEnd?: OnStreamEnd;
Expand Down Expand Up @@ -36,18 +43,13 @@ export class Stream<T> {
);
}

subscribe(onResult: OnStreamResult<T>): Stream<T> {
this.onResult = onResult;
return this;
}

catch(onError: OnStreamError): Stream<T> {
this.onError = onError;
return this;
}

finally(onEnd: OnStreamEnd): Stream<T> {
this.onEnd = onEnd;
return this;
subscribe(subscription: Subscription<T>) {
if (this.subscribed) {
throw new Error("Already subscribed");
}
this.subscribed = true;
this.onResult = subscription.onResult;
this.onError = subscription.onError;
this.onEnd = subscription.onEnd;
}
}
9 changes: 5 additions & 4 deletions frontend/openchat-worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ function streamReplies(
chain: Stream<WorkerResponseInner>,
) {
const start = Date.now();
chain
.subscribe((value, final) => {
chain.subscribe({
onResult: (value, final) => {
console.debug(
`WORKER: sending streamed reply ${Date.now() - start}ms after subscribing`,
correlationId,
Expand All @@ -169,8 +169,9 @@ function streamReplies(
final,
);
sendResponse(correlationId, value, final);
})
.catch(sendError(correlationId, payload));
},
onError: sendError(correlationId, payload),
});
}

function executeThenReply(
Expand Down
Loading