celeris

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Celeris Go client

Go Reference License

Realtime client for Celeris channels: connection lifecycle with automatic recovery, segment messaging, and presence.

The model in three sentences. A Channel is one WebSocket client: creating another Channel, even for the same reference, opens another socket. Every segment of that channel is multiplexed over that single connection, and connecting automatically makes you a member of the "default" segment. Segment handles are lightweight: create as many as you like, they share the socket and one interest count.

Install

go get github.com/useceleris/sdk-go-client

Go 1.27 or newer. The package name is celeris, and its only dependency is github.com/coder/websocket.

Quickstart

client, err := celeris.NewClient(celeris.ClientOptions{CredentialProvider: fetchCredentials})

if err != nil {
	log.Fatal(err)
}

channel, err := client.Channel("room-42")

if err != nil {
	log.Fatal(err)
}

defer channel.Close()

chat, err := channel.Segment("chat")

if err != nil {
	log.Fatal(err)
}

chat.OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
	fmt.Println(metadata.MessageID, string(payload))
})

if _, err := chat.Subscribe(); err != nil {
	log.Fatal(err)
}

ctx := context.Background()

if err := channel.Connect(ctx); err != nil {
	log.Fatal(err)
}

if err := chat.Publish(ctx, celeris.TextPayload("hello")); err != nil {
	log.Fatal(err)
}

examples/quickstart is the same flow as a complete program, with presence.

Credentials

The client never signs. A CredentialProvider fetches fresh credentials from your own authenticated endpoint, which signs them with sdk-go-server. Never ship a signing secret in an application.

func fetchCredentials(ctx context.Context, request celeris.CredentialRequest) (celeris.Credentials, error) {
	body, err := json.Marshal(map[string]any{
		"channelReference": request.ChannelReference,
		"replayLookbackMs": request.ReplayLookback.Milliseconds(),
	})

	if err != nil {
		return celeris.Credentials{}, err
	}

	httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, os.Getenv("CELERIS_CREDENTIAL_URL"), bytes.NewReader(body))

	if err != nil {
		return celeris.Credentials{}, err
	}

	httpRequest.Header.Set("Authorization", "Bearer "+os.Getenv("CELERIS_SESSION"))
	httpRequest.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(httpRequest)

	if err != nil {
		return celeris.Credentials{}, err
	}

	defer func() { _ = response.Body.Close() }()

	if response.StatusCode != http.StatusOK {
		return celeris.Credentials{}, fmt.Errorf("credential endpoint answered %s", response.Status)
	}

	var credentials celeris.Credentials
	err = json.NewDecoder(response.Body).Decode(&credentials)

	return credentials, err
} // end function fetchCredentials

The provider runs once per connection attempt, reconnects included, and must honour ctx: the connect deadline and Close both cancel it. On a reconnect, request.Reconnect is true and ReplayLookback suggests how much history to replay: the outage so far plus five seconds. Your endpoint decides whether to grant it. A provider's error is reported as ErrTransport, ErrTimeout or ErrCancelled, and its text is never passed on. Credentials print as redacted through fmt and slog.

Channels and connection

Connect returns once the socket is up and your subscriptions are queued to be restored. A first connect that fails is not retried: the channel becomes failed and you may call Connect again. Only a connection that was up recovers automatically. Close is terminal and idempotent, returns within about five seconds, and fails waiting publishes and presence queries with ErrCancelled.

States run idle → connecting → connected, then reconnecting and back to connected on recovery, failed when recovery gives up, and closing → closed on Close.

channel.Events().OnStateChange(func(state celeris.ChannelState) {
	switch state {
	case celeris.StateReconnecting:
		fmt.Println("connection lost; recovering")
	case celeris.StateFailed:
		fmt.Println("gave up; call Connect to try again")
	}
})

A channel reference is 1 to 255 ASCII letters, digits, - or _. A segment id is any non-empty valid UTF-8 without CR or LF.

Subscribing and receiving

Subscribe registers interest in a segment. The first interest subscribes it, the last Cancel unsubscribes it, and subscriptions are restored after every reconnect. The protocol has no acknowledgement, so a denial arrives later through OnError. A subscription needs read access to the segment, and a publish needs write access. The default segment is joined on connect and never needs a subscription.

stop := chat.OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
	sent := time.UnixMilli(metadata.Timestamp)
	fmt.Println(metadata.TokenReference, "at", sent.Format(time.Kitchen), "said", string(payload))
})

defer stop()

subscription, err := chat.Subscribe()

if err != nil {
	log.Fatal(err)
}

defer subscription.Cancel()

The payload is the SDK's own copy, shared by every listener of that delivery: treat it as read-only. Each message id is delivered once within the deduplication window (DeduplicationWindowSize, 1024 ids by default).

The server, not a listener, controls the messages that you receive from a segment:

  • When you hold a subscription to a segment, the connection receives the messages of that segment. A listener alone receives no messages.
  • A publish does not join the connection to the segment. To receive the messages of a segment, your own echo included, call Subscribe.
  • With write access only, the connection can publish, and the server refuses Subscribe with a PermissionDeniedError through OnError. With read access only, the connection can subscribe, and the server refuses the publish.
  • When you cancel the last subscription of a segment, the server removes the connection from the segment. A presence subscription does not join or keep a segment.
  • After a reconnect, the SDK subscribes again to the segments that you hold a subscription for.
  • The connection always receives the messages of "default".
  • Listeners and subscriptions are different. When you remove one, the other does not change.

To receive all messages that the connection gets, from all segments, add a channel listener. The segment listeners get each message first, then the channel listeners:

removeChannelListener := channel.Events().OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
	fmt.Println(metadata.SegmentID, string(payload))
})

defer removeChannelListener()

removeChannelListener removes only this channel listener. The other channel listeners and the segment listeners continue to receive messages. Your subscriptions do not change, and the SDK does not send a message to the server. When you call the function again, it has no effect.

