Skip to content
Get started

API ​

Every export of @netifyjs/netify grouped by area, followed by the main classes member by member. Import everything from the package root, @netifyjs/netify. The options types have their own tables in Options.

Exports ​

Bootstraps ​

Starting TCP servers and clients. See How it works and TCP.

ExportKindWhat it is
ServerBootstrapClassBuilds and binds a TCP or Unix socket server
BootstrapClassBuilds and connects a TCP or Unix client
ReconnectingClientClassClient that reconnects with backoff
DispatcherClassBun socket handler that turns sockets into channels
BindOptionsTypeTcpBindOptions | UnixBindOptions
TcpBindOptionsTypeHost and port to listen on
UnixBindOptionsTypeUnix socket path to listen on
ConnectOptionsTypeTcpConnectOptions | UnixConnectOptions
TcpConnectOptionsTypeHost and port to connect to
UnixConnectOptionsTypeUnix socket path to connect to
ServerOptionsTypeSettings for the listening socket
ClientOptionsTypeSocket settings for a client, with TLS
SocketOptionsTypeSettings for each TCP connection
ReconnectOptionsTypeBackoff settings for ReconnectingClient
ReconnectEventsTypeConnect, disconnect and retry callbacks
DispatcherEventsTypeCallbacks a Dispatcher reports to
SocketDataTypeChannel | undefined, the data on a Bun socket

Buffers ​

Reading and writing bytes. See ByteBuf, and Games for bit packing and quantising.

ExportKindWhat it is
ByteBufClassGrowable buffer with reader and writer indexes
ByteBufPoolClassFree list that pooled buffers go back to
BitReaderClassReads values a few bits at a time
BitWriterClassWrites values a few bits at a time
QuantizerClassPacks a number range into a fixed bit width
EndianType'big' | 'little'
QuantizerOptionsTypeRange and bit width for a Quantizer

Channels ​

Connections, pipelines and the pieces under them. See How it works and Pipeline.

ExportKindWhat it is
ChannelClassOne connection and its pipeline
ServerChannelClassA listening server and its child channels
ShutdownEventClassFired on each channel by shutdownGracefully
PipelineClassOrdered chain of handlers on a channel
HandlerContextClassA handler's link in the pipeline
ChannelInitializerClassHandler that runs a setup function once
ChannelGroupClassSet of channels for broadcasting
AttributeKeyClassTyped key for per channel state
AttributeMapClassPer channel state store
EventQueueClassRuns a channel's inbound events in order
OutboundBufferClassQueued writes and writability tracking
WriteTrackerClassKeeps flushes behind writes still in progress
HeadHandlerClassFirst handler, hands bytes to the transport
TailHandlerClassLast handler, logs anything left unhandled
SocketTransportClassTransport over a Bun TCP socket
ChannelOptionsTypeLogger and write limits for a channel
ChannelSetupTypeFunction that builds a channel's pipeline
ChannelMatcherTypePicks channels in a ChannelGroup
GroupResultTypeChannels that succeeded and failed in a group call
GroupFailureTypeOne failed channel and its error
OutboundOptionsTypeSettings for an OutboundBuffer
QueueEventsTypeBusy and idle callbacks for an EventQueue
ServerAddressTypeHost and port, or Unix path, of a server
SinkTypeWhere a HeadHandler sends bytes
TransportTypeThe socket under a channel

Handlers ​

Handler types and the base classes to extend. See Handlers.

ExportKindWhat it is
InboundHandlerAdapterClassBase for inbound handlers, forwards every event
OutboundHandlerAdapterClassBase for outbound handlers, forwards every call
DuplexHandlerAdapterClassBase for handlers that do both
SimpleInboundHandlerClassInbound base that only takes one message type
ChannelHandlerTypeInboundHandler | OutboundHandler
InboundHandlerTypeCallbacks for inbound events
OutboundHandlerTypeCallbacks for write, flush and close
DuplexHandlerTypeInboundHandler & OutboundHandler
LifecycleCallbacksTypehandlerAdded and handlerRemoved

