Policy
Socket policies attach automated behavior to a socket. A pool runs each policy in pool.socketPolicies once for every socket it creates.
Types
SocketPolicy
type SocketPolicy = (socket: Socket) => UnsubscriberA policy takes a socket and returns a cleanup function, which runs when the socket is cleaned up.
Built-in Policies
socketPolicyAuthBuffer
Buffers messages during the authentication flow and replays them after successful auth. The buffer holds 1000 messages. A subscription dropped from a full buffer is closed with a CLOSED that stands in for the relay's, and so is one still buffered when auth fails.
socketPolicyCancelUnsent
Drops a REQ or NEG-OPEN from the send queue, along with its close, when the close is queued before the request was sent.
socketPolicyMultiplex
Sends subscriptions that wait together in the send queue as one merged REQ, so requests made at the same time share one of the relay's subscriptions. A REQ queued while another is still waiting joins it as a member of a merged REQ under a new MUX- id, which unions the members' filters and holds at most MULTIPLEX_MAX_FILTERS (10). A lone REQ goes out unchanged.
The policy hands the relay's events for the merged id to each member whose filters match, and its EOSE and CLOSED to every member. It also leaves the merged CLOSED in the receive queue, so the policies that counted the merged REQ see it end. A member's CLOSE goes no further while other members remain. After the merged REQ eoses, the policy sends it again under the same id with only the remaining filters, starting from now, which replaces the relay's subscription without replaying history. The last member's CLOSE closes the merged id, or drops the merged REQ if it has not gone out.
The policy pushes merged REQs onto the queue rather than sending them, so the auth buffer keeps the original REQs to replay. A merged REQ carries its members' ids, which getSubscriptions reads, so a request can tell when it went out. It runs after the auth buffer and cancel-unsent, and ignores any message they take back out of a queue. Leaving it out of pool.socketPolicies sends every subscription as it was asked for, and a request's multiplex: false (setMultiplex(req, false) on a single REQ) sends just its own that way.
socketPolicyConnectOnSend
Opens a closed socket when a message is sent, unless the socket errored in the last five seconds.
socketPolicyLifecycle
Owns a socket's lifecycle. It closes sockets after 30 seconds of inactivity, and reopens ones that still have pending requests or publishes, backing off between attempts. The backoff resets only once the relay answers a request, so a relay that greets a connection and drops it is retried less and less often. On reopening it re-sends each request bounded at the outage, so a live subscription catches up on what it missed. It forgets a request as soon as its CLOSE is queued, so it never replays a request closed while the socket was down. A filter that names gift wraps reaches back two days further, since NIP-59 lets a wrap's timestamp sit up to two days in the past.
A socket that still has work outstanding but has heard nothing for 30 seconds is probed with a REQ the relay must answer. If nothing comes back within 10 seconds the socket is closed, which triggers the reconnect above. This catches a socket that reports itself open after its relay has gone, as happens when a device returns from suspend.
Custom Auth Policy
makeSocketPolicyAuth(options)
Creates a policy that answers authentication challenges.
Options:
sign: (event) => Promise<SignedEvent>- Signing functionshouldAuth?: (socket) => boolean- Optional auth conditionrecheck?: {subscribe(run)}- Notifies whenshouldAuth's inputs change, such as a svelte store of the lists it reads. A challengeshouldAuthdeclined is answered once it changes its mind
Refusal Tracking
makeSocketPolicyRefusals(options)
Creates a policy that reports how the relay answers each request and publish. It holds no state of its own beyond the messages awaiting an answer, so the caller decides what the answers add up to.
Options:
onAllowed: (socket) => void- The relay served a request (EOSEorNEG-MSG) or accepted a publish (OKtrue)onRefused: (socket, reason) => void- The relay turned one away with NIP-01'srestricted:orblocked:reason
Other failures report nothing, including an auth-required: refusal, since the message is sent again once auth completes. The policy isn't in defaultSocketPolicies.
pool.addSocketPolicy(
makeSocketPolicyRefusals({
onAllowed: socket => console.log("served by", socket.url),
onRefused: (socket, reason) => console.log("refused by", socket.url, reason),
}),
)Default Policies
defaultSocketPolicies includes all built-in policies except auth, which requires configuration. A new Pool copies it into pool.socketPolicies, so policies go on the pool before it creates any sockets. To enable automatic authentication on all connections:
pool.socketPolicies = [
...defaultSocketPolicies,
makeSocketPolicyAuth({
sign: (event: StampedEvent) => signer.sign(event),
shouldAuth: (socket: Socket) => true,
}),
]Example
A custom policy is a function that returns a cleanup function:
import {on} from "@welshman/lib"
import {SocketEvent, Socket, SocketStatus} from "@welshman/net"
const logStatusChangePolicy = (socket: Socket) =>
on(socket, SocketEvent.Status, (newStatus: SocketStatus) => {
console.log(socket.url, newStatus)
})