Publishing

Publish sends with a generated message id; PublishWithMessageID sends with yours. Returning nil means the local socket accepted the bytes, not that anyone received them.

A generated id is msg__go_v, the SDK version, two underscores, then 32 random lowercase hex digits, for example msg__go_v1.0.0__4f1c9a0b7d2e43f6a8b5c1d0e9f27364. It holds only letters, digits, dots and underscores, and the double underscores keep it apart from the ids that the server generates (msg_{node}_…). Your own id must have at least one character and no CR or LF, and the SDK sends it exactly as you give it.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err := chat.PublishWithMessageID(ctx, celeris.TextPayload("Order 1042 shipped"), "order-1042-shipped")

switch {
case err == nil:
	fmt.Println("handed to the socket")
case errors.Is(err, celeris.ErrBackpressure):
	fmt.Println("the publish queue is full (PublishQueueSize, 64 by default); retry later")
case errors.Is(err, celeris.ErrDeliveryUnknown):
	fmt.Println("may or may not have been sent; do not resend blindly")
default:
	fmt.Println("not sent:", err)
}

While the channel reconnects, Publish waits: the publish stays in the publish queue and is sent after the reconnect, once your subscriptions are restored, or fails with the terminal error if recovery ends in failed, with ErrCancelled if you close the channel, or when its context ends. Before the first connect, while connecting, and once failed or closed, Publish returns ErrNotConnected. Your plan's cap counts the whole encoded command, not only the payload. A publish over the cap still returns nil, and the server refuses it afterwards with a MessageSizeLimitError through OnError. A publish does not join the segment: call Subscribe to receive from it.

Payloads

Payloads are opaque bytes. TextPayload and ReadText handle UTF-8 text, JSONPayload and ReadJSON[T] handle JSON:

type typing struct {
	Active bool `json:"active"`
}

chat.OnMessage(func(payload []byte, _ celeris.MessageMetadata) {
	event, err := celeris.ReadJSON[typing](payload)

	if err != nil {
		return // not a typing event
	}

	fmt.Println("typing:", event.Active)
})

payload, err := celeris.JSONPayload(typing{Active: true})

if err != nil {
	log.Fatal(err)
}

if err := chat.Publish(ctx, payload); err != nil {
	log.Fatal(err)
}

NewPayloadCodec gives any other serializer, such as protobuf, MessagePack or CBOR, the same shape, without this module depending on it:

type position struct{ X, Y int }

codec, err := celeris.NewPayloadCodec(
	func(value position) ([]byte, error) {
		var encoded bytes.Buffer
		err := gob.NewEncoder(&encoded).Encode(value)

		return encoded.Bytes(), err
	},
	func(payload []byte) (position, error) {
		var value position
		err := gob.NewDecoder(bytes.NewReader(payload)).Decode(&value)

		return value, err
	},
)

ReadJSON asserts a type; it does not validate. Check payloads from peers you do not control.

Presence

A presence subscription delivers joins and leaves. It watches without joining: it delivers no messages, and the watcher is not itself announced or listed. Events and PresenceList cover every server node serving the channel.

chat.OnPresence(func(event celeris.PresenceEvent) {
	if event.Joined {
		fmt.Println(event.TokenReference, "joined on connection", event.ConnectionID)
	} else {
		fmt.Println(event.TokenReference, "left from connection", event.ConnectionID)
	}
})

presence, err := chat.SubscribePresence()

if err != nil {
	log.Fatal(err)
}

defer presence.Cancel()

PresenceList reads one page of who is present, up to 100 per page:

for page := int32(1); ; page++ {
	result, err := chat.PresenceList(ctx, page, 100)

	if err != nil {
		log.Fatal(err)
	}

	for _, connection := range result.Connections {
		fmt.Println(connection.TokenReference, connection.ConnectionID)
	}

	if len(result.Connections) == 0 || result.To >= result.Total {
		break
	}
}

One query may be in flight per channel; another returns ErrOperationInProgress, and a query times out after PresenceQueryTimeout (10 s by default) without affecting the connection. Its reply is routed by the goroutine that runs listeners, so a query made inside a listener always times out: start it from a goroutine of your own.

Errors

The SDK's own failures are *celeris.Error values, matched by code with errors.Is. Their messages name what failed and the rule it broke, never your input values, credentials or server bytes.

Code Meaning
ErrConfiguration Invalid options, identifiers or payloads, or credentials a provider returned
ErrTimeout A connect attempt, presence query or context deadline ran out
ErrCancelled Cancelled by its context or by Close
ErrTransport The provider failed, the handshake was refused, or the socket broke
ErrNotConnected The operation needs a connection the channel does not have
ErrBackpressure the publish queue (PublishQueueSize, 64 by default) is full, or sending is paused after a rate limit
ErrOperationInProgress A second Connect, or a second presence query, while the first runs
ErrDeliveryUnknown A publish that may or may not have left the socket; never resent automatically
ErrProtocol A server message could not be decoded; it is dropped and the connection stays up

A refused handshake is ErrTransport: the SDK never reports an authentication failure. Errors the server sends arrive through OnError as *celeris.ServerError, with its Type (PermissionDeniedError, RateLimitError, MessageSizeLimitError, ParserError, SendError or InternalError), SubType (the command it answers), Message and Resource:

channel.Events().OnError(func(err error) {
	if serverError, ok := errors.AsType[*celeris.ServerError](err); ok {
		fmt.Println("server:", serverError.Type, serverError.SubType, serverError.Resource)

		return
	}

	fmt.Println("sdk:", err)
})

OnNotice delivers the server's raw notices, such as greetings, as prose. Never branch on their text.

Reconnection and recovery

