Giter Site home page Giter Site logo

y-webrtc's Issues

The editor content does not sync on different browsers

Please save me some time and use the following template. In 90% of all issues I can't reproduce the problem because I don't know what exactly you are doing, in which environment, or which y-* version is responsible. Just use the following template even if you think the problem is obvious.

Checklist

Describe the bug
The editor content is sync across the tabs of the same browsers.
But it does not sync with different browsers.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/github/tiavina-mika/tiptap-editor-mui
  2. Open the page in another tabs
  3. Write something
  4. The content is shared accross the tabs
  5. Open the page in another browser
  6. The content is not the same

Expected behavior
The editor content should be the same on different browsers.

Environment Information

  • Browser [e.g. Chrome, Firefox]
  • Yjs version: yjs v13.6.10. y-webrtc: v10.2.6

TypeError: Assignment to constant variable

I was building my Angular application for production use where I ran into this weird issue (after some research, it turns out it isn't uncommon for production builds to have, what appears to be, breaking differences for both React and Angular - I suspect the same may apply for other frameworks).

It complains about the _docUpdateHandler function saying it is assigning something to a constant variable.

const encoder = encoding.createEncoder()

The only const I could see defined was on line 355 so I changed this to a let and the issue went away. This seems odd since this encoder variable is only being passed through to those other preceding functions.

It might be something worth looking into. Since I'm submitting my work, I'm making these hacky edits - limited by time to investigate this any further but thought I'd raise the issue if there is one that I'm not seeing :D

emit 'sync'

Checklist

[x] Are you reporting a bug? Use github issues for bug reports and feature requests. For general questions, please use https://discuss.yjs.dev/
[x] Try to report your issue in the correct repository. Yjs consists of many modules. When in doubt, report it to https://github.com/yjs/yjs/issues/

Is your feature request related to a problem? Please describe.

When implementing a Lexical editor with the Collaborative plugin, it expects the provider to emit 'sync' so that it can initialize the state, just like y-websocket

Describe the solution you'd like

When it's clear that everything is synced, emit 'sync'

Describe alternatives you've considered

I did setTimeout(() => provider.emit('sync', [true]), 0) for now ;-)

Implement a peer to peer mesh topology/routing

Is your feature request related to a problem? Please describe.
Multiple webrtc connections create unnecessary load with direct connect to all users. Implement a mesh network topology.

Prior art: https://github.com/lazorfuzz/liowebrtc

Describe the solution you'd like
As seen above, past a certain threshold, implement something like a Kademlia hash table for peer-to-peer mesh network.

Useful example/potential dependency: https://github.com/jeanlauliac/kademlia-dht

Describe alternatives you've considered
I used liowebrtc initially, but the complicated handshakes and necessary wiring made it burdensome. Also, it's just another dependency that duplicates what this library seems intent on doing: improving peer to peer use of yjs

Additional context
It may make sense to do this alonside the potential fixing of #20 as it would require some heavy lifting and additional lifetime maintenance

Allow for or extend checking connectedness of the provider

Is your feature request related to a problem? Please describe.
I want to properly check the connectedness status of the provider, I am unsure if the connected flag of the WebrtcProvider is properly representative of this status, as it is true if the room is created, but not if any networking has been done.

Describe the solution you'd like
One of the following come to mind:

  • The connection being properly represented as a flag so I can check it with e.g. promise.until from lib0
  • Connection events to resolve new promises
  • An async function in the provider connectedAsync that resolves if connected at call time or when the connection is established

Describe alternatives you've considered
Checking the connected flag, but as stated earlier, I am not sure if this is fully representative of what I would expect.

Additional context
I am not certain if a connection status can generally be determined in this configuration and if I am asking for a feature that cannot be implemented.

Node lock version

Trying to install this and getting an error that it requires node version 10. Downgrade to v10 and it complains about
error [email protected]: The engine "node" is incompatible with this module. Expected version ">=12". Got "10.19.0"

