client

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

SPDX-License-Identifier: Apache-2.0

Package client provides a typed Go client for the Sharkfin messaging server.

There are two client types:

  • *Client — connects via WebSocket for real-time events and also offers a handful of REST methods (webhook registration, identity registration). Use this when you need the server's event stream.

  • *RESTClient — HTTP-only, no WebSocket. Use this when your service receives events via a registered webhook and therefore does not need the WS event channel. No goroutines, no Dial step, no reconnection state.

Usage (WebSocket):

c, err := client.Dial(ctx, "ws://localhost:16000/ws", client.WithAPIKey(tok))
if err != nil { log.Fatal(err) }
defer c.Close()

for ev := range c.Events() {
    switch ev.Type {
    case "message.new":
        msg, _ := ev.AsMessage()
        fmt.Printf("%s: %s\n", msg.From, msg.Body)
    }
}

Usage (REST-only):

c := client.NewRESTClient("http://localhost:16000", client.WithAPIKey(tok))
defer c.Close()

if err := c.Register(ctx); err != nil { log.Fatal(err) }
if err := c.CreateChannel(ctx, "general", true); err != nil { log.Fatal(err) }
id, err := c.SendMessage(ctx, "general", "hello", nil)
if err != nil { log.Fatal(err) }
_ = id

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

SPDX-License-Identifier: Apache-2.0

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotConnected is returned when a method is called on a closed or
	// disconnected client.
	ErrNotConnected = errors.New("client: not connected")

	// ErrTimeout is returned when a request does not receive a reply
	// within the context deadline.
	ErrTimeout = errors.New("client: request timeout")

	// ErrClosed is returned when operations are attempted on a closed client.
	ErrClosed = errors.New("client: closed")

	// ErrBadRequest wraps HTTP 400 responses.
	ErrBadRequest = errors.New("client: bad request")

	// ErrUnauthorized wraps HTTP 401 responses.
	ErrUnauthorized = errors.New("client: unauthorized")

	// ErrNotFound wraps HTTP 404 responses.
	ErrNotFound = errors.New("client: not found")

	// ErrConflict wraps HTTP 409 responses.
	ErrConflict = errors.New("client: conflict")
)

Functions

This section is empty.

Types

type BackoffFunc

type BackoffFunc func(attempt int) time.Duration

BackoffFunc returns the delay before reconnection attempt N (0-indexed). Return a negative duration to stop reconnecting.

type BroadcastMessage

type BroadcastMessage struct {
	ID          int64    `json:"id"`
	Channel     string   `json:"channel"`
	ChannelType string   `json:"channel_type"`
	From        string   `json:"from"`
	Body        string   `json:"body"`
	SentAt      string   `json:"sent_at"`
	ThreadID    *int64   `json:"thread_id,omitempty"`
	Mentions    []string `json:"mentions,omitempty"`
}

BroadcastMessage is the payload of a message.new server push.

type Channel

type Channel struct {
	Name   string `json:"name"`
	Public bool   `json:"public"`
	Member bool   `json:"member"`
}

Channel represents a channel returned by channel_list.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a WebSocket client for the Sharkfin messaging server.

func Dial

func Dial(ctx context.Context, url string, opts ...Option) (*Client, error)

Dial connects to a Sharkfin server at the given WebSocket URL (e.g. "ws://localhost:16000/ws") and starts the background read pump. Authentication is provided via the WithAPIKey option.

func (*Client) AddMentionGroupMember

func (c *Client) AddMentionGroupMember(ctx context.Context, slug, username string) error

AddMentionGroupMember adds a user to a mention group.

func (*Client) Capabilities

func (c *Client) Capabilities(ctx context.Context) ([]string, error)

Capabilities returns the current user's permissions.

func (*Client) Channels

func (c *Client) Channels(ctx context.Context) ([]Channel, error)

Channels returns all channels visible to the current user.

func (*Client) Close

func (c *Client) Close() error