A connection that drops is recovered automatically: up to MaximumReconnectAttempts failed attempts (10 by default, 1 to 100) with full jitter up to 30 s, each with fresh credentials, bounded by ReconnectTimeout (ConnectTimeout by default), and with a replay lookback covering the outage. The retry budget resets after a connection stays up for 60 s. A ping every 20 s keeps the connection open while a listener runs, and a ping left unanswered for 15 s of reading time means the path is dead, so the connection is recovered. Time a listener holds delivery never counts, so a slow listener never looks like a dead link. When recovery gives up, OnError reports why and the channel becomes failed.

channel.Events().OnRecovery(func(event celeris.RecoveryEvent) {
	// Replay is a bounded window: gaps and duplicates are always possible.
	fmt.Println("recovered on retry", event.RetryIndex)
})

Recovery restores every subscription and reports possible gaps and duplicates every time. Replayed messages already seen are dropped within the deduplication window (DeduplicationWindowSize, 1024 ids by default); duplicates beyond it reach your listeners.

Delivery semantics, honestly

  • There is no server receipt or ack anywhere in the protocol. Publish returning means the local socket accepted the bytes.
  • No offline queue beyond a reconnect, no durable history, no global ordering. Publishes still waiting in the publish queue when the connection drops wait for the reconnect and go out in call order after the restored subscriptions; they fail with the terminal error if recovery ends in failed, and with ErrCancelled on Close. Publishes the socket had not started writing go back to the front of the queue in their order; the one being written when the connection dropped reports ErrDeliveryUnknown and is never sent again.
  • A RateLimitError never names the command it dropped, so the client pauses and resends what it sent in the last two seconds: subscriptions as their current state, then up to 64 publishes, each at most once and with its original id so receivers drop a copy that already arrived. After eight limits in a row the limit is treated as a used-up quota: resending stops, and dropped subscriptions are retried on a slow probe, after a minute and doubling to an hour. Resends count toward usage.
  • Subscriptions and publishes wait for room when the writer is full instead of failing. A subscription change goes out ahead of publishes, but never ahead of a publish to its own segment that was queued before it.
  • A publish does not join a segment, and a presence subscription does not. Only Subscribe joins.

Limits and defaults

What Value
Outbound command 2 MiB encoded, refused before any write
Plan cap 64 KiB free, 128 KiB standard, 512 KiB pro, 1024 KiB prime, on the whole encoded command; enforced by the server
Writer bounds 64 commands / 2 MiB not yet written; PublishQueueSize queued publishes (64 by default), plus resends
Rate-limit pause 1 s plus full jitter growing with consecutive limits, at most 31 s
Resends last 2 s of commands, at most 64 publishes, each once
Quota probe after 8 limits in a row: dropped subscriptions retried after 1 min, doubling to 1 h
Connect deadline ConnectTimeout, default 15 s, covering credentials and the handshake
Timeout options each 1 ms to 15 min; 0 means the default
Reconnect deadline ReconnectTimeout per reconnect attempt, covering credentials and the handshake; defaults to ConnectTimeout
Presence query one in flight per channel; PresenceQueryTimeout, default 10 s; a timeout never drops the connection
Reconnect MaximumReconnectAttempts failed attempts, default 10, 1 to 100; full jitter up to 30 s, reset after 60 s connected
Heartbeat a WebSocket ping every 20 s
Dead connection a ping unanswered for 15 s of reading time, time in listeners excluded: noticed within about 35 s, then recovered
Dedup window DeduplicationWindowSize message ids per channel, 1024 by default
Close at most about 5 s, even when the server does not answer

Received messages are never size-checked: they are already in memory when they arrive. A publish rejected for your plan's cap still counts toward your usage.

Goroutines, contexts and cancellation

A Client, its channels and their segments are safe for concurrent use. Listeners run one at a time, in the order events happened, never under an SDK lock: a slow listener slows delivery rather than growing a queue, and a listener may call Publish, Subscribe, Close or Connect. Its own calls never wait for their events; those follow once it returns. The exception is PresenceList, as above.

ctx bounds only the call it is passed to; it never closes the channel. Cancelling Connect abandons the attempt and leaves the channel failed. Cancelling Publish takes back a publish the socket has not started writing (ErrCancelled, or ErrTimeout for a deadline); one the socket is already writing reports ErrDeliveryUnknown. Cancelling PresenceList frees the query slot.

Local development and self-hosting

The production endpoint is built in. Set BaseURL only for a local stack or another deployment; ws:// is accepted only for a loopback host, and only when you opt in:

client, err := celeris.NewClient(celeris.ClientOptions{
	CredentialProvider: fetchCredentials,
	BaseURL:            os.Getenv("CELERIS_WS_URL"),
	// A local ws:// stack; production uses the built-in wss:// endpoint.
	AllowInsecureLoopback: true,
})

TLS is always verified, through the module's own HTTP transport: changes an application makes to http.DefaultTransport cannot weaken it.

Versioning

Releases follow semantic versioning. Before v1.0.0, a minor release may change the API.

More documentation

Development

make check runs formatting, go vet, golangci-lint, govulncheck, module tidiness, and the unit suites under the race detector, including the package checks: pinned exports, no signing facility reachable, nothing printed, and every snippet in this README compiled. make live runs the acceptance suites against a real Celeris stack; they read CELERIS_WS_URL, CELERIS_CLIENT_ID and CELERIS_SIGNING_SECRET from a gitignored .env or the environment. make fuzz fuzzes the decoder for a minute.

Read CONVENTIONS.md before contributing, and SECURITY.md before reporting a vulnerability.

License

Apache 2.0.

Documentation

Overview

Package celeris is the Celeris realtime client.

A Client holds configuration and creates channels. A Channel is one WebSocket connection; every segment of the channel is multiplexed over it. A Segment handle subscribes, listens, publishes and queries presence.

Credentials come from a CredentialProvider, called afresh for every connection attempt, reconnects included. Fetch them from your own backend, which signs them with the server SDK; a client never signs.

Publish returns once the socket accepted the bytes. The protocol has no acknowledgements, so that is not receipt or delivery. A dropped connection is recovered automatically with fresh credentials, and every recovery declares that gaps and duplicates are possible.

