-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathchat-stream.ts
More file actions
183 lines (170 loc) · 5.99 KB
/
chat-stream.ts
File metadata and controls
183 lines (170 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import type { Logger } from '@slack/logger';
import type { ChatAppendStreamArguments, ChatStartStreamArguments, ChatStopStreamArguments } from './types/request';
import type { ChatAppendStreamResponse, ChatStartStreamResponse, ChatStopStreamResponse } from './types/response';
import type WebClient from './WebClient';
export interface ChatStreamerOptions {
/**
* @description The length of markdown_text to buffer in-memory before calling a method. Increasing this value decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
* @default 256
*/
buffer_size?: number;
}
export class ChatStreamer {
private buffer = '';
private client: WebClient;
private logger: Logger;
private options: Required<ChatStreamerOptions>;
private state: 'starting' | 'in_progress' | 'completed';
private streamArgs: ChatStartStreamArguments;
private streamTs: string | undefined;
private token: string | undefined;
/**
* Instantiate a new chat streamer.
*
* @description The "constructor" method creates a unique {@link ChatStreamer} instance that keeps track of one chat stream.
* @example
* const client = new WebClient(process.env.SLACK_BOT_TOKEN);
* const logger = new ConsoleLogger();
* const args = {
* channel: "C0123456789",
* thread_ts: "1700000001.123456",
* recipient_team_id: "T0123456789",
* recipient_user_id: "U0123456789",
* };
* const streamer = new ChatStreamer(client, logger, args, { buffer_size: 512 });
* await streamer.append({
* markdown_text: "**hello world!**",
* });
* await streamer.stop();
* @see {@link https://docs.slack.dev/reference/methods/chat.startStream}
* @see {@link https://docs.slack.dev/reference/methods/chat.appendStream}
* @see {@link https://docs.slack.dev/reference/methods/chat.stopStream}
*/
constructor(client: WebClient, logger: Logger, args: ChatStartStreamArguments, options: ChatStreamerOptions) {
this.client = client;
this.logger = logger;
this.options = {
buffer_size: options.buffer_size ?? 256,
};
this.state = 'starting';
this.streamArgs = args;
}
/**
* Append to the stream.
*
* @description The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream is stopped this method cannot be called.
* @example
* const streamer = client.chatStream({
* channel: "C0123456789",
* thread_ts: "1700000001.123456",
* recipient_team_id: "T0123456789",
* recipient_user_id: "U0123456789",
* });
* await streamer.append({
* markdown_text: "**hello wo",
* });
* await streamer.append({
* markdown_text: "rld!**",
* });
* await streamer.stop();
* @see {@link https://docs.slack.dev/reference/methods/chat.appendStream}
*/
async append(
args: Omit<ChatAppendStreamArguments, 'channel' | 'ts'>,
): Promise<ChatStartStreamResponse | ChatAppendStreamResponse | null> {
if (this.state === 'completed') {
throw new Error(`failed to append stream: stream state is ${this.state}`);
}
if (args.token) {
this.token = args.token;
}
this.buffer += args.markdown_text;
if (this.buffer.length >= this.options.buffer_size) {
return await this.flushBuffer(args);
}
const details = {
bufferLength: this.buffer.length,
bufferSize: this.options.buffer_size,
channel: this.streamArgs.channel,
recipientTeamId: this.streamArgs.recipient_team_id,
recipientUserId: this.streamArgs.recipient_user_id,
threadTs: this.streamArgs.thread_ts,
};
this.logger.debug(`ChatStreamer appended to buffer: ${JSON.stringify(details)}`);
return null;
}
/**
* Stop the stream and finalize the message.
*
* @description The "stop" method stops the chat stream being used. This method can be called once to end the stream. Additional "blocks" and "metadata" can be provided.
*
* @example
* const streamer = client.chatStream({
* channel: "C0123456789",
* thread_ts: "1700000001.123456",
* recipient_team_id: "T0123456789",
* recipient_user_id: "U0123456789",
* });
* await streamer.append({
* markdown_text: "**hello world!**",
* });
* await streamer.stop();
* @see {@link https://docs.slack.dev/reference/methods/chat.stopStream}
*/
async stop(args?: Omit<ChatStopStreamArguments, 'channel' | 'ts'>): Promise<ChatStopStreamResponse> {
if (this.state === 'completed') {
throw new Error(`failed to stop stream: stream state is ${this.state}`);
}
if (args?.token) {
this.token = args.token;
}
if (args?.markdown_text) {
this.buffer += args.markdown_text;
}
if (!this.streamTs) {
const response = await this.client.chat.startStream({
...this.streamArgs,
token: this.token,
});
if (!response.ts) {
throw new Error('failed to stop stream: stream not started');
}
this.streamTs = response.ts;
this.state = 'in_progress';
}
const response = await this.client.chat.stopStream({
token: this.token,
channel: this.streamArgs.channel,
ts: this.streamTs,
...args,
markdown_text: this.buffer,
});
this.state = 'completed';
return response;
}
private async flushBuffer(
args: Omit<ChatStartStreamArguments | ChatAppendStreamArguments, 'channel' | 'ts'>,
): Promise<ChatStartStreamResponse | ChatAppendStreamResponse> {
if (!this.streamTs) {
const response = await this.client.chat.startStream({
...this.streamArgs,
token: this.token,
...args,
markdown_text: this.buffer,
});
this.buffer = '';
this.streamTs = response.ts;
this.state = 'in_progress';
return response;
}
const response = await this.client.chat.appendStream({
token: this.token,
channel: this.streamArgs.channel,
ts: this.streamTs,
...args,
markdown_text: this.buffer,
});
this.buffer = '';
return response;
}
}