Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
95 changes: 83 additions & 12 deletions src/transmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ type TransmitMessage = {
exceptUids?: string | string[]
}

/**
* A subscription change for a stream that another instance holds. It goes on
* its own bus channel, which older versions do not listen to: they would
* broadcast it to the channel as a message.
*/
type SubscriptionMessage = {
type: typeof TransportMessageType.Subscribe | typeof TransportMessageType.Unsubscribe
uid: string
channel: string
}

export class Transmit<Context extends unknown> {
/**
* The configuration for the transmit instance
Expand All @@ -51,6 +62,12 @@ export class Transmit<Context extends unknown> {
*/
readonly #transportChannel: string

/**
* The transport channel that relays subscriptions to the instance that
* holds the stream.
*/
readonly #subscriptionChannel: string

/**
* The transport provider to synchronize messages and subscriptions
* across multiple instance.
Expand All @@ -73,12 +90,27 @@ export class Transmit<Context extends unknown> {
this.#emittery = new Emittery()
this.#bus = transport ? new Bus(transport, { retryQueue: { enabled: true } }) : null
this.#transportChannel = this.#config.transport?.channel ?? 'transmit::broadcast'
this.#subscriptionChannel = `${this.#transportChannel}::subscriptions`

// Subscribe to the transport channel and handle incoming messages
void this.#bus?.subscribe<TransmitMessage>(this.#transportChannel, (message) => {
this.#broadcastLocally(message.channel, message.payload, message.exceptUids)
})

// Apply the subscriptions that another instance authorized for a stream
// this one may hold. An instance that does not hold it ignores them.
void this.#bus?.subscribe<SubscriptionMessage>(this.#subscriptionChannel, (message) => {
if (message.type === TransportMessageType.Subscribe) {
void this.#manager.subscribe({
uid: message.uid,
channel: message.channel,
skipAuthorization: true,
})
} else {
void this.#manager.unsubscribe({ uid: message.uid, channel: message.channel })
}
})

// Start the ping interval if configured
if (this.#config.pingInterval) {
const intervalValue =
Expand Down Expand Up @@ -123,20 +155,40 @@ export class Transmit<Context extends unknown> {
this.#manager.authorize(channel, callback)
}

subscribe(params: Omit<SubscribeParams<Context>, 'onSubscribe'>) {
return this.#manager.subscribe({
...params,
onSubscribe: ({ uid, channel, context }) => {
void this.#emittery.emit('subscribe', {
uid,
channel,
context,
})
},
})
/**
* Subscribes a stream to a channel. With a transport, the request may reach
* an instance that does not hold the stream: this instance authorizes it and
* relays it to the others, so it returns true without knowing whether any
* instance holds the stream.
*/
async subscribe({
uid,
channel,
context,
skipAuthorization,
}: Omit<SubscribeParams<Context>, 'onSubscribe'>) {
if (!skipAuthorization && !(await this.#manager.verifyAccess(channel, context!))) {
return false
}

const subscribed =
(await this.#manager.subscribe({ uid, channel, skipAuthorization: true })) ||
(await this.#relaySubscription(TransportMessageType.Subscribe, uid, channel))

if (subscribed) {
void this.#emittery.emit('subscribe', { uid, channel, context: context! })
}

return subscribed
}

unsubscribe(params: Omit<UnsubscribeParams<Context>, 'onUnsubscribe'>) {
/**
* Unsubscribes a stream from a channel, on this instance and on the one
* that holds the stream.
*/
async unsubscribe(params: Omit<UnsubscribeParams<Context>, 'onUnsubscribe'>) {
await this.#relaySubscription(TransportMessageType.Unsubscribe, params.uid, params.channel)

return this.#manager.unsubscribe({
...params,
onUnsubscribe: ({ uid, channel, context }) => {
Expand All @@ -149,6 +201,25 @@ export class Transmit<Context extends unknown> {
})
}

/**
* Publishes a subscription change and waits until the transport has it, so
* a client that waits for the response before its next request gets its
* changes applied in order, even through different instances.
*/
async #relaySubscription(type: SubscriptionMessage['type'], uid: string, channel: string) {
if (!this.#bus) {
return false
}

await this.#bus.publish(this.#subscriptionChannel, {
type,
uid,
channel,
} satisfies SubscriptionMessage)

return true
}

#broadcastLocally(channel: string, payload: Broadcastable, senderUid?: string | string[]) {
const subscribers = this.#manager.findByChannel(channel)

Expand Down
2 changes: 2 additions & 0 deletions src/transport_message_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@

export const TransportMessageType = {
Broadcast: 1,
Subscribe: 2,
Unsubscribe: 3,
} as const
88 changes: 88 additions & 0 deletions tests/transmit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,94 @@ test.group('Transmit', () => {
assert.deepEqual(received, [excluded.getUid(), receiver.getUid(), receiver.getUid()])
})

test('should subscribe and unsubscribe a stream held by another instance', async ({ assert }) => {
const transmit = makeTransmitWithTransport(makeTransport())
const holder = makeTransmitWithTransport(makeTransport())
const stream = makeStream(holder)

// The receiving instance authorizes; the holder must not ask again.
transmit.authorize('relayed', () => true)
holder.authorize('relayed', () => false)

const events: string[] = []
transmit.on('subscribe', ({ context }) => events.push(`receiver:${context}`))
holder.on('subscribe', ({ context }) => events.push(`holder:${context}`))

// Watches the channel that older versions broadcast to clients.
const broadcastChannel = makeTransport().transport.setId('observer')
const broadcastMessages: unknown[] = []
await broadcastChannel.subscribe('transmit::broadcast', (message) => {
broadcastMessages.push(message)
})

const received: unknown[] = []
stream.on('data', (message: any) => {
if (message !== '\n') received.push(message)
})

const subscribed = await transmit.subscribe({
uid: stream.getUid(),
channel: 'relayed',
context: 'request',
})
assert.isTrue(subscribed)
transmit.broadcast('relayed', { message: 'first' })

assert.isTrue(await transmit.unsubscribe({ uid: stream.getUid(), channel: 'relayed' }))
transmit.broadcast('relayed', { message: 'second' })

await broadcastChannel.disconnect()

assert.lengthOf(received, 1)
assert.include(String(received[0]), 'first')
assert.deepEqual(holder.getSubscribersFor('relayed'), [])
assert.deepEqual(events, ['receiver:request'])
assert.lengthOf(broadcastMessages, 2)
assert.notInclude(JSON.stringify(broadcastMessages), stream.getUid())
})

test('should apply sequential changes in order through different instances', async ({
assert,
}) => {
const slowTransport = makeTransport()
const slow = makeTransmitWithTransport(slowTransport)
const fast = makeTransmitWithTransport(makeTransport())
const holder = makeTransmitWithTransport(makeTransport())
const stream = makeStream(holder)

// The slow instance takes 20ms to reach the bus.
const publish = slowTransport.transport.publish.bind(slowTransport.transport)
slowTransport.transport.publish = async (channel, message) => {
await new Promise((resolve) => setTimeout(resolve, 20))
return publish(channel, message)
}

await holder.subscribe({ uid: stream.getUid(), channel: 'ordered' })
await slow.unsubscribe({ uid: stream.getUid(), channel: 'ordered' })
await fast.subscribe({ uid: stream.getUid(), channel: 'ordered' })
await new Promise((resolve) => setTimeout(resolve, 40))

assert.deepEqual(holder.getSubscribersFor('ordered'), [stream.getUid()])
})

test('should not relay a subscription the receiving instance refuses', async ({ assert }) => {
const transmit = makeTransmitWithTransport(makeTransport())
const holder = makeTransmitWithTransport(makeTransport())
const stream = makeStream(holder)

transmit.authorize('private', () => false)
holder.authorize('private', () => true)

assert.isFalse(await transmit.subscribe({ uid: stream.getUid(), channel: 'private' }))
assert.deepEqual(holder.getSubscribersFor('private'), [])
})

test('should refuse a stream it does not hold without a transport', async ({ assert }) => {
const transmit = new Transmit({ transport: null })

assert.isFalse(await transmit.subscribe({ uid: randomUUID(), channel: 'channel1' }))
})

test('should broadcast falsy payloads without converting them to empty object', async ({
assert,
}) => {
Expand Down
Loading