This repository has been archived on 2022-10-04. You can view files and clone it, but cannot push or open issues or pull requests.
foundkey.js/src/streaming.ts

341 lines
8.4 KiB
TypeScript
Raw Normal View History

2021-05-14 02:46:39 +00:00
import autobind from 'autobind-decorator';
import { EventEmitter } from 'eventemitter3';
import ReconnectingWebsocket from 'reconnecting-websocket';
2021-07-10 14:20:56 +00:00
import { BroadcastEvents, Channels } from './streaming.types';
2021-05-14 02:46:39 +00:00
2022-01-01 17:11:35 +00:00
export function urlQuery(obj: Record<string, string | number | boolean | undefined>): string {
2021-11-20 02:47:19 +00:00
const params = Object.entries(obj)
2021-05-14 02:46:39 +00:00
.filter(([, v]) => Array.isArray(v) ? v.length : v !== undefined)
2022-01-01 17:11:35 +00:00
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.reduce((a, [k, v]) => (a[k] = v!, a), {} as Record<string, string | number | boolean>);
2021-11-20 02:47:19 +00:00
return Object.entries(params)
.map((e) => `${e[0]}=${encodeURIComponent(e[1])}`)
.join('&');
2021-05-14 02:46:39 +00:00
}
2021-07-02 13:48:07 +00:00
type AnyOf<T extends Record<any, any>> = T[keyof T];
type StreamEvents = {
_connected_: void;
_disconnected_: void;
2021-07-10 14:20:56 +00:00
} & BroadcastEvents;
2021-05-14 02:46:39 +00:00
/**
* Misskey stream connection
*/
export default class Stream extends EventEmitter<StreamEvents> {
2021-05-14 02:46:39 +00:00
private stream: ReconnectingWebsocket;
public state: 'initializing' | 'reconnecting' | 'connected' = 'initializing';
private sharedConnectionPools: Pool[] = [];
private sharedConnections: SharedConnection[] = [];
private nonSharedConnections: NonSharedConnection[] = [];
2021-06-28 08:49:25 +00:00
private idCounter = 0;
2021-05-14 02:46:39 +00:00
2021-05-14 14:49:09 +00:00
constructor(origin: string, user: { token: string; } | null, options?: {
2021-05-23 07:53:11 +00:00
WebSocket?: any;
2021-05-14 02:46:39 +00:00
}) {
super();
2021-05-23 07:53:11 +00:00
options = options || { };
2021-05-14 02:46:39 +00:00
const query = urlQuery({
i: user?.token,
2021-05-17 18:27:03 +00:00
// To prevent cache of an HTML such as error screen
2021-05-14 02:46:39 +00:00
_t: Date.now(),
});
2021-07-02 13:48:07 +00:00
const wsOrigin = origin.replace('http://', 'ws://').replace('https://', 'wss://');
this.stream = new ReconnectingWebsocket(`${wsOrigin}/streaming?${query}`, '', {
2021-05-23 07:53:11 +00:00
minReconnectionDelay: 1, // https://github.com/pladaria/reconnecting-websocket/issues/91
2021-12-27 15:45:47 +00:00
WebSocket: options.WebSocket,
2021-05-14 14:49:09 +00:00
});
2021-05-14 02:46:39 +00:00
this.stream.addEventListener('open', this.onOpen);
this.stream.addEventListener('close', this.onClose);
this.stream.addEventListener('message', this.onMessage);
}
2021-06-28 08:49:25 +00:00
@autobind
private genId(): string {
return (++this.idCounter).toString();
}
2021-05-23 04:34:36 +00:00
@autobind
2021-06-27 12:17:38 +00:00
public useChannel<C extends keyof Channels>(channel: C, params?: Channels[C]['params'], name?: string): Connection<Channels[C]> {
2021-05-23 04:34:36 +00:00
if (params) {
return this.connectToChannel(channel, params);
} else {
2021-05-31 02:28:20 +00:00
return this.useSharedConnection(channel, name);
2021-05-23 04:34:36 +00:00
}
}
2021-05-14 02:46:39 +00:00
@autobind
2021-06-27 12:17:38 +00:00
private useSharedConnection<C extends keyof Channels>(channel: C, name?: string): SharedConnection<Channels[C]> {
2021-05-14 02:46:39 +00:00
let pool = this.sharedConnectionPools.find(p => p.channel === channel);
if (pool == null) {
2021-06-28 08:49:25 +00:00
pool = new Pool(this, channel, this.genId());
2021-05-14 02:46:39 +00:00
this.sharedConnectionPools.push(pool);
}
2021-07-02 10:13:18 +00:00
const connection = new SharedConnection(this, channel, pool, name);
2021-05-14 02:46:39 +00:00
this.sharedConnections.push(connection);
return connection;
}
@autobind
2021-12-27 15:45:47 +00:00
public removeSharedConnection(connection: SharedConnection): void {
2021-05-14 02:46:39 +00:00
this.sharedConnections = this.sharedConnections.filter(c => c !== connection);
}
@autobind
2021-12-27 15:45:47 +00:00
public removeSharedConnectionPool(pool: Pool): void {
2021-05-14 02:46:39 +00:00
this.sharedConnectionPools = this.sharedConnectionPools.filter(p => p !== pool);
}
@autobind
2021-06-27 12:17:38 +00:00
private connectToChannel<C extends keyof Channels>(channel: C, params: Channels[C]['params']): NonSharedConnection<Channels[C]> {
2021-07-02 10:13:18 +00:00
const connection = new NonSharedConnection(this, channel, this.genId(), params);
2021-05-14 02:46:39 +00:00
this.nonSharedConnections.push(connection);
return connection;
}
@autobind
2021-12-27 15:45:47 +00:00
public disconnectToChannel(connection: NonSharedConnection): void {
2021-05-14 02:46:39 +00:00
this.nonSharedConnections = this.nonSharedConnections.filter(c => c !== connection);
}
/**
* Callback of when open connection
*/
@autobind
2021-12-27 15:45:47 +00:00
private onOpen(): void {
2021-05-14 02:46:39 +00:00
const isReconnect = this.state === 'reconnecting';
this.state = 'connected';
this.emit('_connected_');
// チャンネル再接続
if (isReconnect) {
2021-12-27 15:45:47 +00:00
for (const p of this.sharedConnectionPools) p.connect();
for (const c of this.nonSharedConnections) c.connect();
2021-05-14 02:46:39 +00:00
}
}
/**
* Callback of when close connection
*/
@autobind
2021-12-27 15:45:47 +00:00
private onClose(): void {
2021-05-14 02:46:39 +00:00
if (this.state === 'connected') {
this.state = 'reconnecting';
this.emit('_disconnected_');
}
}
/**
* Callback of when received a message from connection
*/
@autobind
2021-12-27 15:45:47 +00:00
private onMessage(message: { data: string; }): void {
2021-05-14 02:46:39 +00:00
const { type, body } = JSON.parse(message.data);
if (type === 'channel') {
const id = body.id;
let connections: Connection[];
connections = this.sharedConnections.filter(c => c.id === id);
if (connections.length === 0) {
const found = this.nonSharedConnections.find(c => c.id === id);
if (found) {
connections = [found];
}
}
2021-12-27 15:45:47 +00:00
for (const c of connections) {
2022-01-30 02:27:43 +00:00
c.emit(body.type, body.body);
2021-05-14 02:46:39 +00:00
c.inCount++;
}
} else {
2022-01-30 02:27:43 +00:00
this.emit(type, body);
2021-05-14 02:46:39 +00:00
}
}
/**
* Send a message to connection
*/
@autobind
2021-12-27 15:45:47 +00:00
public send(typeOrPayload: any, payload?: any): void {
2021-05-14 02:46:39 +00:00
const data = payload === undefined ? typeOrPayload : {
type: typeOrPayload,
2021-12-27 15:45:47 +00:00
body: payload,
2021-05-14 02:46:39 +00:00
};
this.stream.send(JSON.stringify(data));
}
/**
* Close this connection
*/
@autobind
2021-12-27 15:45:47 +00:00
public close(): void {
2021-06-12 14:01:48 +00:00
this.stream.close();
2021-05-14 02:46:39 +00:00
}
}
2021-06-27 12:17:38 +00:00
// TODO: これらのクラスを Stream クラスの内部クラスにすれば余計なメンバをpublicにしないで済むかも
2021-06-28 08:49:25 +00:00
// もしくは @internal を使う? https://www.typescriptlang.org/tsconfig#stripInternal
2021-05-14 02:46:39 +00:00
class Pool {
public channel: string;
public id: string;
protected stream: Stream;
public users = 0;
private disposeTimerId: any;
private isConnected = false;
2021-06-28 08:49:25 +00:00
constructor(stream: Stream, channel: string, id: string) {
2021-05-14 02:46:39 +00:00
this.channel = channel;
this.stream = stream;
2021-06-28 08:49:25 +00:00
this.id = id;
2021-05-14 02:46:39 +00:00
this.stream.on('_disconnected_', this.onStreamDisconnected);
}
@autobind
2021-12-27 15:45:47 +00:00
private onStreamDisconnected(): void {
2021-05-14 02:46:39 +00:00
this.isConnected = false;
}
@autobind
2021-12-27 15:45:47 +00:00
public inc(): void {
2021-05-14 02:46:39 +00:00
if (this.users === 0 && !this.isConnected) {
this.connect();
}
this.users++;
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
}
@autobind
2021-12-27 15:45:47 +00:00
public dec(): void {
2021-05-14 02:46:39 +00:00
this.users--;
// そのコネクションの利用者が誰もいなくなったら
if (this.users === 0) {
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
this.disconnect();
}, 3000);
}
}
@autobind
2021-12-27 15:45:47 +00:00
public connect(): void {
2021-05-14 02:46:39 +00:00
if (this.isConnected) return;
this.isConnected = true;
this.stream.send('connect', {
channel: this.channel,
2021-12-27 15:45:47 +00:00
id: this.id,
2021-05-14 02:46:39 +00:00
});
}
@autobind
2021-12-27 15:45:47 +00:00
private disconnect(): void {
2021-05-14 02:46:39 +00:00
this.stream.off('_disconnected_', this.onStreamDisconnected);
this.stream.send('disconnect', { id: this.id });
this.stream.removeSharedConnectionPool(this);
}
}
2022-01-13 16:33:42 +00:00
export abstract class Connection<Channel extends AnyOf<Channels> = any> extends EventEmitter<Channel['events']> {
2021-05-14 02:46:39 +00:00
public channel: string;
protected stream: Stream;
public abstract id: string;
public name?: string; // for debug
2021-12-27 15:45:47 +00:00
public inCount = 0; // for debug
public outCount = 0; // for debug
2021-05-14 02:46:39 +00:00
constructor(stream: Stream, channel: string, name?: string) {
super();
this.stream = stream;
this.channel = channel;
this.name = name;
}
@autobind
2021-12-27 15:45:47 +00:00
public send<T extends keyof Channel['receives']>(type: T, body: Channel['receives'][T]): void {
2021-05-14 02:46:39 +00:00
this.stream.send('ch', {
2021-06-28 09:34:10 +00:00
id: this.id,
2021-05-14 02:46:39 +00:00
type: type,
2021-12-27 15:45:47 +00:00
body: body,
2021-05-14 02:46:39 +00:00
});
this.outCount++;
}
public abstract dispose(): void;
}
2021-07-02 13:48:07 +00:00
class SharedConnection<Channel extends AnyOf<Channels> = any> extends Connection<Channel> {
2021-05-14 02:46:39 +00:00
private pool: Pool;
public get id(): string {
return this.pool.id;
}
constructor(stream: Stream, channel: string, pool: Pool, name?: string) {
super(stream, channel, name);
this.pool = pool;
this.pool.inc();
}
@autobind
2021-12-27 15:45:47 +00:00
public dispose(): void {
2021-05-14 02:46:39 +00:00
this.pool.dec();
this.removeAllListeners();
this.stream.removeSharedConnection(this);
}
}
2021-07-02 13:48:07 +00:00
class NonSharedConnection<Channel extends AnyOf<Channels> = any> extends Connection<Channel> {
2021-05-14 02:46:39 +00:00
public id: string;
2021-06-27 12:17:38 +00:00
protected params: Channel['params'];
2021-05-14 02:46:39 +00:00
2021-06-28 08:49:25 +00:00
constructor(stream: Stream, channel: string, id: string, params: Channel['params']) {
2021-05-14 02:46:39 +00:00
super(stream, channel);
this.params = params;
2021-06-28 08:49:25 +00:00
this.id = id;
2021-05-14 02:46:39 +00:00
this.connect();
}
@autobind
2021-12-27 15:45:47 +00:00
public connect(): void {
2021-05-14 02:46:39 +00:00
this.stream.send('connect', {
channel: this.channel,
id: this.id,
2021-12-27 15:45:47 +00:00
params: this.params,
2021-05-14 02:46:39 +00:00
});
}
@autobind
2021-12-27 15:45:47 +00:00
public dispose(): void {
2021-05-14 02:46:39 +00:00
this.removeAllListeners();
this.stream.send('disconnect', { id: this.id });
this.stream.disconnectToChannel(this);
}
}