# Library issue: yJs synchronisation and client (state) being overwritten

**URL:** <https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681>\
**Category:** Help\
**Created:** [June 11, 2022, 4:03pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681 "2022-06-11T16:03:16Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 11, 2022, 4:03pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/1 "2022-06-11T16:03:16Z")

</div>

As detailed [elsewhere](https://discuss.yjs.dev/t/un-expected-ymap-key-behaviour-for-reactive-components-in-observable-notebook/1143), I am running into issues syncing a slider between notebooks.

While my [Stackblitz example](https://shared-slider.stackblitz.io/) demonstrates how a shared slider using yJs can sync seamlessly between multiple clients (open the link in two tabs, side-by-side), a similar implementation on Observable runs into one big issue: _the first client’s state is overwritten as soon as a second client interacts with the shared slider_.

- Open [Yjs / Ymap on Observable / dleeftink / Observable](https://observablehq.com/d/a785401ff17adc64) in two tabs, side-by-side (EDIT: [Here is a notebook](https://observablehq.com/d/7f0c156c168080cc) mirroring the Stackblitz example 1:1)
- Interact with the slider on the first tab (second tab updates fine), then the second (first tab state is overwritten)
  - E.g. observe how the `sliderState` becomes `undefined` after interacting with it in the second tab.

As this implementation works fine on Stackblitz, I am wondering whether the Observable runtime prevents third-party libraries to access websockets/webworkers across domains (e.g. cross scripting between [user.static.observableusercontent.com/next/worker.html](http://user.static.observableusercontent.com/next/worker.html) and [observablehq.com](http://observablehq.com)) or that other CORS issues prevent yJs from functioning.

Maybe someone can shed some light on whether Observable’s sandboxing prevents libraries like yJs to communicate between clients?

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 12, 2022, 9:27am UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/2 "2022-06-12T09:27:46Z")

</div>

_Link to stackblitz source: [Shared slider (yJs) - StackBlitz](https://stackblitz.com/edit/shared-slider?file=index.ts)_

The fact that you can still modify the shared value from both tabs shows that the contexts can still communicate.

One noticeable difference is that in your Observable notebook [no other cell](https://observablehq.com/@observablehq/notebook-visualizer?id=d/a785401ff17adc64) depends on `provider`. The order in which cells are run is arbitrary, so `provider` might execute _after_ other cells which rely on it, unless you add an explicit reference.

I would perhaps suggest to add logging for the document level events, like

```javascript
ydoc = {
  const d = new Y.Doc({gc:true})
  invalidation.then(() => d.destroy())
  d.on('beforeTransaction', console.log)
  d.on('beforeObserverCalls', console.log)
  d.on('afterTransaction', console.log)
  d.on('update', console.log)
  return d
}

```

and to consume the generator directly to figure out what’s going on:

```javascript
sliderState = {

  let cycle = new Mutable()
  let renew = event => {
    viewof comp.value = cycle.value = ymap.get('slider')
  }
  
  ymap.observe(renew)
  invalidation.then(()=>ymap.unobserve(renew ) )

  let value
  do {
    value = cycle.generator.next()
    const v = await value.value
    yield ({current: v, value})
  } while(!value.done)
       
}

```

If you can, you may also want to include an unminified version of the library to ease analysis.

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 12, 2022, 11:25am UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/3 "2022-06-12T11:25:14Z")

</div>

Thank you Fabian for checking, will see if some of the logging and unminified versions turns up some more information.

You are correct that contexts are communicating, albeit in one(1.5?)-way: the first client sends data and the second client listens, while in reverse the second client seems to emit an initial ‘tick’ upon which the first client erases the shared variable set by `ymap.set('value', ...)`.

I have tried various configurations and update patterns, all leading to the same effect, even when using third-party libraries build on yJs such as `sync-store` that work quite well outside of Observable. Whenever a second client starts interacting with a shared yJs type (array, map or else), the variable in the first client becomes `undefined`. Maybe unsurprising, this does not happen when each Observable client appends a (device) UID to the variable name.

Regarding the `provider` being a sink, this was setup by following the [yJs documentation](https://github.com/yjs/y-webrtc), where the provider is defined by `new WebrtcProvider('room name', referenceToYDocVariable)`.

In any case, I’ve [drawn up a notebook](https://observablehq.com/d/7f0c156c168080cc) closer to the Stackblitz example, exhibiting the same issue as before: _updates shared from client 1 \> 2 are blocked in reverse_.

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 12, 2022, 8:55pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/4 "2022-06-12T20:55:36Z")

</div>

> [@dleeftink](#):
>
> I’ve [drawn up a notebook](https://observablehq.com/d/7f0c156c168080cc) closer to the Stackblitz example

Not close enough I’m afraid, since you rely on Stackblitz to resolve and bundle the packages. If you take a look at the initial console output of your notebook you’ll see several warnings:

![image](https://canada1.discourse-cdn.com/flex030/uploads/observablehq/original/2X/e/efce81f0399735b22b1350a2bb58d3bb55361ee3.png)

You may want to try to create a bundle locally that reexports all the necessary API, then include it both in your notebook and on Stackblitz.

Similarly you could try to dynamically import the packages from your notebook in your Stackblitz example.

And lastly you **must** reference your HTML cells directly, or ensure that the cells that define your elements have run before you initialize ydoc.

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 12, 2022, 9:57pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/5 "2022-06-12T21:57:55Z")

</div>

> [@mootari](#):
>
> and to consume the generator directly to figure out what’s going on:

It took me until now to realize that `new Mutable()` comes from [Observable’s stdlib](https://github.com/observablehq/stdlib/blob/48c788ba3de6fe9ab78102e7a797677843c684ea/src/mutable.js), not Yjs. 🤦‍♂️

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 12, 2022, 10:21pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/6 "2022-06-12T22:21:59Z")

</div>

Yes, not sure if its documented somewhere but I find it a quick and succint way of ‘cycling’ through generator functions and/or defining a scoped mutable. In any case, I’ve only included it to display intermittent slider values in the notebook rather than logging them to the console, as I’ve also posted this issue on the yJs community board who may be less familiar with Observable.

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 12, 2022, 10:59pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/7 "2022-06-12T22:59:15Z")

</div>

The problem isn’t Observable, but the bundles used. Here’s a Stackblitz repro using the imports from your notebook that exhibits the exact same problem: [https://web-platform-skvosp.stackblitz.io/](https://web-platform-skvosp.stackblitz.io/) ([edit link](https://stackblitz.com/edit/web-platform-skvosp?file=script.js))

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 12, 2022, 11:26pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/8 "2022-06-12T23:26:51Z")

</div>

Nice find! Seems like a bundling issue from the looks of it. When trying to use the advised [browser import method](https://github.com/yjs/yjs/issues/282), some modules seem to not have a `default` module export (for instance using `import('https://unpkg.com/y-webrtc?module')`).

Let’s see if there is any easy way to bundle this up elsewhere.

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 12, 2022, 11:46pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/9 "2022-06-12T23:46:33Z")

</div>

Specifically, `simple-peer` seems to cause [an issue](https://github.com/yjs/y-webrtc/issues/36).

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 13, 2022, 8:54am UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/10 "2022-06-13T08:54:50Z")

</div>

Yes, and y-webrtc defines yjs as peer dependency, which is why skypack pulls it in as well. If you want to attempt client-side bundling and are feeling adventurous, you could take a stab at jspm + import maps: [Import Map Generator - JSPM2](https://generator.jspm.io/#Y2JgYGBiDs0rySzJSU1hqNQtT00qKkl2MDTQM9IzZqjMKnYwNNYz1TO2AACUR2p0KgA)

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 13, 2022, 9:37pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/11 "2022-06-13T21:37:34Z")

</div>

I felt quite adventurous indeed, a [shared state notebook](https://observablehq.com/@dleeftink/shared-state) with `esmap` based modules is now up and running.

Thanks again for the pointers Fabian!

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 13, 2022, 10:53pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/12 "2022-06-13T22:53:33Z")

</div>

Nice work!

There’s a few things I would recommend to change or add. Are you open to suggestions?

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 13, 2022, 10:58pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/13 "2022-06-13T22:58:50Z")

</div>

Please do! There is probably a better way to ‘hot-load’ importmaps…

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 14, 2022, 3:59pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/14 "2022-06-14T15:59:13Z")

</div>

Thanks for the suggestions, merged them in. As @tomlarkworthy noted, the signalling server unfortunately has issues connecting clients under certain conditions; this happens even when switching to the dependencies used in the official documentation.

Not sure where to start hunting this one down, as I am not that familiar with Webrtc; will try and investigate the `peerOpts` used by simple-peer.

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 14, 2022, 7:08pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/15 "2022-06-14T19:08:25Z")

</div>

There are still a couple of questions that I’d love to see answered:

1. Adding the static module requires the use of a proxy iframe. That iframe has to be kept around because the imported libraries now reference the builtins of that browsing context. Can we call importShim() instead with a dynamic import, and keep the entire import handling in the parent frame?
2. Debug output is only logged to the dev tools console. Is there a way to attach custom consoles instead (they’re referenced as `vconsoles` in the source) so that we can access the debug information directly?
3. To figure out wether there are any connected peers you have to observe the debug messages. Can we somehow access that information directly and expose it to the user?

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 14, 2022, 8:21pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/16 "2022-06-14T20:21:09Z")

</div>

To 1&2, I’d need to experiment some more, but it may require bringing in some of the parent environment variables needed by the modules in the proxy. Re: 3, I encountered two error messages pointing to the [`simple-peer`](https://github.com/feross/simple-peer) library when a remote connection is established:

1. `ERR_SET_REMOTE_DESCRIPTION`

> Error: Failed to execute ‘setRemoteDescription’ on ‘RTCPeerConnection’: Failed to set remote answer sdp: Called in wrong state: stable

1. `ERR_CONNECTION_FAILURE`

> Error in connection to \<GUID\>

In another session, the Observable runtime produced an error for the `y-webrtc` module at `new Websocket`( [`wsclient.url`](https://github.com/dmonad/lib0/blob/deea8b173395b216af8f52482d7c063a7600847f/websocket.js#L25)).

Maybe pointing to cross-origin issues after all? Will keep exploring!

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 14, 2022, 9:22pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/17 "2022-06-14T21:22:12Z")

</div>

> [@mootari](#):
>
> 1. Debug output is only logged to the dev tools console. Is there a way to attach custom consoles instead (they’re referenced as `vconsoles` in the source) so that we can access the debug information directly?

I can answer question 2. The short answer is “no”. The longer answer is “kind of, but it’s not pretty”.

### Option 1: Override `console`

Because we instantiate the modules inside an iframe, we’re free to do with that scope as we please. That means we can shim `console`:

```javascript
mutable log = []

```

```javascript
proxyConsole = ({
  _push(type, args) {
    mutable log.push([type, ...args]);
    mutable log = mutable log;
  },
  debug(...args) { this._push('debug', args) },
  info(...args) { this._push('info', args) },
  log(...args) { this._push('log', args) },
  warn(...args) { this._push('warn', args) },
  error(...args) { this._push('error', args) },
})

```

```javascript
// ...
    proxy.contentWindow.console = proxyConsole;
// ...

```

However, the logging messages are heavily formatted:

```plaintext
Array(6) [
  0: "log"
  1: "%cy-webrtc: %cbroadcast message in %cobservable-shared-state%c +34ms"
  2: "color:green;"
  3: "color:black;"
  4: "color:black;font-weight:bold;"
  5: "color:green;font-weight:normal;"
]

```

I guess one could strip the color formatters (`%c`) though, assuming there’s no other kind of formatting (or value placeholders) being used.

### Option 2: Virtual console

[lib0/logging](https://github.com/dmonad/lib0/blob/v0.2.51/logging.js) hardcodes its reference to `console`, but allows one to instantiate “virtual consoles”, which are basically consoles rendered to a DOM. For this to work we must reference the exact same module instance that is pulled in by `y-webrtc`.

First we need to obtain the module instance, by modifying our proxy module. I had to reference the full path instead of “lib0/logging”, so I decided to play it safe and pull the path directly from the import map:

```javascript
 // ...
import { VConsole } from "${esmap.scopes['https://ga.jspm.io/']['lib0/logging']}";
 window.__resolveModules({ Y, WebrtcProvider, VConsole });

```

Then we create an instance and add auto-scrolling to our wrapping element:

```javascript
{
  const element = html`<div style="height:20em;font-size:14px;overflow:auto">`;
  const observer = new MutationObserver(() => element.scrollTo(0, element.scrollHeight));
  observer.observe(element, {childList: true});
  const vconsole = new module.VConsole(element);
  invalidation.then(() => vconsole.destroy());
  return element;
}

```

which gives us

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/observablehq/original/2X/9/92d79476c4f2abc89529a85c431543942a58a19e.png)

---

<div class="post-metadata">

**Author:** ![mootari](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mootari/32/581_2.png) [@mootari](https://talk.observablehq.com/u/mootari)\
**Post date:** [June 14, 2022, 9:58pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/18 "2022-06-14T21:58:28Z")

</div>

> [@mootari](#):
>
> To figure out wether there are any connected peers you have to observe the debug messages. Can we somehow access that information directly and expose it to the user?

We can access the current number of peers via

```javascript
provider.room.webrtcConns.size

```

`webrtcConns` is a map of `WebrtcConn` instances, keyed by `peerId`:

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/observablehq/original/2X/c/cb6921c15175af1cec4ac0d30d6ae3266787ff6b.png)

It should suffice to query/update that list every few seconds. I haven’t found a way yet to subscribe to broadcast events (haven’t looked too hard either).

The `y-webrtc` source is surprisingly easy to follow and worth a look if one wants to learn about the available API: [https://github.com/yjs/y-webrtc/blob/v10.2.3/src/y-webrtc.js](https://github.com/yjs/y-webrtc/blob/v10.2.3/src/y-webrtc.js)

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 14, 2022, 10:14pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/19 "2022-06-14T22:14:31Z")

</div>

Awesome! Should come in handy in quite a few situations. I was also getting these messages in my native console (Chrome), weren’t they displaying on your end? (EDIT: Scratch that, didn’t fully read your post). In any case, we can build on this.

Regarding the cellular issues, it is apparently [well-known](https://stackoverflow.com/questions/34693571/websocket-send-not-working-from-phone-network) (I didn’t) that Websockets can be finicky over cellular networks if the provider blocks certain ports or adds intermediate proxies. `wss` with ssl should solve it (the yJs signaling servers use `wss`), but maybe this is something worth looking into as well.

---

<div class="post-metadata">

**Author:** ![dleeftink](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/dleeftink/32/7049_2.png) [@dleeftink](https://talk.observablehq.com/u/dleeftink)\
**Post date:** [June 14, 2022, 10:16pm UTC](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681/20 "2022-06-14T22:16:35Z")

</div>

I think the [Awareness API](https://docs.yjs.dev/api/about-awareness) also covers quite some ground re:observing client status.

[Next page](https://talk.observablehq.com/t/library-issue-yjs-synchronisation-and-client-state-being-overwritten/6681.md?page=2)