Built in handlers ​

Timeouts, batching, rate limits, metrics, logging and offloading. See Safety for limits, Metrics for metrics and Workers for offloading.

ExportKindWhat it is
IdleStateHandlerClassFires an IdleStateEvent after quiet time
IdleStateEventClassWhich side went idle
ReadTimeoutHandlerClassCloses a channel that stops reading
ReadTimeoutErrorClassRaised by ReadTimeoutHandler
WriteTimeoutHandlerClassCloses a channel whose write takes too long
WriteTimeoutErrorClassRaised by WriteTimeoutHandler
FlushConsolidationHandlerClassBatches flushes to cut syscalls
LoggingHandlerClassLogs every event that passes
MetricsHandlerClassCounts connections, bytes and messages
ChannelTrafficShapingHandlerClassLimits one channel's bytes a second
GlobalTrafficShapingHandlerClassLimits bytes a second across channels
TrafficShapingHandlerClassBase of both traffic shaping handlers
TokenBucketClassThe rate a shaping handler spends against
OffloadHandlerClassSends messages to a WorkerPool
IdleStateType'reader' | 'writer' | 'all'
IdleOptionsTypeTimeouts for IdleStateHandler
FlushConsolidationOptionsTypeSettings for FlushConsolidationHandler
OffloadOptionsTypePool and limits for OffloadHandler
MetricsOptionsTypeSettings for MetricsHandler
MetricsSnapshotTypeWhat MetricsHandler.snapshot returns
TrafficShapingOptionsTypeLimits for the traffic shaping handlers

Codecs ​

Framing and encoding. See Codecs.

ExportKindWhat it is
ByteToMessageDecoderClassBase for decoders that frame bytes
MessageToByteEncoderClassBase for encoders that write bytes
MessageToMessageDecoderClassBase for decoders that turn one message into others
MessageToMessageEncoderClassBase for encoders that turn one message into others
LengthFieldBasedFrameDecoderClassFrames by a length field
LengthFieldPrependerClassWrites a length field before each message
DelimiterBasedFrameDecoderClassFrames by delimiter bytes
LineBasedFrameDecoderClassFrames by LF or CRLF
FixedLengthFrameDecoderClassFrames by a fixed size
StringDecoderClassTurns frames into strings
StringEncoderClassTurns strings into UTF-8 bytes
BinaryCodecClassEncodes and decodes with your own functions
ProtobufCodecClassBinaryCodec for protobufjs types
MessagePackCodecClassBinaryCodec for a MessagePack library
DecoderErrorClassRaised when input can't be decoded
EncoderErrorClassRaised when a message can't be encoded
DecoderOptionsTypeCumulation limit for ByteToMessageDecoder
LengthFieldOptionsTypeLayout of the length field
LengthFieldLengthType1 | 2 | 3 | 4 | 8
PrependerOptionsTypeLayout of the prepended length
DelimiterOptionsTypeDelimiters and frame limit
LineOptionsTypeLine limit and stripping
BinaryCodecOptionsTypeEncode, decode and accepts functions
ProtobufTypeTypeShape of a protobufjs message type
MessagePackerTypeShape of a MessagePack library

HTTP codecs ​

HTTP/1.1 codecs and messages. See HTTP.

ExportKindWhat it is
HttpServerCodecClassRequest decoder and response encoder together
HttpClientCodecClassRequest encoder and response decoder together
HttpRequestDecoderClassBytes to requests and content
HttpResponseDecoderClassBytes to responses and content
HttpObjectDecoderClassBase for both decoders
HttpRequestEncoderClassRequests and content to bytes
HttpResponseEncoderClassResponses and content to bytes
HttpObjectEncoderClassBase for both encoders
HttpObjectAggregatorClassJoins a message and its content into one
HttpMessageClassBase for requests and responses
HttpRequestClassRequest line and headers
HttpResponseClassStatus line and headers
FullHttpRequestClassRequest with its whole body
FullHttpResponseClassResponse with its whole body
HttpContentClassA piece of a body
LastHttpContentClassThe last piece of a body, with trailers
HttpHeadersClassCase insensitive header list
HttpMethodClassRequest method, with constants like GET
HttpResponseStatusClassStatus code and phrase, with constants like OK
HttpVersionClassHTTP_1_0 or HTTP_1_1
HttpDecoderOptionsTypeLine, header and chunk limits
HttpObjectTypeHttpMessage | HttpContent
FullHttpMessageTypeFullHttpRequest | FullHttpResponse
ContentSourceTypeByteBuf | Uint8Array | string
HeaderEntryTypeA name and value pair
HeaderValueTypestring | number

