ai/src/stream.ts

306 lines
6.7 KiB
TypeScript
Raw Normal View History

2018-10-09 15:47:03 +00:00
import autobind from 'autobind-decorator';
import { EventEmitter } from 'events';
import * as WebSocket from 'ws';
const ReconnectingWebsocket = require('reconnecting-websocket');
import config from './config';
/**
* Misskey stream connection
*/
export default class Stream extends EventEmitter {
private stream: any;
private state: string;
2018-10-10 18:00:54 +00:00
private buffer: any[];
private sharedConnectionPools: Pool[] = [];
2018-10-09 15:47:03 +00:00
private sharedConnections: SharedConnection[] = [];
private nonSharedConnections: NonSharedConnection[] = [];
constructor() {
super();
this.state = 'initializing';
2018-10-10 18:00:54 +00:00
this.buffer = [];
2018-10-09 15:47:03 +00:00
this.stream = new ReconnectingWebsocket(`${config.wsUrl}/streaming?i=${config.i}`, [], {
WebSocket: WebSocket
});
this.stream.addEventListener('open', this.onOpen);
this.stream.addEventListener('close', this.onClose);
this.stream.addEventListener('message', this.onMessage);
}
2018-10-10 18:00:54 +00:00
@autobind
public useSharedConnection(channel: string): SharedConnection {
let pool = this.sharedConnectionPools.find(p => p.channel === channel);
2018-10-09 15:47:03 +00:00
2018-10-10 18:00:54 +00:00
if (pool == null) {
pool = new Pool(this, channel);
this.sharedConnectionPools.push(pool);
2018-10-09 15:47:03 +00:00
}
2018-10-10 18:00:54 +00:00
const connection = new SharedConnection(this, channel, pool);
this.sharedConnections.push(connection);
return connection;
2018-10-09 15:47:03 +00:00
}
@autobind
public removeSharedConnection(connection: SharedConnection) {
2018-10-10 18:00:54 +00:00
this.sharedConnections = this.sharedConnections.filter(c => c !== connection);
2018-10-09 15:47:03 +00:00
}
2018-10-10 18:00:54 +00:00
@autobind
public connectToChannel(channel: string, params?: any): NonSharedConnection {
2018-10-09 15:47:03 +00:00
const connection = new NonSharedConnection(this, channel, params);
this.nonSharedConnections.push(connection);
return connection;
}
@autobind
public disconnectToChannel(connection: NonSharedConnection) {
2018-10-10 18:00:54 +00:00
this.nonSharedConnections = this.nonSharedConnections.filter(c => c !== connection);
2018-10-09 15:47:03 +00:00
}
/**
* Callback of when open connection
*/
@autobind
private onOpen() {
const isReconnect = this.state == 'reconnecting';
this.state = 'connected';
this.emit('_connected_');
2018-10-10 18:00:54 +00:00
// バッファーを処理
2020-09-02 12:54:01 +00:00
const _buffer = [...this.buffer]; // Shallow copy
2018-10-10 18:00:54 +00:00
this.buffer = []; // Clear buffer
2020-09-02 12:54:01 +00:00
for (const data of _buffer) {
2018-10-10 18:00:54 +00:00
this.send(data); // Resend each buffered messages
2020-09-02 12:54:01 +00:00
}
2018-10-09 15:47:03 +00:00
// チャンネル再接続
if (isReconnect) {
2018-10-10 18:00:54 +00:00
this.sharedConnectionPools.forEach(p => {
p.connect();
2018-10-09 15:47:03 +00:00
});
this.nonSharedConnections.forEach(c => {
c.connect();
});
}
}
/**
* Callback of when close connection
*/
@autobind
private onClose() {
this.state = 'reconnecting';
this.emit('_disconnected_');
}
/**
* Callback of when received a message from connection
*/
@autobind
private onMessage(message) {
const { type, body } = JSON.parse(message.data);
if (type == 'channel') {
const id = body.id;
2018-10-10 18:00:54 +00:00
2020-09-02 12:54:01 +00:00
let connections: (Connection | undefined)[];
2018-10-10 18:00:54 +00:00
connections = this.sharedConnections.filter(c => c.id === id);
if (connections.length === 0) {
connections = [this.nonSharedConnections.find(c => c.id === id)];
}
2020-09-02 12:54:01 +00:00
for (const c of connections.filter(c => c != null)) {
c!.emit(body.type, body.body);
c!.emit('*', { type: body.type, body: body.body });
}
2018-10-09 15:47:03 +00:00
} else {
this.emit(type, body);
this.emit('*', { type, body });
}
}
/**
* Send a message to connection
*/
@autobind
public send(typeOrPayload, payload?) {
const data = payload === undefined ? typeOrPayload : {
type: typeOrPayload,
body: payload
};
2018-10-10 18:00:54 +00:00
// まだ接続が確立されていなかったらバッファリングして次に接続した時に送信する
if (this.state != 'connected') {
this.buffer.push(data);
return;
}
2018-10-09 15:47:03 +00:00
this.stream.send(JSON.stringify(data));
}
/**
* Close this connection
*/
@autobind
public close() {
this.stream.removeEventListener('open', this.onOpen);
this.stream.removeEventListener('message', this.onMessage);
}
}
2018-10-10 18:00:54 +00:00
class Pool {
2018-10-09 15:47:03 +00:00
public channel: string;
public id: string;
protected stream: Stream;
2018-10-10 18:00:54 +00:00
private users = 0;
private disposeTimerId: any;
private isConnected = false;
2018-10-09 15:47:03 +00:00
2018-10-10 18:00:54 +00:00
constructor(stream: Stream, channel: string) {
2018-10-09 15:47:03 +00:00
this.channel = channel;
2018-10-10 18:00:54 +00:00
this.stream = stream;
2018-10-09 15:47:03 +00:00
this.id = Math.random().toString();
2018-10-10 18:00:54 +00:00
}
@autobind
public inc() {
if (this.users === 0 && !this.isConnected) {
this.connect();
}
this.users++;
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
}
@autobind
public dec() {
this.users--;
// そのコネクションの利用者が誰もいなくなったら
if (this.users === 0) {
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
this.disconnect();
}, 3000);
}
2018-10-09 15:47:03 +00:00
}
@autobind
public connect() {
2018-10-10 18:00:54 +00:00
this.isConnected = true;
2018-10-09 15:47:03 +00:00
this.stream.send('connect', {
channel: this.channel,
2018-10-10 18:00:54 +00:00
id: this.id
2018-10-09 15:47:03 +00:00
});
}
@autobind
2018-10-10 18:00:54 +00:00
private disconnect() {
this.isConnected = false;
this.disposeTimerId = null;
this.stream.send('disconnect', { id: this.id });
}
}
abstract class Connection extends EventEmitter {
public channel: string;
protected stream: Stream;
public abstract id: string;
constructor(stream: Stream, channel: string) {
super();
this.stream = stream;
this.channel = channel;
}
@autobind
public send(id: string, typeOrPayload, payload?) {
2018-10-09 15:47:03 +00:00
const type = payload === undefined ? typeOrPayload.type : typeOrPayload;
const body = payload === undefined ? typeOrPayload.body : payload;
2018-10-10 18:00:54 +00:00
this.stream.send('ch', {
id: id,
2018-10-09 15:47:03 +00:00
type: type,
body: body
});
}
public abstract dispose(): void;
}
2018-10-10 18:00:54 +00:00
class SharedConnection extends Connection {
private pool: Pool;
2018-10-09 15:47:03 +00:00
2018-10-10 18:00:54 +00:00
public get id(): string {
return this.pool.id;
}
constructor(stream: Stream, channel: string, pool: Pool) {
2018-10-09 15:47:03 +00:00
super(stream, channel);
2018-10-10 18:00:54 +00:00
this.pool = pool;
this.pool.inc();
2018-10-09 15:47:03 +00:00
}
@autobind
2018-10-10 18:00:54 +00:00
public send(typeOrPayload, payload?) {
super.send(this.pool.id, typeOrPayload, payload);
2018-10-09 15:47:03 +00:00
}
@autobind
public dispose() {
2018-10-10 18:00:54 +00:00
this.pool.dec();
this.removeAllListeners();
this.stream.removeSharedConnection(this);
2018-10-09 15:47:03 +00:00
}
}
2018-10-10 18:00:54 +00:00
class NonSharedConnection extends Connection {
public id: string;
protected params: any;
2018-10-09 15:47:03 +00:00
constructor(stream: Stream, channel: string, params?: any) {
2018-10-10 18:00:54 +00:00
super(stream, channel);
this.params = params;
this.id = Math.random().toString();
this.connect();
}
@autobind
public connect() {
this.stream.send('connect', {
channel: this.channel,
id: this.id,
params: this.params
});
}
@autobind
public send(typeOrPayload, payload?) {
super.send(this.id, typeOrPayload, payload);
2018-10-09 15:47:03 +00:00
}
@autobind
public dispose() {
this.removeAllListeners();
this.stream.send('disconnect', { id: this.id });
this.stream.disconnectToChannel(this);
}
}