|
| 1 | +import { RoomSnapshot, TLSocketRoom } from "@tldraw/sync-core"; |
| 2 | +import { |
| 3 | + TLRecord, |
| 4 | + createTLSchema, |
| 5 | + defaultBindingSchemas, |
| 6 | + defaultShapeSchemas, |
| 7 | +} from "@tldraw/tlschema"; |
| 8 | +import { AutoRouter, IRequest, error } from "itty-router"; |
| 9 | +import throttle from "lodash.throttle"; |
| 10 | +import { Environment } from "./types"; |
| 11 | + |
| 12 | +type RoomSchemaConfig = { |
| 13 | + shapeTypes: string[]; |
| 14 | + bindingTypes: string[]; |
| 15 | +}; |
| 16 | + |
| 17 | +const STORAGE_SCHEMA_CONFIG_KEY = "schemaConfig"; |
| 18 | + |
| 19 | +const createRoomSchema = ({ shapeTypes, bindingTypes }: RoomSchemaConfig) => { |
| 20 | + const customShapeSchemas = Object.fromEntries( |
| 21 | + shapeTypes.map((type) => [type, {}]), |
| 22 | + ); |
| 23 | + const customBindingSchemas = Object.fromEntries( |
| 24 | + bindingTypes.map((type) => [type, {}]), |
| 25 | + ); |
| 26 | + |
| 27 | + return createTLSchema({ |
| 28 | + shapes: { |
| 29 | + ...defaultShapeSchemas, |
| 30 | + ...customShapeSchemas, |
| 31 | + }, |
| 32 | + bindings: { |
| 33 | + ...defaultBindingSchemas, |
| 34 | + ...customBindingSchemas, |
| 35 | + }, |
| 36 | + }); |
| 37 | +}; |
| 38 | + |
| 39 | +const dedupeAndSort = (values: string[]): string[] => { |
| 40 | + return Array.from(new Set(values.filter(Boolean))).sort((a, b) => |
| 41 | + a.localeCompare(b), |
| 42 | + ); |
| 43 | +}; |
| 44 | + |
| 45 | +const mergeSchemaConfig = ( |
| 46 | + baseConfig: RoomSchemaConfig, |
| 47 | + incomingConfig: RoomSchemaConfig, |
| 48 | +): RoomSchemaConfig => ({ |
| 49 | + shapeTypes: dedupeAndSort( |
| 50 | + baseConfig.shapeTypes.concat(incomingConfig.shapeTypes), |
| 51 | + ), |
| 52 | + bindingTypes: dedupeAndSort( |
| 53 | + baseConfig.bindingTypes.concat(incomingConfig.bindingTypes), |
| 54 | + ), |
| 55 | +}); |
| 56 | + |
| 57 | +const isSameSchemaConfig = ( |
| 58 | + a: RoomSchemaConfig, |
| 59 | + b: RoomSchemaConfig, |
| 60 | +): boolean => { |
| 61 | + return ( |
| 62 | + a.shapeTypes.length === b.shapeTypes.length && |
| 63 | + a.bindingTypes.length === b.bindingTypes.length && |
| 64 | + a.shapeTypes.every((value, index) => value === b.shapeTypes[index]) && |
| 65 | + a.bindingTypes.every((value, index) => value === b.bindingTypes[index]) |
| 66 | + ); |
| 67 | +}; |
| 68 | + |
| 69 | +// each whiteboard room is hosted in a DurableObject: |
| 70 | +// https://developers.cloudflare.com/durable-objects/ |
| 71 | + |
| 72 | +// there's only ever one durable object instance per room. it keeps all the room state in memory and |
| 73 | +// handles websocket connections. periodically, it persists the room state to the R2 bucket. |
| 74 | +export class TldrawDurableObject { |
| 75 | + private r2: R2Bucket; |
| 76 | + // the room ID will be missing whilst the room is being initialized |
| 77 | + private roomId: string | null = null; |
| 78 | + private roomSchemaConfig: RoomSchemaConfig = { |
| 79 | + shapeTypes: [], |
| 80 | + bindingTypes: [], |
| 81 | + }; |
| 82 | + // when we load the room from the R2 bucket, we keep it here. it's a promise so we only ever |
| 83 | + // load it once. |
| 84 | + private roomPromise: Promise<TLSocketRoom<TLRecord, void>> | null = null; |
| 85 | + |
| 86 | + constructor( |
| 87 | + private readonly ctx: DurableObjectState, |
| 88 | + env: Environment, |
| 89 | + ) { |
| 90 | + this.r2 = env.TLDRAW_BUCKET; |
| 91 | + |
| 92 | + ctx.blockConcurrencyWhile(async () => { |
| 93 | + this.roomId = ((await this.ctx.storage.get("roomId")) ?? null) as |
| 94 | + | string |
| 95 | + | null; |
| 96 | + const schemaConfig = |
| 97 | + ((await this.ctx.storage.get( |
| 98 | + STORAGE_SCHEMA_CONFIG_KEY, |
| 99 | + )) as RoomSchemaConfig) ?? null; |
| 100 | + if (schemaConfig) { |
| 101 | + this.roomSchemaConfig = { |
| 102 | + shapeTypes: dedupeAndSort(schemaConfig.shapeTypes ?? []), |
| 103 | + bindingTypes: dedupeAndSort(schemaConfig.bindingTypes ?? []), |
| 104 | + }; |
| 105 | + } |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + private readonly router = AutoRouter({ |
| 110 | + catch: (e) => { |
| 111 | + console.log(e); |
| 112 | + return error(e); |
| 113 | + }, |
| 114 | + }) |
| 115 | + // when we get a connection request, we stash the room id if needed and handle the connection |
| 116 | + .get("/connect/:roomId", async (request) => { |
| 117 | + if (!this.roomId) { |
| 118 | + await this.ctx.blockConcurrencyWhile(async () => { |
| 119 | + await this.ctx.storage.put("roomId", request.params.roomId); |
| 120 | + this.roomId = request.params.roomId; |
| 121 | + }); |
| 122 | + } |
| 123 | + return this.handleConnect(request); |
| 124 | + }); |
| 125 | + |
| 126 | + // `fetch` is the entry point for all requests to the Durable Object |
| 127 | + fetch(request: Request): Response | Promise<Response> { |
| 128 | + return this.router.fetch(request); |
| 129 | + } |
| 130 | + |
| 131 | + // what happens when someone tries to connect to this room? |
| 132 | + async handleConnect(request: IRequest): Promise<Response> { |
| 133 | + // extract query params from request |
| 134 | + const sessionId = request.query.sessionId as string; |
| 135 | + if (!sessionId) return error(400, "Missing sessionId"); |
| 136 | + const incomingSchemaConfig = this.getIncomingSchemaConfig(request); |
| 137 | + await this.ensureSchemaConfig(incomingSchemaConfig); |
| 138 | + |
| 139 | + // Create the websocket pair for the client |
| 140 | + const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair(); |
| 141 | + serverWebSocket.accept(); |
| 142 | + |
| 143 | + // load the room, or retrieve it if it's already loaded |
| 144 | + const room = await this.getRoom(); |
| 145 | + |
| 146 | + // connect the client to the room |
| 147 | + room.handleSocketConnect({ sessionId, socket: serverWebSocket }); |
| 148 | + |
| 149 | + // return the websocket connection to the client |
| 150 | + return new Response(null, { status: 101, webSocket: clientWebSocket }); |
| 151 | + } |
| 152 | + |
| 153 | + private getIncomingSchemaConfig(request: IRequest): RoomSchemaConfig { |
| 154 | + const url = new URL(request.url); |
| 155 | + return { |
| 156 | + shapeTypes: dedupeAndSort(url.searchParams.getAll("shapeType")), |
| 157 | + bindingTypes: dedupeAndSort(url.searchParams.getAll("bindingType")), |
| 158 | + }; |
| 159 | + } |
| 160 | + |
| 161 | + private async ensureSchemaConfig( |
| 162 | + incomingSchemaConfig: RoomSchemaConfig, |
| 163 | + ): Promise<void> { |
| 164 | + const nextConfig = mergeSchemaConfig( |
| 165 | + this.roomSchemaConfig, |
| 166 | + incomingSchemaConfig, |
| 167 | + ); |
| 168 | + if (isSameSchemaConfig(this.roomSchemaConfig, nextConfig)) return; |
| 169 | + |
| 170 | + this.roomSchemaConfig = nextConfig; |
| 171 | + await this.ctx.storage.put( |
| 172 | + STORAGE_SCHEMA_CONFIG_KEY, |
| 173 | + this.roomSchemaConfig, |
| 174 | + ); |
| 175 | + |
| 176 | + if (this.roomPromise) { |
| 177 | + const previousRoom = await this.roomPromise; |
| 178 | + const snapshot = previousRoom.getCurrentSnapshot(); |
| 179 | + previousRoom.close(); |
| 180 | + this.roomPromise = Promise.resolve(this.createRoom(snapshot)); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + private createRoom( |
| 185 | + initialSnapshot?: RoomSnapshot, |
| 186 | + ): TLSocketRoom<TLRecord, void> { |
| 187 | + return new TLSocketRoom<TLRecord, void>({ |
| 188 | + schema: createRoomSchema(this.roomSchemaConfig), |
| 189 | + initialSnapshot, |
| 190 | + onDataChange: () => { |
| 191 | + // and persist whenever the data in the room changes |
| 192 | + this.schedulePersistToR2(); |
| 193 | + }, |
| 194 | + }); |
| 195 | + } |
| 196 | + |
| 197 | + getRoom() { |
| 198 | + const roomId = this.roomId; |
| 199 | + if (!roomId) throw new Error("Missing roomId"); |
| 200 | + |
| 201 | + if (!this.roomPromise) { |
| 202 | + this.roomPromise = (async () => { |
| 203 | + // fetch the room from R2 |
| 204 | + const roomFromBucket = await this.r2.get(`rooms/${roomId}`); |
| 205 | + |
| 206 | + // if it doesn't exist, we'll just create a new empty room |
| 207 | + const initialSnapshot = roomFromBucket |
| 208 | + ? ((await roomFromBucket.json()) as RoomSnapshot) |
| 209 | + : undefined; |
| 210 | + |
| 211 | + // create a new TLSocketRoom. This handles all the sync protocol & websocket connections. |
| 212 | + // it's up to us to persist the room state to R2 when needed though. |
| 213 | + return this.createRoom(initialSnapshot); |
| 214 | + })(); |
| 215 | + } |
| 216 | + |
| 217 | + return this.roomPromise; |
| 218 | + } |
| 219 | + |
| 220 | + // we throttle persistance so it only happens every 10 seconds |
| 221 | + schedulePersistToR2: () => void = throttle(async () => { |
| 222 | + if (!this.roomPromise || !this.roomId) return; |
| 223 | + try { |
| 224 | + const room = await this.getRoom(); |
| 225 | + const snapshot = JSON.stringify(room.getCurrentSnapshot()); |
| 226 | + await this.r2.put(`rooms/${this.roomId}`, snapshot); |
| 227 | + } catch (e) { |
| 228 | + console.error("Failed to persist room to R2", { |
| 229 | + roomId: this.roomId, |
| 230 | + error: e, |
| 231 | + }); |
| 232 | + } |
| 233 | + }, 10_000); |
| 234 | +} |
0 commit comments