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

initial invite api #217

Merged
merged 31 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
811591f
initial invite api
sethvincent Aug 23, 2023
88d06c9
small type fixes
sethvincent Aug 24, 2023
9011e1a
speculative isMember and addProject function usage
sethvincent Aug 31, 2023
fad5bf7
Merge branch 'main' into invite-api
achou11 Sep 12, 2023
9a82b7f
Merge branch 'main' into invite-api
achou11 Sep 19, 2023
057d8d6
fix type errors in tests
achou11 Sep 19, 2023
754ea9c
revert manual change to generated rpc type
achou11 Sep 19, 2023
09ec579
types improvements
achou11 Sep 19, 2023
1d30037
variable names and types updates
achou11 Sep 20, 2023
284cffe
revert unused type change in keyToId util
achou11 Sep 20, 2023
fafbef5
revert change in tests/rpc.js to clean up PR diff
achou11 Sep 20, 2023
a7f6e85
fix lint errors
achou11 Sep 20, 2023
fc3ef15
fix usage of projectKeyToPublicId
achou11 Sep 20, 2023
7f849ee
move retrieval of invite in respond method
achou11 Sep 20, 2023
d9b147e
fix isMember mock in tests
achou11 Sep 20, 2023
69a560a
small optimizations to respond method
achou11 Sep 20, 2023
08a5eaf
add test for autoresponding with already response
achou11 Sep 20, 2023
8003252
minor tests refactor
achou11 Sep 20, 2023
efe181a
add event typing for InviteApi and update emitted value
achou11 Sep 20, 2023
b2ff8d4
fix addProject mock in tests
achou11 Sep 20, 2023
5c3f473
refactor respond method to not be recursive
achou11 Sep 20, 2023
09738ca
fix lint error
achou11 Sep 20, 2023
8168ebb
Cleanup code and add more tests
gmaclennan Sep 21, 2023
146606f
Merge branch 'main' into invite-api
achou11 Sep 21, 2023
54b9585
add test for when addProject throws
achou11 Sep 21, 2023
cb1a2e7
add test checking payload of invite-received event
achou11 Sep 21, 2023
2c64ed2
add test for sending reject response after invitor disconnects
achou11 Sep 21, 2023
bccebdb
add test for sending already response after invitor disconnects
achou11 Sep 21, 2023
9407be3
Merge branch 'main' into invite-api
achou11 Sep 25, 2023
693af73
use public id instead of project id for public interface
achou11 Sep 25, 2023
370b4be
remove commented-out line
achou11 Sep 25, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 199 additions & 0 deletions src/invite-api.js
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,
})
Copy link
Member

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?

Copy link
Member

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)

Copy link
Member

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

}

/**
* @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
}
}
}
1 change: 1 addition & 0 deletions src/rpc/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export class MapeoRPC extends TypedEmitter {
*/
async invite(peerId, { timeout, ...invite }) {
const peer = this.#peers.get(peerId)
if (!peer) console.log([...this.#peers.keys()])
if (!peer) throw new UnknownPeerError('Unknown peer ' + peerId)
/** @type {Promise<InviteResponse['decision']>} */
return new Promise((origResolve, origReject) => {
Expand Down
15 changes: 11 additions & 4 deletions tests/helpers/rpc.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import NoiseSecretStream from '@hyperswarm/secret-stream'

export function replicate(rpc1, rpc2) {
const n1 = new NoiseSecretStream(true, undefined, {
export function replicate(
rpc1,
rpc2,
{
// Keep keypairs deterministic for tests, since we use peer.publicKey as an identifier.
keyPair: NoiseSecretStream.keyPair(Buffer.allocUnsafe(32).fill(0)),
kp1 = NoiseSecretStream.keyPair(Buffer.allocUnsafe(32).fill(0)),
kp2 = NoiseSecretStream.keyPair(Buffer.allocUnsafe(32).fill(1)),
} = {}
) {
const n1 = new NoiseSecretStream(true, undefined, {
keyPair: kp1,
})
const n2 = new NoiseSecretStream(false, undefined, {
keyPair: NoiseSecretStream.keyPair(Buffer.allocUnsafe(32).fill(1)),
keyPair: kp2,
})
n1.rawStream.pipe(n2.rawStream).pipe(n1.rawStream)

Expand Down
Loading