WebSocket codecs ​

WebSocket frames and protocol handlers for pipelines. See WebSocket.

ExportKindWhat it is
WebSocketServerProtocolHandlerClassServer handshake and control frames
WebSocketClientProtocolHandlerClassClient handshake and control frames
WebSocketProtocolHandlerClassBase for both protocol handlers
WebSocketFrameDecoderClassBytes to frames
WebSocketFrameEncoderClassFrames to bytes
WebSocketFrameClassBase for every frame
TextWebSocketFrameClassText frame
BinaryWebSocketFrameClassBinary frame
ContinuationWebSocketFrameClassNext piece of a fragmented message
CloseWebSocketFrameClassClose frame with status and reason
PingWebSocketFrameClassPing frame
PongWebSocketFrameClassPong frame
WebSocketHandshakeCompleteClassUser event fired after the upgrade
WebSocketUpgradeClassSwaps the HTTP codec for frame codecs
WebSocketKeyClassSec-WebSocket-Key and its accept value
WebSocketCloseStatusClassClose codes, with constants like NORMAL_CLOSURE
CorruptedFrameErrorClassRaised on a bad frame, with a close code
HandshakeErrorClassRaised when the upgrade fails
WebSocketOpcodeConstantFrame opcodes by name
WebSocketOpcodeValueTypeOne of the WebSocketOpcode values
WebSocketServerOptionsTypePath, subprotocols and frame limit
WebSocketClientOptionsTypeURL, subprotocols, headers and frame limit
WebSocketDecoderOptionsTypeMasking rule and frame limit
WebSocketEncoderOptionsTypeMasking rule
FrameSourceTypeByteBuf | Uint8Array | string

Datagrams ​

UDP channels. See UDP.

ExportKindWhat it is
DatagramBootstrapClassBuilds and binds a UDP channel
DatagramChannelClassChannel over a UDP socket
DatagramPacketClassPayload with sender and recipient
DatagramTransportClassTransport over a Bun UDP socket
DatagramBindOptionsTypeLocal host and port
DatagramConnectOptionsTypeRemote host and port, plus local ones
PacketAddressTypeHost and port of a packet
UdpHandleTypeA bound or connected Bun UDP socket

Reliable UDP ​

Reliable UDP with lanes, acks and optional encryption. See Reliable UDP.

ExportKindWhat it is
ReliableBootstrapClassBinds a reliable server or connects a client
ReliableHandlerClassPipeline handler that runs the protocol
ReliablePeerClassOne connected peer
ReliableMessageClassA message from a peer on a lane
PeerConnectedClassUser event when a peer connects
PeerDisconnectedClassUser event when a peer leaves
PeerRegistryClassPeers by address
LaneClassSend and receive state for one lane
PacketCipherClassSeals and opens packets
CookieJarClassIssues and checks handshake cookies
PacketKindConstantPacket type bytes by name
connectPacketFunctionBuilds a connect packet
ReliableOptionsTypeEvery setting for ReliableHandler
ReliableSettingsTypeReliableOptions without role and server
ReliableRoleType'server' | 'client'
ReliableServerTypeChannel and handler from bind
ReliableClientTypeChannel, handler and peer from connect
LaneOptionsTypeDelivery mode for a lane
DeliveryType'reliable-ordered' | 'reliable-unordered' | 'unreliable-sequenced' | 'unreliable'
DeliverTypeCallback that receives a whole message
OutgoingTypeA queued message fragment
EncryptionOptionsTypeKey pair and expected server key
KeyPairTypeX25519 public and private key
SimulateOptionsTypeFake loss, latency, jitter and duplicates
DisconnectReasonType'closed' | 'timeout' | 'resends' | 'local'
PeerOptionsTypeSettings a ReliablePeer is built with
PeerStateType'connecting' | 'connected' | 'closed'
PeerStatsTypePacket and resend counters

