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

perf: targeted events #1385

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
48 changes: 46 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import {
ErrorFromResponse,
Event,
EventHandler,
EventTypes,
ExportChannelOptions,
ExportChannelRequest,
ExportChannelResponse,
Expand Down Expand Up @@ -218,6 +219,11 @@ function isString(x: unknown): x is string {
return typeof x === 'string' || x instanceof String;
}

export type TargetFactory<
SCG extends ExtendableGenerics = DefaultGenerics,
T extends Exclude<EventTypes, 'all'> = Exclude<EventTypes, 'all'>
> = (event: Event<SCG>) => `${T}${string}` | `${string}${T}` | `${string}${T}${string}` | null;

export class StreamChat<StreamChatGenerics extends ExtendableGenerics = DefaultGenerics> {
private static _instance?: unknown | StreamChat; // type is undefined|StreamChat, unknown is due to TS limitations with statics

Expand Down Expand Up @@ -269,6 +275,7 @@ export class StreamChat<StreamChatGenerics extends ExtendableGenerics = DefaultG
defaultWSTimeoutWithFallback: number;
defaultWSTimeout: number;
private nextRequestAbortController: AbortController | null = null;
private targetFactoriesByType = new Map<Exclude<EventTypes, 'all'>, Set<TargetFactory<StreamChatGenerics>>>();

/**
* Initialize a client
Expand Down Expand Up @@ -911,6 +918,29 @@ export class StreamChat<StreamChatGenerics extends ExtendableGenerics = DefaultG
return JWTUserToken(this.secret, userID, extra, {});
}

public registerTargetFactory = <T extends Exclude<EventTypes, 'all'>>(
eventType: T,
factory: TargetFactory<StreamChatGenerics, T>,
) => {
let set = this.targetFactoriesByType.get(eventType);

if (!set) {
set = new Set();
this.targetFactoriesByType.set(eventType, set);
}

set.add(factory);

return () => {
// @ts-expect-error
set.delete(factory);
// @ts-expect-error
if (!set.size) {
this.targetFactoriesByType.delete(eventType);
}
};
};

/**
* on - Listen to events on all channels and users your watching
*
Expand Down Expand Up @@ -938,6 +968,7 @@ export class StreamChat<StreamChatGenerics extends ExtendableGenerics = DefaultG
tags: ['event', 'client'],
});
this.listeners[key].push(callback);

return {
unsubscribe: () => {
this.logger('info', `Removing listener for ${key} event`, {
Expand Down Expand Up @@ -1366,8 +1397,21 @@ export class StreamChat<StreamChatGenerics extends ExtendableGenerics = DefaultG
if (client.listeners.all) {
listeners.push(...client.listeners.all);
}
if (client.listeners[event.type]) {
listeners.push(...client.listeners[event.type]);

const eventTypes: string[] = [event.type];

// factories
const factorySet = client.targetFactoriesByType.get(event.type as Exclude<EventTypes, 'all'>);
factorySet?.forEach((factory) => {
// a specific value could be missing from the event payload so factory can return "null" to be skipped
const targetedEventType = factory(event);
if (targetedEventType) eventTypes.push(targetedEventType);
});

for (const eventType of eventTypes) {
if (client.listeners[eventType]) {
listeners.push(...client.listeners[eventType]);
}
}

// call the event and send it to the listeners
Expand Down
19 changes: 16 additions & 3 deletions src/thread.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Channel } from './channel';
import type { StreamChat } from './client';
import type { StreamChat, TargetFactory } from './client';
import { StateStore } from './store';
import type {
AscDesc,
Expand Down Expand Up @@ -62,6 +62,16 @@ export type ThreadReadState<SCG extends ExtendableGenerics = DefaultGenerics> =
ThreadUserReadState<SCG> | undefined
>;

// TODO: figure out generics here
// @ts-expect-error
const messageNewFactory: TargetFactory<DefaultGenerics, 'message.new'> = (event) => {
return event.parent_id ? `message.new-${event.parent_id}` : null;
};
// @ts-expect-error
const threadMessageReadFactory: TargetFactory<DefaultGenerics, 'message.read'> = (event) => {
return event.thread ? `message.read-${event.thread.parent_message_id}` : null;
};

const DEFAULT_PAGE_LIMIT = 50;
const DEFAULT_SORT: { created_at: AscDesc }[] = [{ created_at: -1 }];
const MARK_AS_READ_THROTTLE_TIMEOUT = 1000;
Expand Down Expand Up @@ -186,6 +196,9 @@ export class Thread<SCG extends ExtendableGenerics = DefaultGenerics> {
return;
}

this.unsubscribeFunctions.add(this.client.registerTargetFactory('message.new', messageNewFactory));
this.unsubscribeFunctions.add(this.client.registerTargetFactory('message.read', threadMessageReadFactory));

this.unsubscribeFunctions.add(this.subscribeMarkActiveThreadRead());
this.unsubscribeFunctions.add(this.subscribeReloadActiveStaleThread());
this.unsubscribeFunctions.add(this.subscribeMarkThreadStale());
Expand Down Expand Up @@ -230,7 +243,7 @@ export class Thread<SCG extends ExtendableGenerics = DefaultGenerics> {
}).unsubscribe;

private subscribeNewReplies = () =>
this.client.on('message.new', (event) => {
this.client.on(`message.new-${this.id}`, (event) => {
if (!this.client.userID || event.message?.parent_id !== this.id) {
return;
}
Expand Down Expand Up @@ -284,7 +297,7 @@ export class Thread<SCG extends ExtendableGenerics = DefaultGenerics> {
}).unsubscribe;

private subscribeRepliesRead = () =>
this.client.on('message.read', (event) => {
this.client.on(`message.read-${this.id}`, (event) => {
if (!event.user || !event.created_at || !event.thread) return;
if (event.thread.parent_message_id !== this.id) return;

Expand Down
Loading