Close cleanly shuts down the client connection.

func (*Client) CreateChannel

func (c *Client) CreateChannel(ctx context.Context, name string, public bool) error

CreateChannel creates a new channel.

func (*Client) CreateMentionGroup

func (c *Client) CreateMentionGroup(ctx context.Context, slug string) (int64, error)

CreateMentionGroup creates a new mention group. Returns the group ID.

func (*Client) DMList

func (c *Client) DMList(ctx context.Context) ([]DM, error)

DMList returns all DM channels for the current user.

func (*Client) DMOpen

func (c *Client) DMOpen(ctx context.Context, username string) (*DMOpenResult, error)

DMOpen opens or retrieves a DM channel with the given user.

func (*Client) DeleteMentionGroup

func (c *Client) DeleteMentionGroup(ctx context.Context, slug string) error

DeleteMentionGroup deletes a mention group by slug.

func (*Client) Events

func (c *Client) Events() <-chan Event

Events returns a channel that receives server-pushed broadcasts (message.new, presence, etc.). The channel is closed when the client disconnects.

func (*Client) GetMentionGroup

func (c *Client) GetMentionGroup(ctx context.Context, slug string) (*MentionGroup, error)

GetMentionGroup returns a mention group by slug.

func (*Client) GetSettings

func (c *Client) GetSettings(ctx context.Context) (map[string]string, error)

GetSettings returns all server settings.

func (*Client) History

func (c *Client) History(ctx context.Context, channel string, opts *HistoryOpts) ([]Message, error)

History retrieves message history for a channel.

func (*Client) InviteToChannel

func (c *Client) InviteToChannel(ctx context.Context, channel, username string) error

InviteToChannel invites a user to a channel.

func (*Client) JoinChannel

func (c *Client) JoinChannel(ctx context.Context, channel string) error

JoinChannel joins a public channel.

func (*Client) ListMentionGroups

func (c *Client) ListMentionGroups(ctx context.Context) ([]MentionGroup, error)

ListMentionGroups returns all mention groups.

func (*Client) ListWebhooks

func (c *Client) ListWebhooks(ctx context.Context) ([]Webhook, error)

ListWebhooks returns all active webhooks for the calling identity.

func (*Client) MarkRead

func (c *Client) MarkRead(ctx context.Context, channel string, messageID int64) error

MarkRead marks messages as read in a channel. If messageID is 0, all messages in the channel are marked read.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping sends an application-level ping and waits for pong.

func (*Client) Register

func (c *Client) Register(ctx context.Context) error

Register registers the calling identity as a service bot.

func (*Client) RegisterWebhook

func (c *Client) RegisterWebhook(ctx context.Context, url string) (string, error)

RegisterWebhook registers a webhook URL for the calling identity. Returns the webhook ID.

func (*Client) RemoveMentionGroupMember

func (c *Client) RemoveMentionGroupMember(ctx context.Context, slug, username string) error

RemoveMentionGroupMember removes a user from a mention group.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, channel, body string, opts *SendOpts) (int64, error)

SendMessage sends a message to a channel. Returns the message ID.

func (*Client) SetSetting

func (c *Client) SetSetting(ctx context.Context, key, value string) error

SetSetting sets a server setting key-value pair.

func (*Client) SetState

func (c *Client) SetState(ctx context.Context, state string) error

SetState sets the user's presence state ("active" or "idle").

func (*Client) UnreadCounts

func (c *Client) UnreadCounts(ctx context.Context) ([]UnreadCount, error)

UnreadCounts returns unread and mention counts per channel.

func (*Client) UnreadMessages

func (c *Client) UnreadMessages(ctx context.Context, channel string, opts *UnreadOpts) ([]Message, error)

UnreadMessages retrieves unread messages, optionally filtered.

func (*Client) UnregisterWebhook

func (c *Client) UnregisterWebhook(ctx context.Context, id string) error