WebSocket server ​

WebSocket servers on Bun.serve. See WebSocket.

ExportKindWhat it is
WebSocketBootstrapClassBuilds and binds a WebSocket server
WebSocketServerClassA running server and its channels
WebSocketChannelClassChannel over a Bun ServerWebSocket
WebSocketFrameWriterClassOutbound handler that sends frames natively
WebSocketOutboxClassQueue for sends Bun can't take yet
WebSocketTransportClassTransport over a ServerWebSocket
WebSocketBootstrapOptionsTypePath, TLS, limits and upgrade hook
WebSocketBindOptionsTypeHost and port to listen on
UpgradeHandlerTypeDecides whether to accept an upgrade
UpgradeVerdictTypeAccept with data, or refuse with a status
WebSocketStateTypeData kept on each Bun socket
OutgoingMessageTypeA binary, text, ping, pong or close send
SendResultType'sent' | 'queued' | 'full' | 'closed'
OutboxEventsTypeBlocked and cleared callbacks

Workers ​

Worker threads. See Workers.

ExportKindWhat it is
WorkerPoolClassRuns jobs on a pool of threads
WorkerServiceClassAnswers pool jobs inside a thread
WorkerGroupClassStarts the same script on several threads
WorkerPoolOptionsTypeScript, thread count and queue limit
WorkerGroupOptionsTypeScript, thread count and shared memory
WorkerTaskTypeFunction a WorkerService runs
WorkerRequestTypeJob sent to a thread
WorkerReplyTypeAnswer from a thread

Cluster ​

Processes sharing a port. See Clustering.

ExportKindWhat it is
ClusterClassStarts, stops and reloads worker processes
ClusterOptionsTypeScript, worker count, restarts and timeouts
ReloadOrderType'start-first' | 'stop-first'

Sharding ​

Zones split over processes. See Sharding.

ExportKindWhat it is
ShardMapClassMaps zones to shards and ports
ShardMapOptionsTypeShard count and first port
ShardLinkClassMessages, requests, handoffs and recalls
ShardLinkOptionsTypeId, peers, timeouts and message size
ShardPeerTypeWhere a shard listens, TCP or Unix socket
ShardListenerTypeGets a message from another shard
ShardResponderTypeAnswers a request from another shard
GatewayClassTopics with subscribers on any shard

Logging ​

ExportKindWhat it is
ConsoleLoggerClassDefault logger, writes to the console
LoggerTypedebug and warn with fields
LogFieldsTypeRecord<string, unknown>

Any logger with these two methods works, like pino. Pass it as logger in ChannelOptions.

Classes ​

Signatures leave out public. get marks a getter and static a static member.

Channel ​

