nst

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 21 Imported by: 0

README

nst.go

Coverage Status License Apache 2 Go Report Card

utilities for using a nats-server in test

Documentation

Index

Constants

View Source
const UserInfoSubj = "$SYS.REQ.USER.INFO"

Variables

This section is empty.

Functions

func DeleteRequestToken added in v0.0.13

func DeleteRequestToken(operator authb.Operator, key string, account ...string) (string, error)

func GetAccount added in v0.0.14

func GetAccount(nc *nats.Conn, id string) (string, error)

func NewDiscardLogger added in v0.1.20

func NewDiscardLogger() *slog.Logger

NewDiscardLogger creates a new slog.Logger that discards all output

func NewNilLogger added in v0.0.7

func NewNilLogger() server.Logger

func NewTestLogger

func NewTestLogger(t testing.TB) *slog.Logger

NewTestLogger creates a new slog.Logger that outputs to testing.TB

func ServerReload added in v0.1.2

func ServerReload(t testing.TB, sys *nats.Conn) error

Types

type Account added in v0.0.4

type Account struct {
	Users     Users             `json:"users,omitempty"`
	JetStream *AccountJetStream `json:"jetstream,omitempty"`
}

func (*Account) DisableJetStream added in v0.1.17

func (a *Account) DisableJetStream()

func (*Account) EnableJetStream added in v0.1.17

func (a *Account) EnableJetStream(opts ...AccountJetStreamOpt)

type AccountJetStream added in v0.1.22

type AccountJetStream struct {
	Enabled            bool   `json:"-"`
	MaxMemory          uint64 `json:"max_memory,omitempty"`
	MaxStore           uint64 `json:"max_store,omitempty"`
	MaxStreams         int    `json:"max_streams,omitempty"`
	MaxConsumers       int    `json:"max_consumers,omitempty"`
	MaxBytesRequired   bool   `json:"max_bytes_required,omitempty"`
	MemMaxStreamBytes  int64  `json:"mem_max_stream_bytes,omitempty"`
	DiskMaxStreamBytes int64  `json:"disk_max_stream_bytes,omitempty"`
	MaxAckPending      int    `json:"max_ack_pending,omitempty"`
}

AccountJetStream represents per-account JetStream configuration. Marshals as "enabled"/"disabled" when no settings are set, or as an object with settings.

func (AccountJetStream) MarshalJSON added in v0.1.22

func (a AccountJetStream) MarshalJSON() ([]byte, error)

func (*AccountJetStream) UnmarshalJSON added in v0.1.22

func (a *AccountJetStream) UnmarshalJSON(data []byte) error

type AccountJetStreamOpt added in v0.1.22

type AccountJetStreamOpt func(*AccountJetStream)

func DiskMaxStreamBytes added in v0.1.22

func DiskMaxStreamBytes(v int64) AccountJetStreamOpt

func MaxAckPending added in v0.1.22

func MaxAckPending(v int) AccountJetStreamOpt

func MaxBytesRequired added in v0.1.22

func MaxBytesRequired() AccountJetStreamOpt

func MaxConsumers added in v0.1.22

func MaxConsumers(v int) AccountJetStreamOpt

func MaxMemory added in v0.1.22

func MaxMemory(v uint64) AccountJetStreamOpt

func MaxStore added in v0.1.22

func MaxStore(v uint64) AccountJetStreamOpt

func MaxStreams added in v0.1.22

func MaxStreams(v int) AccountJetStreamOpt

func MemMaxStreamBytes added in v0.1.22

func MemMaxStreamBytes(v int64) AccountJetStreamOpt

type Accounts added in v0.0.4

type Accounts map[string]Account

type AllowDeny

type AllowDeny struct {
	Allow jwt.StringList `json:"allow,omitempty"`
	Deny  jwt.StringList `json:"deny,omitempty"`
}

AllowDeny block

type AuthCallout added in v0.0.4