Explore options for smaller footprint, browser-based webrtc clients

After installing the y-webrtc package, my unminified JavaScript bundle went from 219.7kb to 417.6kb (197.9kb difference) and my minified bundle went from 90kb to 202kb.

I was naturally curious, so I found BundleBuddy and here's the report they generated.
image

It looks like simple-peer represents the lion's share of the size increase (96kb minified) and a quick glance at the source file indicates there are quite a few nodejs modules being pulled into what is ostensibly meant to run in a browser.

I haven't dug deep into this yet, but thought I'd check in to see if anyone is already looking into ideas here.

Overall outstanding library and thanks so much for all your hard work!

Reactive "connected" property

Checklist

[X] Are you reporting a bug? Use github issues for bug reports and feature requests. For general questions, please use https://discuss.yjs.dev/
[X] Try to report your issue in the correct repository. Yjs consists of many modules. When in doubt, report it to https://github.com/yjs/yjs/issues/

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
On my GUI I'm showing a "connected"/"disconnected" icon. However, the connected property is not reactive.
It would be nice to expose the connected property as an event, or make it otherwise reactive.
I see that an "Observable" class is used, I am not familiar with it. Could it be that SyncedStore already makes this reactive?

Describe alternatives you've considered
I have no (good) alternative ideas.

Additional context
Related:
https://discuss.yjs.dev/t/vue3-syncedstore-reactivity/1683

Over-strict type declaration for the options of WebRtcProvider

Please save me some time and use the following template. In 90% of all issues I can't reproduce the problem because I don't know what exactly you are doing, in which environment, or which y-* version is responsible. Just use the following template even if you think the problem is obvious.

Checklist

Describe the bug

I'm using TypeScript, and want to pass the URL for a local signaling server to the WebRtcProvider. My code has:

const provider = new WebrtcProvider('testApp', ydoc, { signaling: ['wss://localhost:4444'] })

This produces an error from the TypeScript compiler, because the elements of the peerOpts structure are not marked as optional:

ERROR in src/views/YjsTest.vue:12:57
TS2345: Argument of type '{ signaling: string[]; }' is not assignable to parameter of type 
'{ signaling: string[]; password: string | null; awareness: Awareness; maxConns: number; filterBcConns: 
boolean; peerOpts: any; }'.
  Type '{ signaling: string[]; }' is missing the following properties from type '{ signaling: string[]; 
password: string | null; awareness: Awareness; maxConns: number; filterBcConns: boolean; peerOpts: any; }': 
password, awareness, maxConns, filterBcConns, peerOpts
    10 |
    11 |     const ydoc = new Y.Doc()
  > 12 |     const provider = new WebrtcProvider('dystil', ydoc, { signaling: ['http://localhost:4444'] })
       |                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To Reproduce
Steps to reproduce the behavior:

  1. Create a skeleton app that creates a WebRtcCompiler
  2. pass the URL of a non-default signalling server
  3. compile with TypeScript
  4. See error

Expected behavior

It should be possible to pass only a subset of the elements of the options, with the non-specified options falling back to their default values

Screenshots

Not applicable

Environment Information

  • Typescript 4.4.4
  •   "y-webrtc": "^10.2.0",
      "yjs": "^13.5.16"
    

Additional context
Add any other context about the problem here.

Issue when peer got reconnected after disconnected by using webrtc provider

Describe the bug
I’m currently trying to run two instances of this demo (but changed the provider to webrtc) on my local (using two different port). When one instance (user1) got disconnected and then got reconnected again, at first both content from user1 and user will get synced again.

But when user1 tries to add new content, user2 will not receive the update from user1 anymore, but update user2 will still be received by user1 (the updates will become one-direction only).

But this issue didn’t occur when I tried this by using websocket provider. Is there some extra configuration needed to make sure y-webrtc can handle this scenario? or is this a bug on y-webrtc? please let me know if I’m missing something or if you need more information.