MemberSignatureWhat it does
idreadonly numberUnique id in this process
pipelinereadonly PipelineThe handler chain
attributesreadonly AttributeMapPer channel state
closedreadonly Promise<void>Resolves once the channel has shut down
isActiveget booleanConnected and set up
isWritableget booleanFalse above the high water mark
pendingBytesget numberBytes waiting for the socket
remoteAddressget stringPeer IP
remotePortget numberPeer port
write(message: unknown): Promise<void>Writes through the pipeline
flush(): Promise<void>Sends what's been written
writeAndFlush(message: unknown): Promise<void>Writes and flushes
writeSync(message: unknown): voidWrite with no promise
writeAndFlushSync(message: unknown): voidWrite and flush with no promise
writeEncoded(bytes: Uint8Array | ByteBuf): Promise<void>Writes bytes past every handler
writeAndFlushEncoded(bytes: Uint8Array | ByteBuf): Promise<void>writeEncoded plus a flush
writeAndFlushEncodedSync(bytes: Uint8Array | ByteBuf): voidSame with no promise
writeEncodedSync(bytes: Uint8Array | ByteBuf): voidQueues encoded bytes, no flush
close(): Promise<void>Closes through the outbound handlers
execute(task: () => void | Promise<void>): Promise<void>Runs a task in line with inbound events
activate(setup?: ChannelSetup | null): Promise<void>Runs setup and fires channelActive
handleData(bytes: Uint8Array): Promise<void>Transport hook for incoming bytes
handleMessage(message: unknown): Promise<void>Transport hook for incoming messages
handleDrain(): voidTransport hook for socket drain
handleClose(): Promise<void>Transport hook for socket close
handleError(error: unknown): Promise<void>Transport hook for socket errors
Channel.defaultHighWaterMarkstatic number65536
Channel.defaultLowWaterMarkstatic number32768
Channel.defaultMaxPendingBytesstatic number67108864

Pipeline ​

MemberSignatureWhat it does
channelreadonly ChannelChannel it belongs to
loggerreadonly LoggerLogger for unhandled events
trackerreadonly WriteTrackerWrite and flush ordering
syncingbooleanSet during a sync write
addFirst<T>(name: string, handler: T): thisAdds next to the head
addLast<T>(name: string, handler: T): thisAdds next to the tail
addBefore<T>(base: string, name: string, handler: T): thisAdds on the head side of base
addAfter<T>(base: string, name: string, handler: T): thisAdds on the tail side of base
remove<T>(name: string): TRemoves and returns a handler
replace<T>(base: string, name: string, handler: T): ChannelHandlerSwaps a handler and returns the old one
get<T>(name: string): T | nullHandler by name
find<T>(type: abstract new (...parameters: never[]) => T): T | nullHandler by class
context(name: string): HandlerContext | nullContext by name
names(): string[]Handler names in order
settle(): Promise<void>Waits for every add and remove hook
fireChannelActive(): Promise<void>Starts channelActive at the head
fireChannelInactive(): Promise<void>Starts channelInactive at the head
fireChannelRead(message: unknown): Promise<void>Starts a read at the head
fireChannelReadComplete(): Promise<void>Starts channelReadComplete
fireChannelWritabilityChanged(): Promise<void>Starts channelWritabilityChanged
fireUserEventTriggered(event: unknown): Promise<void>Sends a user event through
fireExceptionCaught(error: unknown): Promise<void>Sends an error through
write(message: unknown): Promise<void>Writes from the tail
writeSync(message: unknown): voidWrite with no promise
flush(): Promise<void>Flushes from the tail
writeAndFlush(message: unknown): Promise<void>Writes and flushes
writeAndFlushSync(message: unknown): voidWrite and flush with no promise
close(): Promise<void>Closes from the tail

T extends ChannelHandler throughout.

HandlerContext ​

MemberSignatureWhat it does
namereadonly stringName in the pipeline
pipelinereadonly PipelinePipeline it belongs to
previousHandlerContext | nullNeighbour towards the head
nextHandlerContext | nullNeighbour towards the tail
handlerget ChannelHandlerThe handler it wraps
channelget ChannelThe channel
fireChannelActive(): Promise<void>Passes channelActive on
fireChannelInactive(): Promise<void>Passes channelInactive on
fireChannelRead(message: unknown): Promise<void>Passes a message on
fireChannelReadComplete(): Promise<void>Passes channelReadComplete on
fireChannelWritabilityChanged(): Promise<void>Passes a writability change on
fireUserEventTriggered(event: unknown): Promise<void>Passes a user event on
fireExceptionCaught(error: unknown): Promise<void>Passes an error on
write(message: unknown): Promise<void>Writes from this point
flush(): Promise<void>Flushes from this point
writeAndFlush(message: unknown): Promise<void>Writes and flushes from this point
writeSync(message: unknown): voidWrite with no promise
writeAndFlushSync(message: unknown): voidWrite and flush with no promise
close(): Promise<void>Closes from this point

