Add message to handlers

This commit is contained in:
Jon Staab
2024-08-27 11:54:04 -07:00
parent fcbaa67ade
commit 8a8bea71be
13 changed files with 71 additions and 61 deletions
+10 -10
View File
@@ -3303,8 +3303,8 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/net": "0.0.19", "@welshman/net": "0.0.20",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"nostr-tools": "^2.7.2" "nostr-tools": "^2.7.2"
}, },
"devDependencies": { "devDependencies": {
@@ -3342,7 +3342,7 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27" "@welshman/util": "0.0.28"
}, },
"devDependencies": { "devDependencies": {
"gts": "^5.0.1", "gts": "^5.0.1",
@@ -3376,11 +3376,11 @@
}, },
"packages/net": { "packages/net": {
"name": "@welshman/net", "name": "@welshman/net",
"version": "0.0.19", "version": "0.0.20",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"isomorphic-ws": "^5.0.0", "isomorphic-ws": "^5.0.0",
"ws": "^8.16.0" "ws": "^8.16.0"
}, },
@@ -3396,8 +3396,8 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/net": "0.0.19", "@welshman/net": "0.0.20",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"nostr-tools": "^2.7.2" "nostr-tools": "^2.7.2"
}, },
"devDependencies": { "devDependencies": {
@@ -3408,11 +3408,11 @@
}, },
"packages/store": { "packages/store": {
"name": "@welshman/store", "name": "@welshman/store",
"version": "0.0.3", "version": "0.0.4",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"svelte": "^4.2.18" "svelte": "^4.2.18"
}, },
"devDependencies": { "devDependencies": {
@@ -3423,7 +3423,7 @@
}, },
"packages/util": { "packages/util": {
"name": "@welshman/util", "name": "@welshman/util",
"version": "0.0.27", "version": "0.0.28",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
+3 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/dvm", "name": "@welshman/dvm",
"version": "0.0.5", "version": "0.0.6",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of utilities for building nostr DVMs.", "description": "A collection of utilities for building nostr DVMs.",
@@ -32,8 +32,8 @@
}, },
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/net": "0.0.19", "@welshman/net": "0.0.20",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"nostr-tools": "^2.7.2" "nostr-tools": "^2.7.2"
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/feeds", "name": "@welshman/feeds",
"version": "0.0.15", "version": "0.0.16",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "Utilities for building dynamic nostr feeds.", "description": "Utilities for building dynamic nostr feeds.",
@@ -32,6 +32,6 @@
}, },
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27" "@welshman/util": "0.0.28"
} }
} }
+1 -1
View File
@@ -99,7 +99,7 @@ export const stripProtocol = (url: string) => url.replace(/.*:\/\//, "")
export const displayUrl = (url: string) => stripProtocol(url).replace(/^(www\.)?/i, "").replace(/\/$/, "") export const displayUrl = (url: string) => stripProtocol(url).replace(/^(www\.)?/i, "").replace(/\/$/, "")
export const displayDomain = (url: string) => first(displayUrl(url).split(/[\/\?]/)) export const displayDomain = (url: string) => displayUrl(first(url.split(/[\/\?]/)))
export const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t)) export const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t))
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/net", "name": "@welshman/net",
"version": "0.0.19", "version": "0.0.20",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "Utilities for connecting with nostr relays.", "description": "Utilities for connecting with nostr relays.",
@@ -32,7 +32,7 @@
}, },
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"isomorphic-ws": "^5.0.0", "isomorphic-ws": "^5.0.0",
"ws": "^8.16.0" "ws": "^8.16.0"
} }
+3 -3
View File
@@ -83,11 +83,11 @@ export const publish = (request: PublishRequest) => {
// Delegate to our executor // Delegate to our executor
const executorSub = executor.publish(event, { const executorSub = executor.publish(event, {
verb: request.verb || "EVENT", verb: request.verb || "EVENT",
onOk: (url: string, eventId: string, ok: boolean) => { onOk: (url: string, eventId: string, ok: boolean, message: string) => {
if (ok) { if (ok) {
pub.emitter.emit(PublishStatus.Success, url) pub.emitter.emit(PublishStatus.Success, url, message)
} else { } else {
pub.emitter.emit(PublishStatus.Failure, url) pub.emitter.emit(PublishStatus.Failure, url, message)
} }
}, },
onError: (url: string) => { onError: (url: string) => {
+3 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/signer", "name": "@welshman/signer",
"version": "0.0.3", "version": "0.0.4",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A nostr signer implemenation supporting several login methods.", "description": "A nostr signer implemenation supporting several login methods.",
@@ -32,8 +32,8 @@
}, },
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/net": "0.0.19", "@welshman/net": "0.0.20",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"nostr-tools": "^2.7.2" "nostr-tools": "^2.7.2"
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/store", "name": "@welshman/store",
"version": "0.0.3", "version": "0.0.4",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of utilities based on svelte/store for use with welshman", "description": "A collection of utilities based on svelte/store for use with welshman",
@@ -32,7 +32,7 @@
}, },
"dependencies": { "dependencies": {
"@welshman/lib": "0.0.15", "@welshman/lib": "0.0.15",
"@welshman/util": "0.0.27", "@welshman/util": "0.0.28",
"svelte": "^4.2.18" "svelte": "^4.2.18"
} }
} }
+14
View File
@@ -61,6 +61,20 @@ export const custom = <T>(start: Start<T>, opts: {throttle?: number} = {}) => {
} }
} }
export const adapter = <Source, Target>({
store,
forward,
backward,
}: {
store: Writable<Source>,
forward: (x: Source) => Target,
backward: (x: Target) => Source,
}) => ({
...derived(store, forward),
set: (x: Target) => store.set(backward(x)),
update: (f: (x: Target) => Target) => store.update((x: Source) => backward(f(forward(x)))),
})
export function withGetter<T>(store: Writable<T>): Writable<T> & {get: () => T} export function withGetter<T>(store: Writable<T>): Writable<T> & {get: () => T}
export function withGetter<T>(store: Readable<T>): Readable<T> & {get: () => T} export function withGetter<T>(store: Readable<T>): Readable<T> & {get: () => T}
export function withGetter<T>(store: Readable<T> | Writable<T>) { export function withGetter<T>(store: Readable<T> | Writable<T>) {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/util", "name": "@welshman/util",
"version": "0.0.27", "version": "0.0.28",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of nostr-related utilities.", "description": "A collection of nostr-related utilities.",
+2 -2
View File
@@ -51,10 +51,10 @@ export const createEvent = (kind: number, {content = "", tags = [], created_at =
({kind, content, tags, created_at}) ({kind, content, tags, created_at})
export const isEventTemplate = (e: EventTemplate): e is EventTemplate => export const isEventTemplate = (e: EventTemplate): e is EventTemplate =>
Boolean(typeof e.kind === "number" && e.tags && typeof e.content === "string") Boolean(typeof e.kind === "number" && Array.isArray(e.tags) && typeof e.content === "string")
export const isStampedEvent = (e: StampedEvent): e is StampedEvent => export const isStampedEvent = (e: StampedEvent): e is StampedEvent =>
Boolean(isEventTemplate(e) && e.created_at) Boolean(isEventTemplate(e) && e.created_at >= 0)
export const isOwnedEvent = (e: OwnedEvent): e is OwnedEvent => export const isOwnedEvent = (e: OwnedEvent): e is OwnedEvent =>
Boolean(isStampedEvent(e) && e.pubkey) Boolean(isStampedEvent(e) && e.pubkey)
+5 -5
View File
@@ -2,7 +2,7 @@ import {last, Emitter, normalizeUrl, sleep, stripProtocol} from '@welshman/lib'
import {matchFilters} from './Filters' import {matchFilters} from './Filters'
import type {Repository} from './Repository' import type {Repository} from './Repository'
import type {Filter} from './Filters' import type {Filter} from './Filters'
import type {TrustedEvent} from './Events' import type {HashedEvent, TrustedEvent} from './Events'
// Constants and types // Constants and types
@@ -75,22 +75,22 @@ export const displayRelayUrl = (url: string) => last(url.split("://")).replace(/
// In-memory relay implementation backed by Repository // In-memory relay implementation backed by Repository
export class Relay extends Emitter { export class Relay<E extends HashedEvent = TrustedEvent> extends Emitter {
subs = new Map<string, Filter[]>() subs = new Map<string, Filter[]>()
constructor(readonly repository: Repository) { constructor(readonly repository: Repository<E>) {
super() super()
} }
send(type: string, ...message: any[]) { send(type: string, ...message: any[]) {
switch(type) { switch(type) {
case 'EVENT': return this.handleEVENT(message as [TrustedEvent]) case 'EVENT': return this.handleEVENT(message as [E])
case 'CLOSE': return this.handleCLOSE(message as [string]) case 'CLOSE': return this.handleCLOSE(message as [string])
case 'REQ': return this.handleREQ(message as [string, ...Filter[]]) case 'REQ': return this.handleREQ(message as [string, ...Filter[]])
} }
} }
handleEVENT([event]: [TrustedEvent]) { handleEVENT([event]: [E]) {
this.repository.publish(event) this.repository.publish(event)
// Callers generally expect async relays // Callers generally expect async relays
+23 -27
View File
@@ -1,22 +1,22 @@
import {flatten, Emitter, sortBy, inc, chunk, sleep, uniq, omit, now, range, identity} from '@welshman/lib' import {flatten, Emitter, sortBy, inc, chunk, sleep, uniq, omit, now, range, identity} from '@welshman/lib'
import {DELETE} from './Kinds' import {DELETE} from './Kinds'
import {EPOCH, matchFilter} from './Filters' import {EPOCH, matchFilter} from './Filters'
import {isReplaceable, isTrustedEvent} from './Events' import {isReplaceable, isUnwrappedEvent} from './Events'
import {getAddress} from './Address' import {getAddress} from './Address'
import type {Filter} from './Filters' import type {Filter} from './Filters'
import type {TrustedEvent} from './Events' import type {TrustedEvent, HashedEvent} from './Events'
export const DAY = 86400 export const DAY = 86400
const getDay = (ts: number) => Math.floor(ts / DAY) const getDay = (ts: number) => Math.floor(ts / DAY)
export class Repository extends Emitter { export class Repository<E extends HashedEvent = TrustedEvent> extends Emitter {
eventsById = new Map<string, TrustedEvent>() eventsById = new Map<string, E>()
eventsByWrap = new Map<string, TrustedEvent>() eventsByWrap = new Map<string, E>()
eventsByAddress = new Map<string, TrustedEvent>() eventsByAddress = new Map<string, E>()
eventsByTag = new Map<string, TrustedEvent[]>() eventsByTag = new Map<string, E[]>()
eventsByDay = new Map<number, TrustedEvent[]>() eventsByDay = new Map<number, E[]>()
eventsByAuthor = new Map<string, TrustedEvent[]>() eventsByAuthor = new Map<string, E[]>()
deletes = new Map<string, number>() deletes = new Map<string, number>()
// Dump/load/clear // Dump/load/clear
@@ -25,7 +25,7 @@ export class Repository extends Emitter {
return Array.from(this.eventsById.values()) return Array.from(this.eventsById.values())
} }
load = async (events: TrustedEvent[], chunkSize = 1000) => { load = async (events: E[], chunkSize = 1000) => {
this.clear() this.clear()
const added = [] const added = []
@@ -69,7 +69,7 @@ export class Repository extends Emitter {
: this.eventsById.get(idOrAddress) : this.eventsById.get(idOrAddress)
} }
hasEvent = (event: TrustedEvent) => { hasEvent = (event: E) => {
const duplicate = ( const duplicate = (
this.eventsById.get(event.id) || this.eventsById.get(event.id) ||
this.eventsByAddress.get(getAddress(event)) this.eventsByAddress.get(getAddress(event))
@@ -79,12 +79,12 @@ export class Repository extends Emitter {
} }
query = (filters: Filter[], {includeDeleted = false} = {}) => { query = (filters: Filter[], {includeDeleted = false} = {}) => {
const result: TrustedEvent[][] = [] const result: E[][] = []
for (let filter of filters) { for (let filter of filters) {
let events: TrustedEvent[] = Array.from(this.eventsById.values()) let events: E[] = Array.from(this.eventsById.values())
if (filter.ids) { if (filter.ids) {
events = filter.ids!.map(id => this.eventsById.get(id)).filter(identity) as TrustedEvent[] events = filter.ids!.map(id => this.eventsById.get(id)).filter(identity) as E[]
filter = omit(['ids'], filter) filter = omit(['ids'], filter)
} else if (filter.authors) { } else if (filter.authors) {
events = uniq(filter.authors!.flatMap(pubkey => this.eventsByAuthor.get(pubkey) || [])) events = uniq(filter.authors!.flatMap(pubkey => this.eventsByAuthor.get(pubkey) || []))
@@ -112,8 +112,8 @@ export class Repository extends Emitter {
} }
} }
const chunk: TrustedEvent[] = [] const chunk: E[] = []
for (const event of sortBy((e: TrustedEvent) => -e.created_at, events)) { for (const event of sortBy((e: E) => -e.created_at, events)) {
if (filter.limit && chunk.length >= filter.limit) { if (filter.limit && chunk.length >= filter.limit) {
break break
} }
@@ -133,11 +133,7 @@ export class Repository extends Emitter {
return uniq(flatten(result)) return uniq(flatten(result))
} }
publish = (event: TrustedEvent, {shouldNotify = true} = {}): boolean => { publish = (event: E, {shouldNotify = true} = {}): boolean => {
if (!isTrustedEvent(event)) {
throw new Error("Invalid event published to Repository", event)
}
// If we've already seen this event, or it's been deleted, we're done // If we've already seen this event, or it's been deleted, we're done
if (this.eventsById.get(event.id) || this.isDeleted(event)) { if (this.eventsById.get(event.id) || this.isDeleted(event)) {
return false return false
@@ -169,7 +165,7 @@ export class Repository extends Emitter {
} }
// Save wrapper index // Save wrapper index
if (event.wrap) { if (isUnwrappedEvent(event)) {
this.eventsByWrap.set(event.wrap.id, event) this.eventsByWrap.set(event.wrap.id, event)
} }
@@ -203,19 +199,19 @@ export class Repository extends Emitter {
return true return true
} }
isDeletedByAddress = (event: TrustedEvent) => (this.deletes.get(getAddress(event)) || 0) > event.created_at isDeletedByAddress = (event: E) => (this.deletes.get(getAddress(event)) || 0) > event.created_at
isDeletedById = (event: TrustedEvent) => (this.deletes.get(event.id) || 0) > event.created_at isDeletedById = (event: E) => (this.deletes.get(event.id) || 0) > event.created_at
isDeleted = (event: TrustedEvent) => this.isDeletedByAddress(event) || this.isDeletedById(event) isDeleted = (event: E) => this.isDeletedByAddress(event) || this.isDeletedById(event)
// Utilities // Utilities
_updateIndex<K>(m: Map<K, TrustedEvent[]>, k: K, e: TrustedEvent, duplicate?: TrustedEvent) { _updateIndex<K>(m: Map<K, E[]>, k: K, e: E, duplicate?: E) {
let a = m.get(k) || [] let a = m.get(k) || []
if (duplicate) { if (duplicate) {
a = a.filter((x: TrustedEvent) => x !== duplicate) a = a.filter((x: E) => x !== duplicate)
} }
a.push(e) a.push(e)