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)
}
}
Output:
Index ¶
- func JSONPayload(value any) ([]byte, error)
- func ReadJSON[T any](payload []byte) (T, error)
- func ReadText(payload []byte) (string, error)
- func TextPayload(text string) []byte
- type Channel
- func (channel *Channel) Close()
- func (channel *Channel) Connect(ctx context.Context) error
- func (channel *Channel) DefaultSegment() *Segment
- func (channel *Channel) Events() ChannelEventHandler
- func (channel *Channel) Segment(segmentID string) (*Segment, error)
- func (channel *Channel) State() ChannelState
- type ChannelEventHandler
- func (handler ChannelEventHandler) OnError(listener func(error)) (remove func())
- func (handler ChannelEventHandler) OnMessage(listener func(payload []byte, metadata MessageMetadata)) (remove func())
- func (handler ChannelEventHandler) OnNotice(listener func(ServerNotice)) (remove func())
- func (handler ChannelEventHandler) OnRecovery(listener func(RecoveryEvent)) (remove func())
- func (handler ChannelEventHandler) OnStateChange(listener func(ChannelState)) (remove func())
- type ChannelState
- type Client
- type ClientOptions
- type CredentialProvider
- type CredentialRequest
- type Credentials
- type Error
- type ErrorCode
- type MessageMetadata
- type PayloadCodec
- type PresenceConnection
- type PresenceEvent
- type PresencePage
- type RecoveryEvent
- type Segment
- func (segment *Segment) ID() string
- func (segment *Segment) OnMessage(listener func(payload []byte, metadata MessageMetadata)) (remove func())
- func (segment *Segment) OnPresence(listener func(PresenceEvent)) (remove func())
- func (segment *Segment) PresenceList(ctx context.Context, page, perPage int32) (PresencePage, error)
- func (segment *Segment) Publish(ctx context.Context, payload []byte) error
- func (segment *Segment) PublishWithMessageID(ctx context.Context, payload []byte, messageID string) error
- func (segment *Segment) Subscribe() (*Subscription, error)
- func (segment *Segment) SubscribePresence() (*Subscription, error)
- type ServerError
- type ServerErrorType
- type ServerNotice
- type Subscription
Examples ¶
- Package
- ChannelEventHandler.OnError
- ChannelEventHandler.OnMessage
- ChannelEventHandler.OnRecovery
- ChannelEventHandler.OnStateChange
- Credentials
- ErrorCode
- JSONPayload
- JSONPayload (Segment)
- NewPayloadCodec
- ReadJSON
- ReadText
- Segment.OnMessage
- Segment.PresenceList
- Segment.PresenceList (AllPages)
- Segment.PublishWithMessageID
- Segment.SubscribePresence
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func JSONPayload ¶
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)
}
}
Output:
func ReadJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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)
})
}
Output:
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()
}
Output:
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)
})
}
Output:
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")
}
})
}
Output:
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 ¶
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.
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" )
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) 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()
}
Output:
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")
}()
})
}
Output:
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
}
}
}
Output:
func (*Segment) Publish ¶
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.
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. 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.
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)
}
}
Output:
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. 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()
}
Output:
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 ¶
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.
Source Files
¶
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. |