Events are listener registrations that return a function removing the listener. Listeners run one at a time, in the order events happened, never under an SDK lock; a slow listener holds up the next event. A Channel and its segments are safe for concurrent use.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

// fetchCredentials stands for a call to your own credential endpoint, which
// signs credentials with the server SDK.
func fetchCredentials(context.Context, celeris.CredentialRequest) (celeris.Credentials, error) {
	return celeris.Credentials{}, errors.New("call your credential endpoint here")
}

func main() {
	client, err := celeris.NewClient(celeris.ClientOptions{CredentialProvider: fetchCredentials})

	if err != nil {
		log.Fatal(err)
	}

	channel, err := client.Channel("room-42")

	if err != nil {
		log.Fatal(err)
	}

	defer channel.Close()

	chat, err := channel.Segment("chat")

	if err != nil {
		log.Fatal(err)
	}

	chat.OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
		fmt.Println(metadata.MessageID, string(payload))
	})

	if _, err := chat.Subscribe(); err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	if err := channel.Connect(ctx); err != nil {
		log.Fatal(err)
	}

	if err := chat.Publish(ctx, celeris.TextPayload("hello")); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSONPayload

func JSONPayload(value any) ([]byte, error)

JSONPayload encodes value as JSON with encoding/json, without escaping HTML characters. It fails with ErrConfiguration when value cannot be encoded, such as a channel, a function or a cyclic structure.

Example
package main

import (
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	payload, err := celeris.JSONPayload(map[string]any{"text": "<hi>", "count": 2})

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(payload))
}
Output:
{"count":2,"text":"<hi>"}
Example (Segment)

Encode a typed value as JSON, and read it back in a listener.

package main

import (
	"context"
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	ctx := context.Background()

	type typing struct {
		Active bool `json:"active"`
	}

	chat.OnMessage(func(payload []byte, _ celeris.MessageMetadata) {
		event, err := celeris.ReadJSON[typing](payload)

		if err != nil {
			return // not a typing event
		}

		fmt.Println("typing:", event.Active)
	})

	payload, err := celeris.JSONPayload(typing{Active: true})

	if err != nil {
		log.Fatal(err)
	}

	if err := chat.Publish(ctx, payload); err != nil {
		log.Fatal(err)
	}
}

func ReadJSON

func ReadJSON[T any](payload []byte) (T, error)

ReadJSON decodes a JSON payload into a T. The type is an assertion, not a validation: check payloads from peers you do not control against a schema.

Example
package main

import (
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	type message struct {
		Text string `json:"text"`
	}

	decoded, err := celeris.ReadJSON[message]([]byte(`{"text":"hello"}`))

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(decoded.Text)

	_, err = celeris.ReadJSON[message]([]byte("not json"))
	fmt.Println(err)
}
Output:
hello
Payload is valid UTF-8 but not valid JSON.

func ReadText

func ReadText(payload []byte) (string, error)

ReadText decodes a UTF-8 payload. It fails with ErrConfiguration when the payload is not valid UTF-8.

Example
package main

import (
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	text, err := celeris.ReadText(celeris.TextPayload("héllo"))
	fmt.Println(text, err)

	_, err = celeris.ReadText([]byte{0xff})
	fmt.Println(err)
}
Output:
héllo <nil>
Payload is not valid UTF-8, so it cannot be read as text.

func TextPayload

func TextPayload(text string) []byte

TextPayload encodes text as UTF-8. Invalid UTF-8 in text is replaced with U+FFFD, so the payload is always valid text.

Types

type Channel

type Channel struct {
	// contains filtered or unexported fields

} // end struct Channel

Channel is one WebSocket connection. Every segment of the channel is multiplexed over it; another Channel, even for the same reference, is another connection (SEG-01). Obtain one with Client.Channel.

A Channel is safe for concurrent use. Close it when done.

func (*Channel) Close

func (channel *Channel) Close()

Close closes the connection and every segment handle with it. It is terminal and idempotent, and returns within about five seconds even when the server does not answer the closing handshake. Publishes and presence queries still waiting fail with ErrCancelled.

Listeners may still receive events queued before Close returned, including the closing and closed state changes.

func (*Channel) Connect

func (channel *Channel) Connect(ctx context.Context) error

Connect opens the connection. It returns once the WebSocket is established and held subscriptions are queued to be restored ahead of any publish, or fails without retrying: only a connection that was up recovers automatically.

It fails with ErrOperationInProgress while connecting, connected or reconnecting, and with ErrNotConnected once the channel is closing or closed. A failed attempt leaves the channel StateFailed, from which Connect may be called again. Cancelling ctx abandons the attempt.

func (*Channel) DefaultSegment

func (channel *Channel) DefaultSegment() *Segment

DefaultSegment returns a handle for the segment every connection joins automatically (SEG-01).

func (*Channel) Events

func (channel *Channel) Events() ChannelEventHandler

Events returns the handler for channel-wide listeners.

func (*Channel) Segment

func (channel *Channel) Segment(segmentID string) (*Segment, error)

Segment returns a handle for the segment with the given id. It does no network work, and any number of handles for one segment share its subscriptions and listeners. It fails with ErrConfiguration for an id that is empty, contains CR or LF, or is not valid UTF-8.

func (*Channel) State

func (channel *Channel) State() ChannelState

State returns the current state. It may change as soon as it is read.

type ChannelEventHandler

type ChannelEventHandler struct {
	// contains filtered or unexported fields

} // end struct ChannelEventHandler

ChannelEventHandler registers channel-wide listeners. Obtain one with Channel.Events. Each registration returns a function that removes exactly that listener; calling it again does nothing.

func (ChannelEventHandler) OnError

func (handler ChannelEventHandler) OnError(listener func(error)) (remove func())

OnError registers a listener for failures no caller is waiting for: a *ServerError the server sent, or an *Error such as an undecodable message, a failed reconnect, or a listener that panicked.

