Skip to content

AI-native design editor. Open-source Figma alternative.

perf(collab): compress the first sync and send Yjs V2 updates (#1136)

Danila Poyarkov871a8948b767
diff --git a/changes/1136/performance.md b/changes/1136/performance.md
new file mode 100644
index 000000000..da32915be
--- /dev/null
+++ b/changes/1136/performance.md
@@ -0,0 +1 @@
+- Joining a shared room is faster: the document a person receives on joining is compressed, about a twelfth of its size before (480 KB instead of 5.7 MB for the demo tour), and edits travel in Yjs's more compact encoding.
diff --git a/src/app/collab/room/connection.ts b/src/app/collab/room/connection.ts
index 3f6c84638..edf57ba86 100644
--- a/src/app/collab/room/connection.ts
+++ b/src/app/collab/room/connection.ts
@@ -1,9 +1,11 @@
+import { deflateSync, Inflate } from 'fflate'
import * as decoding from 'lib0/decoding'
import * as awarenessProtocol from 'y-protocols/awareness'
import * as Y from 'yjs'
import { joinCollabRoom, type JoinCollabRoom } from '@/app/collab/transport'
import type { CollabAction } from '@/app/collab/transport/types'
+import { MAX_COLLAB_MESSAGE_BYTES } from '@/constants'
export type CollabRoomOptions = {
roomId: string
@@ -11,6 +13,8 @@ export type CollabRoomOptions = {
awareness: awarenessProtocol.Awareness
updatePeersList: () => void
joinRoom?: JoinCollabRoom
+ /** The most a peer's update may decode to; `MAX_COLLAB_MESSAGE_BYTES` unless a test lowers it. */
+ maxMessageBytes?: number
}
export type CollabRoomConnection = {
@@ -28,6 +32,69 @@ export type CollabRoomConnection = {
type AwarenessEntry = { clientId: number; removed: boolean }
+/**
+ * What a peer joining needs is the whole document, which repeats the same field names across
+ * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already
+ * groups that repetition, and together they make a room's first sync about a twelfth the size.
+ * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.
+ */
+function encodeSyncReply(ydoc: Y.Doc, stateVector: Uint8Array): Uint8Array {
+ return deflateSync(Y.encodeStateAsUpdateV2(ydoc, stateVector))
+}
+
+/**
+ * Compressed input is inflated this much at a time, so a reply stops within a step of passing
+ * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.
+ */
+const INFLATE_STEP = 16 * 1024
+
+/** `data` inflated, or null once it would decode past `limit` bytes. */
+function inflateWithin(data: Uint8Array, limit: number): Uint8Array | null {
+ const chunks: Uint8Array[] = []
+ let size = 0
+ const inflate = new Inflate((chunk) => {
+ size += chunk.length
+ if (size <= limit) chunks.push(chunk)
+ })
+ for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {
+ inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length)
+ if (size > limit) return null
+ }
+ const inflated = new Uint8Array(size)
+ let at = 0
+ for (const chunk of chunks) {
+ inflated.set(chunk, at)
+ at += chunk.length
+ }
+ return inflated
+}
+
+/**
+ * Applies what a peer sent, inflated first when `compressed`, as a sync reply is. An update past
+ * `limit` is dropped with a warning; data that does not inflate or decode came from a build that
+ * does not share this room's format, or from a broken peer, and is dropped rather than thrown
+ * from the transport's handler. Returns whether it applied.
+ */
+function applyRemote(
+ ydoc: Y.Doc,
+ data: Uint8Array,
+ { limit, peerId, compressed = false }: { limit: number; peerId: string; compressed?: boolean }
+): boolean {
+ try {
+ let update: Uint8Array | null = null
+ if (compressed) update = inflateWithin(data, limit)
+ else if (data.length <= limit) update = data
+ if (!update) {
+ console.warn(`[Collab] Dropped an update from peer ${peerId} past ${limit} bytes`)
+ return false
+ }
+ Y.applyUpdateV2(ydoc, update, 'remote')
+ return true
+ } catch {
+ return false
+ }
+}
+
function awarenessEntries(data: Uint8Array): AwarenessEntry[] {
try {
const decoder = decoding.createDecoder(data)
@@ -49,7 +116,8 @@ export function connectCollabRoom({
ydoc,
awareness,
updatePeersList,
- joinRoom = joinCollabRoom
+ joinRoom = joinCollabRoom,
+ maxMessageBytes = MAX_COLLAB_MESSAGE_BYTES
}: CollabRoomOptions): CollabRoomConnection {
const room = joinRoom(roomId)
const [sendYjsUpdate, getUpdate] = room.makeAction('yjs-update')
@@ -62,8 +130,8 @@ export function connectCollabRoom({
const awarenessClientsByPeer = new Map<string, Set<number>>()
- getUpdate((data) => {
- Y.applyUpdate(ydoc, data, 'remote')
+ getUpdate((data, peerId) => {
+ applyRemote(ydoc, data, { limit: maxMessageBytes, peerId })
})
getAwareness((data, peerId) => {
@@ -78,15 +146,14 @@ export function connectCollabRoom({
})
getSyncStep1((stateVector, peerId) => {
- const update = Y.encodeStateAsUpdate(ydoc, stateVector)
- sendSyncReply(update, peerId)
+ sendSyncReply(encodeSyncReply(ydoc, stateVector), peerId)
})
- getSyncReply((data) => {
- Y.applyUpdate(ydoc, data, 'remote')
+ getSyncReply((data, peerId) => {
+ applyRemote(ydoc, data, { limit: maxMessageBytes, peerId, compressed: true })
})
- ydoc.on('update', (update: Uint8Array, origin: unknown) => {
+ ydoc.on('updateV2', (update: Uint8Array, origin: unknown) => {
if (origin === 'remote') return
sendYjsUpdate(update)
})
diff --git a/src/constants.ts b/src/constants.ts
index eab0e5436..3a02d3bd1 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -64,10 +64,17 @@ export {
import type { Color } from '@open-pencil/scene-graph/primitives'
/**
- * The collaboration namespace. It names the shared document format, so builds that sync the layer
- * tree differently never join each other's rooms; change it with the format.
+ * The collaboration namespace. It names the shared document format and how peers send it, so
+ * builds that sync the layer tree differently, or encode what they send differently, never join
+ * each other's rooms; change it with either.
*/
-export const COLLAB_APP_ID = 'openpencil/3'
+export const COLLAB_APP_ID = 'openpencil/4'
+
+/**
+ * The most a room message may decode to, compressed or not. A peer's update past it is dropped
+ * before it is decoded, so a small compressed reply cannot expand without bound.
+ */
+export const MAX_COLLAB_MESSAGE_BYTES = 256 * 1024 * 1024
// 32 base36 characters provide roughly 165 bits of entropy. The room ID is a
// bearer credential and must resist offline enumeration from public signaling topics.
export const ROOM_ID_LENGTH = 32
diff --git a/tests/app/collab/room/connection.test.ts b/tests/app/collab/room/connection.test.ts
new file mode 100644
index 000000000..63c1601a8
--- /dev/null
+++ b/tests/app/collab/room/connection.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, spyOn, test } from 'bun:test'
+
+import { deflateSync } from 'fflate'
+import { Awareness } from 'y-protocols/awareness'
+import * as Y from 'yjs'
+
+import { connectCollabRoom } from '@/app/collab/room/connection'
+import type { JoinCollabRoom } from '@/app/collab/transport'
+
+import { createMemoryRooms } from '#tests/helpers/collab/memory-transport'
+
+const ROOM = 'dddddddddddddddddddddddddddddddd'
+
+/** Joins through `rooms`, recording the size of every message sent, by action. */
+function recordingJoin(rooms: ReturnType<typeof createMemoryRooms>) {
+ const sent = new Map<string, number[]>()
+ const join: JoinCollabRoom = (roomId) => {
+ const room = rooms.join(roomId)
+ return {
+ ...room,
+ makeAction(namespace) {
+ const [send, receive] = room.makeAction(namespace)
+ return [
+ (data, peerId) => {
+ sent.set(namespace, [...(sent.get(namespace) ?? []), data.byteLength])
+ send(data, peerId)
+ },
+ receive
+ ]
+ }
+ }
+ }
+ return { join, sent }
+}
+
+function connect(join: JoinCollabRoom, maxMessageBytes?: number) {
+ const ydoc = new Y.Doc()
+ connectCollabRoom({
+ roomId: ROOM,
+ ydoc,
+ awareness: new Awareness(ydoc),
+ updatePeersList: () => undefined,
+ joinRoom: join,
+ maxMessageBytes
+ })
+ return ydoc
+}
+
+/** Layers whose fields repeat, as a page's do. */
+function fillLayers(ydoc: Y.Doc, count: number, from = 0) {
+ const nodes = ydoc.getMap<Y.Map<unknown>>('nodes')
+ ydoc.transact(() => {
+ for (let index = from; index < from + count; index++) {
+ const node = new Y.Map<unknown>()
+ node.set('type', 'RECTANGLE')
+ node.set('name', `Rectangle ${index}`)
+ node.set('x', index * 10)
+ node.set('y', 0)
+ node.set('fills', [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true }])
+ nodes.set(`0:${index}`, node)
+ }
+ })
+}
+
+describe('collab room connection', () => {
+ test("brings a joining peer the room's document compressed, then syncs edits both ways", async () => {
+ const rooms = createMemoryRooms()
+ const recording = recordingJoin(rooms)
+ const host = connect(recording.join)
+ fillLayers(host, 200)
+ const v1Size = Y.encodeStateAsUpdate(host).byteLength
+
+ const guest = connect(rooms.join)
+ await rooms.settle()
+ const [reply] = recording.sent.get('sync-reply') ?? []
+ expect(reply).toBeLessThan(v1Size / 4)
+
+ const nodes = (doc: Y.Doc) => doc.getMap<Y.Map<unknown>>('nodes')
+ expect(nodes(guest).size).toBe(200)
+ expect(nodes(guest).get('0:199')?.get('name')).toBe('Rectangle 199')
+
+ nodes(guest).get('0:5')?.set('x', 999)
+ await rooms.settle()
+ expect(nodes(host).get('0:5')?.get('x')).toBe(999)
+
+ nodes(host).get('0:6')?.set('name', 'Renamed')
+ await rooms.settle()
+ expect(nodes(guest).get('0:6')?.get('name')).toBe('Renamed')
+ })
+
+ test('drops what does not inflate or decode instead of throwing from the transport', async () => {
+ const rooms = createMemoryRooms()
+ const ydoc = connect(rooms.join)
+ const intruder = rooms.join(ROOM)
+ const [sendReply] = intruder.makeAction('sync-reply')
+ const [sendUpdate] = intruder.makeAction('yjs-update')
+ await rooms.settle()
+
+ const garbage = new Uint8Array([255, 255, 255, 255, 255, 1, 2, 3])
+ sendReply(Y.encodeStateAsUpdate(new Y.Doc()))
+ sendReply(deflateSync(garbage))
+ sendUpdate(garbage)
+ await rooms.settle()
+ expect(ydoc.getMap('nodes').size).toBe(0)
+ })
+
+ test('drops a sync reply that would inflate past the limit, however small it travels', async () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => undefined)
+ const rooms = createMemoryRooms()
+ const host = connect(rooms.join)
+ fillLayers(host, 200)
+ const update = Y.encodeStateAsUpdateV2(host)
+ const limit = update.byteLength - 1
+ expect(deflateSync(update).byteLength).toBeLessThan(limit)
+
+ const guest = connect(rooms.join, limit)
+ await rooms.settle()
+ expect(guest.getMap('nodes').size).toBe(0)
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+
+ test('drops an edit past the limit and applies those under it', async () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => undefined)
+ const rooms = createMemoryRooms()
+ const host = connect(rooms.join)
+ const guest = connect(rooms.join, 2000)
+ await rooms.settle()
+
+ fillLayers(host, 1)
+ await rooms.settle()
+ expect(guest.getMap('nodes').size).toBe(1)
+
+ fillLayers(host, 300, 1)
+ await rooms.settle()
+ expect(guest.getMap('nodes').size).toBe(1)
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+})