ByteBuf ​

Creating ​

MemberSignatureWhat it does
ByteBuf.allocatestatic (capacity?: number, maxCapacity?: number): ByteBufEmpty buffer
ByteBuf.wrapstatic (bytes: Uint8Array): ByteBufBuffer over existing bytes
ByteBuf.fromStringstatic (value: string): ByteBufBuffer holding UTF-8 text
ByteBuf.copyBytesstatic (source: Uint8Array, from: number, target: Uint8Array, to: number, size: number): voidCopies between arrays
ByteBuf.defaultCapacitystatic number256
ByteBuf.defaultMaxCapacitystatic number67108864

Indexes and capacity ​

MemberSignatureWhat it does
readerIndexget set numberNext byte to read
writerIndexget set numberNext byte to write
readableBytesget numberBytes between the indexes
writableBytesget numberRoom before capacity
capacityget numberCurrent size
maxCapacityget numberSize it can grow to
arrayget Uint8ArrayBacking array
arrayOffsetget numberStart of this buffer in array
isReadable(size?: number): booleanHas at least size bytes to read
ensureWritable(size: number): thisGrows to fit size more bytes
clear(): thisResets both indexes
markReaderIndex(): thisSaves the reader index
resetReaderIndex(): thisGoes back to the mark
skipBytes(size: number): thisMoves the reader index on
discardReadBytes(): thisDrops bytes already read

Reading and writing ​

Each number type comes in four forms. getX(index) and setX(index, value) work at an absolute index and don't move the reader or writer index. readX() and writeX(value) do. Multi byte forms take an optional endian, 'big' by default.

TypeValueBytes
Int8 / Uint8number1
Int16 / Uint16number2
Uint24number3
Int32 / Uint32number4
Int64 / Uint64bigint8
Float32number4
Float64number8
MemberSignatureWhat it does
readBytes(size: number): Uint8ArrayReads bytes into a copy
readSlice(size: number): ByteBufReads bytes as a shared view
slice(index: number, size: number): ByteBufShared view, reader stays put
sliceInto(index: number, size: number, target: ByteBuf): ByteBufPoints target at a shared view
writeBytes(source: Uint8Array | ByteBuf): thisWrites bytes
writeBytes(source: ByteBuf, index: number, length: number): thisWrites part of another buffer
readString(size: number): stringReads size bytes of UTF-8
writeString(value: string): numberWrites UTF-8, returns bytes written
readVarUint(): numberReads an unsigned varint
writeVarUint(value: number): thisWrites an unsigned varint
readVarInt(): numberReads a zigzag varint
writeVarInt(value: number): thisWrites a zigzag varint
indexOf(value: number | Uint8Array, from?: number, to?: number): numberFinds a byte or sequence
toUint8Array(): Uint8ArrayReadable bytes as a view
copy(): ByteBufIndependent copy
duplicate(): ByteBufShared bytes, own indexes
toString(): stringReadable bytes as UTF-8

Reference counts ​

See Pooled frames.

MemberSignatureWhat it does
retain(): thisAdds an owner
release(): booleanDrops an owner, true if it was the last
refCntnumberOwners it has
pooledbooleanWhether release hands it back to a pool
detach(): thisLeaves its pool for good
ByteBuf.forPoolstatic (pool: ByteBufPool): ByteBufEmpty buffer that belongs to a pool

ByteBufPool ​

MemberSignatureWhat it does
constructor(limit?: number)Keeps at most limit free buffers
take(): ByteBuf | nullA free buffer, or null
give(buffer: ByteBuf): voidKeeps a released buffer
ByteBufPool.defaultLimitstatic number1024

ChannelGroup ​

