Persist data in postgres

EDIT: I resolved the issue. See the response below.

I am trying to persist a state in a Postgres database and it works fine only the first time.

  1. A document is created
  2. Changes are made to this document. Everything works fine, all connected users are synced.
  3. All users quit. writeState is called and the document is correctly written into the database.
  4. The same document is opened.
  5. Data is retrieved. Everything works fine.
  6. But now, whenever the document is updated, updates won’t be persisted. Arriving users will retrieve the previous state, not the up-to-date state.

It’s weird because subsequent writeState seem to work: the encoded state is different all the time. But it’s still the first version that is loaded every time.

These are my Postgres persistence functions, simple enough:

async bindState(id: string, document: Doc) {
	// initialize the document with persisted content
	console.log("Binding state", id);

	const persisted = await db.document.findUnique({
		where: { id },
	});

	if (persisted?.content) {
		applyUpdate(document, persisted.content);
	} else {
		console.log("Document not found", id);
	}
}

async writeState(id: string, document: Doc) {
	// store the Yjs document to your database
	// this is called when all clients disconnect
	console.log("writing state", id);
	const content = Buffer.from(encodeStateAsUpdate(document));

	await db.document.upsert({
		create: { id, content },
		update: { content },
		where: { id },
	});
}

Did I make something wrong?

Why would subsequent writes to the database not apply? (when they seem to apply, the encoded state changes on DB)

In case someone has a similar issue, the problem was due to the fact that two different versions of “yjs” were imported.

I had the following warning: "Yjs was already imported. Importing different versions of Yjs often leads to issues."

… even though I had only one version of Yjs installed.

After triple-checking which packages could import a different version and I found no guilty.

This import was responsible for the issue:

import { setupWSConnection, setPersistence } from "y-websocket/bin/utils"

Because of some unknown dark magic, this unusual import caused Yjs to be imported twice.

I copied the content of the y-websocket/bin/utils file into an esm module and it worked fine.