-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathchatRoom.ts
254 lines (219 loc) · 7.15 KB
/
chatRoom.ts
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import type * as Party from "partykit/server";
import { nanoid } from "nanoid";
import { User, getNextAuthSession, isSessionValid } from "./utils/auth";
import { SINGLETON_ROOM_ID } from "./chatRooms";
import type {
Message,
SyncMessage,
UserMessage,
ClearRoomMessage,
} from "./utils/message";
import {
editMessage,
newMessage,
syncMessage,
systemMessage,
} from "./utils/message";
import { error, json, notFound, ok } from "./utils/response";
import { AI_USER } from "./ai";
const DELETE_MESSAGES_AFTER_INACTIVITY_PERIOD = 1000 * 60 * 60 * 24; // 24 hours
// track additional information on room and connection objects
type ChatConnectionState = { user?: User | null };
type ChatConnection = Party.Connection<ChatConnectionState>;
/**
* This party manages the state and behaviour of an individual chat room
*/
export default class ChatRoomServer implements Party.Server {
messages?: Message[];
botId?: string;
constructor(public party: Party.Party) {}
/** Retrieve messages from room storage and store them on room instance */
async ensureLoadMessages() {
if (!this.messages) {
this.messages =
(await this.party.storage.get<Message[]>("messages")) ?? [];
}
return this.messages;
}
/** Clear room storage */
async removeRoomMessages() {
await this.party.storage.delete("messages");
this.messages = [];
}
/** Remove this room from the room listing party */
async removeRoomFromRoomList(id: string) {
return this.party.context.parties.chatrooms.get(SINGLETON_ROOM_ID).fetch({
method: "POST",
body: JSON.stringify({
id,
action: "delete",
}),
});
}
/** Request the AI bot party to connect to this room, if not already connected */
async ensureAIParticipant() {
if (!this.botId) {
this.botId = nanoid();
this.party.context.parties.ai.get(this.party.id).fetch({
method: "POST",
body: JSON.stringify({
action: "connect",
roomId: this.party.id,
botId: this.botId,
}),
});
}
}
/** Send room presence to the room listing party */
async updateRoomList(action: "enter" | "leave", connection: ChatConnection) {
return this.party.context.parties.chatrooms.get(SINGLETON_ROOM_ID).fetch({
method: "POST",
body: JSON.stringify({
id: this.party.id,
connections: [...this.party.getConnections()].length,
user: connection.state?.user,
action,
}),
});
}
async authenticateUser(proxiedRequest: Party.Request) {
// find the connection
const id = new URL(proxiedRequest.url).searchParams.get("_pk");
const connection = id && this.party.getConnection(id);
if (!connection) {
return error(`No connection with id ${id}`);
}
// authenticate the user
const session = await getNextAuthSession(proxiedRequest);
if (!session) {
return error(`No session found`);
}
this.updateRoomList("enter", connection);
connection.setState({ user: session });
connection.send(
newMessage({
from: { id: "system" },
text: `Welcome ${session.username}!`,
})
);
if (!this.party.env.OPENAI_API_KEY) {
connection.send(
systemMessage("OpenAI API key not configured. AI bot is not available")
);
}
}
/**
* Responds to HTTP requests to /parties/chatroom/:roomId endpoint
*/
async onRequest(request: Party.Request) {
const messages = await this.ensureLoadMessages();
// mark room as created by storing its id in object storage
if (request.method === "POST") {
// respond to authentication requests proxied through the app's
// rewrite rules. See next.config.js in project root.
if (new URL(request.url).pathname.endsWith("/auth")) {
await this.authenticateUser(request);
return ok();
}
await this.party.storage.put("id", this.party.id);
return ok();
}
// return list of messages for server rendering pages
if (request.method === "GET") {
if (await this.party.storage.get("id")) {
return json<SyncMessage>({ type: "sync", messages });
}
return notFound();
}
// clear room history
if (request.method === "DELETE") {
await this.removeRoomMessages();
this.party.broadcast(JSON.stringify(<ClearRoomMessage>{ type: "clear" }));
this.party.broadcast(
newMessage({
from: { id: "system" },
text: `Room history cleared`,
})
);
return ok();
}
// respond to cors preflight requests
if (request.method === "OPTIONS") {
return ok();
}
return notFound();
}
/**
* Executes when a new WebSocket connection is made to the room
*/
async onConnect(connection: ChatConnection) {
await this.ensureLoadMessages();
await this.ensureAIParticipant();
// if user is the bot we invited, mark them as an AI user
if (connection.id === this.botId) {
connection.setState({ user: AI_USER });
}
// send the whole list of messages to user when they connect
connection.send(syncMessage(this.messages ?? []));
// keep track of connections
this.updateRoomList("enter", connection);
}
async onMessage(
messageString: string,
connection: Party.Connection<{ user: User | null }>
) {
const message = JSON.parse(messageString) as UserMessage;
// handle user messages
if (message.type === "new" || message.type === "edit") {
const user = connection.state?.user;
if (!isSessionValid(user)) {
return connection.send(
systemMessage("You must sign in to send messages to this room")
);
}
if (message.text.length > 1000) {
return connection.send(systemMessage("Message too long"));
}
const payload = <Message>{
id: message.id ?? nanoid(),
from: { id: user.username, image: user.image },
text: message.text,
at: Date.now(),
};
// send new message to all connections
if (message.type === "new") {
this.party.broadcast(newMessage(payload));
this.messages!.push(payload);
}
// send edited message to all connections
if (message.type === "edit") {
this.party.broadcast(editMessage(payload), []);
this.messages = this.messages!.map((m) =>
m.id == message.id ? payload : m
);
}
// persist the messages to storage
await this.party.storage.put("messages", this.messages);
// automatically clear the room storage after period of inactivity
await this.party.storage.deleteAlarm();
await this.party.storage.setAlarm(
new Date().getTime() + DELETE_MESSAGES_AFTER_INACTIVITY_PERIOD
);
}
}
async onClose(connection: Party.Connection) {
this.updateRoomList("leave", connection);
}
/**
* A scheduled job that executes when the room storage alarm is triggered
*/
async onAlarm() {
// alarms don't have access to room id, so retrieve it from storage
const id = await this.party.storage.get<string>("id");
if (id) {
await this.removeRoomMessages();
await this.removeRoomFromRoomList(id);
}
}
}
ChatRoomServer satisfies Party.Worker;