Skip to content

Commit

Permalink
make publish() timeout.
Browse files Browse the repository at this point in the history
  • Loading branch information
AsaiToshiya authored and fiatjaf committed Oct 30, 2024
1 parent 94f841f commit d062ab8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
16 changes: 13 additions & 3 deletions abstract-relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class AbstractRelay {

public baseEoseTimeout: number = 4400
public connectionTimeout: number = 4400
public publishTimeout: number = 4400
public openSubs: Map<string, Subscription> = new Map()
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined

Expand Down Expand Up @@ -198,9 +199,11 @@ export class AbstractRelay {
const ok: boolean = data[2]
const reason: string = data[3]
const ep = this.openEventPublishes.get(id) as EventPublishResolver
if (ok) ep.resolve(reason)
else ep.reject(new Error(reason))
this.openEventPublishes.delete(id)
if (ep) {
if (ok) ep.resolve(reason)
else ep.reject(new Error(reason))
this.openEventPublishes.delete(id)
}
return
}
case 'CLOSED': {
Expand Down Expand Up @@ -248,6 +251,13 @@ export class AbstractRelay {
this.openEventPublishes.set(event.id, { resolve, reject })
})
this.send('["EVENT",' + JSON.stringify(event) + ']')
setTimeout(() => {
const ep = this.openEventPublishes.get(event.id) as EventPublishResolver
if (ep) {
ep.reject(new Error('publish timed out'))
this.openEventPublishes.delete(event.id)
}
}, this.publishTimeout)
return ret
}

Expand Down
27 changes: 26 additions & 1 deletion relay.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test'

import { Server } from 'mock-socket'
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
import { Relay, useWebSocketImplementation } from './relay.ts'
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
Expand Down Expand Up @@ -92,3 +92,28 @@ test('listening and publishing and closing', async done => {
),
)
})

test('publish timeout', async () => {
const url = 'wss://relay.example.com'
new Server(url)

const relay = new Relay(url)
relay.publishTimeout = 100
await relay.connect()

setTimeout(() => relay.close(), 20000) // close the relay to fail the test on timeout

expect(
relay.publish(
finalizeEvent(
{
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'hello',
},
generateSecretKey(),
),
),
).rejects.toThrow('publish timed out')
})

0 comments on commit d062ab8

Please sign in to comment.