Skip to content

Y.Doc hydration can race #3141

Closed
Closed

Description

@JammingBen

Initial Checklist

  • I understand this is a bug report and questions should be posted in the Community Discussions
  • I searched issues and couldn’t find anything (or linked relevant results below)

Bug Description

The hydration of a Y.Doc can race if 2 peers open a document at the exact same time, causing the content to be displayed twice.

Reproduction Steps

Hard to reproduce locally, but this unit tests proofs it and be used during development as verifier:

Show unit test
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { ref, shallowRef, unref } from 'vue'
import * as Y from 'yjs'
import type { Resource } from '@opencloud-eu/web-client'

import { useYjsSession, type YjsAdapter, type YjsSession } from '../../../../src/composables/yjs'
import { getComposableWrapper } from '@opencloud-eu/web-test-helpers'

interface MockProvider {
  name: string
  document: Y.Doc
  awareness: any
  stopped: boolean
  triggerSynced(): void
}

const { providerInstances, relay } = vi.hoisted(() => {
  return {
    providerInstances: [] as MockProvider[],
    relay: { awarenessDelayMs: 0, docDelayMs: 0 }
  }
})

vi.mock('@hocuspocus/provider', async () => {
  const Yjs = await import('yjs')
  const { Awareness } = await import('y-protocols/awareness')

  const RELAY_ORIGIN = Symbol('relay')

  class MockHocuspocusProvider {
    url: string
    name: string
    document: Y.Doc
    awareness: any
    stopped = false
    private _opts: any

    destroy = vi.fn(() => {
      this.stopped = true
      this.awareness.destroy()
    })
    disconnect = vi.fn(() => {
      this.stopped = true
    })
    detach = vi.fn()
    setAwarenessField = vi.fn((field: string, value: unknown) => {
      this.awareness.setLocalStateField(field, value)
      this.broadcastAwareness()
    })

    constructor(opts: any) {
      this.url = opts.url
      this.name = opts.name
      this.document = opts.document
      this.awareness = new Awareness(opts.document)
      this._opts = opts
      providerInstances.push(this as unknown as MockProvider)

      this.document.on('update', (update: Uint8Array, origin: unknown) => {
        if (origin === RELAY_ORIGIN || this.stopped) return
        setTimeout(() => {
          for (const peer of this.peers()) {
            if (peer.document.isDestroyed) continue
            Yjs.applyUpdate(peer.document, update, RELAY_ORIGIN)
          }
        }, relay.docDelayMs)
      })
    }

    private peers(): MockHocuspocusProvider[] {
      return providerInstances.filter(
        (p) => p !== (this as unknown as MockProvider) && p.name === this.name && !p.stopped
      ) as unknown as MockHocuspocusProvider[]
    }

    private broadcastAwareness() {
      const clientId = this.document.clientID
      setTimeout(() => {
        const state = { ...this.awareness.getLocalState() }
        for (const peer of this.peers()) {
          peer.awareness.states.set(clientId, state)
        }
      }, relay.awarenessDelayMs)
    }

    triggerSynced() {
      this._opts.onSynced?.({ state: true })
    }
  }

  return { HocuspocusProvider: MockHocuspocusProvider }
})

const SHARED_TEXT_KEY = 'content'
const YJS_SERVER_URL = 'wss://example.test/yjs'
const FILE_BODY = 'the file body'

const testAdapter: YjsAdapter = {
  hydrate(ydoc: Y.Doc, content: string) {
    const yText = ydoc.getText(SHARED_TEXT_KEY)
    if (yText.length > 0) return
    if (!content) return
    ydoc.transact(() => {
      yText.insert(0, content)
    }, 'hydrate')
  },
  serialize(ydoc: Y.Doc): string {
    return ydoc.getText(SHARED_TEXT_KEY).toString()
  },
  hasContent(ydoc: Y.Doc): boolean {
    return ydoc.getText(SHARED_TEXT_KEY).length > 0
  },
  reset(ydoc: Y.Doc) {
    const yText = ydoc.getText(SHARED_TEXT_KEY)
    if (yText.length === 0) return
    yText.delete(0, yText.length)
  }
}

function openClient(currentContent = FILE_BODY) {
  const resourceRef = ref({ id: 'storage$space!item-1', etag: 'etag-initial' } as Resource)
  let session: YjsSession

  const wrapper = getComposableWrapper(
    () => {
      session = useYjsSession({
        resource: resourceRef,
        currentContent: ref(currentContent),
        enabled: ref(true),
        isReadOnly: ref(false),
        adapter: shallowRef(testAdapter),
        appVersion: '1.2.3',
        documentPrefix: 'test-app',
        onContentChange: vi.fn(),
        onServerContentChange: vi.fn(),
        onEtagChange: vi.fn()
      })
    },
    {
      pluginOptions: {
        piniaOptions: {
          configState: { options: { yjsServerUrl: YJS_SERVER_URL } },
          authState: { accessToken: 'access-token' }
        }
      }
    }
  )

  return {
    wrapper,
    get session() {
      return session
    },
    get ydoc() {
      return unref(session.ydoc)
    },
    get text() {
      return unref(session.ydoc)!.getText(SHARED_TEXT_KEY).toString()
    }
  }
}

async function bothOpenSimultaneously() {
  const a = openClient()
  const b = openClient()
  await flushPromises()

  providerInstances[0].triggerSynced()
  providerInstances[1].triggerSynced()

  // Well past the 150ms election wait and both relay hops.
  await vi.advanceTimersByTimeAsync(2_000)
  await flushPromises()

  return { a, b }
}

beforeEach(() => {
  providerInstances.length = 0
  relay.awarenessDelayMs = 0
  relay.docDelayMs = 0
  vi.useFakeTimers()
})

afterEach(() => {
  vi.useRealTimers()
})

describe('useYjsSession — simultaneous hydration', () => {
  it('seeds the body once when awareness crosses inside the election window', async () => {
    relay.awarenessDelayMs = 20
    relay.docDelayMs = 20

    const { a, b } = await bothOpenSimultaneously()

    expect(a.text).toBe(FILE_BODY)
    expect(b.text).toBe(FILE_BODY)
  })

  it('seeds the body once when the awareness round-trip outlives the election window', async () => {
    relay.awarenessDelayMs = 300
    relay.docDelayMs = 20

    const { a, b } = await bothOpenSimultaneously()

    expect(a.text).toBe(b.text)
    expect(a.text).toBe(FILE_BODY)
  })

  it('does not seed the room twice', async () => {
    relay.awarenessDelayMs = 300
    relay.docDelayMs = 20

    const { a } = await bothOpenSimultaneously()

    expect(a.text.length).toBe(FILE_BODY.length)
  })
})

Expected Outcome

Only one peer hydrates, no duplicated content.

Actual Outcome

Both peers hydrate, duplicated content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions