Skip to content

Commit 5937dda

Browse files
authored
Fix race condition when connecting to Fishjam (#214)
## Description ## Motivation and Context Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. ## Documentation impact - [ ] Documentation update required - [ ] Documentation updated [in another PR](_) - [ ] No documentation update required ## Types of changes - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
1 parent 3894dc4 commit 5937dda

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

packages/js-server-sdk/src/agent.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ export type AgentEvents = { [K in ExpectedAgentEvents]: (message: NonNullable<Re
4242
export class FishjamAgent extends (EventEmitter as new () => TypedEmitter<AgentEvents>) {
4343
private readonly client: WebSocket;
4444

45+
private resolveConnectionPromise: ((value: void | PromiseLike<void>) => void) | null = null;
46+
private readonly connectionPromise: Promise<void>;
47+
4548
constructor(config: FishjamConfig, agentToken: string, callbacks?: AgentCallbacks) {
4649
super();
4750

@@ -57,6 +60,17 @@ export class FishjamAgent extends (EventEmitter as new () => TypedEmitter<AgentE
5760

5861
this.client.onmessage = (message) => this.dispatchNotification(message);
5962
this.client.onopen = () => this.setupConnection(agentToken);
63+
64+
this.connectionPromise = new Promise<void>((resolve) => {
65+
this.resolveConnectionPromise = resolve;
66+
});
67+
}
68+
69+
/**
70+
* Await Agent connection to Fishjam.
71+
*/
72+
public async awaitConnected(): Promise<void> {
73+
return this.connectionPromise;
6074
}
6175

6276
/**
@@ -132,6 +146,11 @@ export class FishjamAgent extends (EventEmitter as new () => TypedEmitter<AgentE
132146
const auth = AgentRequest.encode({ authRequest: { token: agentToken } }).finish();
133147

134148
this.client.send(auth);
149+
150+
if (this.resolveConnectionPromise) {
151+
this.resolveConnectionPromise();
152+
this.resolveConnectionPromise = null;
153+
}
135154
}
136155

137156
private isExpectedEvent(notification: string): notification is ExpectedAgentEvents {

packages/js-server-sdk/src/client.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ export class FishjamClient {
129129
data: { data },
130130
} = response;
131131
const agent = new FishjamAgent(this.fishjamConfig, data.token, callbacks);
132+
await agent.awaitConnected();
132133

133134
return { agent: agent, peer: data.peer as Peer };
134135
} catch (error) {

0 commit comments

Comments
 (0)