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: add isPubSub method to detect PubSub implementations #2707

Merged
merged 4 commits into from
Sep 19, 2024
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
6 changes: 5 additions & 1 deletion packages/interface-compliance-tests/src/pubsub/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isStartable, start, stop } from '@libp2p/interface'
import { isPubSub, isStartable, start, stop } from '@libp2p/interface'
import { expect } from 'aegir/chai'
import delay from 'delay'
import pDefer from 'p-defer'
Expand Down Expand Up @@ -39,6 +39,10 @@ export default (common: TestSetup<PubSub, PubSubArgs>): void => {
mockNetwork.reset()
})

it('is a PubSub implementation', () => {
expect(isPubSub(pubsub)).to.be.true()
})

it('can start correctly', async () => {
if (!isStartable(pubsub)) {
return
Expand Down
13 changes: 13 additions & 0 deletions packages/interface/src/pubsub/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,16 @@ export interface PeerStreamEvents {
'stream:outbound': CustomEvent<never>
'close': CustomEvent<never>
}

/**
* All Pubsub implementations must use this symbol as the name of a property
* with a boolean `true` value
*/
export const pubSubSymbol = Symbol.for('@libp2p/pubsub')

/**
* Returns true if the passed argument is a PubSub implementation
*/
export function isPubSub (obj?: any): obj is PubSub {
return Boolean(obj?.[pubSubSymbol])
}
4 changes: 3 additions & 1 deletion packages/pubsub-floodsub/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
* ```
*/

import { serviceDependencies } from '@libp2p/interface'
import { pubSubSymbol, serviceDependencies } from '@libp2p/interface'
import { PubSubBaseProtocol, type PubSubComponents } from '@libp2p/pubsub'
import { toString } from 'uint8arrays/to-string'
import { SimpleTimeCache } from './cache.js'
Expand Down Expand Up @@ -78,6 +78,8 @@ export class FloodSub extends PubSubBaseProtocol {
})
}

readonly [pubSubSymbol] = true

readonly [Symbol.toStringTag] = '@libp2p/floodsub'

readonly [serviceDependencies]: string[] = [
Expand Down
Loading