type AuthCallout struct {
	// AuthUsers is a list of authorized users under Account that will handle callout requests
	AuthUsers jwt.StringList `json:"auth_users"`
	// Account containing the AuthUsers
	Account string `json:"account,omitempty"`
	// Issuer the public key that will issue jwt.AuthorizationResponseClaims
	Issuer string `json:"issuer"`
	// XKey optional public curve key, activates encryption
	XKey string `json:"xkey,omitempty"`
	// AllowedAccounts optional public list of accounts that users can be placed in
	AllowedAccounts jwt.StringList `json:"allowed_accounts,omitempty"`
}

type Authorization

type Authorization struct {
	Token       string       `json:"token,omitempty"`
	Users       Users        `json:"users,omitempty"`
	AuthCallout *AuthCallout `json:"auth_callout,omitempty"`
}

Authorization block

type CaptureLogger added in v0.1.21

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

CaptureLogger implements server.Logger and captures all messages.

func NewCaptureLogger added in v0.1.21

func NewCaptureLogger() *CaptureLogger

func (*CaptureLogger) Debugf added in v0.1.21

func (l *CaptureLogger) Debugf(format string, v ...interface{})

func (*CaptureLogger) Errorf added in v0.1.21

func (l *CaptureLogger) Errorf(format string, v ...interface{})

func (*CaptureLogger) Fatalf added in v0.1.21

func (l *CaptureLogger) Fatalf(format string, v ...interface{})

func (*CaptureLogger) Messages added in v0.1.21

func (l *CaptureLogger) Messages() []string

Messages returns a copy of all captured messages.

func (*CaptureLogger) Noticef added in v0.1.21

func (l *CaptureLogger) Noticef(format string, v ...interface{})

func (*CaptureLogger) Tracef added in v0.1.21

func (l *CaptureLogger) Tracef(format string, v ...interface{})

func (*CaptureLogger) Warnf added in v0.1.21

func (l *CaptureLogger) Warnf(format string, v ...interface{})

type Cluster added in v0.1.3

type Cluster struct {
	Name           string                `json:"name,omitempty"`
	Port           int                   `json:"port,omitempty"`
	NoAdvertise    bool                  `json:"no_advertise,omitempty"`
	ConnectRetries int                   `json:"connect_retries,omitempty"`
	Authorization  *ClusterAuthorization `json:"authorization,omitempty"`
	Routes         []string              `json:"routes,omitempty"`
}

type ClusterAuthorization added in v0.1.3