UnregisterWebhook removes a registered webhook by ID.

func (*Client) Users

func (c *Client) Users(ctx context.Context) ([]User, error)

Users returns all registered users.

func (*Client) Version

func (c *Client) Version(ctx context.Context) (string, error)

Version returns the server version string.

type DM

type DM struct {
	Channel      string   `json:"channel"`
	Participants []string `json:"participants"`
}

DM is one entry in the dm_list response.

type DMOpenResult

type DMOpenResult struct {
	Channel     string `json:"channel"`
	Participant string `json:"participant"`
	Created     bool   `json:"created"`
}

DMOpenResult is the response from dm_open.

type Event

type Event struct {
	// Type is the envelope type, e.g. "message.new", "presence".
	Type string

	// Data is the raw JSON payload from the "d" field.
	Data json.RawMessage
}

Event is a server-pushed message delivered via the Events() channel.

func (Event) AsMessage

func (e Event) AsMessage() (*BroadcastMessage, error)

AsMessage decodes the event data as a BroadcastMessage. Returns an error if the data does not match.

func (Event) AsPresence

func (e Event) AsPresence() (*PresenceUpdate, error)

AsPresence decodes the event data as a PresenceUpdate.

type HistoryOpts

type HistoryOpts struct {
	Before   *int64
	After    *int64
	Limit    *int
	ThreadID *int64
}

HistoryOpts are optional parameters for History.

type MentionGroup

type MentionGroup struct {
	ID        int64    `json:"id"`
	Slug      string   `json:"slug"`
	CreatedBy string   `json:"created_by,omitempty"`
	Members   []string `json:"members,omitempty"`
}

MentionGroup represents a mention group.

type Message

type Message struct {
	ID       int64    `json:"id,omitempty"`
	Channel  string   `json:"channel,omitempty"`
	From     string   `json:"from"`
	Body     string   `json:"body"`
	SentAt   string   `json:"sent_at"`
	ThreadID *int64   `json:"thread_id,omitempty"`
	Mentions []string `json:"mentions,omitempty"`
}

Message represents a message in history or unread_messages responses.

type Option

type Option func(*clientOpts)

Option configures a Client.

func WithAPIKey

func WithAPIKey(k string) Option

WithAPIKey sets an API key for authentication.

func WithDialer

func WithDialer(d *websocket.Dialer) Option

WithDialer sets a custom websocket.Dialer.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets a structured logger for the client.

func WithReconnect

func WithReconnect(backoff BackoffFunc) Option

WithReconnect enables automatic reconnection with the given backoff function.

type PresenceUpdate

type PresenceUpdate struct {
	Username string `json:"username"`
	Status   string `json:"status"`
	State    string `json:"state,omitempty"`
}

PresenceUpdate is the payload of a presence server push.

type RESTClient added in v0.2.0

type RESTClient struct {
	// contains filtered or unexported fields
}

RESTClient is a stateless HTTP-only client for the Sharkfin server. Unlike *Client it does not open a WebSocket connection and does not receive server-pushed events. Consumers that receive events via a registered webhook instead of the WS event stream should use this type — it has no background goroutines, no reconnection state, and no Dial step.

func NewRESTClient added in v0.2.0

func NewRESTClient(baseURL string, opts ...Option) *RESTClient

NewRESTClient constructs a REST-only Sharkfin client. baseURL must point at the server root (e.g. "http://localhost:16000"), not at a sub-path — REST method paths like "/api/v1/channels" are appended directly. A WebSocket URL such as "ws://localhost:16000/ws" is also accepted: the scheme is rewritten to http(s) and a trailing "/ws" is trimmed. Authentication is provided via WithAPIKey; other Options (WithDialer, WithReconnect) are accepted for signature compatibility but are ignored because there is no WS connection.

func (*RESTClient) Channels added in v0.2.0

func (c *RESTClient) Channels(ctx context.Context) ([]Channel, error)