MemberSignatureWhat it does
sizeget numberMember count
[Symbol.iterator](): Iterator<Channel>Iterates the members
add(channel: Channel): thisAdds a channel until it closes
remove(channel: Channel): booleanRemoves without closing
has(channel: Channel): booleanChecks membership
find(id: number): Channel | nullMember by id
write(message: unknown, matcher?: ChannelMatcher): Promise<GroupResult>Writes to each match
flush(matcher?: ChannelMatcher): Promise<GroupResult>Flushes each match
writeAndFlush(message: unknown, matcher?: ChannelMatcher): Promise<GroupResult>Writes and flushes each match
broadcast(bytes: Uint8Array | ByteBuf, matcher?: ChannelMatcher): Promise<GroupResult>Sends encoded bytes past the pipelines
broadcastSync(bytes: Uint8Array | ByteBuf, matcher?: ChannelMatcher | null): numberSame with no promise, returns the count
close(matcher?: ChannelMatcher): Promise<GroupResult>Closes each match
ChannelGroup.allstatic (): ChannelMatcherMatches everyone
ChannelGroup.exceptstatic (excluded: Channel): ChannelMatcherMatches everyone but one

ServerBootstrap ​

MemberSignatureWhat it does
childHandler<T extends ChannelHandler>(handler: T): thisHandler for each connection
childHandler(setup: ChannelSetup): thisSetup for each connection
options(options: ServerOptions): thisListening socket settings
childOptions(options: SocketOptions): thisSettings for each connection
bind(address: BindOptions): Promise<ServerChannel>Starts listening
ServerBootstrap.defaultHostnamestatic string'0.0.0.0'

ServerChannel ​

MemberSignatureWhat it does
closedreadonly Promise<void>Resolves once every child has closed
addressget ServerAddressHost and port, or Unix path
hostnameget stringBound host, throws on Unix sockets
portget numberBound port, throws on Unix sockets
isOpenget booleanFalse once closing starts
channelsget readonly Channel[]Snapshot of open connections
close(): Promise<void>Stops listening and closes children

Bootstrap ​

MemberSignatureWhat it does
handler<T extends ChannelHandler>(handler: T): thisHandler for the channel
handler(setup: ChannelSetup): thisSetup for the channel
options(options: ClientOptions): thisSocket settings
connect(address: ConnectOptions): Promise<Channel>Connects

ReconnectingClient ​

new ReconnectingClient(bootstrap: Bootstrap, address: ConnectOptions, options?: ReconnectOptions, events?: ReconnectEvents)

MemberSignatureWhat it does
channelget Channel | nullCurrent channel, or null
isRunningget booleanStarted and not given up
start(): Promise<Channel>Connects and keeps reconnecting
waitForChannel(): Promise<Channel>Resolves on the next connection
stop(): Promise<void>Stops retrying and closes

DatagramBootstrap ​

MemberSignatureWhat it does
handler<T extends ChannelHandler>(handler: T): thisHandler for the channel
handler(setup: ChannelSetup<DatagramChannel>): thisSetup for the channel
options(options: ChannelOptions): thisChannel settings
bind(options?: DatagramBindOptions): Promise<DatagramChannel>Binds a socket for any peer
connect(options: DatagramConnectOptions): Promise<DatagramChannel>Binds a socket for one peer
DatagramBootstrap.defaultHostnamestatic string'0.0.0.0'

DatagramChannel ​

Extends Channel. Writes take a DatagramPacket, or bytes on a connected channel.

MemberSignatureWhat it does
localAddressget PacketAddressBound host and port
isConnectedget booleanTied to one peer
sendMany(content: ByteBuf | Uint8Array, recipients: readonly PacketAddress[]): numberOne payload to many peers in one syscall
setBroadcast(enabled: boolean): thisAllows broadcast addresses
setTtl(ttl: number): thisSets the hop limit
joinGroup(group: string, interfaceAddress?: string | null): booleanJoins a multicast group
leaveGroup(group: string, interfaceAddress?: string | null): booleanLeaves a multicast group

ReliableBootstrap ​

MemberSignatureWhat it does
options(options: ReliableSettings): thisProtocol settings
channelOptions(options: ChannelOptions): thisChannel settings
handler(setup: ChannelSetup<DatagramChannel>): thisSetup after the reliable handler
bind(address: DatagramBindOptions): Promise<ReliableServer>Starts a server
connect(server: PacketAddress): Promise<ReliableClient>Connects to a server