Example

Failures no caller is waiting for arrive here: errors the server sent, and the SDK's own, such as a message that could not be decoded.

package main

import (
	"errors"
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var channel *celeris.Channel // from client.Channel("room-42")

	channel.Events().OnError(func(err error) {
		if serverError, ok := errors.AsType[*celeris.ServerError](err); ok {
			fmt.Println("server:", serverError.Type, serverError.SubType, serverError.Resource)

			return
		}

		fmt.Println("sdk:", err)
	})
}

func (ChannelEventHandler) OnMessage added in v1.0.0

func (handler ChannelEventHandler) OnMessage(listener func(payload []byte, metadata MessageMetadata)) (remove func())

OnMessage registers a listener for every delivery from any segment the connection is a member of, whether or not that segment has listeners of its own. Within one delivery it runs after the segment's listeners (MSG-02).

The returned function removes only this channel listener. The other channel listeners and the segment listeners continue to receive messages. The subscriptions do not change, and the SDK does not send a message to the server. When you call the function again, it has no effect.

Example

A channel listener sees every delivery, from any segment, after that segment's own listeners.

package main

import (
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var channel *celeris.Channel // from client.Channel("room-42")

	removeChannelListener := channel.Events().OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
		fmt.Println(metadata.SegmentID, string(payload))
	})

	defer removeChannelListener()
}

func (ChannelEventHandler) OnNotice

func (handler ChannelEventHandler) OnNotice(listener func(ServerNotice)) (remove func())

OnNotice registers a listener for the server's raw notices.

func (ChannelEventHandler) OnRecovery

func (handler ChannelEventHandler) OnRecovery(listener func(RecoveryEvent)) (remove func())

OnRecovery registers a listener for every successful reconnect.

Example
package main

import (
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var channel *celeris.Channel // from client.Channel("room-42")

	channel.Events().OnRecovery(func(event celeris.RecoveryEvent) {
		// Replay is a bounded window: gaps and duplicates are always possible.
		fmt.Println("recovered on retry", event.RetryIndex)
	})
}

func (ChannelEventHandler) OnStateChange

func (handler ChannelEventHandler) OnStateChange(listener func(ChannelState)) (remove func())

OnStateChange registers a listener for every state transition.

Example

A state listener sees every transition, in the order it happened.

package main

import (
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var channel *celeris.Channel // from client.Channel("room-42")

	channel.Events().OnStateChange(func(state celeris.ChannelState) {
		switch state {
		case celeris.StateReconnecting:
			fmt.Println("connection lost; recovering")
		case celeris.StateFailed:
			fmt.Println("gave up; call Connect to try again")
		}
	})
}

type ChannelState

type ChannelState string

ChannelState is where a channel is in its lifecycle.

const (
	// StateIdle means created and never connected.
	StateIdle ChannelState = "idle"

	// StateConnecting means the first connection attempt is running.
	StateConnecting ChannelState = "connecting"

	// StateConnected means a WebSocket is established. Nothing more is
	// implied.
	StateConnected ChannelState = "connected"

	// StateReconnecting means the connection dropped and is being recovered.
	StateReconnecting ChannelState = "reconnecting"

	// StateFailed means connecting or recovery failed. Connect may be called
	// again.
	StateFailed ChannelState = "failed"

	// StateClosing means Close is shutting the connection down.
	StateClosing ChannelState = "closing"

	// StateClosed is terminal. Create a new channel to connect again.
	StateClosed ChannelState = "closed"
)

type Client

type Client struct {
	// contains filtered or unexported fields

} // end struct Client

Client creates channels. It holds configuration only and does no network work. It is safe for concurrent use.

func NewClient

func NewClient(options ClientOptions) (*Client, error)

NewClient validates options and returns a client. It fails with ErrConfiguration for a missing provider, a nonzero timeout outside 1 ms to 15 minutes, a negative size, a maximum reconnect attempts outside 0 to 100, or a base URL that is not wss://, or ws:// for a loopback host when allowed.

func (*Client) Channel

func (client *Client) Channel(reference string) (*Channel, error)

Channel returns a handle for the channel with the given reference. It does no network work; each call returns a new channel with its own connection. It fails with ErrConfiguration unless the reference is 1 to 255 ASCII letters, digits, hyphens or underscores.

type ClientOptions

type ClientOptions struct {
	// CredentialProvider fetches fresh credentials for every connection
	// attempt.
	CredentialProvider CredentialProvider

	// BaseURL defaults to the production endpoint. Set it only for local, CI
	// or self-hosted targets.
	BaseURL string

	// AllowInsecureLoopback permits a ws:// BaseURL for a loopback host.
	AllowInsecureLoopback bool

	// ConnectTimeout covers credential acquisition and the handshake
	// together. Zero means 15 seconds; otherwise it is 1 ms to 15 minutes.
	ConnectTimeout time.Duration

	// ReconnectTimeout covers credential acquisition and the handshake
	// together for a reconnect attempt. Zero means ConnectTimeout; otherwise
	// it is 1 ms to 15 minutes.
	ReconnectTimeout time.Duration

	// PresenceQueryTimeout bounds each presence query. Zero means 10 seconds;
	// otherwise it is 1 ms to 15 minutes.
	PresenceQueryTimeout time.Duration

	// PublishQueueSize caps the publishes waiting for room in the writer.
	// Zero means 64.
	PublishQueueSize int

	// DeduplicationWindowSize is how many delivered message ids each channel
	// remembers, to drop replayed duplicates. Zero means 1024.
	DeduplicationWindowSize int

	// MaximumReconnectAttempts is how many failed reconnect attempts, in one
	// retry budget, end recovery in StateFailed. Zero means 10; otherwise it
	// is 1 to 100.
	MaximumReconnectAttempts int

} // end struct ClientOptions

ClientOptions configures a Client. Only CredentialProvider is required.