Channels returns all channels visible to the current user. The REST endpoint shape matches the shared Channel type's JSON tags ({name, public, member}); the server also includes an {id} field which the client ignores.

func (*RESTClient) Close added in v0.2.0

func (c *RESTClient) Close() error

Close releases any resources held by the client. Currently a no-op because the underlying http.Client does not require explicit cleanup. Provided so callers can write symmetric setup/teardown code.

func (*RESTClient) CreateChannel added in v0.2.0

func (c *RESTClient) CreateChannel(ctx context.Context, name string, public bool) error

CreateChannel creates a new channel.

func (*RESTClient) JoinChannel added in v0.2.0

func (c *RESTClient) JoinChannel(ctx context.Context, channel string) error

JoinChannel joins a public channel by name.

func (*RESTClient) ListMessages added in v0.2.0

func (c *RESTClient) ListMessages(ctx context.Context, channel string, opts *HistoryOpts) ([]Message, error)

ListMessages retrieves messages from a channel, subject to optional before/after/limit pagination.

func (*RESTClient) ListWebhooks added in v0.2.0

func (c *RESTClient) ListWebhooks(ctx context.Context) ([]Webhook, error)

ListWebhooks returns all active webhooks for the calling identity.

func (*RESTClient) Register added in v0.2.0

func (c *RESTClient) Register(ctx context.Context) error

Register registers the calling identity as a service bot.

func (*RESTClient) RegisterWebhook added in v0.2.0

func (c *RESTClient) RegisterWebhook(ctx context.Context, hookURL string) (string, error)

RegisterWebhook registers a webhook URL for the calling identity. Returns the webhook ID.

func (*RESTClient) SendMessage added in v0.2.0

func (c *RESTClient) SendMessage(ctx context.Context, channel, body string, opts *SendOpts) (int64, error)

SendMessage sends a message to a channel. Returns the message ID assigned by the server.

SendOpts.Metadata is a JSON-encoded string matching the WS path's type. The REST endpoint expects a JSON object, not a string, so the metadata is parsed into a map before sending. Invalid JSON returns an error without contacting the server.

func (*RESTClient) UnregisterWebhook added in v0.2.0

func (c *RESTClient) UnregisterWebhook(ctx context.Context, id string) error

UnregisterWebhook removes a registered webhook by ID.

type SendOpts

type SendOpts struct {
	ThreadID *int64
	Metadata *string // JSON string
}

SendOpts are optional parameters for SendMessage.

type ServerError

type ServerError struct {
	Message string
	Status  int
	// contains filtered or unexported fields
}

ServerError is returned when the server replies with an error. For WS replies this is constructed from an ok:false envelope and leaves Status zero. For REST replies Status carries the HTTP code and (when the code maps to one) wrapped is set to a sentinel so errors.Is(err, ErrNotFound) and friends work.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) Unwrap added in v0.2.0

func (e *ServerError) Unwrap() error

Unwrap returns the wrapped sentinel error if any. Enables errors.Is(err, ErrNotFound) etc. for REST callers.

type UnreadCount

type UnreadCount struct {
	Channel      string `json:"channel"`
	Type         string `json:"type"`
	UnreadCount  int    `json:"unread_count"`
	MentionCount int    `json:"mention_count"`
}

UnreadCount is one entry in the unread_counts response.

type UnreadOpts

type UnreadOpts struct {
	MentionsOnly bool
	ThreadID     *int64
}

UnreadOpts are optional parameters for UnreadMessages.

type User

type User struct {
	Username string `json:"username"`
	Online   bool   `json:"online"`
	Type     string `json:"type"`
	State    string `json:"state,omitempty"`
}

User represents a user returned by the user_list operation.

type Webhook

type Webhook struct {
	ID     string `json:"id"`
	URL    string `json:"url"`
	Active bool   `json:"active"`
}

Webhook represents a registered per-identity webhook.

Jump to

Keyboard shortcuts

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