type ClusterAuthorization struct {
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`
	Timeout  string `json:"timeout,omitempty"`
}

type Conf

type Conf struct {
	PortsFileDir    string        `json:"ports_file_dir,omitempty"`
	Debug           bool          `json:"debug,omitempty"`
	Trace           bool          `json:"trace,omitempty"`
	Port            int           `json:"port,omitempty"`
	Include         string        `json:"include,omitempty"`
	Accounts        Accounts      `json:"accounts,omitempty"`
	SystemAccount   *string       `json:"system_account,omitempty"`
	Authorization   Authorization `json:"authorization,omitempty"`
	DefaultSentinel string        `json:"default_sentinel,omitempty"`
	JetStream       *JetStream    `json:"jetstream,omitempty"`
	LeafNodes       *LeafNodes    `json:"leafnodes,omitempty"`
	WriteDeadline   string        `json:"write_deadline,omitempty"`
	WebSocket       *WebSocket    `json:"websocket,omitempty"`
	MonitoringPort  int           `json:"http,omitempty"`
	Cluster         *Cluster      `json:"cluster,omitempty"`
	MaxPending      int           `json:"max_pending,omitempty"`
}

Conf rudimentary struct representing a configuration, missing most :)

func (Conf) Marshal

func (c Conf) Marshal(t testing.TB) []byte

Marshal serializes a Conf into JSON. This is necessary because some permissions setups will have subject wildcards which will serialize incorrectly as JSON.

type ConnectionPorts added in v0.1.0

type ConnectionPorts struct {
	Nats       []string
	WebSocket  []string
	Cluster    []string
	Monitoring []string
}

type Connections added in v0.1.0

type Connections struct {
	ConnectionPorts
	sync.Mutex
	Conns []*nats.Conn
	// contains filtered or unexported fields
}

func (*Connections) ClusterURLs added in v0.1.3

func (ts *Connections) ClusterURLs() []string

func (*Connections) MaybeConnect added in v0.1.0

func (ts *Connections) MaybeConnect(options ...nats.Option) (*nats.Conn, error)

MaybeConnect this connection could fail and tests want to verify it

func (*Connections) NatsURLs added in v0.1.0

func (ts *Connections) NatsURLs() []string

func (*Connections) RequireConnect added in v0.1.0

func (ts *Connections) RequireConnect(opts ...nats.Option) *nats.Conn

RequireConnect returns a connection, the server must not have auth enabled

func (*Connections) Shutdown added in v0.1.0

func (ts *Connections) Shutdown()

func (*Connections) TrackConn added in v0.1.0

func (ts *Connections) TrackConn(conn ...*nats.Conn)

func (*Connections) UntrackedConnection added in v0.1.0

func (ts *Connections) UntrackedConnection(opts ...nats.Option) (*nats.Conn, error)

func (*Connections) WsMaybeConnect added in v0.1.0

func (ts *Connections) WsMaybeConnect(opts ...nats.Option) (*nats.Conn, error)

func (*Connections) WsURLs added in v0.1.0

func (ts *Connections) WsURLs() []string

type ErrorDetails added in v0.0.13

type ErrorDetails struct {
	Account     string `json:"account"`
	Code        int    `json:"code"`
	Description string `json:"description"`
}

type ExternalNatsServer added in v0.1.0

type ExternalNatsServer struct {
	Process *exec.Cmd
	Connections
	// contains filtered or unexported fields
}

func StartExternalProcessWithConfig added in v0.1.0

func StartExternalProcessWithConfig(t testing.TB, fp string) *ExternalNatsServer

func (*ExternalNatsServer) Shutdown added in v0.1.0

func (es *ExternalNatsServer) Shutdown()

type JetStream added in v0.0.10

type JetStream struct {
	StoreDir string `json:"store_dir,omitempty"`
	Domain   string `json:"domain,omitempty"`
	MaxMem   uint64 `json:"max_mem,omitempty"`
	MaxFile  uint64 `json:"max_file,omitempty"`
}

type LeafNodes added in v0.0.10

type LeafNodes struct {
	Compression string   `json:"compression,omitempty"`
	Port        int      `json:"port,omitempty"`
	Remotes     []Remote `json:"remotes,omitempty"`
}

type NatsServer

type NatsServer interface {
	// RequireConnect creates a connection that is not expected to fail, if it fail test will fail
	RequireConnect(opts ...nats.Option) *nats.Conn
	// MaybeConnect attempts to create a TCP connection
	MaybeConnect(options ...nats.Option) (*nats.Conn, error)
	// WsMaybeConnect attempts to create a connection via WebSocket.
	WsMaybeConnect(opts ...nats.Option) (*nats.Conn, error)
	// TrackConn simply adds a connection made to the server via direct client API to be discarded on ShutDown
	TrackConn(conn ...*nats.Conn)
	// UntrackedConnection convenience function to create a connection that is not tracked
	UntrackedConnection(opts ...nats.Option) (*nats.Conn, error)
	// Shutdown stop the server closing all connections initiated via the API if tracked.
	Shutdown()
	// NatsURLs returns a list of all the connection URLs (tcp)
	NatsURLs() []string
	// WsURLs returns a list of all the connection URLs (websocket)
	WsURLs() []string
	// ClusterURLs returns a list of all the cluster connection URLs (tcp)
	ClusterURLs() []string
}

func NewNatsServer

func NewNatsServer(dir *TestDir, opts *Options) NatsServer

type NilLogger added in v0.0.6

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

func (*NilLogger) Debugf added in v0.0.6

func (l *NilLogger) Debugf(format string, v ...interface{})

func (*NilLogger) Errorf added in v0.0.6

func (l *NilLogger) Errorf(format string, v ...interface{})

func (*NilLogger) Fatalf added in v0.0.6

func (l *NilLogger) Fatalf(format string, v ...interface{})

func (*NilLogger) Noticef added in v0.0.6

func (l *NilLogger) Noticef(format string, v ...interface{})

func (*NilLogger) Tracef added in v0.0.6

func (l *NilLogger) Tracef(format string, v ...interface{})

func (*NilLogger) Warnf added in v0.0.6

func (l *NilLogger) Warnf(format string, v ...interface{})

type Options added in v0.1.0

type Options struct {
	Debug      bool
	Trace      bool
	ConfigFile string
	Port       int
	JetStream  bool
	StoreDir   string
	InProcess  bool
}

func DefaultNatsServerOptions

func DefaultNatsServerOptions() *Options

func DefaultNatsServerWithJetStreamOptions

func DefaultNatsServerWithJetStreamOptions(tempDir string) *Options

DefaultNatsServerWithJetStreamOptions basic config for supporting JetStream

type Permissions

type Permissions struct {
	Pub            AllowDeny `json:"publish,omitempty"`
	Sub            AllowDeny `json:"subscribe,omitempty"`
	AllowResponses bool      `json:"allow_responses,omitempty"`
}

Permissions block

type Ports added in v0.1.0

type Ports struct {
	Nats       []string `json:"nats,omitempty"`
	Cluster    []string `json:"cluster,omitempty"`
	Monitoring []string `json:"monitoring,omitempty"`
	WebSocket  []string `json:"websocket,omitempty"`
}

type Remote added in v0.0.10

type Remote struct {
	Urls        []string `json:"urls,omitempty"`
	Account     string   `json:"account,omitempty"`
	Credentials string   `json:"credentials,omitempty"`
}

type Resolver

type Resolver struct {
	Type           ResolverType `json:"type,omitempty"`
	Dir            string       `json:"dir,omitempty"`
	AllowDelete    bool         `json:"allow_delete,omitempty"`
	UpdateInterval string       `json:"interval,omitempty"`
	Timeout        string       `json:"timeout,omitempty"`
}

type ResolverConf

type ResolverConf struct {
	Conf
	Operator      string            `json:"operator,omitempty"`
	SystemAccount string            `json:"system_account,omitempty"`
	Resolver      *Resolver         `json:"resolver,omitempty"`
	Preload       map[string]string `json:"resolver_preload,omitempty"`
}

ResolverConf a Conf using delegated authentication

func ParseConf added in v0.1.0

func ParseConf(t testing.TB, fp string) *ResolverConf

func ResolverFromAuth

func ResolverFromAuth(t testing.TB, operator authb.Operator) *ResolverConf

func (*ResolverConf) Marshal

func (r *ResolverConf) Marshal(t testing.TB) []byte

func (*ResolverConf) UnmarshalJSON added in v0.1.5

func (r *ResolverConf) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler for ResolverConf

type ResolverListResponse added in v0.0.13

type ResolverListResponse struct {
	ResolverResponse
	Accounts []string `json:"data"`
}

func ListAccounts added in v0.0.13

func ListAccounts(nc *nats.Conn) (*ResolverListResponse, error)

type ResolverResponse added in v0.0.13

type ResolverResponse struct {
	Error  *ErrorDetails `json:"error,omitempty"`
	Server ServerDetails `json:"server"`
}

func DeleteAccount added in v0.0.13

func DeleteAccount(nc *nats.Conn, token string) (*ResolverResponse, error)

DeleteAccount will only work if https://github.com/nats-io/nats-server/pull/6427 is merged

type ResolverType added in v0.0.13

type ResolverType string
const (
	FullResolver  ResolverType = "FULL"
	MemResolver   ResolverType = "MEMORY"
	CacheResolver ResolverType = "CACHE"
)

type ResolverUpdateResponse added in v0.0.13

type ResolverUpdateResponse struct {
	ResolverResponse
	UpdateData UpdateData `json:"data"`
}

func UpdateAccount added in v0.0.13

func UpdateAccount(nc *nats.Conn, token string) (*ResolverUpdateResponse, error)

type ServerDetails added in v0.0.4

type ServerDetails struct {
	Name      string    `json:"name"`
	Host      string    `json:"host"`
	ID        string    `json:"id"`
	Version   string    `json:"ver"`
	Jetstream bool      `json:"jetstream"`
	Flags     int       `json:"flags"`
	Sequence  int       `json:"seq"`
	Time      time.Time `json:"time"`
}

type TestDir

type TestDir struct {
	Dir string
	// contains filtered or unexported fields
}

TestDir a directory with some simple powers

func NewTestDir

func NewTestDir(t testing.TB, dir string, pattern string) *TestDir

func (*TestDir) Abs added in v0.1.8

func (td *TestDir) Abs(name string) string

func (*TestDir) Cleanup

func (td *TestDir) Cleanup()

func (*TestDir) CopyFile added in v0.1.6

func (td *TestDir) CopyFile(paths ...string)

func (*TestDir) ReadFile

func (td *TestDir) ReadFile(name string) []byte

func (*TestDir) String added in v0.0.3

func (td *TestDir) String() string

func (*TestDir) T added in v0.1.12

func (td *TestDir) T() testing.TB

func (*TestDir) WriteFile

func (td *TestDir) WriteFile(name string, conf []byte) string

type TestHandler added in v0.1.7

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

TestHandler implements slog.Handler and outputs to testing.TB

func (*TestHandler) Enabled added in v0.1.7

func (h *TestHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler

func (*TestHandler) Handle added in v0.1.7

func (h *TestHandler) Handle(ctx context.Context, record slog.Record) error

Handle implements slog.Handler

func (*TestHandler) WithAttrs added in v0.1.7

func (h *TestHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler

func (*TestHandler) WithGroup added in v0.1.7

func (h *TestHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler

type UpdateData added in v0.0.13

type UpdateData struct {
	Account string `json:"account"`
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type User

type User struct {
	User        string       `json:"user,omitempty"`
	Password    string       `json:"password,omitempty"`
	Token       string       `json:"token,omitempty"`
	NKEY        string       `json:"nkey,omitempty"`
	Permissions *Permissions `json:"permissions,omitempty"`
}

User represents Username/Password/Token/Permissions

type UserData added in v0.0.4

type UserData struct {
	User        string      `json:"user"`
	Account     string      `json:"account"`
	Permissions Permissions `json:"permissions"`
	Expires     int64       `json:"expires"`
}

type UserInfo added in v0.0.4

type UserInfo struct {
	ServerDetails
	Data UserData `json:"data"`
}

func ClientInfo added in v0.0.4

func ClientInfo(t testing.TB, nc *nats.Conn) UserInfo

type Users

type Users []User

Users block

func (*Users) Add

func (u *Users) Add(user ...User)

type WebSocket added in v0.0.12

type WebSocket struct {
	Port        int    `json:"port,omitempty"`
	NoTls       bool   `json:"no_tls,omitempty"`
	JwtCookie   string `json:"jwt_cookie,omitempty"`
	UserCookie  string `json:"user_cookie,omitempty"`
	PassCookie  string `json:"pass_cookie,omitempty"`
	TokenCookie string `json:"token_cookie,omitempty"`
}

Jump to

Keyboard shortcuts

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