type CredentialProvider

type CredentialProvider func(ctx context.Context, request CredentialRequest) (Credentials, error)

CredentialProvider fetches credentials for one attempt, typically from your own credential endpoint. It must honour ctx: the attempt's deadline and Channel.Close both cancel it, and a result it returns afterwards is discarded.

Any error it returns is reported as ErrTransport, ErrTimeout or ErrCancelled; its text is never inspected or passed on.

type CredentialRequest

type CredentialRequest struct {
	ChannelReference string

	// Reconnect is false for the attempt Connect starts and true for every
	// automatic reconnect.
	Reconnect bool

	// DisconnectedAt is when the connection dropped. It is zero unless
	// Reconnect is true.
	DisconnectedAt time.Time

	// ReplayLookback suggests how much history to replay: the outage so far
	// plus five seconds of overlap. It is zero unless Reconnect is true. The
	// signing server decides whether to sign any replay into the credentials.
	ReplayLookback time.Duration

} // end struct CredentialRequest

CredentialRequest describes the attempt credentials are wanted for. They are requested fresh for every attempt, reconnects included (D-001).

type Credentials

type Credentials struct {
	Payload   string `json:"payload"`
	Signature string `json:"signature"`

} // end struct Credentials

Credentials authorize one connection attempt. Both values are opaque: the SDK never parses, re-serializes or generates them. A trusted server signs them; a client only passes them on.

Credentials never print: fmt verbs and slog show them as redacted. The JSON tags let a credential endpoint encode them directly and a client decode its response.

Example
package main

import (
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	credentials := celeris.Credentials{Payload: "opaque", Signature: "opaque"}
	fmt.Println(credentials)
	fmt.Printf("%#v\n", credentials)
}
Output:
celeris.Credentials{redacted}
celeris.Credentials{redacted}

func (Credentials) Format

func (Credentials) Format(state fmt.State, _ rune)

Format redacts the credentials for every fmt verb, %#v and %d included.

func (Credentials) LogValue

func (Credentials) LogValue() slog.Value

LogValue redacts the credentials in slog output.

func (Credentials) String

func (Credentials) String() string

type Error

type Error struct {
	Code    ErrorCode
	Message string

	// Field and Offset locate a decoding failure: a field name this package
	// chose and a zero-based byte offset into the server message. They are set
	// only when Code is ErrProtocol.
	Field  string
	Offset int

} // end struct Error

Error is a failure the SDK detected. Its message names what failed and the rule or limit it broke; it never carries input values, credentials, or bytes the server sent.

func (*Error) Error

func (sdkError *Error) Error() string

func (*Error) Is

func (sdkError *Error) Is(target error) bool

Is reports whether target is this error's code, so errors.Is(err, celeris.ErrTimeout) matches every timeout.

type ErrorCode

type ErrorCode string

ErrorCode names the kind of failure the SDK itself detected. The codes are a closed set and are also the sentinels callers match with errors.Is:

if errors.Is(err, celeris.ErrBackpressure) { ... }

There is no authentication code: a handshake the server refuses for its credentials cannot be told apart from a network failure (DEV-02), so it is reported as ErrTransport.

Example

Match the SDK's own failures by code, and the server's by type.

package main

import (
	"errors"
	"fmt"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	describe := func(err error) string {
		if serverError, ok := errors.AsType[*celeris.ServerError](err); ok && serverError.Type == celeris.MessageSizeLimitError {
			return "shrink the payload"
		}

		switch {
		case errors.Is(err, celeris.ErrBackpressure):
			return "slow down and retry"
		case errors.Is(err, celeris.ErrNotConnected):
			return "wait for the connection"
		default:
			return "unexpected: " + err.Error()
		}
	}

	fmt.Println(describe(&celeris.Error{Code: celeris.ErrBackpressure}))
	fmt.Println(describe(&celeris.ServerError{Type: celeris.MessageSizeLimitError, Message: "Message size limit exceeded"}))
}
Output:
slow down and retry
shrink the payload
const (
	// ErrConfiguration reports invalid input: options, identifiers, payload
	// helpers, or credentials a provider returned.
	ErrConfiguration ErrorCode = "Configuration"

	// ErrTimeout reports a connection attempt or presence query that ran past
	// its deadline.
	ErrTimeout ErrorCode = "Timeout"

	// ErrCancelled reports an operation cancelled by its context or by
	// [Channel.Close].
	ErrCancelled ErrorCode = "Cancelled"

	// ErrTransport reports a failed connection: the credential provider
	// failed, the handshake was refused, or the socket broke.
	ErrTransport ErrorCode = "Transport"

	// ErrNotConnected reports an operation that needs a connection the
	// channel does not have.
	ErrNotConnected ErrorCode = "NotConnected"

	// ErrBackpressure reports that the outbound queue is full or sending is
	// paused after a rate limit. Retry once it drains.
	ErrBackpressure ErrorCode = "Backpressure"

	// ErrOperationInProgress reports a second connect or presence query while
	// the first is still running.
	ErrOperationInProgress ErrorCode = "OperationInProgress"

	// ErrDeliveryUnknown reports a publish that may or may not have left the
	// socket. It is never resent automatically.
	ErrDeliveryUnknown ErrorCode = "DeliveryUnknown"

	// ErrProtocol reports a server message that could not be decoded. The
	// message is dropped and the connection stays up (DECODE-01).
	ErrProtocol ErrorCode = "ProtocolError"
)

func (ErrorCode) Error

func (code ErrorCode) Error() string

Error returns the code itself, so a bare code can be returned and matched like any sentinel error.

type MessageMetadata

type MessageMetadata struct {
	TokenReference string
	SegmentID      string

	// MessageID is always present: the publisher's, or one the server
	// assigned (REV-01).
	MessageID string

	// Timestamp is Unix milliseconds. Convert it with [time.UnixMilli].
	Timestamp int64

} // end struct MessageMetadata

MessageMetadata describes a delivery, beside its payload (MSG-01).

type PayloadCodec

type PayloadCodec[T any] struct {
	// contains filtered or unexported fields

} // end struct PayloadCodec

PayloadCodec gives a serializer of your choice, such as protobuf or MessagePack, the same shape as the built-in helpers. Create one with NewPayloadCodec.

func NewPayloadCodec

func NewPayloadCodec[T any](encode func(T) ([]byte, error), decode func([]byte) (T, error)) (PayloadCodec[T], error)

NewPayloadCodec wraps an encoder and decoder pair. It fails with ErrConfiguration when either is nil.

Example

Wrap any serializer in the shape of the built-in helpers. Its own errors pass through unchanged.

package main

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	type position struct{ X, Y int }

	codec, err := celeris.NewPayloadCodec(
		func(value position) ([]byte, error) {
			var encoded bytes.Buffer
			err := gob.NewEncoder(&encoded).Encode(value)

			return encoded.Bytes(), err
		},
		func(payload []byte) (position, error) {
			var value position
			err := gob.NewDecoder(bytes.NewReader(payload)).Decode(&value)

			return value, err
		},
	)

	if err != nil {
		log.Fatal(err)
	}

	payload, err := codec.EncodePayload(position{X: 3, Y: 4})

	if err != nil {
		log.Fatal(err)
	}

	decoded, err := codec.ReadPayload(payload)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(decoded.X, decoded.Y)
}
Output:
3 4

func (PayloadCodec[T]) EncodePayload

func (codec PayloadCodec[T]) EncodePayload(value T) ([]byte, error)

EncodePayload encodes value with the codec's encoder. The encoder's own errors are returned unchanged: they are the caller's, not this package's.

func (PayloadCodec[T]) ReadPayload

func (codec PayloadCodec[T]) ReadPayload(payload []byte) (T, error)

ReadPayload decodes payload with the codec's decoder. The decoder's own errors are returned unchanged.

type PresenceConnection

type PresenceConnection struct {
	TokenReference string
	ConnectionID   string
	Timestamp      int64

} // end struct PresenceConnection

PresenceConnection is one connection present in a segment. A token reference can hold several connections.

type PresenceEvent

type PresenceEvent struct {
	SegmentID      string
	TokenReference string
	ConnectionID   string
	Joined         bool // false: the connection left
	Timestamp      int64

} // end struct PresenceEvent

PresenceEvent is one connection joining or leaving one segment (PRES-01).

type PresencePage

type PresencePage struct {
	SegmentID   string
	Total       int32
	PerPage     int32
	CurrentPage int32
	From        int32
	To          int32
	Connections []PresenceConnection

} // end struct PresencePage

PresencePage is one page of a segment's presence, every figure exactly as the server sent it. Past the last page From exceeds To and Connections is empty; that is not an error.

type RecoveryEvent

type RecoveryEvent struct {
	// RetryIndex is the zero-based retry that succeeded.
	RetryIndex int

	// PossibleGaps and PossibleDuplicates are always true.
	PossibleGaps       bool
	PossibleDuplicates bool

} // end struct RecoveryEvent

RecoveryEvent reports a reconnect. Replay is a bounded window, not a durable log, so gaps and duplicates are always possible after one.

type Segment

type Segment struct {
	// contains filtered or unexported fields

} // end struct Segment

Segment is a handle for one segment of a channel. It holds only its id: subscriptions, listeners and the connection belong to the channel, so any number of handles for one segment share them. Obtain one with Channel.Segment or Channel.DefaultSegment.

func (*Segment) ID

func (segment *Segment) ID() string

ID returns the segment's id.

func (*Segment) OnMessage

func (segment *Segment) OnMessage(listener func(payload []byte, metadata MessageMetadata)) (remove func())

OnMessage registers a listener for the segment's deliveries. The payload is the SDK's own copy, shared by every listener of that delivery: treat it as read-only. Each message id is delivered once within a bounded window (REV-01).

Example

Listeners receive the payload, then its metadata. Registering returns a function that removes the listener; a subscription is cancelled on its own.

package main

import (
	"fmt"
	"log"
	"time"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	stop := chat.OnMessage(func(payload []byte, metadata celeris.MessageMetadata) {
		sent := time.UnixMilli(metadata.Timestamp)
		fmt.Println(metadata.TokenReference, "at", sent.Format(time.Kitchen), "said", string(payload))
	})

	defer stop()

	subscription, err := chat.Subscribe()

	if err != nil {
		log.Fatal(err)
	}

	defer subscription.Cancel()
}

func (*Segment) OnPresence

func (segment *Segment) OnPresence(listener func(PresenceEvent)) (remove func())

OnPresence registers a listener for joins and leaves. Events arrive only while a presence subscription is held: the server sends them to presence subscribers alone (PRES-01).

func (*Segment) PresenceList

func (segment *Segment) PresenceList(ctx context.Context, page, perPage int32) (PresencePage, error)

PresenceList returns one page of the segment's presence. One query may be in flight per channel; it fails with ErrOperationInProgress while another is pending, and with ErrTimeout after the presence query timeout.

The reply is routed by the goroutine that runs listeners, so a query made inside a listener always times out. Call it from your own goroutine.

Example

Listeners run one at a time and never under an SDK lock, so they may call back into the channel. A presence query's reply is routed by the goroutine running listeners, so query from a goroutine of your own.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	chat.OnPresence(func(celeris.PresenceEvent) {
		go func() {
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()

			page, err := chat.PresenceList(ctx, 1, 25)

			if err != nil {
				log.Println("presence:", err)

				return
			}

			fmt.Println(page.Total, "connections present")
		}()
	})
}
Example (AllPages)

Read every page of a segment's presence.

package main