To Reproduce

  1. Clone this example, change the provider from websocket to webrtc, like this:
  // const provider = new WebsocketProvider('wss://demos.yjs.dev', 'prosemirror-demo', ydoc) #commented
  const provider = new WebrtcProvider('demo-ywebrtc', ydoc);
  1. Run two instances of the example on your local
  2. Make one of the instances offline
  3. Make that instance online again
  4. Now changes from that instance won't get synced with other instances anymore, but changes from other instances will still get synced with that instance.

Expected behavior
The reconnected instance's update will get propagated to other peers as usual.

Screenshots
Not a screenshot, but I’ve created a short screencast to reproduce the issue in case my explanation is not clear enough.

Environment Information

Edit: Still got the same issue on [email protected]

Additional context
I don't know if this is relevant, but this issue is also occurring on a real connection test (using two ubuntu VM connected by VirtualBox's default NAT network config, and by making one of the VM offline).

TypeError: Cannot read property 'encrypt' of undefined

Describe the bug
I was trying to disconnect and connect the room but encounter an error

TypeError: Cannot read property 'encrypt' of undefined
Module.encrypt

  49 |   return /** @type {PromiseLike<Uint8Array>} */ (promise.resolve(data))
  50 | }
  51 | const iv = crypto.getRandomValues(new Uint8Array(12))
