Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Promise-like API for PeerJS #1127

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft

feat: Promise-like API for PeerJS #1127

wants to merge 11 commits into from

Conversation

jonasgloning
Copy link
Member

@jonasgloning jonasgloning commented Aug 28, 2023

Hey @WofWca, you recently proposed a Promise-based API in #924 (comment).

This is a quick draft of how this could look like. Is this roughly how you would imagine it?

(Only for Peer, connections are not included yet).

Implementation

Edit tasklist title
Beta Give feedback Tasklist Implementation, more options

Delete tasklist

Delete tasklist block?
Are you sure? All relationships in this tasklist will be removed.
  1. private then: (onfulfilled?: (value: IDataConnection) => any, onrejected?: (reason: PeerError<DataConnectionErrorType>) => any,) => void;
    Options
  2. Mediastream
    Options

Documentation

Edit tasklist title
Beta Give feedback Tasklist Documentation, more options

Delete tasklist

Delete tasklist block?
Are you sure? All relationships in this tasklist will be removed.
  1. Inline
    Options
  2. Website
    Options

@jonasgloning
Copy link
Member Author

Hey @WofWca, I just added add await peer.connect(...):

const peer = new Peer();
peer.once("open", id => {
  const conn = peer.connect(remote_id)
  conn.once("open, () => {
   /* connection established */
  })
})

should be equivalent to

const peer = await new Peer();
const conn = await peer.connect(remote_id);
/* connection established */

Example with error handling:

try {
const peer = await new Peer();
await peer.connect(not_existing_peer);
} catch (error) {
if (error.type === "peer-unavailable") {
messages.textContent = "Success: Peer unavailable";
} else {
errors.textContent += JSON.stringify(error);
}
}
})();


I'd love a quick review, if you have the time, to see if this meets your expectations.

Copy link
Contributor

@WofWca WofWca left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, sorry for such a late response.
I stated my concern about a thing. Otherwise overall looks like an improvement. I hope it doesn't become a maintenance burden.

Making DataConnection thenable is a fun and original idea, though I was thinking about making connect() return an actual Promise (or, for a non-breaking change, adding a new function that does this), since it's not really possible to send() on a DataConnection that is not open, and send() is the main purpose of DataConnection.
I'm not sure if it's a good idea though. It sounds like a trade-off between control and convenience. Maybe having two functions - one Promise-based, the other like it is now - is the way.

Also if we're going for this I think it makes sense to do the same for MediaConnection.

Comment on lines 70 to 73
// We don’t need to worry about cleaning up listeners here
// `await`ing a Promise will make sure only one of the paths executes
this.once("open", () => onfulfilled(this));
this.once("error", onrejected);
Copy link
Contributor

@WofWca WofWca Sep 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though I believe the listeners would still remain in memory (a.k.a. a memory leak). Though currently then can only be executed once, so no big deal.
If not, some apps might have async code that does something like connectionPromise.then(c = c.send('something')).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great point. Now removing the other listener when firing an event:

const onOpen = () => {
this.off("error", onError);
// Remove 'then' to prevent potential recursion issues
// `await` will wait for a Promise-like to resolve recursively
resolve?.(proxyWithoutThen(this));
};
const onError = (err: PeerError<`${ErrorType}`>) => {
this.off("open", onOpen);
reject(err);
};

Comment on lines 66 to 68
// Remove 'then' to prevent potential recursion issues
// `await` will wait for a Promise-like to resolve recursively
delete this.then;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this mean you cannot do e.g.

const connectionPromise = peer.connect(peer);
connectionPromise.then(() => console.log(1));
connectionPromise.then(() => console.log(2));

and

const connectionPromise = peer.connect(peer);
connectionPromise
  .then(() => console.log(1))
  .then(() => console.log(2))
  .catch(e => console.error(e))

? Also I think this will behave in an unexpected way, because the second await would finish before the connection is actually open:

const connectionPromise = peer.connect(peer);
(async () => {
  await connectionPromise;
  console.log('connected');
})();
(async () => {
  await connectionPromise;
  console.log('connected');
  console.error('Sike! Not connected');
})();

While I think the first two examples are fine as long as it's clear to the users that it's not a perfect Promise implementation, the third one seems dangerous to me, it would be very hard to catch such a bug.

Here's a doc I found on how to make a good thenable: https://promisesaplus.com/#point-36

I think there must be an easy way to implement this by proxying then (and catch?) to a real Promise object.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original intention was to use then as a hack to be able to use await. It was even marked private as to explicitly disallow the first two.
But great suggestion, there's no good reason for this. All PeerJS objects now implement Promise (including catch/finally). then internally constructs and returns a real Promise, meaning the first two work correctly.

You are totally right, 3 is confusing. I hope I adequately addressed this with this

// Remove 'then' to prevent potential recursion issues
// `await` will wait for a Promise-like to resolve recursively
resolve?.(proxyWithoutThen(this));

Instead of patching this at runtime I create a Proxy without a then property. Subsequent calls to then will have the some consistent behavior.

lib/peer.ts Outdated Show resolved Hide resolved
@jonasgloning
Copy link
Member Author

jonasgloning commented Sep 7, 2023

Thank you for your feedback! Please let me know if there's anything I can do to incentivize you to review future pull-requests.

I favor making Peer and DataConnection thenable on their own instead of creating a new method that returns a Promise, as it enables the setting of event listeners in a single step:

const peer = await new Peer().on("call", ...).on("disconnected", ...).once("open", ...)
const conn = await peer.connect().on("data", ...)

@jonasgloning jonasgloning marked this pull request as ready for review September 7, 2023 14:22
@jonasgloning jonasgloning marked this pull request as draft September 7, 2023 14:48
This requires some `// @ts-expect-error` until we find out how to tell
the typescript compiler what events are available
@WofWca
Copy link
Contributor

WofWca commented Nov 20, 2023

Sorry for such a late response. You asked a tough question.

if there's anything I can do to incentivize you to review future pull-requests

I don't think there is anything specific. I'm not that involved in the PeerJS project. I don't use it too much, and I don't know the codebase and the domain well, so I probably won't be the most productive person for most of the MRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants