celeris

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 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

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.

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)
}

fetchCredentials is a celeris.CredentialProvider: it calls your own authenticated endpoint, which signs credentials with sdk-go-server, and decodes its JSON response into celeris.Credentials. Never ship a signing secret in client code. The endpoint is built in; set BaseURL only for a local or self-hosted stack.

Payloads are opaque bytes: TextPayload/JSONPayload and ReadText/ReadJSON cover the common cases, and NewPayloadCodec wraps any other serializer (protobuf, MessagePack, CBOR) without the module depending on one. The package documentation carries runnable examples of each, and examples/quickstart runs against a real Celeris stack in the live suite.

Delivery semantics, honestly

  • Publish returns when the local socket accepted the bytes. There is no server receipt or ack anywhere in the protocol. Every publish carries a message id, yours (PublishWithMessageID) or a generated one.
  • Lost connections retry automatically (10 attempts, full jitter, fresh credentials, replay lookback). Recovery restores your subscriptions and reports possible gaps and duplicates; a bounded 1024-id window deduplicates replayed messages, and duplicates beyond it remain possible.
  • A RateLimitError never names the command it dropped, so the client pauses and resends what it sent in the last two seconds: subscriptions first, as their current state, then up to the last 64 publishes, each at most once and with its original id so receivers drop a copy that had already arrived. After eight limits in a row the client treats the limit as a used-up quota: it stops resending, and re-sends the subscriptions it dropped on a slow probe (after a minute, doubling to at most an hour) until commands go two seconds without a limit. 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. Publish fails with ErrBackpressure only when 64 publishes are already waiting; a presence query does when the writer is full or sending is paused.
  • No offline queue (publishes still waiting when the connection drops fail with ErrNotConnected), no durable history, no global ordering.
  • Errors the server sends arrive through Events().OnError as a *celeris.ServerError carrying the server's Type, SubType (the command it answers), Message and Resource (what that command names, such as the segment). A denied or oversized publish still returns normally. A failed presence query is the exception: its error names the query, so PresenceList returns it at once.
  • Publishing to a segment joins it server-side; subscribing to presence also joins it for messages.

Limits and defaults

What Value
Outbound command 2 MiB encoded, refused before any write
Plan payload cap enforced by the server per plan; see below
Writer bounds 64 commands / 2 MiB not yet written; 64 queued publishes, 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
Presence query one in flight per channel, PresenceQueryTimeout default 10 s; a timeout never drops the connection
Reconnect 10 retries, full jitter up to 30 s, reset after 60 s connected
Dedup window 1024 message ids per channel
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. Each plan caps publish payloads: 64 KiB free, 128 KiB standard, 512 KiB pro, 1024 KiB prime. A publish over your plan's cap returns locally and is rejected afterwards with a MessageSizeLimitError, and it still counts toward your usage.

Goroutines, contexts and cancellation

A Channel and its 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 one exception is PresenceList, whose reply cannot be routed until the listener returns: call it from a goroutine of your own.

ctx bounds the call it is passed to. Cancelling Connect abandons the attempt and leaves the channel failed. Cancelling Publish withdraws 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. The CredentialProvider receives the attempt's context, which Close and the connect deadline both cancel.

Match failures with errors.Is(err, celeris.ErrBackpressure) and friends, and server errors with errors.AsType[*celeris.ServerError](err). SDK errors carry no input values, credentials or server bytes.

Development

make check runs the whole check: 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). 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>"}

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
}

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
}

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.

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.

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
}

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 negative timeout, 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.
	ConnectTimeout time.Duration

	// PresenceQueryTimeout bounds each presence query. Zero means 10 seconds.
	PresenceQueryTimeout time.Duration
}

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
}

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"`
}

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
}

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 (e *Error) Error() string

func (*Error) Is

func (e *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
}

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

type PayloadCodec

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

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
}

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
}

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
}

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
}

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
}

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).

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")
		}()
	})
}

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.

It fails with ErrNotConnected while not connected (there is no offline queue), with ErrBackpressure when 64 publishes are already waiting, and with ErrDeliveryUnknown when the socket failed mid-write; such a publish is never resent. A publish over the plan's payload cap still succeeds here and is refused 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.

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.

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. It also keeps the segment joined for messages; cancelling it does not leave the segment.

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
}

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 (e *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
}

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
}

Subscription is one registered interest. Cancel it when done.

func (*Subscription) Cancel

func (subscription *Subscription) Cancel()

Cancel releases the interest at once. The segment is unsubscribed when its last message and presence interests are both released; cancelling presence never leaves the segment. 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