ReliableHandler ​

MemberSignatureWhat it does
connectedget Promise<ReliablePeer>Server peer, on a client
peersget ReadonlySet<ReliablePeer>Every known peer
publicKeyget Uint8Array | nullOwn public key, or null
ReliableHandler.generateKeyPairstatic (): KeyPairNew key pair for a fixed server identity
ReliableHandler.defaultLanesstatic readonly LaneOptions[]Reliable ordered, then unreliable
ReliableHandler.connectIntervalstatic number100 ms between connect packets

ReliablePeer ​

MemberSignatureWhat it does
addressreadonly PacketAddressPeer address
saltreadonly numberHandshake salt
sessionnumberSession id
statePeerStateWhere it is in its life
statsreadonly PeerStatsPacket and resend counters
lastReceivedAtnumberLast packet in
lastSentAtnumberLast packet out
failedbooleanA message ran out of resends
closingbooleanSet by close
dataunknownYour own data
cipherPacketCipher | nullPacket cipher, or null
rttget numberSmoothed round trip in ms
send(lane: number, content: ByteBuf | Uint8Array | string): voidQueues a message on a lane
close(): voidHangs up on the next tick
receive(bytes: Uint8Array, now: number, out: ReliableMessage[]): voidHandler hook for a data packet
pack(now: number, out: Uint8Array[], force: boolean): voidHandler hook that builds packets
isDue(now: number): booleanHas work on this tick
hasWorkget booleanHas something to send now
owesAckget booleanWaiting to send an ack

ReliableMessage has peer, lane, content and reply(content), which sends back on the same lane.

WebSocketBootstrap ​

MemberSignatureWhat it does
childHandler<T extends ChannelHandler>(handler: T): thisHandler for each socket
childHandler(setup: ChannelSetup<WebSocketChannel>): thisSetup for each socket
options(options: WebSocketBootstrapOptions): thisServer settings
childOptions(options: ChannelOptions): thisSettings for each channel
bind(address: WebSocketBindOptions): Promise<WebSocketServer>Starts listening
WebSocketBootstrap.defaultMaxPayloadLengthstatic number1048576

WebSocketServer ​

MemberSignatureWhat it does
serverreadonly Server<WebSocketState>The Bun server
portget numberBound port
hostnameget stringBound host
channelsget ReadonlySet<WebSocketChannel>Every open channel
publish(topic: string, content: ByteBuf | Uint8Array | string): numberSends to everyone on a topic
subscriberCount(topic: string): numberSockets on a topic
close(): Promise<void>Stops and closes every channel

WebSocketChannel ​

Extends Channel. Writes take frames, strings, Uint8Array or ByteBuf.

MemberSignatureWhat it does
socketreadonly ServerWebSocket<WebSocketState>The Bun socket
dataget unknownData from the upgrade hook, or null
uriget stringRequested path and query
isWritableget booleanFalse while Bun is backed up
pendingBytesget numberBytes queued in Netify
bufferedAmountget numberBytes queued in Bun
subscribe(topic: string): booleanJoins a topic
unsubscribe(topic: string): booleanLeaves a topic
isSubscribed(topic: string): booleanChecks a topic
publish(topic: string, content: ByteBuf | Uint8Array | string): numberSends to everyone else on a topic
sendNative(message: OutgoingMessage): SendResultSends now or queues in order

Gateway ​

MemberSignatureWhat it does
constructor(link: ShardLink)Listens for publishes from other shards
subscribe(channel: Channel, topic: string): voidPuts a local channel on a topic
unsubscribe(channel: Channel, topic: string): booleanTakes it off again
isSubscribed(channel: Channel, topic: string): booleanChecks a local channel
subscriberCount(topic: string): numberLocal channels on a topic
publish(topic: string, bytes: Uint8Array | ByteBuf): numberSends to every shard, returns the local count

Released under the MIT licence.