-
Notifications
You must be signed in to change notification settings - Fork 2
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
initial invite api #217
Merged
Merged
initial invite api #217
Changes from 23 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
811591f
initial invite api
sethvincent 88d06c9
small type fixes
sethvincent 9011e1a
speculative isMember and addProject function usage
sethvincent fad5bf7
Merge branch 'main' into invite-api
achou11 9a82b7f
Merge branch 'main' into invite-api
achou11 057d8d6
fix type errors in tests
achou11 754ea9c
revert manual change to generated rpc type
achou11 09ec579
types improvements
achou11 1d30037
variable names and types updates
achou11 284cffe
revert unused type change in keyToId util
achou11 fafbef5
revert change in tests/rpc.js to clean up PR diff
achou11 a7f6e85
fix lint errors
achou11 fc3ef15
fix usage of projectKeyToPublicId
achou11 7f849ee
move retrieval of invite in respond method
achou11 d9b147e
fix isMember mock in tests
achou11 69a560a
small optimizations to respond method
achou11 08a5eaf
add test for autoresponding with already response
achou11 8003252
minor tests refactor
achou11 efe181a
add event typing for InviteApi and update emitted value
achou11 b2ff8d4
fix addProject mock in tests
achou11 5c3f473
refactor respond method to not be recursive
achou11 09738ca
fix lint error
achou11 8168ebb
Cleanup code and add more tests
gmaclennan 146606f
Merge branch 'main' into invite-api
achou11 54b9585
add test for when addProject throws
achou11 cb1a2e7
add test checking payload of invite-received event
achou11 2c64ed2
add test for sending reject response after invitor disconnects
achou11 bccebdb
add test for sending already response after invitor disconnects
achou11 9407be3
Merge branch 'main' into invite-api
achou11 693af73
use public id instead of project id for public interface
achou11 370b4be
remove commented-out line
achou11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,199 @@ | ||
// @ts-check | ||
import { TypedEmitter } from 'tiny-typed-emitter' | ||
import { InviteResponse_Decision } from './generated/rpc.js' | ||
import { projectKeyToId } from './utils.js' | ||
|
||
/** | ||
* @typedef {Object} InviteApiEvents | ||
* | ||
* @property {(info: { projectId: string, projectName?: string, peerId: string }) => void} invite-received | ||
*/ | ||
|
||
/** | ||
* @template K | ||
* @template V | ||
* @extends {Map<K, Set<V>>} | ||
*/ | ||
class MapOfSets extends Map { | ||
/** @param {K} key */ | ||
get(key) { | ||
const existing = super.get(key) | ||
if (existing) return existing | ||
const set = new Set() | ||
super.set(key, set) | ||
return set | ||
} | ||
} | ||
|
||
/** | ||
* @extends {TypedEmitter<InviteApiEvents>} | ||
*/ | ||
export class InviteApi extends TypedEmitter { | ||
// Maps project id -> set of device ids | ||
/** @type {MapOfSets<string, string>} */ | ||
#peersToRespondTo = new MapOfSets() | ||
|
||
// Maps project id -> { invite, fromPeerId } | ||
/** @type {Map<string, { fromPeerId: string, invite: import('./generated/rpc.js').Invite }>} */ | ||
#pendingInvites = new Map() | ||
|
||
#isMember | ||
#addProject | ||
|
||
/** | ||
* @param {Object} options | ||
* @param {import('./rpc/index.js').MapeoRPC} options.rpc | ||
* @param {object} options.queries | ||
* @param {(projectId: string) => Promise<boolean>} options.queries.isMember | ||
* @param {(invite: import('./generated/rpc.js').Invite) => Promise<void>} options.queries.addProject | ||
*/ | ||
constructor({ rpc, queries }) { | ||
super() | ||
this.rpc = rpc | ||
this.#isMember = queries.isMember | ||
this.#addProject = queries.addProject | ||
|
||
this.rpc.on('invite', (peerId, invite) => { | ||
this.#handleInvite(peerId, invite).catch(() => { | ||
/* c8 ignore next */ | ||
// TODO: Log errors, but otherwise ignore them, but can't think of a reason there would be an error here | ||
}) | ||
}) | ||
} | ||
|
||
/** | ||
* @param {string} peerId | ||
* @param {import('./generated/rpc.js').Invite} invite | ||
*/ | ||
async #handleInvite(peerId, invite) { | ||
const projectId = projectKeyToId(invite.projectKey) | ||
const isAlreadyMember = await this.#isMember(projectId) | ||
|
||
if (isAlreadyMember) { | ||
this.#sendAlreadyResponse({ peerId, projectId }) | ||
return | ||
} | ||
|
||
const peerIds = this.#peersToRespondTo.get(projectId) | ||
peerIds.add(peerId) | ||
|
||
if (this.#pendingInvites.has(projectId)) return | ||
|
||
this.#pendingInvites.set(projectId, { fromPeerId: peerId, invite }) | ||
this.emit('invite-received', { | ||
// TODO: Should this be the project public ID since it can be exposed to the client? | ||
// Probably would require changing the public methods to accept the public ID | ||
// and using the public ID for #invites and #peersToRespondTo keys instead | ||
peerId, | ||
projectId, | ||
projectName: invite.projectInfo?.name, | ||
}) | ||
} | ||
|
||
/** | ||
* @param {string} projectId | ||
* @returns {Promise<void>} | ||
*/ | ||
async accept(projectId) { | ||
const isAlreadyMember = await this.#isMember(projectId) | ||
const peersToRespondTo = this.#peersToRespondTo.get(projectId) | ||
|
||
if (isAlreadyMember) { | ||
for (const peerId of peersToRespondTo) { | ||
this.#sendAlreadyResponse({ peerId, projectId }) | ||
} | ||
return | ||
} | ||
|
||
const pendingInvite = this.#pendingInvites.get(projectId) | ||
|
||
if (!pendingInvite) { | ||
throw new Error(`Cannot find invite for project with ID ${projectId}`) | ||
} | ||
|
||
try { | ||
this.#sendAcceptResponse({ peerId: pendingInvite.fromPeerId, projectId }) | ||
// TODO: Add another RPC message to confirm invitee is written into project after accepting | ||
} catch (e) { | ||
// TODO: If can't accept invite because peer it was sent from has | ||
// disconnected, and another still-connected peer has sent an invite, then | ||
// emit another invite-received event | ||
throw new Error('Could not accept invite: Peer disconnected') | ||
} | ||
|
||
try { | ||
await this.#addProject(pendingInvite.invite) | ||
} catch (e) { | ||
// TODO: Add a reason for the user | ||
throw new Error('Failed to join project') | ||
} | ||
|
||
// Respond to the remaining peers with ALREADY | ||
for (const peerId of peersToRespondTo) { | ||
if (peerId === pendingInvite.fromPeerId) continue | ||
this.#sendAlreadyResponse({ peerId, projectId }) | ||
} | ||
} | ||
|
||
/** | ||
* @param {string} projectId | ||
* @returns {Promise<void>} | ||
*/ | ||
async reject(projectId) { | ||
if (!this.#pendingInvites.has(projectId)) { | ||
throw new Error(`Cannot find invite for project with ID ${projectId}`) | ||
} | ||
for (const peerId of this.#peersToRespondTo.get(projectId)) { | ||
this.#sendRejectResponse({ peerId, projectId }) | ||
} | ||
} | ||
|
||
/** | ||
* Will throw if the response fails to be sent | ||
* | ||
* @param {{ peerId: string, projectId: string }} opts | ||
*/ | ||
#sendAcceptResponse({ peerId, projectId }) { | ||
const projectKey = Buffer.from(projectId, 'hex') | ||
this.rpc.inviteResponse(peerId, { | ||
projectKey, | ||
decision: InviteResponse_Decision.ACCEPT, | ||
}) | ||
} | ||
|
||
/** | ||
* Will not throw, will silently fail if the response fails to send. | ||
* | ||
* @param {{ peerId: string, projectId: string }} opts | ||
*/ | ||
#sendAlreadyResponse({ peerId, projectId }) { | ||
const projectKey = Buffer.from(projectId, 'hex') | ||
try { | ||
this.rpc.inviteResponse(peerId, { | ||
projectKey, | ||
decision: InviteResponse_Decision.ALREADY, | ||
}) | ||
} catch (e) { | ||
// Ignore errors trying to send an already response because the invitor | ||
// will consider the invite failed anyway | ||
} | ||
} | ||
|
||
/** | ||
* Will not throw, will silently fail if the response fails to send. | ||
* | ||
* @param {{ peerId: string, projectId: string }} opts | ||
*/ | ||
#sendRejectResponse({ peerId, projectId }) { | ||
const projectKey = Buffer.from(projectId, 'hex') | ||
try { | ||
this.rpc.inviteResponse(peerId, { | ||
projectKey, | ||
decision: InviteResponse_Decision.REJECT, | ||
}) | ||
} catch (e) { | ||
// Ignore errors trying to send an reject response because the invitor | ||
// will consider the invite failed anyway | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@gmaclennan any thoughts on the question posed here? my understanding is that whatever's emitted here can be surfaced to a client UI. If that's the case, would it be preferable to expose "public" ids instead of or in addition to what's here, or do we let the class consumer (or end-user client) handle that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
looks like we want this to be the public id so that it can be directly used in other project-related APIs (which accept a public id)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
addressed via 693af73
still a little iffy on this but can do a follow-up if needed