import (
	"context"
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	ctx := context.Background()

	for page := int32(1); ; page++ {
		result, err := chat.PresenceList(ctx, page, 100)

		if err != nil {
			log.Fatal(err)
		}

		for _, connection := range result.Connections {
			fmt.Println(connection.TokenReference, connection.ConnectionID)
		}

		if len(result.Connections) == 0 || result.To >= result.Total {
			break
		}
	}
}

func (*Segment) Publish

func (segment *Segment) Publish(ctx context.Context, payload []byte) error

Publish sends payload to the segment with a generated message id. It returns once the socket accepted the bytes. That is not receipt, delivery or durability: the protocol has no acknowledgements.

A publish needs write access to the segment and does not join it. To receive the messages of the segment, your own echo included, call Segment.Subscribe.

While the channel reconnects, the publish waits in the queue and is sent after the reconnect, once the restored subscriptions have gone out. It then fails with the error ChannelEventHandler.OnError reports if recovery stops in StateFailed, and with ErrCancelled if the channel closes.

It fails with ErrNotConnected before the first connect, while connecting, and once failed or closed (there is no offline queue), with ErrBackpressure when the publish queue (ClientOptions.PublishQueueSize, 64 by default) is already full, and with ErrDeliveryUnknown when the socket failed mid-write; such a publish is never resent. The plan's cap counts the whole encoded command. A publish over the cap still succeeds here, and the server refuses it afterwards with a MessageSizeLimitError through ChannelEventHandler.OnError.

func (*Segment) PublishWithMessageID

func (segment *Segment) PublishWithMessageID(ctx context.Context, payload []byte, messageID string) error

PublishWithMessageID is Segment.Publish with your own message id. Receivers drop a repeated id within their deduplication window, so reuse an id only to resend the same message.

Example

Returning nil means the local socket accepted the bytes: there is no receipt. ErrDeliveryUnknown means acceptance is uncertain, and the SDK never resends such a publish.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	err := chat.PublishWithMessageID(ctx, celeris.TextPayload("Order 1042 shipped"), "order-1042-shipped")

	switch {
	case err == nil:
		fmt.Println("handed to the socket")
	case errors.Is(err, celeris.ErrBackpressure):
		fmt.Println("the publish queue is full (PublishQueueSize, 64 by default); retry later")
	case errors.Is(err, celeris.ErrDeliveryUnknown):
		fmt.Println("may or may not have been sent; do not resend blindly")
	default:
		fmt.Println("not sent:", err)
	}
}

func (*Segment) Subscribe

func (segment *Segment) Subscribe() (*Subscription, error)

Subscribe registers interest in the segment's messages. The first interest in a segment subscribes it, and it stays subscribed until every interest is cancelled; subscriptions are restored after every reconnect. The default segment is joined automatically and never subscribed or unsubscribed.

A subscription needs read access to the segment. No acknowledgement exists: a denial arrives later through ChannelEventHandler.OnError. It fails with ErrNotConnected once the channel is closing or closed.

func (*Segment) SubscribePresence

func (segment *Segment) SubscribePresence() (*Subscription, error)

SubscribePresence registers interest in the segment's presence joins and leaves. Watching presence is not membership: it delivers no messages, and the watcher is not itself announced or listed.

Example

A presence subscription delivers joins and leaves. It delivers no messages: watching presence is not membership.

package main

import (
	"fmt"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
)

func main() {
	var chat *celeris.Segment // from channel.Segment("chat")

	chat.OnPresence(func(event celeris.PresenceEvent) {
		if event.Joined {
			fmt.Println(event.TokenReference, "joined on connection", event.ConnectionID)
		} else {
			fmt.Println(event.TokenReference, "left from connection", event.ConnectionID)
		}
	})

	presence, err := chat.SubscribePresence()

	if err != nil {
		log.Fatal(err)
	}

	defer presence.Cancel()
}

type ServerError

type ServerError struct {
	Type ServerErrorType

	// SubType names the command the error answers, such as "SUB" or
	// "PRES_LIST", or is empty when the server named none.
	SubType string

	// Message is the server's own text, for people to read. Never parse it.
	Message string

	// Resource is whatever Type and SubType define it to carry, such as the
	// segment a denial refers to: nil, a string, an int32, an int64, or a
	// []any of these.
	Resource any

} // end struct ServerError

ServerError is an error frame from the server, every field exactly as sent (ERR-01). The server keeps the connection open after sending one.

It has no ErrorCode: it is shaped differently from the SDK's own errors, so match it with errors.AsType and inspect Type.

func (*ServerError) Error

func (serverError *ServerError) Error() string

type ServerErrorType

type ServerErrorType string

ServerErrorType is the kind of an error frame the server sent. The set stays open: a type a newer server adds still reaches the caller unchanged (ERR-01).

const (
	ParserError           ServerErrorType = "ParserError"
	SendError             ServerErrorType = "SendError"
	PermissionDeniedError ServerErrorType = "PermissionDeniedError"
	RateLimitError        ServerErrorType = "RateLimitError"
	MessageSizeLimitError ServerErrorType = "MessageSizeLimitError"
	InternalError         ServerErrorType = "InternalError"
)

The error types the server sends, one per server error variant.

type ServerNotice

type ServerNotice struct {
	Timestamp int64
	Payload   []byte

} // end struct ServerNotice

ServerNotice is a raw notice from the server: greetings, subscription acknowledgements and refusals, as human-readable prose. It names no segment and no command, so nothing may gate on its content.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields

} // end struct Subscription

Subscription is one registered interest. Cancel it when done.

func (*Subscription) Cancel

func (subscription *Subscription) Cancel()

Cancel releases the interest at once. Cancelling the last message interest unsubscribes the segment, and cancelling the last presence interest stops its presence events; neither affects the other. Calling Cancel again does nothing.

Directories

Path Synopsis
examples
quickstart command
Command quickstart connects to Celeris, publishes on a segment it subscribes to, and reads who is present.
Command quickstart connects to Celeris, publishes on a segment it subscribes to, and reads who is present.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL