-
Notifications
You must be signed in to change notification settings - Fork 233
feat(nip66): publish kind 30166 and 10166 relay health events #741
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4b536ab
feat(nip66): publish kind 30166 and 10166 relay health events
Ferryx349 f85dc7c
test(nip66): query event_tags table in 30166 integration assertion
Ferryx349 f615f8d
Merge branch 'main' into feat/nip66-publish-events
Ferryx349 79d04f9
Merge branch 'main' into feat/nip66-publish-events
Ferryx349 513fd07
Merge branch 'main' into feat/nip66-publish-events
Ferryx349 c43552e
Merge branch 'main' into feat/nip66-publish-events
cameri 307373f
fix(nip66): address monitor bootstrap and discovery event review
Ferryx349 c96c9c9
Merge branch 'main' into feat/nip66-publish-events
Ferryx349 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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,11 @@ | ||
| --- | ||
| "nostream": minor | ||
| --- | ||
|
|
||
| feat(nip66): publish kind 30166 and 10166 relay health events after probe runs | ||
|
|
||
| After each relay monitor probe run, sign and store NIP-66 relay discovery and monitor | ||
| announcement events using the configured monitor identity, bootstrap kind 0/10002 on | ||
| first run, and persist via the existing parameterized replaceable event path. | ||
|
|
||
| Fixes #696 |
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,11 +1,18 @@ | ||
| import { RedisAdapter } from '../adapters/redis-adapter' | ||
| import { RelayMonitorWorker } from '../app/relay-monitor-worker' | ||
| import { getCacheClient } from '../cache/client' | ||
| import { getMasterDbClient, getReadReplicaDbClient } from '../database/client' | ||
| import { createSettings } from './settings-factory' | ||
| import { EventRepository } from '../repositories/event-repository' | ||
| import { Nip66EventPublisher } from '../services/nip66-event-publisher' | ||
| import { RelayProbeSnapshotStore } from '../utils/relay-probe-snapshot' | ||
| import { runProbe } from '../utils/relay-probe' | ||
|
|
||
| export const relayMonitorWorkerFactory = () => { | ||
| const snapshotStore = new RelayProbeSnapshotStore(new RedisAdapter(getCacheClient())) | ||
| const cache = new RedisAdapter(getCacheClient()) | ||
| const snapshotStore = new RelayProbeSnapshotStore(cache) | ||
| const eventRepository = new EventRepository(getMasterDbClient(), getReadReplicaDbClient(), createSettings) | ||
| const eventPublisher = new Nip66EventPublisher(eventRepository, cache) | ||
|
|
||
| return new RelayMonitorWorker(process, createSettings, snapshotStore) | ||
| return new RelayMonitorWorker(process, createSettings, snapshotStore, runProbe, eventPublisher) | ||
| } |
This file contains hidden or 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,92 @@ | ||
| import { ICacheAdapter } from '../@types/adapters' | ||
| import { ParameterizedReplaceableEvent, UnidentifiedEvent } from '../@types/event' | ||
| import { RelayProbeRunSnapshot } from '../@types/relay-probe-snapshot' | ||
| import { IEventRepository } from '../@types/repositories' | ||
| import { Settings } from '../@types/settings' | ||
| import { EventDeduplicationMetadataKey, EventTags } from '../constants/base' | ||
| import { createLogger } from '../factories/logger-factory' | ||
| import { getPublicKey, identifyEvent, isParameterizedReplaceableEvent, signEvent } from '../utils/event' | ||
| import { getMonitorPrivateKey } from '../utils/monitor-identity' | ||
| import { | ||
| buildMonitorAnnouncementEvent, | ||
| buildMonitorProfileEvent, | ||
| buildMonitorRelayListEvent, | ||
| buildRelayDiscoveryEvent, | ||
| } from '../utils/nip66-events' | ||
| const logger = createLogger('nip66-event-publisher') | ||
|
|
||
| export const NIP66_MONITOR_BOOTSTRAPPED_KEY = 'nip66:monitor:bootstrapped' | ||
|
|
||
| export interface INip66EventPublisher { | ||
| publishAfterProbe(snapshot: RelayProbeRunSnapshot, settings: Settings): Promise<void> | ||
| } | ||
|
|
||
| export class Nip66EventPublisher implements INip66EventPublisher { | ||
| public constructor( | ||
| private readonly eventRepository: IEventRepository, | ||
| private readonly cache: ICacheAdapter, | ||
| ) {} | ||
|
|
||
| public async publishAfterProbe(snapshot: RelayProbeRunSnapshot, settings: Settings): Promise<void> { | ||
| const privkey = getMonitorPrivateKey() | ||
|
|
||
| if (!privkey) { | ||
| logger.warn('MONITOR_PRIVATE_KEY is not configured; skipping NIP-66 event publish') | ||
| return | ||
| } | ||
|
|
||
| const monitorPubkey = getPublicKey(privkey) | ||
| const createdAt = Math.floor(Date.now() / 1000) | ||
|
|
||
| await this.ensureBootstrap(monitorPubkey, settings, privkey, createdAt) | ||
|
|
||
| await this.persistSignedEvent(buildMonitorAnnouncementEvent(settings, monitorPubkey, createdAt), privkey) | ||
|
|
||
| for (const result of snapshot.results) { | ||
| await this.persistSignedEvent(buildRelayDiscoveryEvent(result, monitorPubkey, createdAt), privkey) | ||
| } | ||
|
|
||
| logger('published NIP-66 events for %d probe target(s)', snapshot.results.length) | ||
| } | ||
|
|
||
| private async ensureBootstrap( | ||
| monitorPubkey: string, | ||
| settings: Settings, | ||
| privkey: string, | ||
| createdAt: number, | ||
| ): Promise<void> { | ||
| const bootstrapped = await this.cache.getKey(NIP66_MONITOR_BOOTSTRAPPED_KEY) | ||
|
|
||
| if (bootstrapped === monitorPubkey) { | ||
| return | ||
| } | ||
|
|
||
| const relayUrl = settings.info.relay_url | ||
|
|
||
| await this.persistSignedEvent(buildMonitorProfileEvent(monitorPubkey, createdAt), privkey) | ||
| await this.persistSignedEvent(buildMonitorRelayListEvent(relayUrl, monitorPubkey, createdAt), privkey) | ||
|
|
||
| await this.cache.setKey(NIP66_MONITOR_BOOTSTRAPPED_KEY, monitorPubkey) | ||
| logger('bootstrapped NIP-66 monitor identity for pubkey %s', monitorPubkey) | ||
| } | ||
|
|
||
| private async persistSignedEvent(unsigned: UnidentifiedEvent, privkey: string): Promise<void> { | ||
| const signed = await signEvent(privkey)(await identifyEvent(unsigned)) | ||
|
|
||
| if (isParameterizedReplaceableEvent(signed)) { | ||
| const [, deduplication] = signed.tags.find((tag) => tag.length >= 2 && tag[0] === EventTags.Deduplication) ?? [ | ||
| null, | ||
| '', | ||
| ] | ||
|
|
||
| await this.eventRepository.upsert({ | ||
| ...signed, | ||
| [EventDeduplicationMetadataKey]: deduplication ? [deduplication] : [''], | ||
| } as ParameterizedReplaceableEvent) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| await this.eventRepository.upsert(signed) | ||
| } | ||
| } |
This file contains hidden or 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,21 @@ | ||
| let monitorPrivateKeyCache: string | undefined | ||
|
|
||
| export const getMonitorPrivateKey = (): string | undefined => { | ||
| if (monitorPrivateKeyCache) { | ||
| return monitorPrivateKeyCache | ||
| } | ||
|
|
||
| const configured = process.env.MONITOR_PRIVATE_KEY?.trim() | ||
|
|
||
| if (!configured) { | ||
| return undefined | ||
| } | ||
|
|
||
| monitorPrivateKeyCache = configured | ||
|
|
||
| return monitorPrivateKeyCache | ||
| } | ||
|
|
||
| export const resetMonitorPrivateKeyCache = (): void => { | ||
| monitorPrivateKeyCache = undefined | ||
| } |
This file contains hidden or 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,161 @@ | ||
| import { UnidentifiedEvent } from '../@types/event' | ||
| import { Tag } from '../@types/base' | ||
| import { StoredProbeResult } from '../@types/relay-probe-snapshot' | ||
| import { Settings } from '../@types/settings' | ||
| import { EventKinds, EventTags } from '../constants/base' | ||
|
|
||
| const DEFAULT_PROBE_INTERVAL_SECONDS = 3600 | ||
| const MIN_PROBE_INTERVAL_SECONDS = 60 | ||
|
|
||
| export const getEffectiveProbeIntervalSeconds = (settings: Settings): number => { | ||
| const configured = settings.nip66?.probeIntervalSeconds ?? DEFAULT_PROBE_INTERVAL_SECONDS | ||
|
|
||
| return Math.max(configured, MIN_PROBE_INTERVAL_SECONDS) | ||
| } | ||
|
|
||
| const appendDnsProbeTags = (tags: Tag[], dns: StoredProbeResult['dns']): void => { | ||
| if (dns.status === 'skipped') { | ||
| tags.push(['dns', 'skipped']) | ||
| return | ||
| } | ||
|
|
||
| if (dns.status === 'error') { | ||
| tags.push(['dns', '!resolved']) | ||
| return | ||
| } | ||
|
|
||
| tags.push(['dns', 'resolved']) | ||
| } | ||
|
|
||
| const appendTlsProbeTags = (tags: Tag[], tls: StoredProbeResult['tls']): void => { | ||
| if (tls.status === 'skipped') { | ||
| tags.push(['ssl', 'skipped']) | ||
| return | ||
| } | ||
|
|
||
| if (tls.status === 'error') { | ||
| tags.push(['ssl', '!valid']) | ||
| return | ||
| } | ||
|
|
||
| const valid = tls.data?.valid === true | ||
| tags.push(['ssl', valid ? 'valid' : '!valid']) | ||
|
|
||
| if (tls.data?.expiresAt) { | ||
| const expiresAtSeconds = Math.floor(new Date(tls.data.expiresAt).getTime() / 1000) | ||
| tags.push(['ssl-expires', String(expiresAtSeconds)]) | ||
| } | ||
|
|
||
| if (tls.data?.issuer) { | ||
| tags.push(['ssl-issuer', tls.data.issuer]) | ||
| } | ||
| } | ||
|
|
||
| export const normalizeRelayUrlForDTag = (relayUrl: string): string => { | ||
| const parsed = new URL(relayUrl) | ||
| parsed.protocol = parsed.protocol.toLowerCase() | ||
| parsed.hostname = parsed.hostname.toLowerCase() | ||
|
|
||
| if ( | ||
| (parsed.protocol === 'wss:' && parsed.port === '443') || | ||
| (parsed.protocol === 'ws:' && parsed.port === '80') | ||
| ) { | ||
| parsed.port = '' | ||
| } | ||
|
|
||
| let normalized = parsed.toString() | ||
|
|
||
| if ((parsed.pathname === '/' || parsed.pathname === '') && !normalized.endsWith('/')) { | ||
| normalized = `${normalized}/` | ||
| } | ||
|
|
||
| return normalized | ||
| } | ||
|
|
||
| export const buildRelayDiscoveryEvent = ( | ||
| result: StoredProbeResult, | ||
| monitorPubkey: string, | ||
| createdAt: number, | ||
| ): UnidentifiedEvent => { | ||
| const tags: Tag[] = [ | ||
| [EventTags.Deduplication, normalizeRelayUrlForDTag(result.target.relayUrl)], | ||
| ['n', result.target.networkType], | ||
| ] | ||
|
|
||
| if (result.wsRtt.status === 'ok' && typeof result.wsRtt.data?.rttOpenMs === 'number') { | ||
| tags.push(['rtt-open', String(result.wsRtt.data.rttOpenMs)]) | ||
| } | ||
|
|
||
| appendDnsProbeTags(tags, result.dns) | ||
| appendTlsProbeTags(tags, result.tls) | ||
|
|
||
| return { | ||
| kind: EventKinds.RELAY_DISCOVERY, | ||
| pubkey: monitorPubkey, | ||
| created_at: createdAt, | ||
| content: '', | ||
| tags, | ||
| } | ||
| } | ||
|
|
||
| export const buildMonitorAnnouncementEvent = ( | ||
| settings: Settings, | ||
| monitorPubkey: string, | ||
| createdAt: number, | ||
| ): UnidentifiedEvent => { | ||
| const nip66 = settings.nip66 | ||
| const timeouts = nip66?.timeouts | ||
|
|
||
| const tags: Tag[] = [ | ||
| ['frequency', String(getEffectiveProbeIntervalSeconds(settings))], | ||
| ['c', 'ws'], | ||
| ['c', 'nip11'], | ||
| ['c', 'ssl'], | ||
| ['c', 'dns'], | ||
| ] | ||
|
|
||
| if (timeouts) { | ||
| tags.push(['timeout', 'open', String(timeouts.wsRttMs)]) | ||
| tags.push(['timeout', 'nip11', String(timeouts.nip11Ms)]) | ||
| tags.push(['timeout', 'dns', String(timeouts.dnsMs)]) | ||
| tags.push(['timeout', 'ssl', String(timeouts.tlsMs)]) | ||
| } | ||
|
|
||
| return { | ||
| kind: EventKinds.RELAY_MONITOR_ANNOUNCEMENT, | ||
| pubkey: monitorPubkey, | ||
| created_at: createdAt, | ||
| content: '', | ||
| tags, | ||
| } | ||
| } | ||
|
|
||
| export const buildMonitorProfileEvent = (monitorPubkey: string, createdAt: number): UnidentifiedEvent => { | ||
| return { | ||
| kind: EventKinds.SET_METADATA, | ||
| pubkey: monitorPubkey, | ||
| created_at: createdAt, | ||
| content: JSON.stringify({ | ||
| name: 'Nostream Relay Monitor', | ||
| about: 'Automated NIP-66 relay health monitor for this Nostream instance.', | ||
| }), | ||
| tags: [], | ||
| } | ||
| } | ||
|
|
||
| export const buildMonitorRelayListEvent = ( | ||
| relayUrl: string, | ||
| monitorPubkey: string, | ||
| createdAt: number, | ||
| ): UnidentifiedEvent => { | ||
| return { | ||
| kind: EventKinds.RELAY_LIST, | ||
| pubkey: monitorPubkey, | ||
| created_at: createdAt, | ||
| content: '', | ||
| tags: [ | ||
| [EventTags.Relay, relayUrl, 'read'], | ||
| [EventTags.Relay, relayUrl, 'write'], | ||
| ], | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.