> 52 | return crypto.subtle.encrypt(
     | ^  53 |   {
  54 |     name: 'AES-GCM',
  55 |     iv

To Reproduce
Steps to reproduce the behavior:

  1. attempts to disconnect room
  2. attempts to destroy room
  3. Error produced

Expected behavior
It should properly destroy the room

Environment Information

  • Chrome
  • yjs v13.5.5, y-webrtc v10.2.0

add STUN/TURN servers after the provider is made

services like metered.ca require using an API to get the STUN and TURN servers. the problem is that waiting for the API to respond adds unnecessary latency to syncronizing with other peers which might not need TURN.

being able to add servers after it has been created solves this.

API modifications proposal

This is a companion issue for features proposal to yrs-webscoket (y-websocket compatible Rust library).

  1. Support for passing messages of any size: right now WebRTC has a limitation over the max message size. This limit can be easier reached with bigger documents - esp. 16KiB limit for Firefox ↔ Chrome. While this should be solved at a transport level, in practice the issue stays and somebody has to fix it. We could add message chunking/assembling at y-sync protocol level ie. by using y-sync protocol extensions capabilities. Also add configuration option to message chunk size (make it 16 KiB by default for seamless support between all browsers).
  2. Support multiplexing single connection over multiple documents: right now the limitation of y-webrtc WebRTCProvider is that it requires a unique connection per document. If users have multiple active documents, they need multiple active connections. WebRTC support having multiple non-blocking data channels over a single connection and we should support this as well. Having extra data channels doesn't cost anything. The only limitation of the WebRTC protocol itself is that AFAIK all data channels must be defined up-front and they cannot be added/removed while connection is active.
  3. Support alternatives for signalling server: currently to exchange signalling info we need a hosted WebSocket server. It would be great if we could abstract that part to allow alternative options like ie. Apple's Bonjour discovery protocol. EDIT: after checking for available options, it seems that currently browsers don't support bonjour/zeroconf, the only option would be to run signalling server over ie. bluetooth, which doesn't seem to be very useful atm. for the scope of this library.

Since y-webrtc is build on top of simple-peer, some of these changes should be probably implemented over there. We might potentially contribute to that project, fork it if necessary or thing about alternatives.

Library fails with missing global declarations when run inside nodejs (ES6)

I'm attempting to run a Webrtc client within browsers and nodejs.

The browser build seems to work well. The nodejs (ES6 modules) side is having some problems.

Here is some sample code that triggers the first error from nodejs (in a file named, demo.js).

import {WebrtcProvider} from 'y-webrtc';
import * as Y from 'yjs';

const id = 1;
const config = {
  signaling: ['ws://localhost:4444'],
  maxConns: 50 + Math.floor(Math.random() * 15),
  peerOpts: {},
};

const doc = new Y.Doc();
const webrtc = new WebrtcProvider(id, doc, config);

Running this with node demo.js fails with the following error:

file:///[proj]/node_modules/lib0/websocket.js:25
    const websocket = new WebSocket(wsclient.url)
                      ^

ReferenceError: WebSocket is not defined
    at setupWS (file:///[proj]/node_modules/lib0/websocket.js:25:23)
    at new WebsocketClient (file:///[proj]/node_modules/lib0/websocket.js:122:5)
    at new SignalingConn (file:///[[proj]/node_modules/y-webrtc/src/y-webrtc.js:473:5)
    at file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:610:75
    at Module.setIfUndefined (file:///[proj]/node_modules/lib0/map.js:49:24)
    at file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:610:33
    at Array.forEach (<anonymous>)
    at WebrtcProvider.connect (file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:609:24)
    at new WebrtcProvider (file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:595:10)
    at file:///proj]/demo.js:19:16

I was able to work around this issue by adding the following to the top of my application entry point (above any imports).

import WebSocket from 'ws';
Object.assign(global, {WebSocket});

This allows the service to start, but whenever a connection is made from a separate browser client, the following error is thrown:

Exit with: Error: Secure random number generation is not supported by this browser.
Use Chrome, Firefox or Internet Explorer 11
    at t.exports (/[proj]/node_modules/simple-peer/simplepeer.min.js:6:37193)
    at new p (/[proj]/node_modules/simple-peer/simplepeer.min.js:6:79527)
    at new WebrtcConn (file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:183:17)
    at file:///[proj]/teak/node_modules/y-webrtc/src/y-webrtc.js:513:68
    at Module.setIfUndefined (file:///proj]/node_modules/lib0/map.js:49:24)
    at execMessage (file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:513:23)
    at file:///[proj]/node_modules/y-webrtc/src/y-webrtc.js:530:13
    at file:///[proj]/node_modules/lib0/observable.js:73:90
    at Array.forEach (<anonymous>)
    at SignalingConn.emit (file:///[proj]/node_modules/lib0/observable.js:73:77)

After digging a little bit, it looks like y-webrtc is loading a pre-minified build of simple-peer that may have been built for the browser and not nodejs.

I was unable to get a similar global hack working for this issue, and instead forked the y-webrtc repo into a vendor folder, loaded as a git submodule and referred to that version from my node application and the npm published version from my browser client code.

I also had to add the following to my imports and update the peerOpts object:

import wrtc from 'wrtc';

const config = {
  signaling: ['ws://localhost:4444'],
  maxConns: 50 + Math.floor(Math.random() * 15),
  peerOpts: {
    wrtc,
  },
};

Unfortunately, wrtc requires node-pre-gyp and node-gyp, which seem to be in a weird state at the moment, so I had to install those both globally, delete my node_modules folder and reinstall local modules in order to get the thing to work.

Expected behavior
The library should work for either node or browser clients

Environment Information

  • node --version: v16.14.2
  • Node in ES6 module mode (e.g., package.json includes "type": "module" entry).
  • uname -a: Linux beefcake 5.13.0-39-generic #44~20.04.1-Ubuntu SMP Thu Mar 24 16:43:35 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
  • y-webrtc: 10.2.3
$ npm ls yjs
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
└── [email protected]

Additional context
FWIW, here's the commit that worked around the issue.

FWIW 2, I also tried pointing into the unminified build of simple-peer, but that did not want to build successfully for the browser (under esbuild with es6 modules) as there were nodejs modules being required in that dependency.

I understand that these issues probably aren't going to be trivial to solve from y-webrtc, so thought I'd post here in case others have the same problems, at least we can discuss workarounds.

How to add twilo turn server in y-webrtc codemirror? Default sigalling server does not work for different network.

Checklist

[ ] Are you reporting a bug? Use github issues for bug reports and feature requests. For general questions, please use https://discuss.yjs.dev/
[ ] Try to report your issue in the correct repository. Yjs consists of many modules. When in doubt, report it to https://github.com/yjs/yjs/issues/

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Allow custom signalling classes

I have a websocket connection that expects a JSON-RPC envelope (Holochain). To support this I need to wrap the message that is sent over the websocket in the SignalingConn class. It would be great if the class would be defined as a constructor argument so it would not be needed to override the WebrtcProvider.connect(). Alternatively the SignalingConn class could be returned by a getSignalingConnectionClass() hook that can be overrided more easily.

const signalingConn = map.setIfUndefined(signalingConns, url, () => new SignalingConn(url))

filterBcConns = true doesn't work

Using filterBcConns: true in options still uses broadcast channels instead of a webrtc connection for tabs in the same browser. Tested on Chrome: Version 79.0.3945.79 (Official Build) (64-bit) and Firefox: 74.0 (64-bit) on Ubuntu 18.04

Use existing (3rd party) signaling server implementation

Checklist

Is your feature request related to a problem? Please describe.
Currently y-webrtc uses a custom server for signaling. I think this is not ideal because it's a comparatively niche thing. Sometimes public servers go down (#43), creating a big headache for app developers that now have to set up a new server (that might go down as well). Having a custom server also adds maintenance costs.

Describe the solution you'd like
Rely on another existing server that can be used for signaling. For example, https://github.com/peers/peerjs-server. Or, I heard, you can use https://github.com/centrifugal/centrifugo for signaling (there is a concept of rooms (channels) as well).

Describe alternatives you've considered

None

Additional context

I'm not 100% sure this is a good idea, and I didn't look into details of how the current signaling server works, or how Centrifugo works. It's just a high-level idea that I think it makes sense to strive for.

y-webrtc doesn't work on different browsers

Content doesn't sync between different browser, or on the same browser when using the incognito mode.

I guess I am missing some configuration or something.

Any help would be appreciated.

    // frontend code...
    const doc = new Y.Doc();
    doc.clientID = randomInt(0, 100);

    const provider = new WebrtcProvider(room, doc, {
      signaling: ["ws://localhost:4444"],
    });
    const type = doc.getText("monaco");
    const awareness = provider.awareness;

    const binding = new MonacoBinding(
      type,
      editorRef.current.getModel(),
      new Set([editorRef.current]),
      awareness
    );

signaling server - https://github.com/yjs/y-webrtc/blob/master/bin/server.js

this.getStateVector is not a function

Hello,

I am currently trying to use yjs, the y-xmpp connector looks like it's working fine but when I try to use the same code for the WebRTC implementation it crashes.

The error appears when I execute the following code on more than one browser:

var options = {}
var connector = new Y.WebRTC("hello", options);
var y = new Y(connector)

If I run this piece of code on a single browser no error is prompted, while if I run it on two or more browsers it return the this.getStateVector is not a function error.
It looks like that the error appears when I try to create the y object while the connector has already some connection.

Use Authentication for allowing/blocking access

I like the signaling server you provide at https://github.com/yjs/y-webrtc/blob/master/bin/server.js, yet I think it makes sense for me to provide it with some authorization depending on a provided JWT token within the request. I think I know that I would have to provide such a thing at https://github.com/yjs/y-webrtc/blob/master/bin/server.js#L127. However, I do not know when I call

const provider = new WebrtcProvider('your-room-name', ydoc, { password: 'optional-room-password' })

or so, where I can send the JWT token in the request.

It would be great if you could help me here.

public signaling servers down?

Hallo,

My app cannot connect to ['wss://signaling.yjs.dev', 'wss://y-webrtc-signaling-eu.herokuapp.com', 'wss://y-webrtc-signaling-us.herokuapp.com']
image

A few weeks back this wasn't the case.

Code used:

import { WebrtcProvider } from "y-webrtc";
import { Doc } from "yjs";

const doc = new Doc();

export const webrtcProvider = new WebrtcProvider(
  "vZ#4h2%60$1H",
  doc,
  { password: "wMrg3@4WVf^q@iK6xukh@86&fCY5GmvX" }
);

export const disconnect = () => webrtcProvider.disconnect();
export const connect = () => webrtcProvider.connect();

// Get the provider's awareness API
export const awareness = webrtcProvider.awareness;

import { Avatar, Divider, Grid, Stack, Tooltip } from "@mui/material";
import ActionDialog from "@src/components/ActionDialog";
import { MIconButton } from "@src/components/minimals/@material-extend";
import useAuth, { User } from "@src/hooks/useAuth";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router";
import { useUsers } from "y-presence";

export type YUser = User & { name: string, orderId: number | null };
export type UseUsers = Map<number, YUser>;
import { awareness } from "../syncedStores/orderSyncedStore";

export default function SyncedUsers({ order_id }: { order_id: number }) {
  const { t: dashboardT } = useTranslation("dashboard");
  const { user } = useAuth();
  const {id} = useParams()
  console.log("synced",{id})

  useEffect(() => {
    if (user && id) {
      const yUser: YUser = {
        name: `${user.first_name} ${user.last_name}`,
        ...user,
        orderId : Number(id),
      };
      awareness.setLocalState(yUser);
    }
  }, [id, user]);

  const users = useUsers(awareness) as UseUsers;
  const orderUsers = Array.from(users.entries()).filter(
    ([_, u]) => u.orderId !== order_id && u.id !== user?.id
  );
  
  return (
    <>
      <Stack gap={2} direction={"row"} ml={"auto"}>
        {orderUsers.map(([_, value]) => {
          return <YUserAvatar key={value.id} user={value} />;
        })}
      </Stack>
      {orderUsers.length >= 1 && (
        <ActionDialog title={dashboardT("warning")} open={true}>
          {dashboardT("there_are_other_users_in_this_order")}
        </ActionDialog>
      )}
    </>
  );
}

export function YUserAvatar({ user }: { user: YUser }) {
  const { t: commonT } = useTranslation("common");
  return (
    <ActionDialog
      title={`${user.name}`}
      openButton={(setOpen) => (
        <Tooltip title={user.name}>
          <MIconButton
            onClick={() => setOpen(true)}
            sx={{
              padding: 0,
              width: 44,
              height: 44,
            }}
          >
            <Avatar
              alt="User avatar"
              sx={{
                mx: "auto",
                bgcolor: "primary.main",
                color: "text.primary",
              }}
            >
              {user.first_name.slice(0, 1)}
              {user.last_name.slice(0, 1)}
            </Avatar>
          </MIconButton>
        </Tooltip>
      )}
    >
      <Grid container>
        <Grid item xs={3}>
          Email
        </Grid>
        <Grid item xs={9}>
          {user.email}
        </Grid>
        <Divider />
        <Grid item xs={3}>
          Rol
        </Grid>
        <Grid item xs={9}>
          {commonT(user.role)}
        </Grid>
        <Divider />
      </Grid>
    </ActionDialog>
  );
}

I would like to deploy my own signaling server but find the tuturial to be unclear. Could anyone help me with this?

Error when updating text field with long string

Checklist

Describe the bug
I'm adding a long string (~300K characters) to a Y.Text type, which causes webrtc errors to show (ERR_SET_REMOTE_DESCRIPTION) on the other clients. The text is never synced. Interestingly, it's possible to add an even longer string by adding it in smaller increments.

I'm not sure if there is an inherent limit to updates when using y-webrtc, I couldn't find anything documented, so I'm filing this as a bug.

Bonus question: is there some way to catch these types of errors so I can display an error message? This is a contrived example but I'm actually running into a variation of this error in the application I'm building.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/cranky-framework-qmsorf?file=/src/index.js
  2. Open the sandbox again on another machine or another browser
  3. In first window, Click on "Add long string"
  4. Open console of the other window
  5. See error, and observe that the string is not synced.

As mentioned, it's easily possible to sync a string that is longer than 500k chars by repeatedly using the "Add short string" button, but adding the long string at once seems to cause problems.

Expected behavior
The string should be synced and no error thrown.

Environment Information
Happens in Chrome and FF

  • yjs 13.5.45
  • y-webrtc 10.2.4

Why keys for webrtcPeers?

Following the code in this PR's comment #6 (comment) doesn't work. provider.on("peers", (e) => sends out an event with no access to the simple-peer objects (webrtcPeers is a list of strings). I have to instead do provider.room.webrtcConns.get(peerId).peer.

It's because of this line:

webrtcPeers: Array.from(room.webrtcConns.keys()),

Problem with firefox and y-webrtc

Describe the bug
I am currently building a collab whiteboard using SyncedStore (wrapper for yjs) and Sveltekit. So far everything works normally in Chrome. I use the y-webrtc provider for the SyncedStore and the connection is established successfully. However, if I use Firefox initially, no connection to the room is established. If I use a Chrome in parallel (Firefox next door still open in the non-synced tab) and establish the connection, Firefox also establishes the connection in parallel and synchronizes the document. I have attached a video below, which shows the exact procedure.

Expected behavior
Firefox connects to the y-webrtc provider just like Chrome when you open the page and synchronizes the document.

Environment Information

  • Firefox 116.0.3
  • Chrome 116.0.5845.111

Additional context

import { syncedStore, getYjsDoc } from '@syncedstore/core';
import { svelteSyncedStore } from '@syncedstore/svelte';
import { env } from '$env/dynamic/public';
import type { RetroBoard } from '$lib/types';
import { WebrtcProvider } from 'y-webrtc';

export const store = syncedStore({
	board: {} as RetroBoard
});
export const svelteStore = svelteSyncedStore(store);

const doc = getYjsDoc(store);

const provider = new WebrtcProvider('retrorealm-room', doc, {
	signaling: [env.PUBLIC_SIGNALING_SERVER],
	filterBcConns: false
});

export const awareness = provider.awareness;
webrtc_firefox_bug.mp4

List of signaling servers

It looks like the default one is currently down. It would be nice to provide a small list somewhere (wiki?) to allow developpers to set it up quickly :)

For example, I tried this:

var connector = new Y.WebRTC("leaflet-yjs", {url: "https://signaling.simplewebrtc.com"})

with no luck :/

Implment Packet buffer for sending

Most browsers currently have a limit for message size:

https://stackoverflow.com/questions/15435121/what-is-the-maximum-size-of-webrtc-data-channel-messages

My testing on chrome gets the following error:
Attempting to send message of size 988606 which is larger than limit 262144

Although the spec is expected to be built into browsers, these arbitrary size limits result in no error message that I see in the console. The above comes from running debug version of chrome.

When I tried to create my own 'sync' system before switching to try y-webrtc, I used protocol buffers to wrap updates, and hashed the data to keep them order/organized. I don't have any real knowledge about best practices, however.

Silencing "Unable to compute message"

In my app I'm using the simple-peer method peer.send(mymessage) to get around some of the overhead(?) involved in the yjs CRDT: i.e., to broadcast cursor position. However, because of the switch statement in this library, unknown types of messages throw an error:

console.error('Unable to compute message')

Could you add a way to silence this error or otherwise allow custom messages to be handled?

Error: A Yjs Doc connected to room "#room-name" already exists

Describe the bug
I'm getting an error when reconnecting and calling new WebrtcProvider() on a page refresh or after a disconnect.

To Reproduce
Steps to reproduce the behavior:

  const provider = new WebrtcProvider(name, doc, {
    password,
    signaling: servers,
    awareness,
  });

Then call provider.disconnect() or provider.destroy(), or just try connecting again with the same code and params as above.

  1. Get error: Error: A Yjs Doc connected to room "#room-name" already exists

Expected behavior
A new provider can be created and sync to the existing room without error. Should return the provider.

Environment Information

  • Happens both in Browser [Chrome] and Node [Vitest]
  • "y-webrtc": "^10.2.5"
  • "yjs": "^13.5.16"

Screenshot 2023-05-06 at 18 16 48

Screenshot 2023-05-06 at 18 16 13

Screenshot 2023-05-06 at 18 15 51

Sorry not sure why sourcemaps aren't working, but I've found where it originates:
// src/y-webrtc.js
const openRoom = (doc, provider, name, key) => {
  // there must only be one room
  if (rooms.has(name)) {
    throw error.create(`A Yjs Doc connected to room "${name}" already exists!`)
  }
  const room = new Room(doc, provider, name, key)
  rooms.set(name, /** @type {Room} */ (room))
  return room
}

Emit events when the connected state changes

Is your feature request related to a problem? Please describe.

I'd like a 'connect' and 'close' events to be emitted after y-webrtc has connected/disconnected so that I can show a connection status badge without the need to poll every so often the 'connected' variable in the provider

'peers' event on on SignalingConn emits 'added' peer from peer's close event

Checklist

Describe the bug

class WebrtcConn {
   ...
   peer.on('close' => ... announceSignalingInfo(room))
}

generates an announcement which triggers remote peers:

class SignalingConn {
             ...
             case 'publish':
             ...
             room.provider.emit('peers', [{
                removed: [],
                added: [data.from],
                webrtcPeers: Array.from(room.webrtcConns.keys()),
                bcPeers: Array.from(room.bcConns)
              }])

message peers then says this peer was added which is not what's happening, as peer is closing.

To Reproduce
Steps to reproduce the behavior:

Open two browsers with peers connected. Listen to room.provider.peers for 'peers' and you'll see the event.removed shows the peerId, but then another events.added shows the peer added again

Expected behavior
When a peer closes, it should not generate a peers event that has the peer added.

Screenshots
debug:

removed:webrtc:[98ee6477-5037-49ee-bd20-b8f69928dade] WebrtcProvider {…}

y-webrtc.js?9b73:270 announceSignalingInfo Room {…} true
eval @ y-webrtc.js:294
announceSignalingInfo @ y-webrtc.js:289
eval @ y-webrtc.js:245
r.emit @ simplepeer.min.js:6
eval @ simplepeer.min.js:6
y-webrtc.js?9b73:270 announceSignalingInfo Room {…} true
eval @ y-webrtc.js:294
announceSignalingInfo @ y-webrtc.js:289
eval @ y-webrtc.js:245
r.emit @ simplepeer.min.js:6
eval @ simplepeer.min.js:6
y-webrtc.js?9b73:270 announceSignalingInfo Room {…} true
eval @ y-webrtc.js:294
announceSignalingInfo @ y-webrtc.js:289
eval @ y-webrtc.js:245
r.emit @ simplepeer.min.js:6
eval @ simplepeer.min.js:6
y-webrtc.js?9b73:491 {to: "abb23ec9-66aa-4cd3-8f4c-9f9e7c58bc83", from: "98ee6477-5037-49ee-bd20-b8f69928dade", type: "signal", signal: {…}} "98ee6477-5037-49ee-bd20-b8f69928dade"
emitPeerChange @ y-webrtc.js:515
execMessage @ y-webrtc.js:532
Promise.then (async)
eval @ y-webrtc.js:539
eval @ observable.js:78
emit @ observable.js:78
websocket.onmessage @ websocket.js:50
SyncPeers.js?a801:234

added:webrtc:[98ee6477-5037-49ee-bd20-b8f69928dade] 

Environment Information
Version 89.0.4389.82 (Official Build) snap (64-bit)
"y-webrtc": "^10.1.7"
"y-protocols": "^1.0.4",
"yjs": "^13.5.2"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.