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

fix: Unsubscribe from WebSocket stream when iterator ended #1219

Merged
merged 1 commit into from
Oct 15, 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
8 changes: 5 additions & 3 deletions src/adapters/action/dispatcher-ws.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MastoUnexpectedError } from "../errors";
import { MastoUnexpectedError, MastoWebSocketError } from "../errors";
import { createLogger } from "../logger";
import { SerializerNativeImpl } from "../serializers";
import {
Expand Down Expand Up @@ -29,7 +29,7 @@ describe("DispatcherWs", () => {
}).toThrow(MastoUnexpectedError);
});

it("can be disposed", () => {
it("can be disposed", async () => {
const connector = new WebSocketConnectorImpl({
constructorParameters: ["wss://example.com"],
});
Expand All @@ -41,6 +41,8 @@ describe("DispatcherWs", () => {
);

dispatcher[Symbol.dispose]();
expect(connector.canAcquire()).toBe(false);
await expect(() => connector.acquire()).rejects.toThrow(
MastoWebSocketError,
);
});
});
14 changes: 10 additions & 4 deletions src/adapters/ws/web-socket-connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ export class WebSocketConnectorImpl implements WebSocketConnector {
});
}

canAcquire(): boolean {
return !this.closed;
}

async acquire(): Promise<WebSocket> {
if (this.closed) {
throw new MastoWebSocketError("WebSocket closed");
}

this.init();

if (this.ws != undefined) {
Expand All @@ -49,6 +49,12 @@ export class WebSocketConnectorImpl implements WebSocketConnector {
return await promiseWithResolvers.promise;
}

async *[Symbol.asyncIterator](): AsyncIterableIterator<WebSocket> {
while (!this.closed) {
yield await this.acquire();
}
}

close(): void {
this.closed = true;
this.ws?.close();
Expand Down
40 changes: 22 additions & 18 deletions src/adapters/ws/web-socket-subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,35 @@
async *values(): AsyncIterableIterator<mastodon.streaming.Event> {
this.logger?.log("info", "Subscribing to stream", this.stream);

while (this.connector.canAcquire()) {
this.connection = await this.connector.acquire();
try {
for await (const connection of this.connector) {
this.connection = connection;

const data = this.serializer.serialize("json", {
type: "subscribe",
stream: this.stream,
...this.params,
});
const data = this.serializer.serialize("json", {
type: "subscribe",
stream: this.stream,
...this.params,
});

this.logger?.log("debug", "↑ WEBSOCKET", data);
this.connection.send(data);
this.counter.increment(this.stream, this.params);
this.logger?.log("debug", "↑ WEBSOCKET", data);
this.connection.send(data);
this.counter.increment(this.stream, this.params);

const messages = toAsyncIterable(this.connection);
const messages = toAsyncIterable(this.connection);

for await (const message of messages) {
const event = await this.parseMessage(message.data as string);
for await (const message of messages) {
const event = await this.parseMessage(message.data as string);

if (!this.test(event)) {
continue;
}
if (!this.test(event)) {
continue;

Check warning on line 48 in src/adapters/ws/web-socket-subscription.ts

View check run for this annotation

Codecov / codecov/patch

src/adapters/ws/web-socket-subscription.ts#L48

Added line #L48 was not covered by tests
}

this.logger?.log("debug", "↓ WEBSOCKET", event);
yield event;
this.logger?.log("debug", "↓ WEBSOCKET", event);
yield event;
}
}
} finally {
this.unsubscribe();
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/interfaces/ws.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { type WebSocket } from "isomorphic-ws";

export interface WebSocketConnector {
export interface WebSocketConnector extends AsyncIterable<WebSocket> {
acquire(): Promise<WebSocket>;
close(): void;
canAcquire(): boolean;
}

export interface WebSocketSubscriptionCounter {
Expand Down
Loading