server

package
v2.10.24 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2024 License: Apache-2.0 Imports: 82 Imported by: 301

README

Tests

Tests that run on Travis have been split into jobs that run in their own VM in parallel. This reduces the overall running time but also is allowing recycling of a job when we get a flapper as opposed to have to recycle the whole test suite.

JetStream Tests

For JetStream tests, we need to observe a naming convention so that no tests are omitted when running on Travis.

The script runTestsOnTravis.sh will run a given job based on the definition found in ".travis.yml".

As for the naming convention:

  • All JetStream tests name should start with TestJetStream
  • Cluster tests should go into jetstream_cluster_test.go and start with TestJetStreamCluster
  • Super-cluster tests should go into jetstream_super_cluster_test.go and start with TestJetStreamSuperCluster

Not following this convention means that some tests may not be executed on Travis.

Documentation

Index

Constants

View Source
const (
	AuthCalloutSubject    = "$SYS.REQ.USER.AUTH"
	AuthRequestSubject    = "nats-authorization-request"
	AuthRequestXKeyHeader = "Nats-Server-Xkey"
)
View Source
const (
	// CLIENT is an end user.
	CLIENT = iota
	// ROUTER represents another server in the cluster.
	ROUTER
	// GATEWAY is a link between 2 clusters.
	GATEWAY
	// SYSTEM is an internal system client.
	SYSTEM
	// LEAF is for leaf node connections.
	LEAF
	// JETSTREAM is an internal jetstream client.
	JETSTREAM
	// ACCOUNT is for the internal client for accounts.
	ACCOUNT
)

Type of client connection.

View Source
const (
	// If the connection is not a CLIENT connection.
	NON_CLIENT = iota
	// Regular NATS client.
	NATS
	// MQTT client.
	MQTT
	// Websocket client.
	WS
)

Extended type of a CLIENT connection. This is returned by c.clientType() and indicate what type of client connection we are dealing with. If invoked on a non CLIENT connection, NON_CLIENT type is returned.

View Source
const (
	// ClientProtoZero is the original Client protocol from 2009.
	// http://nats.io/documentation/internals/nats-protocol/
	ClientProtoZero = iota
	// ClientProtoInfo signals a client can receive more then the original INFO block.
	// This can be used to update clients on other cluster members, etc.
	ClientProtoInfo
)
View Source
const (
	ClientClosed = ClosedState(iota + 1)
	AuthenticationTimeout
	AuthenticationViolation
	TLSHandshakeError
	SlowConsumerPendingBytes
	SlowConsumerWriteDeadline
	WriteError
	ReadError
	ParseError
	StaleConnection
	ProtocolViolation
	BadClientProtocolVersion
	WrongPort
	MaxAccountConnectionsExceeded
	MaxConnectionsExceeded
	MaxPayloadExceeded
	MaxControlLineExceeded
	MaxSubscriptionsExceeded
	DuplicateRoute
	RouteRemoved
	ServerShutdown
	AuthenticationExpired
	WrongGateway
	MissingAccount
	Revocation
	InternalClient
	MsgHeaderViolation
	NoRespondersRequiresHeaders
	ClusterNameConflict
	DuplicateRemoteLeafnodeConnection
	DuplicateClientID
	DuplicateServerName
	MinimumVersionRequired
	ClusterNamesIdentical
	Kicked
)
View Source
const (
	CommandStop   = Command("stop")
	CommandQuit   = Command("quit")
	CommandReopen = Command("reopen")
	CommandReload = Command("reload")
)

Valid Command values.

View Source
const (
	// VERSION is the current version for the server.
	VERSION = "2.10.24"

	// PROTO is the currently supported protocol.
	// 0 was the original
	// 1 maintains proto 0, adds echo abilities for CONNECT from the client. Clients
	// should not send echo unless proto in INFO is >= 1.
	PROTO = 1

	// DEFAULT_PORT is the default port for client connections.
	DEFAULT_PORT = 4222

	// RANDOM_PORT is the value for port that, when supplied, will cause the
	// server to listen on a randomly-chosen available port. The resolved port
	// is available via the Addr() method.
	RANDOM_PORT = -1

	// DEFAULT_HOST defaults to all interfaces.
	DEFAULT_HOST = "0.0.0.0"

	// MAX_CONTROL_LINE_SIZE is the maximum allowed protocol control line size.
	// 4k should be plenty since payloads sans connect/info string are separate.
	MAX_CONTROL_LINE_SIZE = 4096

	// MAX_PAYLOAD_SIZE is the maximum allowed payload size. Should be using
	// something different if > 1MB payloads are needed.
	MAX_PAYLOAD_SIZE = (1024 * 1024)

	// MAX_PAYLOAD_MAX_SIZE is the size at which the server will warn about
	// max_payload being too high. In the future, the server may enforce/reject
	// max_payload above this value.
	MAX_PAYLOAD_MAX_SIZE = (8 * 1024 * 1024)

	// MAX_PENDING_SIZE is the maximum outbound pending bytes per client.
	MAX_PENDING_SIZE = (64 * 1024 * 1024)

	// DEFAULT_MAX_CONNECTIONS is the default maximum connections allowed.
	DEFAULT_MAX_CONNECTIONS = (64 * 1024)

	// TLS_TIMEOUT is the TLS wait time.
	TLS_TIMEOUT = 2 * time.Second

	// DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY is the default amount of
	// time for the server to wait for the TLS handshake with a client to
	// be initiated before falling back to sending the INFO protocol first.
	// See TLSHandshakeFirst and TLSHandshakeFirstFallback options.
	DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY = 50 * time.Millisecond

	// AUTH_TIMEOUT is the authorization wait time.
	AUTH_TIMEOUT = 2 * time.Second

	// DEFAULT_PING_INTERVAL is how often pings are sent to clients, etc...
	DEFAULT_PING_INTERVAL = 2 * time.Minute

	// DEFAULT_PING_MAX_OUT is maximum allowed pings outstanding before disconnect.
	DEFAULT_PING_MAX_OUT = 2

	// CR_LF string
	CR_LF = "\r\n"

	// LEN_CR_LF hold onto the computed size.
	LEN_CR_LF = len(CR_LF)

	// DEFAULT_FLUSH_DEADLINE is the write/flush deadlines.
	DEFAULT_FLUSH_DEADLINE = 10 * time.Second

	// DEFAULT_HTTP_PORT is the default monitoring port.
	DEFAULT_HTTP_PORT = 8222

	// DEFAULT_HTTP_BASE_PATH is the default base path for monitoring.
	DEFAULT_HTTP_BASE_PATH = "/"

	// ACCEPT_MIN_SLEEP is the minimum acceptable sleep times on temporary errors.
	ACCEPT_MIN_SLEEP = 10 * time.Millisecond

	// ACCEPT_MAX_SLEEP is the maximum acceptable sleep times on temporary errors
	ACCEPT_MAX_SLEEP = 1 * time.Second

	// DEFAULT_ROUTE_CONNECT Route solicitation intervals.
	DEFAULT_ROUTE_CONNECT = 1 * time.Second

	// DEFAULT_ROUTE_RECONNECT Route reconnect intervals.
	DEFAULT_ROUTE_RECONNECT = 1 * time.Second

	// DEFAULT_ROUTE_DIAL Route dial timeout.
	DEFAULT_ROUTE_DIAL = 1 * time.Second

	// DEFAULT_ROUTE_POOL_SIZE Route default pool size
	DEFAULT_ROUTE_POOL_SIZE = 3

	// DEFAULT_LEAF_NODE_RECONNECT LeafNode reconnect interval.
	DEFAULT_LEAF_NODE_RECONNECT = time.Second

	// DEFAULT_LEAF_TLS_TIMEOUT TLS timeout for LeafNodes
	DEFAULT_LEAF_TLS_TIMEOUT = 2 * time.Second

	// PROTO_SNIPPET_SIZE is the default size of proto to print on parse errors.
	PROTO_SNIPPET_SIZE = 32

	// MAX_CONTROL_LINE_SNIPPET_SIZE is the default size of proto to print on max control line errors.
	MAX_CONTROL_LINE_SNIPPET_SIZE = 128

	// MAX_MSG_ARGS Maximum possible number of arguments from MSG proto.
	MAX_MSG_ARGS = 4

	// MAX_RMSG_ARGS Maximum possible number of arguments from RMSG proto.
	MAX_RMSG_ARGS = 6

	// MAX_HMSG_ARGS Maximum possible number of arguments from HMSG proto.
	MAX_HMSG_ARGS = 7

	// MAX_PUB_ARGS Maximum possible number of arguments from PUB proto.
	MAX_PUB_ARGS = 3

	// MAX_HPUB_ARGS Maximum possible number of arguments from HPUB proto.
	MAX_HPUB_ARGS = 4

	// MAX_RSUB_ARGS Maximum possible number of arguments from a RS+/LS+ proto.
	MAX_RSUB_ARGS = 6

	// DEFAULT_MAX_CLOSED_CLIENTS is the maximum number of closed connections we hold onto.
	DEFAULT_MAX_CLOSED_CLIENTS = 10000

	// DEFAULT_LAME_DUCK_DURATION is the time in which the server spreads
	// the closing of clients when signaled to go in lame duck mode.
	DEFAULT_LAME_DUCK_DURATION = 2 * time.Minute

	// DEFAULT_LAME_DUCK_GRACE_PERIOD is the duration the server waits, after entering
	// lame duck mode, before starting closing client connections.
	DEFAULT_LAME_DUCK_GRACE_PERIOD = 10 * time.Second

	// DEFAULT_LEAFNODE_INFO_WAIT Route dial timeout.
	DEFAULT_LEAFNODE_INFO_WAIT = 1 * time.Second

	// DEFAULT_LEAFNODE_PORT is the default port for remote leafnode connections.
	DEFAULT_LEAFNODE_PORT = 7422

	// DEFAULT_CONNECT_ERROR_REPORTS is the number of attempts at which a
	// repeated failed route, gateway or leaf node connection is reported.
	// This is used for initial connection, that is, when the server has
	// never had a connection to the given endpoint. Once connected, and
	// if a disconnect occurs, DEFAULT_RECONNECT_ERROR_REPORTS is used
	// instead.
	// The default is to report every 3600 attempts (roughly every hour).
	DEFAULT_CONNECT_ERROR_REPORTS = 3600

	// DEFAULT_RECONNECT_ERROR_REPORTS is the default number of failed
	// attempt to reconnect a route, gateway or leaf node connection.
	// The default is to report every attempt.
	DEFAULT_RECONNECT_ERROR_REPORTS = 1

	// DEFAULT_RTT_MEASUREMENT_INTERVAL is how often we want to measure RTT from
	// this server to clients, routes, gateways or leafnode connections.
	DEFAULT_RTT_MEASUREMENT_INTERVAL = time.Hour

	// DEFAULT_ALLOW_RESPONSE_MAX_MSGS is the default number of responses allowed
	// for a reply subject.
	DEFAULT_ALLOW_RESPONSE_MAX_MSGS = 1

	// DEFAULT_ALLOW_RESPONSE_EXPIRATION is the default time allowed for a given
	// dynamic response permission.
	DEFAULT_ALLOW_RESPONSE_EXPIRATION = 2 * time.Minute

	// DEFAULT_SERVICE_EXPORT_RESPONSE_THRESHOLD is the default time that the system will
	// expect a service export response to be delivered. This is used in corner cases for
	// time based cleanup of reverse mapping structures.
	DEFAULT_SERVICE_EXPORT_RESPONSE_THRESHOLD = 2 * time.Minute

	// DEFAULT_SERVICE_LATENCY_SAMPLING is the default sampling rate for service
	// latency metrics
	DEFAULT_SERVICE_LATENCY_SAMPLING = 100

	// DEFAULT_SYSTEM_ACCOUNT
	DEFAULT_SYSTEM_ACCOUNT = "$SYS"

	// DEFAULT GLOBAL_ACCOUNT
	DEFAULT_GLOBAL_ACCOUNT = "$G"

	// DEFAULT_FETCH_TIMEOUT is the default time that the system will wait for an account fetch to return.
	DEFAULT_ACCOUNT_FETCH_TIMEOUT = 1900 * time.Millisecond
)
View Source
const (
	JSPullRequestPendingMsgs  = "Nats-Pending-Messages"
	JSPullRequestPendingBytes = "Nats-Pending-Bytes"
)

Headers sent with Request Timeout

View Source
const (
	// JsAckWaitDefault is the default AckWait, only applicable on explicit ack policy consumers.
	JsAckWaitDefault = 30 * time.Second
	// JsDeleteWaitTimeDefault is the default amount of time we will wait for non-durable
	// consumers to be in an inactive state before deleting them.
	JsDeleteWaitTimeDefault = 5 * time.Second
	// JsFlowControlMaxPending specifies default pending bytes during flow control that can be outstanding.
	JsFlowControlMaxPending = 32 * 1024 * 1024
	// JsDefaultMaxAckPending is set for consumers with explicit ack that do not set the max ack pending.
	JsDefaultMaxAckPending = 1000
)
View Source
const (
	NoDelete deleteType = iota
	RenameDeleted
	HardDelete
)
View Source
const (

	// Metafiles for streams and consumers.
	JetStreamMetaFile    = "meta.inf"
	JetStreamMetaFileSum = "meta.sum"
	JetStreamMetaFileKey = "meta.key"

	// FileStoreMinBlkSize is minimum size we will do for a blk size.
	FileStoreMinBlkSize = 32 * 1000 // 32kib
	// FileStoreMaxBlkSize is maximum size we will do for a blk size.
	FileStoreMaxBlkSize = maxBlockSize
)
View Source
const (
	// JetStreamStoreDir is the prefix we use.
	JetStreamStoreDir = "jetstream"
	// JetStreamMaxStoreDefault is the default disk storage limit. 1TB
	JetStreamMaxStoreDefault = 1024 * 1024 * 1024 * 1024
	// JetStreamMaxMemDefault is only used when we can't determine system memory. 256MB
	JetStreamMaxMemDefault = 1024 * 1024 * 256
)
View Source
const (
	JSApiPrefix = "$JS.API"

	// JSApiAccountInfo is for obtaining general information about JetStream for this account.
	// Will return JSON response.
	JSApiAccountInfo = "$JS.API.INFO"

	// JSApiTemplateCreate is the endpoint to create new stream templates.
	// Will return JSON response.
	JSApiTemplateCreate  = "$JS.API.STREAM.TEMPLATE.CREATE.*"
	JSApiTemplateCreateT = "$JS.API.STREAM.TEMPLATE.CREATE.%s"

	// JSApiTemplates is the endpoint to list all stream template names for this account.
	// Will return JSON response.
	JSApiTemplates = "$JS.API.STREAM.TEMPLATE.NAMES"

	// JSApiTemplateInfo is for obtaining general information about a named stream template.
	// Will return JSON response.
	JSApiTemplateInfo  = "$JS.API.STREAM.TEMPLATE.INFO.*"
	JSApiTemplateInfoT = "$JS.API.STREAM.TEMPLATE.INFO.%s"

	// JSApiTemplateDelete is the endpoint to delete stream templates.
	// Will return JSON response.
	JSApiTemplateDelete  = "$JS.API.STREAM.TEMPLATE.DELETE.*"
	JSApiTemplateDeleteT = "$JS.API.STREAM.TEMPLATE.DELETE.%s"

	// JSApiStreamCreate is the endpoint to create new streams.
	// Will return JSON response.
	JSApiStreamCreate  = "$JS.API.STREAM.CREATE.*"
	JSApiStreamCreateT = "$JS.API.STREAM.CREATE.%s"

	// JSApiStreamUpdate is the endpoint to update existing streams.
	// Will return JSON response.
	JSApiStreamUpdate  = "$JS.API.STREAM.UPDATE.*"
	JSApiStreamUpdateT = "$JS.API.STREAM.UPDATE.%s"

	// JSApiStreams is the endpoint to list all stream names for this account.
	// Will return JSON response.
	JSApiStreams = "$JS.API.STREAM.NAMES"
	// JSApiStreamList is the endpoint that will return all detailed stream information
	JSApiStreamList = "$JS.API.STREAM.LIST"

	// JSApiStreamInfo is for obtaining general information about a named stream.
	// Will return JSON response.
	JSApiStreamInfo  = "$JS.API.STREAM.INFO.*"
	JSApiStreamInfoT = "$JS.API.STREAM.INFO.%s"

	// JSApiStreamDelete is the endpoint to delete streams.
	// Will return JSON response.
	JSApiStreamDelete  = "$JS.API.STREAM.DELETE.*"
	JSApiStreamDeleteT = "$JS.API.STREAM.DELETE.%s"

	// JSApiStreamPurge is the endpoint to purge streams.
	// Will return JSON response.
	JSApiStreamPurge  = "$JS.API.STREAM.PURGE.*"
	JSApiStreamPurgeT = "$JS.API.STREAM.PURGE.%s"

	// JSApiStreamSnapshot is the endpoint to snapshot streams.
	// Will return a stream of chunks with a nil chunk as EOF to
	// the deliver subject. Caller should respond to each chunk
	// with a nil body response for ack flow.
	JSApiStreamSnapshot  = "$JS.API.STREAM.SNAPSHOT.*"
	JSApiStreamSnapshotT = "$JS.API.STREAM.SNAPSHOT.%s"

	// JSApiStreamRestore is the endpoint to restore a stream from a snapshot.
	// Caller should respond to each chunk with a nil body response.
	JSApiStreamRestore  = "$JS.API.STREAM.RESTORE.*"
	JSApiStreamRestoreT = "$JS.API.STREAM.RESTORE.%s"

	// JSApiMsgDelete is the endpoint to delete messages from a stream.
	// Will return JSON response.
	JSApiMsgDelete  = "$JS.API.STREAM.MSG.DELETE.*"
	JSApiMsgDeleteT = "$JS.API.STREAM.MSG.DELETE.%s"

	// JSApiMsgGet is the template for direct requests for a message by its stream sequence number.
	// Will return JSON response.
	JSApiMsgGet  = "$JS.API.STREAM.MSG.GET.*"
	JSApiMsgGetT = "$JS.API.STREAM.MSG.GET.%s"

	// JSDirectMsgGet is the template for non-api layer direct requests for a message by its stream sequence number or last by subject.
	// Will return the message similar to how a consumer receives the message, no JSON processing.
	// If the message can not be found we will use a status header of 404. If the stream does not exist the client will get a no-responders or timeout.
	JSDirectMsgGet  = "$JS.API.DIRECT.GET.*"
	JSDirectMsgGetT = "$JS.API.DIRECT.GET.%s"

	// This is a direct version of get last by subject, which will be the dominant pattern for KV access once 2.9 is released.
	// The stream and the key will be part of the subject to allow for no-marshal payloads and subject based security permissions.
	JSDirectGetLastBySubject  = "$JS.API.DIRECT.GET.*.>"
	JSDirectGetLastBySubjectT = "$JS.API.DIRECT.GET.%s.%s"

	// JSApiConsumerCreate is the endpoint to create consumers for streams.
	// This was also the legacy endpoint for ephemeral consumers.
	// It now can take consumer name and optional filter subject, which when part of the subject controls access.
	// Will return JSON response.
	JSApiConsumerCreate    = "$JS.API.CONSUMER.CREATE.*"
	JSApiConsumerCreateT   = "$JS.API.CONSUMER.CREATE.%s"
	JSApiConsumerCreateEx  = "$JS.API.CONSUMER.CREATE.*.>"
	JSApiConsumerCreateExT = "$JS.API.CONSUMER.CREATE.%s.%s.%s"

	// JSApiDurableCreate is the endpoint to create durable consumers for streams.
	// You need to include the stream and consumer name in the subject.
	JSApiDurableCreate  = "$JS.API.CONSUMER.DURABLE.CREATE.*.*"
	JSApiDurableCreateT = "$JS.API.CONSUMER.DURABLE.CREATE.%s.%s"

	// JSApiConsumers is the endpoint to list all consumer names for the stream.
	// Will return JSON response.
	JSApiConsumers  = "$JS.API.CONSUMER.NAMES.*"
	JSApiConsumersT = "$JS.API.CONSUMER.NAMES.%s"

	// JSApiConsumerList is the endpoint that will return all detailed consumer information
	JSApiConsumerList  = "$JS.API.CONSUMER.LIST.*"
	JSApiConsumerListT = "$JS.API.CONSUMER.LIST.%s"

	// JSApiConsumerInfo is for obtaining general information about a consumer.
	// Will return JSON response.
	JSApiConsumerInfo  = "$JS.API.CONSUMER.INFO.*.*"
	JSApiConsumerInfoT = "$JS.API.CONSUMER.INFO.%s.%s"

	// JSApiConsumerDelete is the endpoint to delete consumers.
	// Will return JSON response.
	JSApiConsumerDelete  = "$JS.API.CONSUMER.DELETE.*.*"
	JSApiConsumerDeleteT = "$JS.API.CONSUMER.DELETE.%s.%s"

	// JSApiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode.
	JSApiRequestNextT = "$JS.API.CONSUMER.MSG.NEXT.%s.%s"

	// JSApiStreamRemovePeer is the endpoint to remove a peer from a clustered stream and its consumers.
	// Will return JSON response.
	JSApiStreamRemovePeer  = "$JS.API.STREAM.PEER.REMOVE.*"
	JSApiStreamRemovePeerT = "$JS.API.STREAM.PEER.REMOVE.%s"

	// JSApiStreamLeaderStepDown is the endpoint to have stream leader stepdown.
	// Will return JSON response.
	JSApiStreamLeaderStepDown  = "$JS.API.STREAM.LEADER.STEPDOWN.*"
	JSApiStreamLeaderStepDownT = "$JS.API.STREAM.LEADER.STEPDOWN.%s"

	// JSApiConsumerLeaderStepDown is the endpoint to have consumer leader stepdown.
	// Will return JSON response.
	JSApiConsumerLeaderStepDown  = "$JS.API.CONSUMER.LEADER.STEPDOWN.*.*"
	JSApiConsumerLeaderStepDownT = "$JS.API.CONSUMER.LEADER.STEPDOWN.%s.%s"

	// JSApiLeaderStepDown is the endpoint to have our metaleader stepdown.
	// Only works from system account.
	// Will return JSON response.
	JSApiLeaderStepDown = "$JS.API.META.LEADER.STEPDOWN"

	// JSApiRemoveServer is the endpoint to remove a peer server from the cluster.
	// Only works from system account.
	// Will return JSON response.
	JSApiRemoveServer = "$JS.API.SERVER.REMOVE"

	// JSApiAccountPurge is the endpoint to purge the js content of an account
	// Only works from system account.
	// Will return JSON response.
	JSApiAccountPurge  = "$JS.API.ACCOUNT.PURGE.*"
	JSApiAccountPurgeT = "$JS.API.ACCOUNT.PURGE.%s"

	// JSApiServerStreamMove is the endpoint to move streams off a server
	// Only works from system account.
	// Will return JSON response.
	JSApiServerStreamMove  = "$JS.API.ACCOUNT.STREAM.MOVE.*.*"
	JSApiServerStreamMoveT = "$JS.API.ACCOUNT.STREAM.MOVE.%s.%s"

	// JSApiServerStreamCancelMove is the endpoint to cancel a stream move
	// Only works from system account.
	// Will return JSON response.
	JSApiServerStreamCancelMove  = "$JS.API.ACCOUNT.STREAM.CANCEL_MOVE.*.*"
	JSApiServerStreamCancelMoveT = "$JS.API.ACCOUNT.STREAM.CANCEL_MOVE.%s.%s"

	// JSAdvisoryPrefix is a prefix for all JetStream advisories.
	JSAdvisoryPrefix = "$JS.EVENT.ADVISORY"

	// JSMetricPrefix is a prefix for all JetStream metrics.
	JSMetricPrefix = "$JS.EVENT.METRIC"

	// JSMetricConsumerAckPre is a metric containing ack latency.
	JSMetricConsumerAckPre = "$JS.EVENT.METRIC.CONSUMER.ACK"

	// JSAdvisoryConsumerMaxDeliveryExceedPre is a notification published when a message exceeds its delivery threshold.
	JSAdvisoryConsumerMaxDeliveryExceedPre = "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES"

	// JSAdvisoryConsumerMsgNakPre is a notification published when a message has been naked
	JSAdvisoryConsumerMsgNakPre = "$JS.EVENT.ADVISORY.CONSUMER.MSG_NAKED"

	// JSAdvisoryConsumerMsgTerminatedPre is a notification published when a message has been terminated.
	JSAdvisoryConsumerMsgTerminatedPre = "$JS.EVENT.ADVISORY.CONSUMER.MSG_TERMINATED"

	// JSAdvisoryStreamCreatedPre notification that a stream was created.
	JSAdvisoryStreamCreatedPre = "$JS.EVENT.ADVISORY.STREAM.CREATED"

	// JSAdvisoryStreamDeletedPre notification that a stream was deleted.
	JSAdvisoryStreamDeletedPre = "$JS.EVENT.ADVISORY.STREAM.DELETED"

	// JSAdvisoryStreamUpdatedPre notification that a stream was updated.
	JSAdvisoryStreamUpdatedPre = "$JS.EVENT.ADVISORY.STREAM.UPDATED"

	// JSAdvisoryConsumerCreatedPre notification that a template created.
	JSAdvisoryConsumerCreatedPre = "$JS.EVENT.ADVISORY.CONSUMER.CREATED"

	// JSAdvisoryConsumerDeletedPre notification that a template deleted.
	JSAdvisoryConsumerDeletedPre = "$JS.EVENT.ADVISORY.CONSUMER.DELETED"

	// JSAdvisoryStreamSnapshotCreatePre notification that a snapshot was created.
	JSAdvisoryStreamSnapshotCreatePre = "$JS.EVENT.ADVISORY.STREAM.SNAPSHOT_CREATE"

	// JSAdvisoryStreamSnapshotCompletePre notification that a snapshot was completed.
	JSAdvisoryStreamSnapshotCompletePre = "$JS.EVENT.ADVISORY.STREAM.SNAPSHOT_COMPLETE"

	// JSAdvisoryStreamRestoreCreatePre notification that a restore was start.
	JSAdvisoryStreamRestoreCreatePre = "$JS.EVENT.ADVISORY.STREAM.RESTORE_CREATE"

	// JSAdvisoryStreamRestoreCompletePre notification that a restore was completed.
	JSAdvisoryStreamRestoreCompletePre = "$JS.EVENT.ADVISORY.STREAM.RESTORE_COMPLETE"

	// JSAdvisoryDomainLeaderElectedPre notification that a jetstream domain has elected a leader.
	JSAdvisoryDomainLeaderElected = "$JS.EVENT.ADVISORY.DOMAIN.LEADER_ELECTED"

	// JSAdvisoryStreamLeaderElectedPre notification that a replicated stream has elected a leader.
	JSAdvisoryStreamLeaderElectedPre = "$JS.EVENT.ADVISORY.STREAM.LEADER_ELECTED"

	// JSAdvisoryStreamQuorumLostPre notification that a stream and its consumers are stalled.
	JSAdvisoryStreamQuorumLostPre = "$JS.EVENT.ADVISORY.STREAM.QUORUM_LOST"

	// JSAdvisoryConsumerLeaderElectedPre notification that a replicated consumer has elected a leader.
	JSAdvisoryConsumerLeaderElectedPre = "$JS.EVENT.ADVISORY.CONSUMER.LEADER_ELECTED"

	// JSAdvisoryConsumerQuorumLostPre notification that a consumer is stalled.
	JSAdvisoryConsumerQuorumLostPre = "$JS.EVENT.ADVISORY.CONSUMER.QUORUM_LOST"

	// JSAdvisoryServerOutOfStorage notification that a server has no more storage.
	JSAdvisoryServerOutOfStorage = "$JS.EVENT.ADVISORY.SERVER.OUT_OF_STORAGE"

	// JSAdvisoryServerRemoved notification that a server has been removed from the system.
	JSAdvisoryServerRemoved = "$JS.EVENT.ADVISORY.SERVER.REMOVED"

	// JSAdvisoryAPILimitReached notification that a server has reached the JS API hard limit.
	JSAdvisoryAPILimitReached = "$JS.EVENT.ADVISORY.API.LIMIT_REACHED"

	// JSAuditAdvisory is a notification about JetStream API access.
	// FIXME - Add in details about who..
	JSAuditAdvisory = "$JS.EVENT.ADVISORY.API"
)

Request API subjects for JetStream.

View Source
const (
	// ConnOpen filters on open clients.
	ConnOpen = ConnState(iota)
	// ConnClosed filters on closed clients.
	ConnClosed
	// ConnAll returns all clients.
	ConnAll
)
View Source
const (
	OCSPResponseCacheDefaultDir            = "_rc_"
	OCSPResponseCacheDefaultFilename       = "cache.json"
	OCSPResponseCacheDefaultTempFilePrefix = "ocsprc-*"
	OCSPResponseCacheMinimumSaveInterval   = 1 * time.Second
	OCSPResponseCacheDefaultSaveInterval   = 5 * time.Minute
)
View Source
const (
	OP_START parserState = iota
	OP_PLUS
	OP_PLUS_O
	OP_PLUS_OK
	OP_MINUS
	OP_MINUS_E
	OP_MINUS_ER
	OP_MINUS_ERR
	OP_MINUS_ERR_SPC
	MINUS_ERR_ARG
	OP_C
	OP_CO
	OP_CON
	OP_CONN
	OP_CONNE
	OP_CONNEC
	OP_CONNECT
	CONNECT_ARG
	OP_H
	OP_HP
	OP_HPU
	OP_HPUB
	OP_HPUB_SPC
	HPUB_ARG
	OP_HM
	OP_HMS
	OP_HMSG
	OP_HMSG_SPC
	HMSG_ARG
	OP_P
	OP_PU
	OP_PUB
	OP_PUB_SPC
	PUB_ARG
	OP_PI
	OP_PIN
	OP_PING
	OP_PO
	OP_PON
	OP_PONG
	MSG_PAYLOAD
	MSG_END_R
	MSG_END_N
	OP_S
	OP_SU
	OP_SUB
	OP_SUB_SPC
	SUB_ARG
	OP_A
	OP_ASUB
	OP_ASUB_SPC
	ASUB_ARG
	OP_AUSUB
	OP_AUSUB_SPC
	AUSUB_ARG
	OP_L
	OP_LS
	OP_R
	OP_RS
	OP_U
	OP_UN
	OP_UNS
	OP_UNSU
	OP_UNSUB
	OP_UNSUB_SPC
	UNSUB_ARG
	OP_M
	OP_MS
	OP_MSG
	OP_MSG_SPC
	MSG_ARG
	OP_I
	OP_IN
	OP_INF
	OP_INFO
	INFO_ARG
)

Parser constants

View Source
const (
	// RouteProtoZero is the original Route protocol from 2009.
	// http://nats.io/documentation/internals/nats-protocol/
	RouteProtoZero = iota
	// RouteProtoInfo signals a route can receive more then the original INFO block.
	// This can be used to update remote cluster permissions, etc...
	RouteProtoInfo
	// RouteProtoV2 is the new route/cluster protocol that provides account support.
	RouteProtoV2
)
View Source
const (
	ConProto  = "CONNECT %s" + _CRLF_
	InfoProto = "INFO %s" + _CRLF_
)

Route protocol constants

View Source
const (
	CompressionNotSupported   = "not supported"
	CompressionOff            = "off"
	CompressionAccept         = "accept"
	CompressionS2Auto         = "s2_auto"
	CompressionS2Uncompressed = "s2_uncompressed"
	CompressionS2Fast         = "s2_fast"
	CompressionS2Better       = "s2_better"
	CompressionS2Best         = "s2_best"
)

Compression modes.

View Source
const (
	RootPath         = "/"
	VarzPath         = "/varz"
	ConnzPath        = "/connz"
	RoutezPath       = "/routez"
	GatewayzPath     = "/gatewayz"
	LeafzPath        = "/leafz"
	SubszPath        = "/subsz"
	StackszPath      = "/stacksz"
	AccountzPath     = "/accountz"
	AccountStatzPath = "/accstatz"
	JszPath          = "/jsz"
	HealthzPath      = "/healthz"
	IPQueuesPath     = "/ipqueuesz"
	RaftzPath        = "/raftz"
)

HTTP endpoints

View Source
const (
	// File specifies on disk, designated by the JetStream config StoreDir.
	FileStorage = StorageType(22)
	// MemoryStorage specifies in memory only.
	MemoryStorage = StorageType(33)
	// Any is for internals.
	AnyStorage = StorageType(44)
)
View Source
const (
	// DiscardOld will remove older messages to return to the limits.
	DiscardOld = iota
	// DiscardNew will error on a StoreMsg call
	DiscardNew
)
View Source
const (
	JSMsgId               = "Nats-Msg-Id"
	JSExpectedStream      = "Nats-Expected-Stream"
	JSExpectedLastSeq     = "Nats-Expected-Last-Sequence"
	JSExpectedLastSubjSeq = "Nats-Expected-Last-Subject-Sequence"
	JSExpectedLastMsgId   = "Nats-Expected-Last-Msg-Id"
	JSStreamSource        = "Nats-Stream-Source"
	JSLastConsumerSeq     = "Nats-Last-Consumer"
	JSLastStreamSeq       = "Nats-Last-Stream"
	JSConsumerStalled     = "Nats-Consumer-Stalled"
	JSMsgRollup           = "Nats-Rollup"
	JSMsgSize             = "Nats-Msg-Size"
	JSResponseType        = "Nats-Response-Type"
)

Headers for published messages.

View Source
const (
	JSStream       = "Nats-Stream"
	JSSequence     = "Nats-Sequence"
	JSTimeStamp    = "Nats-Time-Stamp"
	JSSubject      = "Nats-Subject"
	JSLastSequence = "Nats-Last-Sequence"
)

Headers for republished messages and direct gets.

View Source
const (
	JSMsgRollupSubject = "sub"
	JSMsgRollupAll     = "all"
)

Rollups, can be subject only or all messages.

View Source
const (
	NoTransform int16 = iota
	BadTransform
	Partition
	Wildcard
	SplitFromLeft
	SplitFromRight
	SliceFromLeft
	SliceFromRight
	Split
	Left
	Right
)

Enum for the subject mapping subjectTransform function types

View Source
const AccountNumConnsMsgType = "io.nats.server.advisory.v1.account_connections"
View Source
const ClientInfoHdr = "Nats-Request-Info"
View Source
const ConnectEventMsgType = "io.nats.server.advisory.v1.client_connect"

ConnectEventMsgType is the schema type for ConnectEventMsg

View Source
const DefaultConnListSize = 1024

DefaultConnListSize is the default size of the connection list.

View Source
const DefaultSubListSize = 1024

DefaultSubListSize is the default size of the subscriptions list.

View Source
const DisconnectEventMsgType = "io.nats.server.advisory.v1.client_disconnect"

DisconnectEventMsgType is the schema type for DisconnectEventMsg

View Source
const (
	InboxPrefix = "$SYS._INBOX."
)

Copied from go client. We could use serviceReply here instead to save some code. I prefer these semantics for the moment, when tracing you know what this is.

View Source
const JSAPIAuditType = "io.nats.jetstream.advisory.v1.api_audit"
View Source
const JSAPILimitReachedAdvisoryType = "io.nats.jetstream.advisory.v1.api_limit_reached"

JSAPILimitReachedAdvisoryType is sent when the JS API request queue limit is reached.

View Source
const JSApiAccountInfoResponseType = "io.nats.jetstream.api.v1.account_info_response"
View Source
const JSApiAccountPurgeResponseType = "io.nats.jetstream.api.v1.account_purge_response"
View Source
const JSApiConsumerCreateResponseType = "io.nats.jetstream.api.v1.consumer_create_response"
View Source
const JSApiConsumerDeleteResponseType = "io.nats.jetstream.api.v1.consumer_delete_response"
View Source
const JSApiConsumerInfoResponseType = "io.nats.jetstream.api.v1.consumer_info_response"
View Source
const JSApiConsumerLeaderStepDownResponseType = "io.nats.jetstream.api.v1.consumer_leader_stepdown_response"
View Source
const JSApiConsumerListResponseType = "io.nats.jetstream.api.v1.consumer_list_response"
View Source
const JSApiConsumerNamesResponseType = "io.nats.jetstream.api.v1.consumer_names_response"
View Source
const JSApiLeaderStepDownResponseType = "io.nats.jetstream.api.v1.meta_leader_stepdown_response"
View Source
const JSApiListLimit = 256
View Source
const JSApiMetaServerRemoveResponseType = "io.nats.jetstream.api.v1.meta_server_remove_response"
View Source
const JSApiMsgDeleteResponseType = "io.nats.jetstream.api.v1.stream_msg_delete_response"
View Source
const JSApiMsgGetResponseType = "io.nats.jetstream.api.v1.stream_msg_get_response"
View Source
const JSApiNamesLimit = 1024

JSApiNamesLimit is the maximum entries we will return for streams or consumers lists. TODO(dlc) - with header or request support could request chunked response.

View Source
const JSApiOverloadedType = "io.nats.jetstream.api.v1.system_overloaded"
View Source
const JSApiStreamCreateResponseType = "io.nats.jetstream.api.v1.stream_create_response"
View Source
const JSApiStreamDeleteResponseType = "io.nats.jetstream.api.v1.stream_delete_response"
View Source
const JSApiStreamInfoResponseType = "io.nats.jetstream.api.v1.stream_info_response"
View Source
const JSApiStreamLeaderStepDownResponseType = "io.nats.jetstream.api.v1.stream_leader_stepdown_response"
View Source
const JSApiStreamListResponseType = "io.nats.jetstream.api.v1.stream_list_response"
View Source
const JSApiStreamNamesResponseType = "io.nats.jetstream.api.v1.stream_names_response"
View Source
const JSApiStreamPurgeResponseType = "io.nats.jetstream.api.v1.stream_purge_response"
View Source
const JSApiStreamRemovePeerResponseType = "io.nats.jetstream.api.v1.stream_remove_peer_response"
View Source
const JSApiStreamRestoreResponseType = "io.nats.jetstream.api.v1.stream_restore_response"
View Source
const JSApiStreamSnapshotResponseType = "io.nats.jetstream.api.v1.stream_snapshot_response"
View Source
const JSApiStreamTemplateCreateResponseType = "io.nats.jetstream.api.v1.stream_template_create_response"
View Source
const JSApiStreamTemplateDeleteResponseType = "io.nats.jetstream.api.v1.stream_template_delete_response"
View Source
const JSApiStreamTemplateInfoResponseType = "io.nats.jetstream.api.v1.stream_template_info_response"
View Source
const JSApiStreamTemplateNamesResponseType = "io.nats.jetstream.api.v1.stream_template_names_response"
View Source
const JSApiStreamUpdateResponseType = "io.nats.jetstream.api.v1.stream_update_response"
View Source
const JSApiSystemResponseType = "io.nats.jetstream.api.v1.system_response"
View Source
const JSConsumerAckMetricType = "io.nats.jetstream.metric.v1.consumer_ack"

JSConsumerAckMetricType is the schema type for JSConsumerAckMetricType

View Source
const JSConsumerActionAdvisoryType = "io.nats.jetstream.advisory.v1.consumer_action"
View Source
const JSConsumerDeliveryExceededAdvisoryType = "io.nats.jetstream.advisory.v1.max_deliver"

JSConsumerDeliveryExceededAdvisoryType is the schema type for JSConsumerDeliveryExceededAdvisory

View Source
const JSConsumerDeliveryNakAdvisoryType = "io.nats.jetstream.advisory.v1.nak"

JSConsumerDeliveryNakAdvisoryType is the schema type for JSConsumerDeliveryNakAdvisory

View Source
const JSConsumerDeliveryTerminatedAdvisoryType = "io.nats.jetstream.advisory.v1.terminated"

JSConsumerDeliveryTerminatedAdvisoryType is the schema type for JSConsumerDeliveryTerminatedAdvisory

View Source
const JSConsumerLeaderElectedAdvisoryType = "io.nats.jetstream.advisory.v1.consumer_leader_elected"

JSConsumerLeaderElectedAdvisoryType is sent when the system elects a leader for a consumer.

View Source
const JSConsumerQuorumLostAdvisoryType = "io.nats.jetstream.advisory.v1.consumer_quorum_lost"

JSConsumerQuorumLostAdvisoryType is sent when the system detects a clustered consumer and is stalled and unable to make progress.

View Source
const JSDefaultRequestQueueLimit = 10_000

JSDefaultRequestQueueLimit is the default number of entries that we will put on the global request queue before we react.

View Source
const JSDomainLeaderElectedAdvisoryType = "io.nats.jetstream.advisory.v1.domain_leader_elected"

JSClusterLeaderElectedAdvisoryType is sent when the system elects a new meta leader.

View Source
const JSMaxDescriptionLen = 4 * 1024

JSMaxDescription is the maximum description length for streams and consumers.

View Source
const JSMaxMetadataLen = 128 * 1024

JSMaxMetadataLen is the maximum length for streams and consumers metadata map. It's calculated by summing length of all keys and values.

View Source
const JSMaxNameLen = 255

JSMaxNameLen is the maximum name lengths for streams, consumers and templates. Picked 255 as it seems to be a widely used file name limit

View Source
const JSMaxSubjectDetails = 100_000

JSMaxSubjectDetails The limit of the number of subject details we will send in a stream info response.

View Source
const JSRestoreCompleteAdvisoryType = "io.nats.jetstream.advisory.v1.restore_complete"

JSRestoreCompleteAdvisoryType is the schema type for JSSnapshotCreateAdvisory

View Source
const JSRestoreCreateAdvisoryType = "io.nats.jetstream.advisory.v1.restore_create"

JSRestoreCreateAdvisoryType is the schema type for JSSnapshotCreateAdvisory

View Source
const JSServerOutOfStorageAdvisoryType = "io.nats.jetstream.advisory.v1.server_out_of_space"

JSServerOutOfStorageAdvisoryType is sent when the server is out of storage space.

View Source
const JSServerRemovedAdvisoryType = "io.nats.jetstream.advisory.v1.server_removed"

JSServerRemovedAdvisoryType is sent when the server has been removed and JS disabled.

View Source
const JSSnapshotCompleteAdvisoryType = "io.nats.jetstream.advisory.v1.snapshot_complete"

JSSnapshotCompleteAdvisoryType is the schema type for JSSnapshotCreateAdvisory

View Source
const JSSnapshotCreatedAdvisoryType = "io.nats.jetstream.advisory.v1.snapshot_create"

JSSnapshotCreatedAdvisoryType is the schema type for JSSnapshotCreateAdvisory

View Source
const JSStreamActionAdvisoryType = "io.nats.jetstream.advisory.v1.stream_action"
View Source
const JSStreamLeaderElectedAdvisoryType = "io.nats.jetstream.advisory.v1.stream_leader_elected"

JSStreamLeaderElectedAdvisoryType is sent when the system elects a new leader for a stream.

View Source
const JSStreamQuorumLostAdvisoryType = "io.nats.jetstream.advisory.v1.stream_quorum_lost"

JSStreamQuorumLostAdvisoryType is sent when the system detects a clustered stream and its consumers are stalled and unable to make progress.

View Source
const JSWaitQueueDefaultMax = 512

JSWaitQueueDefaultMax is the default max number of outstanding requests for pull consumers.

View Source
const JsPullRequestRemainingBytesT = "NATS/1.0 409 Batch Completed\r\n%s: %d\r\n%s: %d\r\n\r\n"

Headers sent when batch size was completed, but there were remaining bytes.

View Source
const MaxAccountCycleSearchDepth = 1024
View Source
const OCSPPeerChainlinkInvalidEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_link_invalid"

OCSPPeerChainlinkInvalidEventMsgType is the schema type for OCSPPeerChainlinkInvalidEventMsg

View Source
const OCSPPeerRejectEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_reject"

OCSPPeerRejectEventMsgType is the schema type for OCSPPeerRejectEventMsg

View Source
const OK = "+OK"

OK

View Source
const ServiceLatencyType = "io.nats.server.metric.v1.service_latency"

ServiceLatencyType is the NATS Event Type for ServiceLatency

View Source
const StreamDefaultDuplicatesWindow = 2 * time.Minute

StreamDefaultDuplicatesWindow default duplicates window.

View Source
const StreamMaxReplicas = 5

Replicas Range

Variables

View Source
var (
	// Ack
	AckAck = []byte("+ACK") // nil or no payload to ack subject also means ACK
	AckOK  = []byte(OK)     // deprecated but +OK meant ack as well.

	// Nack
	AckNak = []byte("-NAK")
	// Progress indicator
	AckProgress = []byte("+WPI")
	// Ack + Deliver the next message(s).
	AckNext = []byte("+NXT")
	// Terminate delivery of the message.
	AckTerm = []byte("+TERM")
)

Ack responses. Note that a nil or no payload is same as AckAck

View Source
var (
	// ErrConnectionClosed represents an error condition on a closed connection.
	ErrConnectionClosed = errors.New("connection closed")

	// ErrAuthentication represents an error condition on failed authentication.
	ErrAuthentication = errors.New("authentication error")

	// ErrAuthTimeout represents an error condition on failed authorization due to timeout.
	ErrAuthTimeout = errors.New("authentication timeout")

	// ErrAuthExpired represents an expired authorization due to timeout.
	ErrAuthExpired = errors.New("authentication expired")

	// ErrMaxPayload represents an error condition when the payload is too big.
	ErrMaxPayload = errors.New("maximum payload exceeded")

	// ErrMaxControlLine represents an error condition when the control line is too big.
	ErrMaxControlLine = errors.New("maximum control line exceeded")

	// ErrReservedPublishSubject represents an error condition when sending to a reserved subject, e.g. _SYS.>
	ErrReservedPublishSubject = errors.New("reserved internal subject")

	// ErrBadPublishSubject represents an error condition for an invalid publish subject.
	ErrBadPublishSubject = errors.New("invalid publish subject")

	// ErrBadSubject represents an error condition for an invalid subject.
	ErrBadSubject = errors.New("invalid subject")

	// ErrBadQualifier is used to error on a bad qualifier for a transform.
	ErrBadQualifier = errors.New("bad qualifier")

	// ErrBadClientProtocol signals a client requested an invalid client protocol.
	ErrBadClientProtocol = errors.New("invalid client protocol")

	// ErrTooManyConnections signals a client that the maximum number of connections supported by the
	// server has been reached.
	ErrTooManyConnections = errors.New("maximum connections exceeded")

	// ErrTooManyAccountConnections signals that an account has reached its maximum number of active
	// connections.
	ErrTooManyAccountConnections = errors.New("maximum account active connections exceeded")

	// ErrLeafNodeLoop signals a leafnode is trying to register for a cluster we already have registered.
	ErrLeafNodeLoop = errors.New("leafnode loop detected")

	// ErrTooManySubs signals a client that the maximum number of subscriptions per connection
	// has been reached.
	ErrTooManySubs = errors.New("maximum subscriptions exceeded")

	// ErrTooManySubTokens signals a client that the subject has too many tokens.
	ErrTooManySubTokens = errors.New("subject has exceeded number of tokens limit")

	// ErrClientConnectedToRoutePort represents an error condition when a client
	// attempted to connect to the route listen port.
	ErrClientConnectedToRoutePort = errors.New("attempted to connect to route port")

	// ErrClientConnectedToLeafNodePort represents an error condition when a client
	// attempted to connect to the leaf node listen port.
	ErrClientConnectedToLeafNodePort = errors.New("attempted to connect to leaf node port")

	// ErrLeafNodeHasSameClusterName represents an error condition when a leafnode is a cluster
	// and it has the same cluster name as the hub cluster.
	ErrLeafNodeHasSameClusterName = errors.New("remote leafnode has same cluster name")

	// ErrLeafNodeDisabled is when we disable leafnodes.
	ErrLeafNodeDisabled = errors.New("leafnodes disabled")

	// ErrConnectedToWrongPort represents an error condition when a connection is attempted
	// to the wrong listen port (for instance a LeafNode to a client port, etc...)
	ErrConnectedToWrongPort = errors.New("attempted to connect to wrong port")

	// ErrAccountExists is returned when an account is attempted to be registered
	// but already exists.
	ErrAccountExists = errors.New("account exists")

	// ErrBadAccount represents a malformed or incorrect account.
	ErrBadAccount = errors.New("bad account")

	// ErrReservedAccount represents a reserved account that can not be created.
	ErrReservedAccount = errors.New("reserved account")

	// ErrMissingAccount is returned when an account does not exist.
	ErrMissingAccount = errors.New("account missing")

	// ErrMissingService is returned when an account does not have an exported service.
	ErrMissingService = errors.New("service missing")

	// ErrBadServiceType is returned when latency tracking is being applied to non-singleton response types.
	ErrBadServiceType = errors.New("bad service response type")

	// ErrBadSampling is returned when the sampling for latency tracking is not 1 >= sample <= 100.
	ErrBadSampling = errors.New("bad sampling percentage, should be 1-100")

	// ErrAccountValidation is returned when an account has failed validation.
	ErrAccountValidation = errors.New("account validation failed")

	// ErrAccountExpired is returned when an account has expired.
	ErrAccountExpired = errors.New("account expired")

	// ErrNoAccountResolver is returned when we attempt an update but do not have an account resolver.
	ErrNoAccountResolver = errors.New("account resolver missing")

	// ErrAccountResolverUpdateTooSoon is returned when we attempt an update too soon to last request.
	ErrAccountResolverUpdateTooSoon = errors.New("account resolver update too soon")

	// ErrAccountResolverSameClaims is returned when same claims have been fetched.
	ErrAccountResolverSameClaims = errors.New("account resolver no new claims")

	// ErrStreamImportAuthorization is returned when a stream import is not authorized.
	ErrStreamImportAuthorization = errors.New("stream import not authorized")

	// ErrStreamImportBadPrefix is returned when a stream import prefix contains wildcards.
	ErrStreamImportBadPrefix = errors.New("stream import prefix can not contain wildcard tokens")

	// ErrStreamImportDuplicate is returned when a stream import is a duplicate of one that already exists.
	ErrStreamImportDuplicate = errors.New("stream import already exists")

	// ErrServiceImportAuthorization is returned when a service import is not authorized.
	ErrServiceImportAuthorization = errors.New("service import not authorized")

	// ErrImportFormsCycle is returned when an import would form a cycle.
	ErrImportFormsCycle = errors.New("import forms a cycle")

	// ErrCycleSearchDepth is returned when we have exceeded our maximum search depth..
	ErrCycleSearchDepth = errors.New("search cycle depth exhausted")

	// ErrClientOrRouteConnectedToGatewayPort represents an error condition when
	// a client or route attempted to connect to the Gateway port.
	ErrClientOrRouteConnectedToGatewayPort = errors.New("attempted to connect to gateway port")

	// ErrWrongGateway represents an error condition when a server receives a connect
	// request from a remote Gateway with a destination name that does not match the server's
	// Gateway's name.
	ErrWrongGateway = errors.New("wrong gateway")

	// ErrNoSysAccount is returned when an attempt to publish or subscribe is made
	// when there is no internal system account defined.
	ErrNoSysAccount = errors.New("system account not setup")

	// ErrRevocation is returned when a credential has been revoked.
	ErrRevocation = errors.New("credentials have been revoked")

	// ErrServerNotRunning is used to signal an error that a server is not running.
	ErrServerNotRunning = errors.New("server is not running")

	// ErrBadMsgHeader signals the parser detected a bad message header
	ErrBadMsgHeader = errors.New("bad message header detected")

	// ErrMsgHeadersNotSupported signals the parser detected a message header
	// but they are not supported on this server.
	ErrMsgHeadersNotSupported = errors.New("message headers not supported")

	// ErrNoRespondersRequiresHeaders signals that a client needs to have headers
	// on if they want no responders behavior.
	ErrNoRespondersRequiresHeaders = errors.New("no responders requires headers support")

	// ErrClusterNameConfigConflict signals that the options for cluster name in cluster and gateway are in conflict.
	ErrClusterNameConfigConflict = errors.New("cluster name conflicts between cluster and gateway definitions")

	// ErrClusterNameRemoteConflict signals that a remote server has a different cluster name.
	ErrClusterNameRemoteConflict = errors.New("cluster name from remote server conflicts")

	// ErrClusterNameHasSpaces signals that the cluster name contains spaces, which is not allowed.
	ErrClusterNameHasSpaces = errors.New("cluster name cannot contain spaces or new lines")

	// ErrMalformedSubject is returned when a subscription is made with a subject that does not conform to subject rules.
	ErrMalformedSubject = errors.New("malformed subject")

	// ErrSubscribePermissionViolation is returned when processing of a subscription fails due to permissions.
	ErrSubscribePermissionViolation = errors.New("subscribe permission violation")

	// ErrNoTransforms signals no subject transforms are available to map this subject.
	ErrNoTransforms = errors.New("no matching transforms available")

	// ErrCertNotPinned is returned when pinned certs are set and the certificate is not in it
	ErrCertNotPinned = errors.New("certificate not pinned")

	// ErrDuplicateServerName is returned when processing a server remote connection and
	// the server reports that this server name is already used in the cluster.
	ErrDuplicateServerName = errors.New("duplicate server name")

	// ErrMinimumVersionRequired is returned when a connection is not at the minimum version required.
	ErrMinimumVersionRequired = errors.New("minimum version required")

	// ErrInvalidMappingDestination is used for all subject mapping destination errors
	ErrInvalidMappingDestination = errors.New("invalid mapping destination")

	// ErrInvalidMappingDestinationSubject is used to error on a bad transform destination mapping
	ErrInvalidMappingDestinationSubject = fmt.Errorf("%w: invalid subject", ErrInvalidMappingDestination)

	// ErrMappingDestinationNotUsingAllWildcards is used to error on a transform destination not using all of the token wildcards
	ErrMappingDestinationNotUsingAllWildcards = fmt.Errorf("%w: not using all of the token wildcard(s)", ErrInvalidMappingDestination)

	// ErrUnknownMappingDestinationFunction is returned when a subject mapping destination contains an unknown mustache-escaped mapping function.
	ErrUnknownMappingDestinationFunction = fmt.Errorf("%w: unknown function", ErrInvalidMappingDestination)

	// ErrMappingDestinationIndexOutOfRange is returned when the mapping destination function is passed an out of range wildcard index value for one of it's arguments
	ErrMappingDestinationIndexOutOfRange = fmt.Errorf("%w: wildcard index out of range", ErrInvalidMappingDestination)

	// ErrMappingDestinationNotEnoughArgs is returned when the mapping destination function is not passed enough arguments
	ErrMappingDestinationNotEnoughArgs = fmt.Errorf("%w: not enough arguments passed to the function", ErrInvalidMappingDestination)

	// ErrMappingDestinationInvalidArg is returned when the mapping destination function is passed and invalid argument
	ErrMappingDestinationInvalidArg = fmt.Errorf("%w: function argument is invalid or in the wrong format", ErrInvalidMappingDestination)

	// ErrMappingDestinationTooManyArgs is returned when the mapping destination function is passed too many arguments
	ErrMappingDestinationTooManyArgs = fmt.Errorf("%w: too many arguments passed to the function", ErrInvalidMappingDestination)

	// ErrMappingDestinationNotSupportedForImport is returned when you try to use a mapping function other than wildcard in a transform that needs to be reversible (i.e. an import)
	ErrMappingDestinationNotSupportedForImport = fmt.Errorf("%w: the only mapping function allowed for import transforms is {{Wildcard()}}", ErrInvalidMappingDestination)
)
View Source
var (
	ApiErrors = map[ErrorIdentifier]*ApiError{}/* 152 elements not displayed */

	// ErrJetStreamNotClustered Deprecated by JSClusterNotActiveErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamNotClustered = ApiErrors[JSClusterNotActiveErr]
	// ErrJetStreamNotAssigned Deprecated by JSClusterNotAssignedErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamNotAssigned = ApiErrors[JSClusterNotAssignedErr]
	// ErrJetStreamNotLeader Deprecated by JSClusterNotLeaderErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamNotLeader = ApiErrors[JSClusterNotLeaderErr]
	// ErrJetStreamConsumerAlreadyUsed Deprecated by JSConsumerNameExistErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamConsumerAlreadyUsed = ApiErrors[JSConsumerNameExistErr]
	// ErrJetStreamResourcesExceeded Deprecated by JSInsufficientResourcesErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamResourcesExceeded = ApiErrors[JSInsufficientResourcesErr]
	// ErrMemoryResourcesExceeded Deprecated by JSMemoryResourcesExceededErr ApiError, use IsNatsError() for comparisons
	ErrMemoryResourcesExceeded = ApiErrors[JSMemoryResourcesExceededErr]
	// ErrJetStreamNotEnabled Deprecated by JSNotEnabledErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamNotEnabled = ApiErrors[JSNotEnabledErr]
	// ErrStorageResourcesExceeded Deprecated by JSStorageResourcesExceededErr ApiError, use IsNatsError() for comparisons
	ErrStorageResourcesExceeded = ApiErrors[JSStorageResourcesExceededErr]
	// ErrJetStreamStreamAlreadyUsed Deprecated by JSStreamNameExistErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamStreamAlreadyUsed = ApiErrors[JSStreamNameExistErr]
	// ErrJetStreamStreamNotFound Deprecated by JSStreamNotFoundErr ApiError, use IsNatsError() for comparisons
	ErrJetStreamStreamNotFound = ApiErrors[JSStreamNotFoundErr]
	// ErrReplicasNotSupported Deprecated by JSStreamReplicasNotSupportedErr ApiError, use IsNatsError() for comparisons
	ErrReplicasNotSupported = ApiErrors[JSStreamReplicasNotSupportedErr]
)
View Source
var (
	// ErrStoreClosed is returned when the store has been closed
	ErrStoreClosed = errors.New("store is closed")
	// ErrStoreMsgNotFound when message was not found but was expected to be.
	ErrStoreMsgNotFound = errors.New("no message found")
	// ErrStoreEOF is returned when message seq is greater than the last sequence.
	ErrStoreEOF = errors.New("stream store EOF")
	// ErrMaxMsgs is returned when we have discard new as a policy and we reached the message limit.
	ErrMaxMsgs = errors.New("maximum messages exceeded")
	// ErrMaxBytes is returned when we have discard new as a policy and we reached the bytes limit.
	ErrMaxBytes = errors.New("maximum bytes exceeded")
	// ErrMaxMsgsPerSubject is returned when we have discard new as a policy and we reached the message limit per subject.
	ErrMaxMsgsPerSubject = errors.New("maximum messages per subject exceeded")
	// ErrStoreSnapshotInProgress is returned when RemoveMsg or EraseMsg is called
	// while a snapshot is in progress.
	ErrStoreSnapshotInProgress = errors.New("snapshot in progress")
	// ErrMsgTooLarge is returned when a message is considered too large.
	ErrMsgTooLarge = errors.New("message to large")
	// ErrStoreWrongType is for when you access the wrong storage type.
	ErrStoreWrongType = errors.New("wrong storage type")
	// ErrNoAckPolicy is returned when trying to update a consumer's acks with no ack policy.
	ErrNoAckPolicy = errors.New("ack policy is none")
	// ErrInvalidSequence is returned when the sequence is not present in the stream store.
	ErrInvalidSequence = errors.New("invalid sequence")
	// ErrSequenceMismatch is returned when storing a raw message and the expected sequence is wrong.
	ErrSequenceMismatch = errors.New("expected sequence does not match store")
	// ErrCorruptStreamState
	ErrCorruptStreamState = errors.New("stream state snapshot is corrupt")
)
View Source
var (
	ErrInvalidSubject    = errors.New("sublist: invalid subject")
	ErrNotFound          = errors.New("sublist: no matches found")
	ErrNilChan           = errors.New("sublist: nil channel")
	ErrAlreadyRegistered = errors.New("sublist: notification already registered")
)

Sublist related errors

View Source
var ErrBadStreamStateEncoding = errors.New("bad stream state encoding")
View Source
var IsPublicExport = []*Account(nil)

IsPublicExport is a placeholder to denote a public export.

View Source
var OCSPResponseCacheTypeMap = map[string]OCSPResponseCacheType{
	"none":  NONE,
	"local": LOCAL,
}
View Source
var OCSPResponseCacheUsage = `` /* 996-byte string literal not displayed */

Functions

func CommandToSignal added in v2.10.0

func CommandToSignal(command Command) (syscall.Signal, error)

Translates a command to a signal number

func ErrorIs added in v2.1.6

func ErrorIs(err, target error) bool

ErrorIs implements: go 1.13 errors.Is(err, target error) bool TODO replace with native code once we no longer support go1.12

func GatewayDoNotForceInterestOnlyMode added in v2.9.0

func GatewayDoNotForceInterestOnlyMode(doNotForce bool)

GatewayDoNotForceInterestOnlyMode is used ONLY in tests. DO NOT USE in normal code or if you embed the NATS Server.

func GenTLSConfig

func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error)

GenTLSConfig loads TLS related configuration parameters.

func IntersectStree added in v2.10.23

func IntersectStree[T any](st *stree.SubjectTree[T], sl *Sublist, cb func(subj []byte, entry *T))

IntersectStree will match all items in the given subject tree that have interest expressed in the given sublist. The callback will only be called once for each subject, regardless of overlapping subscriptions in the sublist.

func IsEncodedStreamState added in v2.10.0

func IsEncodedStreamState(buf []byte) bool

Determine if this is an encoded stream state.

func IsNatsErr added in v2.3.0

func IsNatsErr(err error, ids ...ErrorIdentifier) bool

IsNatsErr determines if an error matches ID, if multiple IDs are given if the error matches any of these the function will be true

func IsValidLiteralSubject

func IsValidLiteralSubject(subject string) bool

IsValidLiteralSubject returns true if a subject is valid and literal (no wildcards), false otherwise

func IsValidPublishSubject added in v2.1.0

func IsValidPublishSubject(subject string) bool

IsValidPublishSubject returns true if a subject is valid and a literal, false otherwise

func IsValidSubject

func IsValidSubject(subject string) bool

IsValidSubject returns true if a subject is valid, false otherwise

func NewErrorCtx added in v2.1.6

func NewErrorCtx(err error, format string, args ...any) error

func NewSubjectTransform added in v2.10.0

func NewSubjectTransform(src, dest string) (*subjectTransform, error)

func NewSubjectTransformStrict added in v2.10.0

func NewSubjectTransformStrict(src, dest string) (*subjectTransform, error)

func NewSubjectTransformWithStrict added in v2.10.0

func NewSubjectTransformWithStrict(src, dest string, strict bool) (*subjectTransform, error)

func NoErrOnUnknownFields

func NoErrOnUnknownFields(noError bool)

NoErrOnUnknownFields can be used to change the behavior the processing of a configuration file. By default, an error is reported if unknown fields are found. If `noError` is set to true, no error will be reported if top-level unknown fields are found.

func PrintAndDie

func PrintAndDie(msg string)

PrintAndDie is exported for access in other packages.

func PrintServerAndExit

func PrintServerAndExit()

PrintServerAndExit will print our version and exit.

func PrintTLSHelpAndDie

func PrintTLSHelpAndDie()

PrintTLSHelpAndDie prints TLS usage and exits.

func ProcessCommandLineArgs

func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error)

ProcessCommandLineArgs takes the command line arguments validating and setting flags for handling in case any sub command was present.

func ProcessSignal

func ProcessSignal(command Command, pidExpr string) error

ProcessSignal sends the given signal command to the given process. If pidStr is empty, this will send the signal to the single running instance of nats-server. If multiple instances are running, pidStr can be a globular expression ending with '*'. This returns an error if the given process is not running or the command is invalid.

func ReadOperatorJWT added in v2.0.2

func ReadOperatorJWT(jwtfile string) (*jwt.OperatorClaims, error)

ReadOperatorJWT will read a jwt file for an operator claim. This can be a decorated file.

func RemoveSelfReference

func RemoveSelfReference(clusterPort int, routes []*url.URL) ([]*url.URL, error)

RemoveSelfReference removes this server from an array of routes

func ResetGatewaysSolicitDelay

func ResetGatewaysSolicitDelay()

ResetGatewaysSolicitDelay resets the initial delay before gateways connections are initiated to its default values. Used by tests.

func ResponseHandler

func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte)

ResponseHandler handles responses for monitoring routes.

func RoutesFromStr

func RoutesFromStr(routesStr string) []*url.URL

RoutesFromStr parses route URLs from a string

func Run

func Run(server *Server) error

Run starts the NATS server. This wrapper function allows Windows to add a hook for running NATS as a service.

func SetGatewaysSolicitDelay

func SetGatewaysSolicitDelay(delay time.Duration)

SetGatewaysSolicitDelay sets the initial delay before gateways connections are initiated. Used by tests.

func SetProcessName

func SetProcessName(name string)

SetProcessName allows to change the expected name of the process.

func SubjectsCollide added in v2.2.0

func SubjectsCollide(subj1, subj2 string) bool

SubjectsCollide will determine if two subjects could both match a single literal subject.

func UnpackIfErrorCtx added in v2.1.6

func UnpackIfErrorCtx(err error) string

UnpackIfErrorCtx return Error or, if type is right error and context

func ValidateMappingDestination added in v2.9.0

func ValidateMappingDestination(subject string) error

ValidateMappingDestination returns nil error if the subject is a valid subject mapping destination subject

Types

type AccInfoEventOptions added in v2.2.0

type AccInfoEventOptions struct {
	// No actual options yet
	EventFilterOptions
}

Options for account Info

type Account

type Account struct {
	Name   string
	Nkey   string
	Issuer string
	// contains filtered or unexported fields
}

Account are subject namespace definitions. By default no messages are shared between accounts. You can share via Exports and Imports of Streams and Services.

func NewAccount

func NewAccount(name string) *Account

NewAccount creates a new unlimited account with the given name.

func (*Account) AddMappedStreamImport added in v2.2.0

func (a *Account) AddMappedStreamImport(account *Account, from, to string) error

AddMappedStreamImport helper for AddMappedStreamImportWithClaim

func (*Account) AddMappedStreamImportWithClaim added in v2.2.0

func (a *Account) AddMappedStreamImportWithClaim(account *Account, from, to string, imClaim *jwt.Import) error

AddMappedStreamImportWithClaim will add in the stream import from a specific account with optional token.

func (*Account) AddMapping added in v2.2.0

func (a *Account) AddMapping(src, dest string) error

AddMapping adds in a simple route mapping from src subject to dest subject for inbound client messages.

func (*Account) AddServiceExport

func (a *Account) AddServiceExport(subject string, accounts []*Account) error

AddServiceExport will configure the account with the defined export.

func (*Account) AddServiceExportWithResponse added in v2.0.4

func (a *Account) AddServiceExportWithResponse(subject string, respType ServiceRespType, accounts []*Account) error

AddServiceExportWithResponse will configure the account with the defined export and response type.

func (*Account) AddServiceImport

func (a *Account) AddServiceImport(destination *Account, from, to string) error

AddServiceImport will add a route to an account to send published messages / requests to the destination account. From is the local subject to map, To is the subject that will appear on the destination account. Destination will need to have an import rule to allow access via addService.

func (*Account) AddServiceImportWithClaim

func (a *Account) AddServiceImportWithClaim(destination *Account, from, to string, imClaim *jwt.Import) error

AddServiceImportWithClaim will add in the service import via the jwt claim.

func (*Account) AddStreamExport

func (a *Account) AddStreamExport(subject string, accounts []*Account) error

AddStreamExport will add an export to the account. If accounts is nil it will signify a public export, meaning anyone can import.

func (*Account) AddStreamImport

func (a *Account) AddStreamImport(account *Account, from, prefix string) error

AddStreamImport will add in the stream import from a specific account.

func (*Account) AddStreamImportWithClaim

func (a *Account) AddStreamImportWithClaim(account *Account, from, prefix string, imClaim *jwt.Import) error

AddStreamImportWithClaim will add in the stream import from a specific account with optional token.

func (*Account) AddWeightedMappings added in v2.2.0

func (a *Account) AddWeightedMappings(src string, dests ...*MapDest) error

AddWeightedMappings will add in a weighted mappings for the destinations.

func (*Account) DisableJetStream added in v2.2.0

func (a *Account) DisableJetStream() error

DisableJetStream will disable JetStream for this account.

func (*Account) EnableJetStream added in v2.2.0

func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits) error

EnableJetStream will enable JetStream on this account with the defined limits. This is a helper for JetStreamEnableAccount.

func (*Account) GetName added in v2.2.0

func (a *Account) GetName() string

GetName will return the accounts name.

func (*Account) Interest added in v2.2.0

func (a *Account) Interest(subject string) int

Interest returns the number of subscriptions for a given subject that match.

func (*Account) IsExpired

func (a *Account) IsExpired() bool

IsExpired returns expiration status.

func (*Account) IsExportService added in v2.1.0

func (a *Account) IsExportService(service string) bool

IsExportService will indicate if this service exists. Will check wildcard scenarios.

func (*Account) IsExportServiceTracking added in v2.1.0

func (a *Account) IsExportServiceTracking(service string) bool

IsExportServiceTracking will indicate if given publish subject is an export service with tracking enabled.

func (*Account) JetStreamEnabled added in v2.2.0

func (a *Account) JetStreamEnabled() bool

JetStreamEnabled is a helper to determine if jetstream is enabled for an account.

func (*Account) JetStreamIsConsumerLeader added in v2.2.0

func (a *Account) JetStreamIsConsumerLeader(stream, consumer string) bool

func (*Account) JetStreamIsStreamLeader added in v2.2.0

func (a *Account) JetStreamIsStreamLeader(stream string) bool

func (*Account) JetStreamUsage added in v2.2.0

func (a *Account) JetStreamUsage() JetStreamAccountStats

JetStreamUsage reports on JetStream usage and limits for an account.

func (*Account) MaxActiveConnections

func (a *Account) MaxActiveConnections() int

MaxActiveConnections return the set limit for the account system wide for total number of active connections.

func (*Account) MaxActiveLeafNodes

func (a *Account) MaxActiveLeafNodes() int

MaxActiveLeafNodes return the set limit for the account system wide for total number of leavenode connections. NOTE: these are tracked separately.

func (*Account) MaxTotalConnectionsReached

func (a *Account) MaxTotalConnectionsReached() bool

MaxTotalConnectionsReached returns if we have reached our limit for number of connections.

func (*Account) MaxTotalLeafNodesReached

func (a *Account) MaxTotalLeafNodesReached() bool

MaxTotalLeafNodesReached returns if we have reached our limit for number of leafnodes.

func (*Account) NumConnections

func (a *Account) NumConnections() int

NumConnections returns active number of clients for this account for all known servers.

func (*Account) NumLeafNodes

func (a *Account) NumLeafNodes() int

NumLeafNodes returns the active number of local and remote leaf node connections.

func (*Account) NumLocalConnections

func (a *Account) NumLocalConnections() int

NumLocalConnections returns active number of clients for this account on this server.

func (*Account) NumPendingAllResponses added in v2.2.0

func (a *Account) NumPendingAllResponses() int

NumPendingAllResponses return the number of all responses outstanding for service exports.

func (*Account) NumPendingResponses added in v2.2.0

func (a *Account) NumPendingResponses(filter string) int

NumPendingResponses returns the number of responses outstanding for service exports on this account. An empty filter string returns all responses regardless of which export. If you specify the filter we will only return ones that are for that export. NOTE this is only for what this server is tracking.

func (*Account) NumPendingReverseResponses added in v2.2.0

func (a *Account) NumPendingReverseResponses() int

NumPendingReverseResponses returns the number of response mappings we have for all outstanding requests for service imports.

func (*Account) NumRemoteConnections added in v2.1.0

func (a *Account) NumRemoteConnections() int

NumRemoteConnections returns the number of client or leaf connections that are not on this server.

func (*Account) NumRemoteLeafNodes

func (a *Account) NumRemoteLeafNodes() int

NumRemoteLeafNodes returns the active number of remote leaf node connections.

func (*Account) NumServiceImports added in v2.1.2

func (a *Account) NumServiceImports() int

NumServiceImports returns the number of service imports we have configured.

func (*Account) RemoveMapping added in v2.2.0

func (a *Account) RemoveMapping(src string) bool

RemoveMapping will remove an existing mapping.

func (*Account) RestoreStream added in v2.2.0

func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error)

RestoreStream will restore a stream from a snapshot.

func (*Account) RoutedSubs

func (a *Account) RoutedSubs() int

RoutedSubs returns how many subjects we would send across a route when first connected or expressing interest. Local client subs.

func (*Account) ServiceExportResponseThreshold added in v2.2.0

func (a *Account) ServiceExportResponseThreshold(export string) (time.Duration, error)

ServiceExportResponseThreshold returns the current threshold.

func (*Account) SetServiceExportResponseThreshold added in v2.2.0

func (a *Account) SetServiceExportResponseThreshold(export string, maxTime time.Duration) error

SetServiceExportResponseThreshold sets the maximum time the system will a response to be delivered from a service export responder.

func (*Account) SetServiceImportSharing added in v2.2.0

func (a *Account) SetServiceImportSharing(destination *Account, to string, allow bool) error

SetServiceImportSharing will allow sharing of information about requests with the export account. Used for service latency tracking at the moment.

func (*Account) String added in v2.2.0

func (a *Account) String() string

func (*Account) SubscriptionInterest added in v2.1.8

func (a *Account) SubscriptionInterest(subject string) bool

SubscriptionInterest returns true if this account has a matching subscription for the given `subject`.

func (*Account) TotalSubs

func (a *Account) TotalSubs() int

TotalSubs returns total number of Subscriptions for this account.

func (*Account) TrackServiceExport added in v2.1.0

func (a *Account) TrackServiceExport(service, results string) error

TrackServiceExport will enable latency tracking of the named service. Results will be published in this account to the given results subject.

func (*Account) TrackServiceExportWithSampling added in v2.1.0

func (a *Account) TrackServiceExportWithSampling(service, results string, sampling int) error

TrackServiceExportWithSampling will enable latency tracking of the named service for the given sampling rate (1-100). Results will be published in this account to the given results subject.

func (*Account) UnTrackServiceExport added in v2.1.0

func (a *Account) UnTrackServiceExport(service string)

UnTrackServiceExport will disable latency tracking of the named service.

func (*Account) UpdateJetStreamLimits added in v2.2.0

func (a *Account) UpdateJetStreamLimits(limits map[string]JetStreamAccountLimits) error

UpdateJetStreamLimits will update the account limits for a JetStream enabled account.

type AccountDetail added in v2.2.0

type AccountDetail struct {
	Name string `json:"name"`
	Id   string `json:"id"`
	JetStreamStats
	Streams []StreamDetail `json:"stream_detail,omitempty"`
}

type AccountGatewayz

type AccountGatewayz struct {
	Name                  string `json:"name"`
	InterestMode          string `json:"interest_mode"`
	NoInterestCount       int    `json:"no_interest_count,omitempty"`
	InterestOnlyThreshold int    `json:"interest_only_threshold,omitempty"`
	TotalSubscriptions    int    `json:"num_subs,omitempty"`
	NumQueueSubscriptions int    `json:"num_queue_subs,omitempty"`
}

AccountGatewayz represents interest mode for this account

type AccountInfo added in v2.2.0

type AccountInfo struct {
	AccountName string               `json:"account_name"`
	LastUpdate  time.Time            `json:"update_time,omitempty"`
	IsSystem    bool                 `json:"is_system,omitempty"`
	Expired     bool                 `json:"expired"`
	Complete    bool                 `json:"complete"`
	JetStream   bool                 `json:"jetstream_enabled"`
	LeafCnt     int                  `json:"leafnode_connections"`
	ClientCnt   int                  `json:"client_connections"`
	SubCnt      uint32               `json:"subscriptions"`
	Mappings    ExtMap               `json:"mappings,omitempty"`
	Exports     []ExtExport          `json:"exports,omitempty"`
	Imports     []ExtImport          `json:"imports,omitempty"`
	Jwt         string               `json:"jwt,omitempty"`
	IssuerKey   string               `json:"issuer_key,omitempty"`
	NameTag     string               `json:"name_tag,omitempty"`
	Tags        jwt.TagList          `json:"tags,omitempty"`
	Claim       *jwt.AccountClaims   `json:"decoded_jwt,omitempty"`
	Vr          []ExtVrIssues        `json:"validation_result_jwt,omitempty"`
	RevokedUser map[string]time.Time `json:"revoked_user,omitempty"`
	Sublist     *SublistStats        `json:"sublist_stats,omitempty"`
	Responses   map[string]ExtImport `json:"responses,omitempty"`
}

type AccountNumConns

type AccountNumConns struct {
	TypedEvent
	Server ServerInfo `json:"server"`
	AccountStat
}

AccountNumConns is an event that will be sent from a server that is tracking a given account when the number of connections changes. It will also HB updates in the absence of any changes.

type AccountResolver

type AccountResolver interface {
	Fetch(name string) (string, error)
	Store(name, jwt string) error
	IsReadOnly() bool
	Start(server *Server) error
	IsTrackingUpdate() bool
	Reload() error
	Close()
}

AccountResolver interface. This is to fetch Account JWTs by public nkeys

type AccountStat added in v2.9.0

type AccountStat struct {
	Account       string    `json:"acc"`
	Conns         int       `json:"conns"`
	LeafNodes     int       `json:"leafnodes"`
	TotalConns    int       `json:"total_conns"`
	NumSubs       uint32    `json:"num_subscriptions"`
	Sent          DataStats `json:"sent"`
	Received      DataStats `json:"received"`
	SlowConsumers int64     `json:"slow_consumers"`
}

AccountStat contains the data common between AccountNumConns and AccountStatz

type AccountStatz added in v2.9.0

type AccountStatz struct {
	ID       string         `json:"server_id"`
	Now      time.Time      `json:"now"`
	Accounts []*AccountStat `json:"account_statz"`
}

Leafz represents detailed information on Leafnodes.

type AccountStatzEventOptions added in v2.9.0

type AccountStatzEventOptions struct {
	AccountStatzOptions
	EventFilterOptions
}

In the context of system events, AccountzEventOptions are options passed to Accountz

type AccountStatzOptions added in v2.9.0

type AccountStatzOptions struct {
	Accounts      []string `json:"accounts"`
	IncludeUnused bool     `json:"include_unused"`
}

LeafzOptions are options passed to Leafz

type Accountz added in v2.2.0

type Accountz struct {
	ID            string       `json:"server_id"`
	Now           time.Time    `json:"now"`
	SystemAccount string       `json:"system_account,omitempty"`
	Accounts      []string     `json:"accounts,omitempty"`
	Account       *AccountInfo `json:"account_detail,omitempty"`
}

type AccountzEventOptions added in v2.2.0

type AccountzEventOptions struct {
	AccountzOptions
	EventFilterOptions
}

In the context of system events, AccountzEventOptions are options passed to Accountz

type AccountzOptions added in v2.2.0

type AccountzOptions struct {
	// Account indicates that Accountz will return details for the account
	Account string `json:"account"`
}

AccountzOptions are options passed to Accountz

type AckPolicy added in v2.2.0

type AckPolicy int

AckPolicy determines how the consumer should acknowledge delivered messages.

const (
	// AckNone requires no acks for delivered messages.
	AckNone AckPolicy = iota
	// AckAll when acking a sequence number, this implicitly acks all sequences below this one as well.
	AckAll
	// AckExplicit requires ack or nack for all messages.
	AckExplicit
)

func (AckPolicy) MarshalJSON added in v2.2.0

func (ap AckPolicy) MarshalJSON() ([]byte, error)

func (AckPolicy) String added in v2.2.0

func (a AckPolicy) String() string

func (*AckPolicy) UnmarshalJSON added in v2.2.0

func (ap *AckPolicy) UnmarshalJSON(data []byte) error

type ActionAdvisoryType added in v2.2.0

type ActionAdvisoryType string

ActionAdvisoryType indicates which action against a stream, consumer or template triggered an advisory

const (
	CreateEvent ActionAdvisoryType = "create"
	DeleteEvent ActionAdvisoryType = "delete"
	ModifyEvent ActionAdvisoryType = "modify"
)

type ApiError added in v2.2.0

type ApiError struct {
	Code        int    `json:"code"`
	ErrCode     uint16 `json:"err_code,omitempty"`
	Description string `json:"description,omitempty"`
}

ApiError is included in all responses if there was an error.

func NewJSAccountResourcesExceededError added in v2.4.0

func NewJSAccountResourcesExceededError(opts ...ErrorOption) *ApiError

NewJSAccountResourcesExceededError creates a new JSAccountResourcesExceededErr error: "resource limits exceeded for account"

func NewJSBadRequestError added in v2.4.0

func NewJSBadRequestError(opts ...ErrorOption) *ApiError

NewJSBadRequestError creates a new JSBadRequestErr error: "bad request"

func NewJSClusterIncompleteError added in v2.4.0

func NewJSClusterIncompleteError(opts ...ErrorOption) *ApiError

NewJSClusterIncompleteError creates a new JSClusterIncompleteErr error: "incomplete results"

func NewJSClusterNoPeersError added in v2.4.0

func NewJSClusterNoPeersError(err error, opts ...ErrorOption) *ApiError

NewJSClusterNoPeersError creates a new JSClusterNoPeersErrF error: "{err}"

func NewJSClusterNotActiveError added in v2.4.0

func NewJSClusterNotActiveError(opts ...ErrorOption) *ApiError

NewJSClusterNotActiveError creates a new JSClusterNotActiveErr error: "JetStream not in clustered mode"

func NewJSClusterNotAssignedError added in v2.4.0

func NewJSClusterNotAssignedError(opts ...ErrorOption) *ApiError

NewJSClusterNotAssignedError creates a new JSClusterNotAssignedErr error: "JetStream cluster not assigned to this server"

func NewJSClusterNotAvailError added in v2.4.0

func NewJSClusterNotAvailError(opts ...ErrorOption) *ApiError

NewJSClusterNotAvailError creates a new JSClusterNotAvailErr error: "JetStream system temporarily unavailable"

func NewJSClusterNotLeaderError added in v2.4.0

func NewJSClusterNotLeaderError(opts ...ErrorOption) *ApiError

NewJSClusterNotLeaderError creates a new JSClusterNotLeaderErr error: "JetStream cluster can not handle request"

func NewJSClusterPeerNotMemberError added in v2.4.0

func NewJSClusterPeerNotMemberError(opts ...ErrorOption) *ApiError

NewJSClusterPeerNotMemberError creates a new JSClusterPeerNotMemberErr error: "peer not a member"

func NewJSClusterRequiredError added in v2.4.0

func NewJSClusterRequiredError(opts ...ErrorOption) *ApiError

NewJSClusterRequiredError creates a new JSClusterRequiredErr error: "JetStream clustering support required"

func NewJSClusterServerNotMemberError added in v2.4.0

func NewJSClusterServerNotMemberError(opts ...ErrorOption) *ApiError

NewJSClusterServerNotMemberError creates a new JSClusterServerNotMemberErr error: "server is not a member of the cluster"

func NewJSClusterTagsError added in v2.4.0

func NewJSClusterTagsError(opts ...ErrorOption) *ApiError

NewJSClusterTagsError creates a new JSClusterTagsErr error: "tags placement not supported for operation"

func NewJSClusterUnSupportFeatureError added in v2.4.0

func NewJSClusterUnSupportFeatureError(opts ...ErrorOption) *ApiError

NewJSClusterUnSupportFeatureError creates a new JSClusterUnSupportFeatureErr error: "not currently supported in clustered mode"

func NewJSConsumerAlreadyExistsError added in v2.10.0

func NewJSConsumerAlreadyExistsError(opts ...ErrorOption) *ApiError

NewJSConsumerAlreadyExistsError creates a new JSConsumerAlreadyExists error: "consumer already exists"

func NewJSConsumerBadDurableNameError added in v2.4.0

func NewJSConsumerBadDurableNameError(opts ...ErrorOption) *ApiError

NewJSConsumerBadDurableNameError creates a new JSConsumerBadDurableNameErr error: "durable name can not contain '.', '*', '>'"

func NewJSConsumerConfigRequiredError added in v2.4.0

func NewJSConsumerConfigRequiredError(opts ...ErrorOption) *ApiError

NewJSConsumerConfigRequiredError creates a new JSConsumerConfigRequiredErr error: "consumer config required"

func NewJSConsumerCreateDurableAndNameMismatchError added in v2.9.1

func NewJSConsumerCreateDurableAndNameMismatchError(opts ...ErrorOption) *ApiError

NewJSConsumerCreateDurableAndNameMismatchError creates a new JSConsumerCreateDurableAndNameMismatch error: "Consumer Durable and Name have to be equal if both are provided"

func NewJSConsumerCreateError added in v2.4.0

func NewJSConsumerCreateError(err error, opts ...ErrorOption) *ApiError

NewJSConsumerCreateError creates a new JSConsumerCreateErrF error: "{err}"

func NewJSConsumerCreateFilterSubjectMismatchError added in v2.9.0

func NewJSConsumerCreateFilterSubjectMismatchError(opts ...ErrorOption) *ApiError

NewJSConsumerCreateFilterSubjectMismatchError creates a new JSConsumerCreateFilterSubjectMismatchErr error: "Consumer create request did not match filtered subject from create subject"

func NewJSConsumerDeliverCycleError added in v2.4.0

func NewJSConsumerDeliverCycleError(opts ...ErrorOption) *ApiError

NewJSConsumerDeliverCycleError creates a new JSConsumerDeliverCycleErr error: "consumer deliver subject forms a cycle"

func NewJSConsumerDeliverToWildcardsError added in v2.4.0

func NewJSConsumerDeliverToWildcardsError(opts ...ErrorOption) *ApiError

NewJSConsumerDeliverToWildcardsError creates a new JSConsumerDeliverToWildcardsErr error: "consumer deliver subject has wildcards"

func NewJSConsumerDescriptionTooLongError added in v2.4.0

func NewJSConsumerDescriptionTooLongError(max interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerDescriptionTooLongError creates a new JSConsumerDescriptionTooLongErrF error: "consumer description is too long, maximum allowed is {max}"

func NewJSConsumerDirectRequiresEphemeralError added in v2.4.0

func NewJSConsumerDirectRequiresEphemeralError(opts ...ErrorOption) *ApiError

NewJSConsumerDirectRequiresEphemeralError creates a new JSConsumerDirectRequiresEphemeralErr error: "consumer direct requires an ephemeral consumer"

func NewJSConsumerDirectRequiresPushError added in v2.4.0

func NewJSConsumerDirectRequiresPushError(opts ...ErrorOption) *ApiError

NewJSConsumerDirectRequiresPushError creates a new JSConsumerDirectRequiresPushErr error: "consumer direct requires a push based consumer"

func NewJSConsumerDoesNotExistError added in v2.10.0

func NewJSConsumerDoesNotExistError(opts ...ErrorOption) *ApiError

NewJSConsumerDoesNotExistError creates a new JSConsumerDoesNotExist error: "consumer does not exist"

func NewJSConsumerDuplicateFilterSubjectsError added in v2.10.0

func NewJSConsumerDuplicateFilterSubjectsError(opts ...ErrorOption) *ApiError

NewJSConsumerDuplicateFilterSubjectsError creates a new JSConsumerDuplicateFilterSubjects error: "consumer cannot have both FilterSubject and FilterSubjects specified"

func NewJSConsumerDurableNameNotInSubjectError added in v2.4.0

func NewJSConsumerDurableNameNotInSubjectError(opts ...ErrorOption) *ApiError

NewJSConsumerDurableNameNotInSubjectError creates a new JSConsumerDurableNameNotInSubjectErr error: "consumer expected to be durable but no durable name set in subject"

func NewJSConsumerDurableNameNotMatchSubjectError added in v2.4.0

func NewJSConsumerDurableNameNotMatchSubjectError(opts ...ErrorOption) *ApiError

NewJSConsumerDurableNameNotMatchSubjectError creates a new JSConsumerDurableNameNotMatchSubjectErr error: "consumer name in subject does not match durable name in request"

func NewJSConsumerDurableNameNotSetError added in v2.4.0

func NewJSConsumerDurableNameNotSetError(opts ...ErrorOption) *ApiError

NewJSConsumerDurableNameNotSetError creates a new JSConsumerDurableNameNotSetErr error: "consumer expected to be durable but a durable name was not set"

func NewJSConsumerEmptyFilterError added in v2.10.0

func NewJSConsumerEmptyFilterError(opts ...ErrorOption) *ApiError

NewJSConsumerEmptyFilterError creates a new JSConsumerEmptyFilter error: "consumer filter in FilterSubjects cannot be empty"

func NewJSConsumerEphemeralWithDurableInSubjectError added in v2.4.0

func NewJSConsumerEphemeralWithDurableInSubjectError(opts ...ErrorOption) *ApiError

NewJSConsumerEphemeralWithDurableInSubjectError creates a new JSConsumerEphemeralWithDurableInSubjectErr error: "consumer expected to be ephemeral but detected a durable name set in subject"

func NewJSConsumerEphemeralWithDurableNameError added in v2.4.0

func NewJSConsumerEphemeralWithDurableNameError(opts ...ErrorOption) *ApiError

NewJSConsumerEphemeralWithDurableNameError creates a new JSConsumerEphemeralWithDurableNameErr error: "consumer expected to be ephemeral but a durable name was set in request"

func NewJSConsumerExistingActiveError added in v2.4.0

func NewJSConsumerExistingActiveError(opts ...ErrorOption) *ApiError

NewJSConsumerExistingActiveError creates a new JSConsumerExistingActiveErr error: "consumer already exists and is still active"

func NewJSConsumerFCRequiresPushError added in v2.4.0

func NewJSConsumerFCRequiresPushError(opts ...ErrorOption) *ApiError

NewJSConsumerFCRequiresPushError creates a new JSConsumerFCRequiresPushErr error: "consumer flow control requires a push based consumer"

func NewJSConsumerFilterNotSubsetError added in v2.4.0

func NewJSConsumerFilterNotSubsetError(opts ...ErrorOption) *ApiError

NewJSConsumerFilterNotSubsetError creates a new JSConsumerFilterNotSubsetErr error: "consumer filter subject is not a valid subset of the interest subjects"

func NewJSConsumerHBRequiresPushError added in v2.4.0

func NewJSConsumerHBRequiresPushError(opts ...ErrorOption) *ApiError

NewJSConsumerHBRequiresPushError creates a new JSConsumerHBRequiresPushErr error: "consumer idle heartbeat requires a push based consumer"

func NewJSConsumerInactiveThresholdExcessError added in v2.10.0

func NewJSConsumerInactiveThresholdExcessError(limit interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerInactiveThresholdExcessError creates a new JSConsumerInactiveThresholdExcess error: "consumer inactive threshold exceeds system limit of {limit}"

func NewJSConsumerInvalidDeliverSubjectError added in v2.6.6

func NewJSConsumerInvalidDeliverSubjectError(opts ...ErrorOption) *ApiError

NewJSConsumerInvalidDeliverSubjectError creates a new JSConsumerInvalidDeliverSubject error: "invalid push consumer deliver subject"

func NewJSConsumerInvalidPolicyError added in v2.4.0

func NewJSConsumerInvalidPolicyError(err error, opts ...ErrorOption) *ApiError

NewJSConsumerInvalidPolicyError creates a new JSConsumerInvalidPolicyErrF error: "{err}"

func NewJSConsumerInvalidSamplingError added in v2.4.0

func NewJSConsumerInvalidSamplingError(err error, opts ...ErrorOption) *ApiError

NewJSConsumerInvalidSamplingError creates a new JSConsumerInvalidSamplingErrF error: "failed to parse consumer sampling configuration: {err}"

func NewJSConsumerMaxDeliverBackoffError added in v2.7.1

func NewJSConsumerMaxDeliverBackoffError(opts ...ErrorOption) *ApiError

NewJSConsumerMaxDeliverBackoffError creates a new JSConsumerMaxDeliverBackoffErr error: "max deliver is required to be > length of backoff values"

func NewJSConsumerMaxPendingAckExcessError added in v2.8.0

func NewJSConsumerMaxPendingAckExcessError(limit interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerMaxPendingAckExcessError creates a new JSConsumerMaxPendingAckExcessErrF error: "consumer max ack pending exceeds system limit of {limit}"

func NewJSConsumerMaxPendingAckPolicyRequiredError added in v2.4.0

func NewJSConsumerMaxPendingAckPolicyRequiredError(opts ...ErrorOption) *ApiError

NewJSConsumerMaxPendingAckPolicyRequiredError creates a new JSConsumerMaxPendingAckPolicyRequiredErr error: "consumer requires ack policy for max ack pending"

func NewJSConsumerMaxRequestBatchExceededError added in v2.8.0

func NewJSConsumerMaxRequestBatchExceededError(limit interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerMaxRequestBatchExceededError creates a new JSConsumerMaxRequestBatchExceededF error: "consumer max request batch exceeds server limit of {limit}"

func NewJSConsumerMaxRequestBatchNegativeError added in v2.7.0

func NewJSConsumerMaxRequestBatchNegativeError(opts ...ErrorOption) *ApiError

NewJSConsumerMaxRequestBatchNegativeError creates a new JSConsumerMaxRequestBatchNegativeErr error: "consumer max request batch needs to be > 0"

func NewJSConsumerMaxRequestExpiresToSmallError added in v2.7.0

func NewJSConsumerMaxRequestExpiresToSmallError(opts ...ErrorOption) *ApiError

NewJSConsumerMaxRequestExpiresToSmallError creates a new JSConsumerMaxRequestExpiresToSmall error: "consumer max request expires needs to be >= 1ms"

func NewJSConsumerMaxWaitingNegativeError added in v2.4.0

func NewJSConsumerMaxWaitingNegativeError(opts ...ErrorOption) *ApiError

NewJSConsumerMaxWaitingNegativeError creates a new JSConsumerMaxWaitingNegativeErr error: "consumer max waiting needs to be positive"

func NewJSConsumerMetadataLengthError added in v2.10.0

func NewJSConsumerMetadataLengthError(limit interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerMetadataLengthError creates a new JSConsumerMetadataLengthErrF error: "consumer metadata exceeds maximum size of {limit}"

func NewJSConsumerMultipleFiltersNotAllowedError added in v2.10.0

func NewJSConsumerMultipleFiltersNotAllowedError(opts ...ErrorOption) *ApiError

NewJSConsumerMultipleFiltersNotAllowedError creates a new JSConsumerMultipleFiltersNotAllowed error: "consumer with multiple subject filters cannot use subject based API"

func NewJSConsumerNameContainsPathSeparatorsError added in v2.9.0

func NewJSConsumerNameContainsPathSeparatorsError(opts ...ErrorOption) *ApiError

NewJSConsumerNameContainsPathSeparatorsError creates a new JSConsumerNameContainsPathSeparatorsErr error: "Consumer name can not contain path separators"

func NewJSConsumerNameExistError added in v2.4.0

func NewJSConsumerNameExistError(opts ...ErrorOption) *ApiError

NewJSConsumerNameExistError creates a new JSConsumerNameExistErr error: "consumer name already in use"

func NewJSConsumerNameTooLongError added in v2.4.0

func NewJSConsumerNameTooLongError(max interface{}, opts ...ErrorOption) *ApiError

NewJSConsumerNameTooLongError creates a new JSConsumerNameTooLongErrF error: "consumer name is too long, maximum allowed is {max}"

func NewJSConsumerNotFoundError added in v2.4.0

func NewJSConsumerNotFoundError(opts ...ErrorOption) *ApiError

NewJSConsumerNotFoundError creates a new JSConsumerNotFoundErr error: "consumer not found"

func NewJSConsumerOfflineError added in v2.8.0

func NewJSConsumerOfflineError(opts ...ErrorOption) *ApiError

NewJSConsumerOfflineError creates a new JSConsumerOfflineErr error: "consumer is offline"

func NewJSConsumerOnMappedError added in v2.4.0

func NewJSConsumerOnMappedError(opts ...ErrorOption) *ApiError

NewJSConsumerOnMappedError creates a new JSConsumerOnMappedErr error: "consumer direct on a mapped consumer"

func NewJSConsumerOverlappingSubjectFiltersError added in v2.10.0

func NewJSConsumerOverlappingSubjectFiltersError(opts ...ErrorOption) *ApiError

NewJSConsumerOverlappingSubjectFiltersError creates a new JSConsumerOverlappingSubjectFilters error: "consumer subject filters cannot overlap"

func NewJSConsumerPullNotDurableError added in v2.4.0

func NewJSConsumerPullNotDurableError(opts ...ErrorOption) *ApiError

NewJSConsumerPullNotDurableError creates a new JSConsumerPullNotDurableErr error: "consumer in pull mode requires a durable name"

func NewJSConsumerPullRequiresAckError added in v2.4.0

func NewJSConsumerPullRequiresAckError(opts ...ErrorOption) *ApiError

NewJSConsumerPullRequiresAckError creates a new JSConsumerPullRequiresAckErr error: "consumer in pull mode requires ack policy"

func NewJSConsumerPullWithRateLimitError added in v2.4.0

func NewJSConsumerPullWithRateLimitError(opts ...ErrorOption) *ApiError

NewJSConsumerPullWithRateLimitError creates a new JSConsumerPullWithRateLimitErr error: "consumer in pull mode can not have rate limit set"

func NewJSConsumerPushMaxWaitingError added in v2.4.0

func NewJSConsumerPushMaxWaitingError(opts ...ErrorOption) *ApiError

NewJSConsumerPushMaxWaitingError creates a new JSConsumerPushMaxWaitingErr error: "consumer in push mode can not set max waiting"

func NewJSConsumerReplacementWithDifferentNameError added in v2.4.0

func NewJSConsumerReplacementWithDifferentNameError(opts ...ErrorOption) *ApiError

NewJSConsumerReplacementWithDifferentNameError creates a new JSConsumerReplacementWithDifferentNameErr error: "consumer replacement durable config not the same"

func NewJSConsumerReplicasExceedsStreamError added in v2.8.3

func NewJSConsumerReplicasExceedsStreamError(opts ...ErrorOption) *ApiError

NewJSConsumerReplicasExceedsStreamError creates a new JSConsumerReplicasExceedsStream error: "consumer config replica count exceeds parent stream"

func NewJSConsumerReplicasShouldMatchStreamError added in v2.9.12

func NewJSConsumerReplicasShouldMatchStreamError(opts ...ErrorOption) *ApiError

NewJSConsumerReplicasShouldMatchStreamError creates a new JSConsumerReplicasShouldMatchStream error: "consumer config replicas must match interest retention stream's replicas"

func NewJSConsumerSmallHeartbeatError added in v2.4.0

func NewJSConsumerSmallHeartbeatError(opts ...ErrorOption) *ApiError

NewJSConsumerSmallHeartbeatError creates a new JSConsumerSmallHeartbeatErr error: "consumer idle heartbeat needs to be >= 100ms"

func NewJSConsumerStoreFailedError added in v2.4.0

func NewJSConsumerStoreFailedError(err error, opts ...ErrorOption) *ApiError

NewJSConsumerStoreFailedError creates a new JSConsumerStoreFailedErrF error: "error creating store for consumer: {err}"

func NewJSConsumerWQConsumerNotDeliverAllError added in v2.4.0

func NewJSConsumerWQConsumerNotDeliverAllError(opts ...ErrorOption) *ApiError

NewJSConsumerWQConsumerNotDeliverAllError creates a new JSConsumerWQConsumerNotDeliverAllErr error: "consumer must be deliver all on workqueue stream"

func NewJSConsumerWQConsumerNotUniqueError added in v2.4.0

func NewJSConsumerWQConsumerNotUniqueError(opts ...ErrorOption) *ApiError

NewJSConsumerWQConsumerNotUniqueError creates a new JSConsumerWQConsumerNotUniqueErr error: "filtered consumer not unique on workqueue stream"

func NewJSConsumerWQMultipleUnfilteredError added in v2.4.0

func NewJSConsumerWQMultipleUnfilteredError(opts ...ErrorOption) *ApiError

NewJSConsumerWQMultipleUnfilteredError creates a new JSConsumerWQMultipleUnfilteredErr error: "multiple non-filtered consumers not allowed on workqueue stream"

func NewJSConsumerWQRequiresExplicitAckError added in v2.4.0

func NewJSConsumerWQRequiresExplicitAckError(opts ...ErrorOption) *ApiError

NewJSConsumerWQRequiresExplicitAckError creates a new JSConsumerWQRequiresExplicitAckErr error: "workqueue stream requires explicit ack"

func NewJSConsumerWithFlowControlNeedsHeartbeatsError added in v2.6.0

func NewJSConsumerWithFlowControlNeedsHeartbeatsError(opts ...ErrorOption) *ApiError

NewJSConsumerWithFlowControlNeedsHeartbeatsError creates a new JSConsumerWithFlowControlNeedsHeartbeats error: "consumer with flow control also needs heartbeats"

func NewJSInsufficientResourcesError added in v2.4.0

func NewJSInsufficientResourcesError(opts ...ErrorOption) *ApiError

NewJSInsufficientResourcesError creates a new JSInsufficientResourcesErr error: "insufficient resources"

func NewJSInvalidJSONError added in v2.4.0

func NewJSInvalidJSONError(opts ...ErrorOption) *ApiError

NewJSInvalidJSONError creates a new JSInvalidJSONErr error: "invalid JSON"

func NewJSMaximumConsumersLimitError added in v2.4.0

func NewJSMaximumConsumersLimitError(opts ...ErrorOption) *ApiError

NewJSMaximumConsumersLimitError creates a new JSMaximumConsumersLimitErr error: "maximum consumers limit reached"

func NewJSMaximumStreamsLimitError added in v2.4.0

func NewJSMaximumStreamsLimitError(opts ...ErrorOption) *ApiError

NewJSMaximumStreamsLimitError creates a new JSMaximumStreamsLimitErr error: "maximum number of streams reached"

func NewJSMemoryResourcesExceededError added in v2.4.0

func NewJSMemoryResourcesExceededError(opts ...ErrorOption) *ApiError

NewJSMemoryResourcesExceededError creates a new JSMemoryResourcesExceededErr error: "insufficient memory resources available"

func NewJSMirrorConsumerSetupFailedError added in v2.4.0

func NewJSMirrorConsumerSetupFailedError(err error, opts ...ErrorOption) *ApiError

NewJSMirrorConsumerSetupFailedError creates a new JSMirrorConsumerSetupFailedErrF error: "{err}"

func NewJSMirrorInvalidStreamNameError added in v2.10.0

func NewJSMirrorInvalidStreamNameError(opts ...ErrorOption) *ApiError

NewJSMirrorInvalidStreamNameError creates a new JSMirrorInvalidStreamName error: "mirrored stream name is invalid"

func NewJSMirrorInvalidSubjectFilterError added in v2.10.0

func NewJSMirrorInvalidSubjectFilterError(opts ...ErrorOption) *ApiError

NewJSMirrorInvalidSubjectFilterError creates a new JSMirrorInvalidSubjectFilter error: "mirror subject filter is invalid"

func NewJSMirrorMaxMessageSizeTooBigError added in v2.4.0

func NewJSMirrorMaxMessageSizeTooBigError(opts ...ErrorOption) *ApiError

NewJSMirrorMaxMessageSizeTooBigError creates a new JSMirrorMaxMessageSizeTooBigErr error: "stream mirror must have max message size >= source"

func NewJSMirrorMultipleFiltersNotAllowedError added in v2.10.0

func NewJSMirrorMultipleFiltersNotAllowedError(opts ...ErrorOption) *ApiError

NewJSMirrorMultipleFiltersNotAllowedError creates a new JSMirrorMultipleFiltersNotAllowed error: "mirror with multiple subject transforms cannot also have a single subject filter"

func NewJSMirrorOverlappingSubjectFiltersError added in v2.10.0

func NewJSMirrorOverlappingSubjectFiltersError(opts ...ErrorOption) *ApiError

NewJSMirrorOverlappingSubjectFiltersError creates a new JSMirrorOverlappingSubjectFilters error: "mirror subject filters can not overlap"

func NewJSMirrorWithFirstSeqError added in v2.10.0

func NewJSMirrorWithFirstSeqError(opts ...ErrorOption) *ApiError

NewJSMirrorWithFirstSeqError creates a new JSMirrorWithFirstSeqErr error: "stream mirrors can not have first sequence configured"

func NewJSMirrorWithSourcesError added in v2.4.0

func NewJSMirrorWithSourcesError(opts ...ErrorOption) *ApiError

NewJSMirrorWithSourcesError creates a new JSMirrorWithSourcesErr error: "stream mirrors can not also contain other sources"

func NewJSMirrorWithStartSeqAndTimeError added in v2.4.0

func NewJSMirrorWithStartSeqAndTimeError(opts ...ErrorOption) *ApiError

NewJSMirrorWithStartSeqAndTimeError creates a new JSMirrorWithStartSeqAndTimeErr error: "stream mirrors can not have both start seq and start time configured"

func NewJSMirrorWithSubjectFiltersError added in v2.4.0

func NewJSMirrorWithSubjectFiltersError(opts ...ErrorOption) *ApiError

NewJSMirrorWithSubjectFiltersError creates a new JSMirrorWithSubjectFiltersErr error: "stream mirrors can not contain filtered subjects"

func NewJSMirrorWithSubjectsError added in v2.4.0

func NewJSMirrorWithSubjectsError(opts ...ErrorOption) *ApiError

NewJSMirrorWithSubjectsError creates a new JSMirrorWithSubjectsErr error: "stream mirrors can not contain subjects"

func NewJSNoAccountError added in v2.4.0

func NewJSNoAccountError(opts ...ErrorOption) *ApiError

NewJSNoAccountError creates a new JSNoAccountErr error: "account not found"

func NewJSNoLimitsError added in v2.8.0

func NewJSNoLimitsError(opts ...ErrorOption) *ApiError

NewJSNoLimitsError creates a new JSNoLimitsErr error: "no JetStream default or applicable tiered limit present"

func NewJSNoMessageFoundError added in v2.4.0

func NewJSNoMessageFoundError(opts ...ErrorOption) *ApiError

NewJSNoMessageFoundError creates a new JSNoMessageFoundErr error: "no message found"

func NewJSNotEmptyRequestError added in v2.4.0

func NewJSNotEmptyRequestError(opts ...ErrorOption) *ApiError

NewJSNotEmptyRequestError creates a new JSNotEmptyRequestErr error: "expected an empty request payload"

func NewJSNotEnabledError added in v2.4.0

func NewJSNotEnabledError(opts ...ErrorOption) *ApiError

NewJSNotEnabledError creates a new JSNotEnabledErr error: "JetStream not enabled"

func NewJSNotEnabledForAccountError added in v2.4.0

func NewJSNotEnabledForAccountError(opts ...ErrorOption) *ApiError

NewJSNotEnabledForAccountError creates a new JSNotEnabledForAccountErr error: "JetStream not enabled for account"

func NewJSPeerRemapError added in v2.4.0

func NewJSPeerRemapError(opts ...ErrorOption) *ApiError

NewJSPeerRemapError creates a new JSPeerRemapErr error: "peer remap failed"

func NewJSRaftGeneralError added in v2.4.0

func NewJSRaftGeneralError(err error, opts ...ErrorOption) *ApiError

NewJSRaftGeneralError creates a new JSRaftGeneralErrF error: "{err}"

func NewJSReplicasCountCannotBeNegativeError added in v2.9.3

func NewJSReplicasCountCannotBeNegativeError(opts ...ErrorOption) *ApiError

NewJSReplicasCountCannotBeNegativeError creates a new JSReplicasCountCannotBeNegative error: "replicas count cannot be negative"

func NewJSRestoreSubscribeFailedError added in v2.4.0

func NewJSRestoreSubscribeFailedError(err error, subject interface{}, opts ...ErrorOption) *ApiError

NewJSRestoreSubscribeFailedError creates a new JSRestoreSubscribeFailedErrF error: "JetStream unable to subscribe to restore snapshot {subject}: {err}"

func NewJSSequenceNotFoundError added in v2.4.0

func NewJSSequenceNotFoundError(seq uint64, opts ...ErrorOption) *ApiError

NewJSSequenceNotFoundError creates a new JSSequenceNotFoundErrF error: "sequence {seq} not found"

func NewJSSnapshotDeliverSubjectInvalidError added in v2.4.0

func NewJSSnapshotDeliverSubjectInvalidError(opts ...ErrorOption) *ApiError

NewJSSnapshotDeliverSubjectInvalidError creates a new JSSnapshotDeliverSubjectInvalidErr error: "deliver subject not valid"

func NewJSSourceConsumerSetupFailedError added in v2.4.0

func NewJSSourceConsumerSetupFailedError(err error, opts ...ErrorOption) *ApiError

NewJSSourceConsumerSetupFailedError creates a new JSSourceConsumerSetupFailedErrF error: "{err}"

func NewJSSourceDuplicateDetectedError added in v2.10.0

func NewJSSourceDuplicateDetectedError(opts ...ErrorOption) *ApiError

NewJSSourceDuplicateDetectedError creates a new JSSourceDuplicateDetected error: "duplicate source configuration detected"

func NewJSSourceInvalidStreamNameError added in v2.10.0

func NewJSSourceInvalidStreamNameError(opts ...ErrorOption) *ApiError

NewJSSourceInvalidStreamNameError creates a new JSSourceInvalidStreamName error: "sourced stream name is invalid"

func NewJSSourceInvalidSubjectFilterError added in v2.10.0

func NewJSSourceInvalidSubjectFilterError(opts ...ErrorOption) *ApiError

NewJSSourceInvalidSubjectFilterError creates a new JSSourceInvalidSubjectFilter error: "source subject filter is invalid"

func NewJSSourceInvalidTransformDestinationError added in v2.10.0

func NewJSSourceInvalidTransformDestinationError(opts ...ErrorOption) *ApiError

NewJSSourceInvalidTransformDestinationError creates a new JSSourceInvalidTransformDestination error: "source transform destination is invalid"

func NewJSSourceMaxMessageSizeTooBigError added in v2.4.0

func NewJSSourceMaxMessageSizeTooBigError(opts ...ErrorOption) *ApiError

NewJSSourceMaxMessageSizeTooBigError creates a new JSSourceMaxMessageSizeTooBigErr error: "stream source must have max message size >= target"

func NewJSSourceMultipleFiltersNotAllowedError added in v2.10.0

func NewJSSourceMultipleFiltersNotAllowedError(opts ...ErrorOption) *ApiError

NewJSSourceMultipleFiltersNotAllowedError creates a new JSSourceMultipleFiltersNotAllowed error: "source with multiple subject transforms cannot also have a single subject filter"

func NewJSSourceOverlappingSubjectFiltersError added in v2.10.0

func NewJSSourceOverlappingSubjectFiltersError(opts ...ErrorOption) *ApiError

NewJSSourceOverlappingSubjectFiltersError creates a new JSSourceOverlappingSubjectFilters error: "source filters can not overlap"

func NewJSStorageResourcesExceededError added in v2.4.0

func NewJSStorageResourcesExceededError(opts ...ErrorOption) *ApiError

NewJSStorageResourcesExceededError creates a new JSStorageResourcesExceededErr error: "insufficient storage resources available"

func NewJSStreamAssignmentError added in v2.4.0

func NewJSStreamAssignmentError(err error, opts ...ErrorOption) *ApiError

NewJSStreamAssignmentError creates a new JSStreamAssignmentErrF error: "{err}"

func NewJSStreamCreateError added in v2.4.0

func NewJSStreamCreateError(err error, opts ...ErrorOption) *ApiError

NewJSStreamCreateError creates a new JSStreamCreateErrF error: "{err}"

func NewJSStreamDeleteError added in v2.4.0

func NewJSStreamDeleteError(err error, opts ...ErrorOption) *ApiError

NewJSStreamDeleteError creates a new JSStreamDeleteErrF error: "{err}"

func NewJSStreamExternalApiOverlapError added in v2.4.0

func NewJSStreamExternalApiOverlapError(prefix interface{}, subject interface{}, opts ...ErrorOption) *ApiError

NewJSStreamExternalApiOverlapError creates a new JSStreamExternalApiOverlapErrF error: "stream external api prefix {prefix} must not overlap with {subject}"

func NewJSStreamExternalDelPrefixOverlapsError added in v2.4.0

func NewJSStreamExternalDelPrefixOverlapsError(prefix interface{}, subject interface{}, opts ...ErrorOption) *ApiError

NewJSStreamExternalDelPrefixOverlapsError creates a new JSStreamExternalDelPrefixOverlapsErrF error: "stream external delivery prefix {prefix} overlaps with stream subject {subject}"

func NewJSStreamGeneralError added in v2.4.0

func NewJSStreamGeneralError(err error, opts ...ErrorOption) *ApiError

NewJSStreamGeneralError creates a new JSStreamGeneralErrorF error: "{err}"

func NewJSStreamHeaderExceedsMaximumError added in v2.6.0

func NewJSStreamHeaderExceedsMaximumError(opts ...ErrorOption) *ApiError

NewJSStreamHeaderExceedsMaximumError creates a new JSStreamHeaderExceedsMaximumErr error: "header size exceeds maximum allowed of 64k"

func NewJSStreamInfoMaxSubjectsError added in v2.7.2

func NewJSStreamInfoMaxSubjectsError(opts ...ErrorOption) *ApiError

NewJSStreamInfoMaxSubjectsError creates a new JSStreamInfoMaxSubjectsErr error: "subject details would exceed maximum allowed"

func NewJSStreamInvalidConfigError added in v2.4.0

func NewJSStreamInvalidConfigError(err error, opts ...ErrorOption) *ApiError

NewJSStreamInvalidConfigError creates a new JSStreamInvalidConfigF error: "{err}"

func NewJSStreamInvalidError added in v2.4.0

func NewJSStreamInvalidError(opts ...ErrorOption) *ApiError

NewJSStreamInvalidError creates a new JSStreamInvalidErr error: "stream not valid"

func NewJSStreamInvalidExternalDeliverySubjError added in v2.4.0

func NewJSStreamInvalidExternalDeliverySubjError(prefix interface{}, opts ...ErrorOption) *ApiError

NewJSStreamInvalidExternalDeliverySubjError creates a new JSStreamInvalidExternalDeliverySubjErrF error: "stream external delivery prefix {prefix} must not contain wildcards"

func NewJSStreamLimitsError added in v2.4.0

func NewJSStreamLimitsError(err error, opts ...ErrorOption) *ApiError

NewJSStreamLimitsError creates a new JSStreamLimitsErrF error: "{err}"

func NewJSStreamMaxBytesRequiredError added in v2.7.0

func NewJSStreamMaxBytesRequiredError(opts ...ErrorOption) *ApiError

NewJSStreamMaxBytesRequiredError creates a new JSStreamMaxBytesRequired error: "account requires a stream config to have max bytes set"

func NewJSStreamMaxStreamBytesExceededError added in v2.8.0

func NewJSStreamMaxStreamBytesExceededError(opts ...ErrorOption) *ApiError

NewJSStreamMaxStreamBytesExceededError creates a new JSStreamMaxStreamBytesExceeded error: "stream max bytes exceeds account limit max stream bytes"

func NewJSStreamMessageExceedsMaximumError added in v2.4.0

func NewJSStreamMessageExceedsMaximumError(opts ...ErrorOption) *ApiError

NewJSStreamMessageExceedsMaximumError creates a new JSStreamMessageExceedsMaximumErr error: "message size exceeds maximum allowed"

func NewJSStreamMirrorNotUpdatableError added in v2.4.0

func NewJSStreamMirrorNotUpdatableError(opts ...ErrorOption) *ApiError

NewJSStreamMirrorNotUpdatableError creates a new JSStreamMirrorNotUpdatableErr error: "stream mirror configuration can not be updated"

func NewJSStreamMismatchError added in v2.4.0

func NewJSStreamMismatchError(opts ...ErrorOption) *ApiError

NewJSStreamMismatchError creates a new JSStreamMismatchErr error: "stream name in subject does not match request"

func NewJSStreamMoveAndScaleError added in v2.8.0

func NewJSStreamMoveAndScaleError(opts ...ErrorOption) *ApiError

NewJSStreamMoveAndScaleError creates a new JSStreamMoveAndScaleErr error: "can not move and scale a stream in a single update"

func NewJSStreamMoveInProgressError added in v2.8.0

func NewJSStreamMoveInProgressError(msg interface{}, opts ...ErrorOption) *ApiError

NewJSStreamMoveInProgressError creates a new JSStreamMoveInProgressF error: "stream move already in progress: {msg}"

func NewJSStreamMoveNotInProgressError added in v2.9.0

func NewJSStreamMoveNotInProgressError(opts ...ErrorOption) *ApiError

NewJSStreamMoveNotInProgressError creates a new JSStreamMoveNotInProgress error: "stream move not in progress"

func NewJSStreamMsgDeleteFailedError added in v2.4.0

func NewJSStreamMsgDeleteFailedError(err error, opts ...ErrorOption) *ApiError

NewJSStreamMsgDeleteFailedError creates a new JSStreamMsgDeleteFailedF error: "{err}"

func NewJSStreamNameContainsPathSeparatorsError added in v2.9.0

func NewJSStreamNameContainsPathSeparatorsError(opts ...ErrorOption) *ApiError

NewJSStreamNameContainsPathSeparatorsError creates a new JSStreamNameContainsPathSeparatorsErr error: "Stream name can not contain path separators"

func NewJSStreamNameExistError added in v2.4.0

func NewJSStreamNameExistError(opts ...ErrorOption) *ApiError

NewJSStreamNameExistError creates a new JSStreamNameExistErr error: "stream name already in use with a different configuration"

func NewJSStreamNameExistRestoreFailedError added in v2.9.0

func NewJSStreamNameExistRestoreFailedError(opts ...ErrorOption) *ApiError

NewJSStreamNameExistRestoreFailedError creates a new JSStreamNameExistRestoreFailedErr error: "stream name already in use, cannot restore"

func NewJSStreamNotFoundError added in v2.4.0

func NewJSStreamNotFoundError(opts ...ErrorOption) *ApiError

NewJSStreamNotFoundError creates a new JSStreamNotFoundErr error: "stream not found"

func NewJSStreamNotMatchError added in v2.4.0

func NewJSStreamNotMatchError(opts ...ErrorOption) *ApiError

NewJSStreamNotMatchError creates a new JSStreamNotMatchErr error: "expected stream does not match"

func NewJSStreamOfflineError added in v2.8.0

func NewJSStreamOfflineError(opts ...ErrorOption) *ApiError

NewJSStreamOfflineError creates a new JSStreamOfflineErr error: "stream is offline"

func NewJSStreamPurgeFailedError added in v2.6.2

func NewJSStreamPurgeFailedError(err error, opts ...ErrorOption) *ApiError

NewJSStreamPurgeFailedError creates a new JSStreamPurgeFailedF error: "{err}"

func NewJSStreamReplicasNotSupportedError added in v2.4.0

func NewJSStreamReplicasNotSupportedError(opts ...ErrorOption) *ApiError

NewJSStreamReplicasNotSupportedError creates a new JSStreamReplicasNotSupportedErr error: "replicas > 1 not supported in non-clustered mode"

func NewJSStreamReplicasNotUpdatableError added in v2.4.0

func NewJSStreamReplicasNotUpdatableError(opts ...ErrorOption) *ApiError

NewJSStreamReplicasNotUpdatableError creates a new JSStreamReplicasNotUpdatableErr error: "Replicas configuration can not be updated"

func NewJSStreamRestoreError added in v2.4.0

func NewJSStreamRestoreError(err error, opts ...ErrorOption) *ApiError

NewJSStreamRestoreError creates a new JSStreamRestoreErrF error: "restore failed: {err}"

func NewJSStreamRollupFailedError added in v2.6.2

func NewJSStreamRollupFailedError(err error, opts ...ErrorOption) *ApiError

NewJSStreamRollupFailedError creates a new JSStreamRollupFailedF error: "{err}"

func NewJSStreamSealedError added in v2.6.2

func NewJSStreamSealedError(opts ...ErrorOption) *ApiError

NewJSStreamSealedError creates a new JSStreamSealedErr error: "invalid operation on sealed stream"

func NewJSStreamSequenceNotMatchError added in v2.4.0

func NewJSStreamSequenceNotMatchError(opts ...ErrorOption) *ApiError

NewJSStreamSequenceNotMatchError creates a new JSStreamSequenceNotMatchErr error: "expected stream sequence does not match"

func NewJSStreamSnapshotError added in v2.4.0

func NewJSStreamSnapshotError(err error, opts ...ErrorOption) *ApiError

NewJSStreamSnapshotError creates a new JSStreamSnapshotErrF error: "snapshot failed: {err}"

func NewJSStreamStoreFailedError added in v2.4.0

func NewJSStreamStoreFailedError(err error, opts ...ErrorOption) *ApiError

NewJSStreamStoreFailedError creates a new JSStreamStoreFailedF error: "{err}"

func NewJSStreamSubjectOverlapError added in v2.4.0

func NewJSStreamSubjectOverlapError(opts ...ErrorOption) *ApiError

NewJSStreamSubjectOverlapError creates a new JSStreamSubjectOverlapErr error: "subjects overlap with an existing stream"

func NewJSStreamTemplateCreateError added in v2.4.0

func NewJSStreamTemplateCreateError(err error, opts ...ErrorOption) *ApiError

NewJSStreamTemplateCreateError creates a new JSStreamTemplateCreateErrF error: "{err}"

func NewJSStreamTemplateDeleteError added in v2.4.0

func NewJSStreamTemplateDeleteError(err error, opts ...ErrorOption) *ApiError

NewJSStreamTemplateDeleteError creates a new JSStreamTemplateDeleteErrF error: "{err}"

func NewJSStreamTemplateNotFoundError added in v2.4.0

func NewJSStreamTemplateNotFoundError(opts ...ErrorOption) *ApiError

NewJSStreamTemplateNotFoundError creates a new JSStreamTemplateNotFoundErr error: "template not found"

func NewJSStreamUpdateError added in v2.4.0

func NewJSStreamUpdateError(err error, opts ...ErrorOption) *ApiError

NewJSStreamUpdateError creates a new JSStreamUpdateErrF error: "{err}"

func NewJSStreamWrongLastMsgIDError added in v2.4.0

func NewJSStreamWrongLastMsgIDError(id interface{}, opts ...ErrorOption) *ApiError

NewJSStreamWrongLastMsgIDError creates a new JSStreamWrongLastMsgIDErrF error: "wrong last msg ID: {id}"

func NewJSStreamWrongLastSequenceError added in v2.4.0

func NewJSStreamWrongLastSequenceError(seq uint64, opts ...ErrorOption) *ApiError

NewJSStreamWrongLastSequenceError creates a new JSStreamWrongLastSequenceErrF error: "wrong last sequence: {seq}"

func NewJSTempStorageFailedError added in v2.4.0

func NewJSTempStorageFailedError(opts ...ErrorOption) *ApiError

NewJSTempStorageFailedError creates a new JSTempStorageFailedErr error: "JetStream unable to open temp storage for restore"

func NewJSTemplateNameNotMatchSubjectError added in v2.4.0

func NewJSTemplateNameNotMatchSubjectError(opts ...ErrorOption) *ApiError

NewJSTemplateNameNotMatchSubjectError creates a new JSTemplateNameNotMatchSubjectErr error: "template name in subject does not match request"

func (*ApiError) Error added in v2.3.0

func (e *ApiError) Error() string

type ApiPaged added in v2.2.0

type ApiPaged struct {
	Total  int `json:"total"`
	Offset int `json:"offset"`
	Limit  int `json:"limit"`
}

ApiPaged includes variables used to create paged responses from the JSON API

type ApiPagedRequest added in v2.2.0

type ApiPagedRequest struct {
	Offset int `json:"offset"`
}

ApiPagedRequest includes parameters allowing specific pages to be requests from APIs responding with ApiPaged

type ApiResponse added in v2.2.0

type ApiResponse struct {
	Type  string    `json:"type"`
	Error *ApiError `json:"error,omitempty"`
}

ApiResponse is a standard response from the JetStream JSON API

func (*ApiResponse) ToError added in v2.3.0

func (r *ApiResponse) ToError() error

ToError checks if the response has a error and if it does converts it to an error avoiding the pitfalls described by https://yourbasic.org/golang/gotcha-why-nil-error-not-equal-nil/

type AuthCallout added in v2.10.0

type AuthCallout struct {
	// Must be a public account Nkey.
	Issuer string
	// Account to be used for sending requests.
	Account string
	// Users that will bypass auth_callout and be used for the auth service itself.
	AuthUsers []string
	// XKey is a public xkey for the authorization service.
	// This will enable encryption for server requests and the authorization service responses.
	XKey string
}

AuthCallout option used to map external AuthN to NATS based AuthZ.

type Authentication

type Authentication interface {
	// Check if a client is authorized to connect
	Check(c ClientAuthentication) bool
}

Authentication is an interface for implementing authentication

type CacheDirAccResolver added in v2.2.0

type CacheDirAccResolver struct {
	DirAccResolver
	// contains filtered or unexported fields
}

Caching resolver using nats for lookups and making use of a directory for storage

func NewCacheDirAccResolver added in v2.2.0

func NewCacheDirAccResolver(path string, limit int64, ttl time.Duration, opts ...DirResOption) (*CacheDirAccResolver, error)

func (*CacheDirAccResolver) Reload added in v2.2.0

func (dr *CacheDirAccResolver) Reload() error

func (*CacheDirAccResolver) Start added in v2.2.0

func (dr *CacheDirAccResolver) Start(s *Server) error

type ClientAuthentication

type ClientAuthentication interface {
	// GetOpts gets options associated with a client
	GetOpts() *ClientOpts
	// GetTLSConnectionState if TLS is enabled, TLS ConnectionState, nil otherwise
	GetTLSConnectionState() *tls.ConnectionState
	// RegisterUser optionally map a user after auth.
	RegisterUser(*User)
	// RemoteAddress expose the connection information of the client
	RemoteAddress() net.Addr
	// GetNonce is the nonce presented to the user in the INFO line
	GetNonce() []byte
	// Kind indicates what type of connection this is matching defined constants like CLIENT, ROUTER, GATEWAY, LEAF etc
	Kind() int
}

ClientAuthentication is an interface for client authentication

type ClientInfo

type ClientInfo struct {
	Start      *time.Time    `json:"start,omitempty"`
	Host       string        `json:"host,omitempty"`
	ID         uint64        `json:"id,omitempty"`
	Account    string        `json:"acc,omitempty"`
	Service    string        `json:"svc,omitempty"`
	User       string        `json:"user,omitempty"`
	Name       string        `json:"name,omitempty"`
	Lang       string        `json:"lang,omitempty"`
	Version    string        `json:"ver,omitempty"`
	RTT        time.Duration `json:"rtt,omitempty"`
	Server     string        `json:"server,omitempty"`
	Cluster    string        `json:"cluster,omitempty"`
	Alternates []string      `json:"alts,omitempty"`
	Stop       *time.Time    `json:"stop,omitempty"`
	Jwt        string        `json:"jwt,omitempty"`
	IssuerKey  string        `json:"issuer_key,omitempty"`
	NameTag    string        `json:"name_tag,omitempty"`
	Tags       jwt.TagList   `json:"tags,omitempty"`
	Kind       string        `json:"kind,omitempty"`
	ClientType string        `json:"client_type,omitempty"`
	MQTTClient string        `json:"client_id,omitempty"` // This is the MQTT client ID
	Nonce      string        `json:"nonce,omitempty"`
}

ClientInfo is detailed information about the client forming a connection.

type ClientOpts added in v2.2.4

type ClientOpts struct {
	Echo         bool   `json:"echo"`
	Verbose      bool   `json:"verbose"`
	Pedantic     bool   `json:"pedantic"`
	TLSRequired  bool   `json:"tls_required"`
	Nkey         string `json:"nkey,omitempty"`
	JWT          string `json:"jwt,omitempty"`
	Sig          string `json:"sig,omitempty"`
	Token        string `json:"auth_token,omitempty"`
	Username     string `json:"user,omitempty"`
	Password     string `json:"pass,omitempty"`
	Name         string `json:"name"`
	Lang         string `json:"lang"`
	Version      string `json:"version"`
	Protocol     int    `json:"protocol"`
	Account      string `json:"account,omitempty"`
	AccountNew   bool   `json:"new_account,omitempty"`
	Headers      bool   `json:"headers,omitempty"`
	NoResponders bool   `json:"no_responders,omitempty"`

	// Routes and Leafnodes only
	Import *SubjectPermission `json:"import,omitempty"`
	Export *SubjectPermission `json:"export,omitempty"`

	// Leafnodes
	RemoteAccount string `json:"remote_account,omitempty"`
}

type ClosedState

type ClosedState int

ClosedState is the reason client was closed. This will be passed into calls to clearConnection, but will only be stored in ConnInfo for monitoring.

func (ClosedState) String

func (reason ClosedState) String() string

type ClusterInfo added in v2.2.0

type ClusterInfo struct {
	Name      string      `json:"name,omitempty"`
	RaftGroup string      `json:"raft_group,omitempty"`
	Leader    string      `json:"leader,omitempty"`
	Replicas  []*PeerInfo `json:"replicas,omitempty"`
}

ClusterInfo shows information about the underlying set of servers that make up the stream or consumer.

type ClusterOpts

type ClusterOpts struct {
	Name              string            `json:"-"`
	Host              string            `json:"addr,omitempty"`
	Port              int               `json:"cluster_port,omitempty"`
	Username          string            `json:"-"`
	Password          string            `json:"-"`
	AuthTimeout       float64           `json:"auth_timeout,omitempty"`
	Permissions       *RoutePermissions `json:"-"`
	TLSTimeout        float64           `json:"-"`
	TLSConfig         *tls.Config       `json:"-"`
	TLSMap            bool              `json:"-"`
	TLSCheckKnownURLs bool              `json:"-"`
	TLSPinnedCerts    PinnedCertSet     `json:"-"`
	ListenStr         string            `json:"-"`
	Advertise         string            `json:"-"`
	NoAdvertise       bool              `json:"-"`
	ConnectRetries    int               `json:"-"`
	PoolSize          int               `json:"-"`
	PinnedAccounts    []string          `json:"-"`
	Compression       CompressionOpts   `json:"-"`
	PingInterval      time.Duration     `json:"-"`
	MaxPingsOut       int               `json:"-"`
	// contains filtered or unexported fields
}

ClusterOpts are options for clusters. NOTE: This structure is no longer used for monitoring endpoints and json tags are deprecated and may be removed in the future.

type ClusterOptsVarz

type ClusterOptsVarz struct {
	Name        string   `json:"name,omitempty"`
	Host        string   `json:"addr,omitempty"`
	Port        int      `json:"cluster_port,omitempty"`
	AuthTimeout float64  `json:"auth_timeout,omitempty"`
	URLs        []string `json:"urls,omitempty"`
	TLSTimeout  float64  `json:"tls_timeout,omitempty"`
	TLSRequired bool     `json:"tls_required,omitempty"`
	TLSVerify   bool     `json:"tls_verify,omitempty"`
	PoolSize    int      `json:"pool_size,omitempty"`
}

ClusterOptsVarz contains monitoring cluster information

type Command

type Command string

Command is a signal used to control a running nats-server process.

type CommittedEntry added in v2.2.0

type CommittedEntry struct {
	Index   uint64
	Entries []*Entry
}

CommittedEntry is handed back to the user to apply a commit to their upper layer.

func (*CommittedEntry) ReturnToPool added in v2.9.16

func (ce *CommittedEntry) ReturnToPool()

ReturnToPool returns the CommittedEntry to the pool, after which point it is no longer safe to reuse.

type CompressionInfo added in v2.10.0

type CompressionInfo struct {
	Algorithm    StoreCompression
	OriginalSize uint64
}

func (*CompressionInfo) MarshalMetadata added in v2.10.0

func (c *CompressionInfo) MarshalMetadata() []byte

func (*CompressionInfo) UnmarshalMetadata added in v2.10.0

func (c *CompressionInfo) UnmarshalMetadata(b []byte) (int, error)

type CompressionOpts added in v2.10.0

type CompressionOpts struct {
	Mode string
	// If `Mode` is set to CompressionS2Auto, RTTThresholds provides the
	// thresholds at which the compression level will go from
	// CompressionS2Uncompressed to CompressionS2Fast, CompressionS2Better
	// or CompressionS2Best. If a given level is not desired, specify 0
	// for this slot. For instance, the slice []{0, 10ms, 20ms} means that
	// for any RTT up to 10ms included the compression level will be
	// CompressionS2Fast, then from ]10ms..20ms], the level will be selected
	// as CompressionS2Better. Anything above 20ms will result in picking
	// the CompressionS2Best compression level.
	RTTThresholds []time.Duration
}

CompressionOpts defines the compression mode and optional configuration.

type ConnInfo

type ConnInfo struct {
	Cid            uint64         `json:"cid"`
	Kind           string         `json:"kind,omitempty"`
	Type           string         `json:"type,omitempty"`
	IP             string         `json:"ip"`
	Port           int            `json:"port"`
	Start          time.Time      `json:"start"`
	LastActivity   time.Time      `json:"last_activity"`
	Stop           *time.Time     `json:"stop,omitempty"`
	Reason         string         `json:"reason,omitempty"`
	RTT            string         `json:"rtt,omitempty"`
	Uptime         string         `json:"uptime"`
	Idle           string         `json:"idle"`
	Pending        int            `json:"pending_bytes"`
	InMsgs         int64          `json:"in_msgs"`
	OutMsgs        int64          `json:"out_msgs"`
	InBytes        int64          `json:"in_bytes"`
	OutBytes       int64          `json:"out_bytes"`
	NumSubs        uint32         `json:"subscriptions"`
	Name           string         `json:"name,omitempty"`
	Lang           string         `json:"lang,omitempty"`
	Version        string         `json:"version,omitempty"`
	TLSVersion     string         `json:"tls_version,omitempty"`
	TLSCipher      string         `json:"tls_cipher_suite,omitempty"`
	TLSPeerCerts   []*TLSPeerCert `json:"tls_peer_certs,omitempty"`
	TLSFirst       bool           `json:"tls_first,omitempty"`
	AuthorizedUser string         `json:"authorized_user,omitempty"`
	Account        string         `json:"account,omitempty"`
	Subs           []string       `json:"subscriptions_list,omitempty"`
	SubsDetail     []SubDetail    `json:"subscriptions_list_detail,omitempty"`
	JWT            string         `json:"jwt,omitempty"`
	IssuerKey      string         `json:"issuer_key,omitempty"`
	NameTag        string         `json:"name_tag,omitempty"`
	Tags           jwt.TagList    `json:"tags,omitempty"`
	MQTTClient     string         `json:"mqtt_client,omitempty"` // This is the MQTT client id
	// contains filtered or unexported fields
}

ConnInfo has detailed information on a per connection basis.

type ConnInfos

type ConnInfos []*ConnInfo

ConnInfos represents a connection info list. We use pointers since it will be sorted.

func (ConnInfos) Len

func (cl ConnInfos) Len() int

For sorting Len returns length for sorting.

func (ConnInfos) Swap

func (cl ConnInfos) Swap(i, j int)

Swap will sawap the elements.

type ConnState

type ConnState int

ConnState is for filtering states of connections. We will only have two, open and closed.

type ConnectEventMsg

type ConnectEventMsg struct {
	TypedEvent
	Server ServerInfo `json:"server"`
	Client ClientInfo `json:"client"`
}

ConnectEventMsg is sent when a new connection is made that is part of an account.

type Connz

type Connz struct {
	ID       string      `json:"server_id"`
	Now      time.Time   `json:"now"`
	NumConns int         `json:"num_connections"`
	Total    int         `json:"total"`
	Offset   int         `json:"offset"`
	Limit    int         `json:"limit"`
	Conns    []*ConnInfo `json:"connections"`
}

Connz represents detailed information on current client connections.

type ConnzEventOptions added in v2.2.0

type ConnzEventOptions struct {
	ConnzOptions
	EventFilterOptions
}

In the context of system events, ConnzEventOptions are options passed to Connz

type ConnzOptions

type ConnzOptions struct {
	// Sort indicates how the results will be sorted. Check SortOpt for possible values.
	// Only the sort by connection ID (ByCid) is ascending, all others are descending.
	Sort SortOpt `json:"sort"`

	// Username indicates if user names should be included in the results.
	Username bool `json:"auth"`

	// Subscriptions indicates if subscriptions should be included in the results.
	Subscriptions bool `json:"subscriptions"`

	// SubscriptionsDetail indicates if subscription details should be included in the results
	SubscriptionsDetail bool `json:"subscriptions_detail"`

	// Offset is used for pagination. Connz() only returns connections starting at this
	// offset from the global results.
	Offset int `json:"offset"`

	// Limit is the maximum number of connections that should be returned by Connz().
	Limit int `json:"limit"`

	// Filter for this explicit client connection.
	CID uint64 `json:"cid"`

	// Filter for this explicit client connection based on the MQTT client ID
	MQTTClient string `json:"mqtt_client"`

	// Filter by connection state.
	State ConnState `json:"state"`

	// Filter by username.
	User string `json:"user"`

	// Filter by account.
	Account string `json:"acc"`

	// Filter by subject interest
	FilterSubject string `json:"filter_subject"`
}

ConnzOptions are the options passed to Connz()

type ConsumerAction added in v2.10.0

type ConsumerAction int
const (
	ActionCreateOrUpdate ConsumerAction = iota
	ActionUpdate
	ActionCreate
)

func (ConsumerAction) MarshalJSON added in v2.10.0

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

func (ConsumerAction) String added in v2.10.0

func (a ConsumerAction) String() string

func (*ConsumerAction) UnmarshalJSON added in v2.10.0

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

type ConsumerConfig added in v2.2.0

type ConsumerConfig struct {
	// Durable is deprecated. All consumers should have names, picked by clients.
	Durable         string          `json:"durable_name,omitempty"`
	Name            string          `json:"name,omitempty"`
	Description     string          `json:"description,omitempty"`
	DeliverPolicy   DeliverPolicy   `json:"deliver_policy"`
	OptStartSeq     uint64          `json:"opt_start_seq,omitempty"`
	OptStartTime    *time.Time      `json:"opt_start_time,omitempty"`
	AckPolicy       AckPolicy       `json:"ack_policy"`
	AckWait         time.Duration   `json:"ack_wait,omitempty"`
	MaxDeliver      int             `json:"max_deliver,omitempty"`
	BackOff         []time.Duration `json:"backoff,omitempty"`
	FilterSubject   string          `json:"filter_subject,omitempty"`
	FilterSubjects  []string        `json:"filter_subjects,omitempty"`
	ReplayPolicy    ReplayPolicy    `json:"replay_policy"`
	RateLimit       uint64          `json:"rate_limit_bps,omitempty"` // Bits per sec
	SampleFrequency string          `json:"sample_freq,omitempty"`
	MaxWaiting      int             `json:"max_waiting,omitempty"`
	MaxAckPending   int             `json:"max_ack_pending,omitempty"`
	Heartbeat       time.Duration   `json:"idle_heartbeat,omitempty"`
	FlowControl     bool            `json:"flow_control,omitempty"`
	HeadersOnly     bool            `json:"headers_only,omitempty"`

	// Pull based options.
	MaxRequestBatch    int           `json:"max_batch,omitempty"`
	MaxRequestExpires  time.Duration `json:"max_expires,omitempty"`
	MaxRequestMaxBytes int           `json:"max_bytes,omitempty"`

	// Push based consumers.
	DeliverSubject string `json:"deliver_subject,omitempty"`
	DeliverGroup   string `json:"deliver_group,omitempty"`

	// Ephemeral inactivity threshold.
	InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`

	// Generally inherited by parent stream and other markers, now can be configured directly.
	Replicas int `json:"num_replicas"`
	// Force memory storage.
	MemoryStorage bool `json:"mem_storage,omitempty"`

	// Don't add to general clients.
	Direct bool `json:"direct,omitempty"`

	// Metadata is additional metadata for the Consumer.
	Metadata map[string]string `json:"metadata,omitempty"`
}

type ConsumerInfo added in v2.2.0

type ConsumerInfo struct {
	Stream         string          `json:"stream_name"`
	Name           string          `json:"name"`
	Created        time.Time       `json:"created"`
	Config         *ConsumerConfig `json:"config,omitempty"`
	Delivered      SequenceInfo    `json:"delivered"`
	AckFloor       SequenceInfo    `json:"ack_floor"`
	NumAckPending  int             `json:"num_ack_pending"`
	NumRedelivered int             `json:"num_redelivered"`
	NumWaiting     int             `json:"num_waiting"`
	NumPending     uint64          `json:"num_pending"`
	Cluster        *ClusterInfo    `json:"cluster,omitempty"`
	PushBound      bool            `json:"push_bound,omitempty"`
	// TimeStamp indicates when the info was gathered
	TimeStamp time.Time `json:"ts"`
}

type ConsumerNakOptions added in v2.7.1

type ConsumerNakOptions struct {
	Delay time.Duration `json:"delay"`
}

ConsumerNakOptions is for optional NAK values, e.g. delay.

type ConsumerState added in v2.2.0

type ConsumerState struct {
	// Delivered keeps track of last delivered sequence numbers for both the stream and the consumer.
	Delivered SequencePair `json:"delivered"`
	// AckFloor keeps track of the ack floors for both the stream and the consumer.
	AckFloor SequencePair `json:"ack_floor"`
	// These are both in stream sequence context.
	// Pending is for all messages pending and the timestamp for the delivered time.
	// This will only be present when the AckPolicy is ExplicitAck.
	Pending map[uint64]*Pending `json:"pending,omitempty"`
	// This is for messages that have been redelivered, so count > 1.
	Redelivered map[uint64]uint64 `json:"redelivered,omitempty"`
}

ConsumerState represents a stored state for a consumer.

type ConsumerStore added in v2.2.0

type ConsumerStore interface {
	SetStarting(sseq uint64) error
	HasState() bool
	UpdateDelivered(dseq, sseq, dc uint64, ts int64) error
	UpdateAcks(dseq, sseq uint64) error
	UpdateConfig(cfg *ConsumerConfig) error
	Update(*ConsumerState) error
	State() (*ConsumerState, error)
	BorrowState() (*ConsumerState, error)
	EncodedState() ([]byte, error)
	Type() StorageType
	Stop() error
	Delete() error
	StreamDelete() error
}

ConsumerStore stores state on consumers for streams.

type CreateConsumerRequest added in v2.2.0

type CreateConsumerRequest struct {
	Stream string         `json:"stream_name"`
	Config ConsumerConfig `json:"config"`
	Action ConsumerAction `json:"action"`
}

type DataStats

type DataStats struct {
	Msgs  int64 `json:"msgs"`
	Bytes int64 `json:"bytes"`
}

DataStats reports how may msg and bytes. Applicable for both sent and received.

type DeleteBlock added in v2.10.0

type DeleteBlock interface {
	State() (first, last, num uint64)
	Range(f func(uint64) bool)
}

Interface for DeleteBlock. These will be of three types: 1. AVL seqsets. 2. Run length encoding of a deleted range. 3. Legacy []uint64

type DeleteBlocks added in v2.10.0

type DeleteBlocks []DeleteBlock

func (DeleteBlocks) NumDeleted added in v2.10.0

func (dbs DeleteBlocks) NumDeleted() (total uint64)

type DeleteRange added in v2.10.0

type DeleteRange struct {
	First uint64
	Num   uint64
}

DeleteRange is a run length encoded delete range.

func (*DeleteRange) Range added in v2.10.0

func (dr *DeleteRange) Range(f func(uint64) bool)

Range will range over all the deleted sequences represented by this block.

func (*DeleteRange) State added in v2.10.0

func (dr *DeleteRange) State() (first, last, num uint64)

type DeleteSlice added in v2.10.0

type DeleteSlice []uint64

Legacy []uint64

func (DeleteSlice) Range added in v2.10.0

func (ds DeleteSlice) Range(f func(uint64) bool)

Range will range over all the deleted sequences represented by this []uint64.

func (DeleteSlice) State added in v2.10.0

func (ds DeleteSlice) State() (first, last, num uint64)

type DeliverPolicy added in v2.2.0

type DeliverPolicy int

DeliverPolicy determines how the consumer should select the first message to deliver.

const (
	// DeliverAll will be the default so can be omitted from the request.
	DeliverAll DeliverPolicy = iota
	// DeliverLast will start the consumer with the last sequence received.
	DeliverLast
	// DeliverNew will only deliver new messages that are sent after the consumer is created.
	DeliverNew
	// DeliverByStartSequence will look for a defined starting sequence to start.
	DeliverByStartSequence
	// DeliverByStartTime will select the first messsage with a timestamp >= to StartTime.
	DeliverByStartTime
	// DeliverLastPerSubject will start the consumer with the last message for all subjects received.
	DeliverLastPerSubject
)

func (DeliverPolicy) MarshalJSON added in v2.2.0

func (p DeliverPolicy) MarshalJSON() ([]byte, error)

func (DeliverPolicy) String added in v2.2.0

func (dp DeliverPolicy) String() string

func (*DeliverPolicy) UnmarshalJSON added in v2.2.0

func (p *DeliverPolicy) UnmarshalJSON(data []byte) error

type DenyRules added in v2.2.3

type DenyRules struct {
	Exports []string `json:"exports,omitempty"`
	Imports []string `json:"imports,omitempty"`
}

DenyRules Contains lists of subjects not allowed to be imported/exported

type DirAccResolver added in v2.2.0

type DirAccResolver struct {
	*DirJWTStore
	*Server
	// contains filtered or unexported fields
}

Resolver based on nats for synchronization and backing directory for storage.

func NewDirAccResolver added in v2.2.0

func NewDirAccResolver(path string, limit int64, syncInterval time.Duration, delete deleteType, opts ...DirResOption) (*DirAccResolver, error)

func (*DirAccResolver) Fetch added in v2.2.0

func (dr *DirAccResolver) Fetch(name string) (string, error)

func (*DirAccResolver) IsTrackingUpdate added in v2.2.0

func (dr *DirAccResolver) IsTrackingUpdate() bool

func (*DirAccResolver) Reload added in v2.2.0

func (dr *DirAccResolver) Reload() error

func (*DirAccResolver) Start added in v2.2.0

func (dr *DirAccResolver) Start(s *Server) error

func (*DirAccResolver) Store added in v2.2.0

func (dr *DirAccResolver) Store(name, jwt string) error

type DirJWTStore added in v2.2.0

type DirJWTStore struct {
	sync.Mutex
	// contains filtered or unexported fields
}

DirJWTStore implements the JWT Store interface, keeping JWTs in an optionally sharded directory structure

func NewDirJWTStore added in v2.2.0

func NewDirJWTStore(dirPath string, shard bool, create bool, _ ...dirJWTStoreOption) (*DirJWTStore, error)

Creates a directory based jwt store. Operates on files only, does NOT watch directories and files.

func NewExpiringDirJWTStore added in v2.2.0

func NewExpiringDirJWTStore(dirPath string, shard bool, create bool, delete deleteType, expireCheck time.Duration, limit int64,
	evictOnLimit bool, ttl time.Duration, changeNotification JWTChanged, _ ...dirJWTStoreOption) (*DirJWTStore, error)

Creates a directory based jwt store.

When ttl is set deletion of file is based on it and not on the jwt expiration To completely disable expiration (including expiration in jwt) set ttl to max duration time.Duration(math.MaxInt64)

limit defines how many files are allowed at any given time. Set to math.MaxInt64 to disable. evictOnLimit determines the behavior once limit is reached. * true - Evict based on lru strategy * false - return an error

func NewImmutableDirJWTStore added in v2.2.0

func NewImmutableDirJWTStore(dirPath string, shard bool, _ ...dirJWTStoreOption) (*DirJWTStore, error)

Creates a directory based jwt store. Reads files only, does NOT watch directories and files.

func (*DirJWTStore) Close added in v2.2.0

func (store *DirJWTStore) Close()

func (*DirJWTStore) Hash added in v2.2.0

func (store *DirJWTStore) Hash() [sha256.Size]byte

returns a hash representing all indexed jwt

func (*DirJWTStore) IsReadOnly added in v2.2.0

func (store *DirJWTStore) IsReadOnly() bool

func (*DirJWTStore) LoadAcc added in v2.2.0

func (store *DirJWTStore) LoadAcc(publicKey string) (string, error)

func (*DirJWTStore) LoadAct added in v2.2.0

func (store *DirJWTStore) LoadAct(hash string) (string, error)

func (*DirJWTStore) Merge added in v2.2.0

func (store *DirJWTStore) Merge(pack string) error

Merge takes the JWTs from package and adds them to the store Merge is destructive in the sense that it doesn't check if the JWT is newer or anything like that.

func (*DirJWTStore) Pack added in v2.2.0

func (store *DirJWTStore) Pack(maxJWTs int) (string, error)

Pack up to maxJWTs into a package

func (*DirJWTStore) PackWalk added in v2.2.0

func (store *DirJWTStore) PackWalk(maxJWTs int, cb func(partialPackMsg string)) error

Pack up to maxJWTs into a message and invoke callback with it

func (*DirJWTStore) Reload added in v2.2.0

func (store *DirJWTStore) Reload() error

func (*DirJWTStore) SaveAcc added in v2.2.0

func (store *DirJWTStore) SaveAcc(publicKey string, theJWT string) error

func (*DirJWTStore) SaveAct added in v2.2.0

func (store *DirJWTStore) SaveAct(hash string, theJWT string) error

type DirResOption added in v2.2.1

type DirResOption func(s *DirAccResolver) error

func FetchTimeout added in v2.2.1

func FetchTimeout(to time.Duration) DirResOption

limits the amount of time spent waiting for an account fetch to complete

type DiscardPolicy added in v2.2.0

type DiscardPolicy int

Discard Policy determines how we proceed when limits of messages or bytes are hit. The default, DicscardOld will remove older messages. DiscardNew will fail to store the new message.

func (DiscardPolicy) MarshalJSON added in v2.2.0

func (dp DiscardPolicy) MarshalJSON() ([]byte, error)

func (DiscardPolicy) String added in v2.2.0

func (dp DiscardPolicy) String() string

func (*DiscardPolicy) UnmarshalJSON added in v2.2.0

func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error

type DisconnectEventMsg

type DisconnectEventMsg struct {
	TypedEvent
	Server   ServerInfo `json:"server"`
	Client   ClientInfo `json:"client"`
	Sent     DataStats  `json:"sent"`
	Received DataStats  `json:"received"`
	Reason   string     `json:"reason"`
}

DisconnectEventMsg is sent when a new connection previously defined from a ConnectEventMsg is closed.

type Entry added in v2.2.0

type Entry struct {
	Type EntryType
	Data []byte
}

type EntryType added in v2.2.0

type EntryType uint8
const (
	EntryNormal EntryType = iota
	EntryOldSnapshot
	EntryPeerState
	EntryAddPeer
	EntryRemovePeer
	EntryLeaderTransfer
	EntrySnapshot
)

func (EntryType) String added in v2.2.0

func (t EntryType) String() string

type ErrorIdentifier added in v2.3.0

type ErrorIdentifier uint16
const (
	// JSAccountResourcesExceededErr resource limits exceeded for account
	JSAccountResourcesExceededErr ErrorIdentifier = 10002

	// JSBadRequestErr bad request
	JSBadRequestErr ErrorIdentifier = 10003

	// JSClusterIncompleteErr incomplete results
	JSClusterIncompleteErr ErrorIdentifier = 10004

	// JSClusterNoPeersErrF Error causing no peers to be available ({err})
	JSClusterNoPeersErrF ErrorIdentifier = 10005

	// JSClusterNotActiveErr JetStream not in clustered mode
	JSClusterNotActiveErr ErrorIdentifier = 10006

	// JSClusterNotAssignedErr JetStream cluster not assigned to this server
	JSClusterNotAssignedErr ErrorIdentifier = 10007

	// JSClusterNotAvailErr JetStream system temporarily unavailable
	JSClusterNotAvailErr ErrorIdentifier = 10008

	// JSClusterNotLeaderErr JetStream cluster can not handle request
	JSClusterNotLeaderErr ErrorIdentifier = 10009

	// JSClusterPeerNotMemberErr peer not a member
	JSClusterPeerNotMemberErr ErrorIdentifier = 10040

	// JSClusterRequiredErr JetStream clustering support required
	JSClusterRequiredErr ErrorIdentifier = 10010

	// JSClusterServerNotMemberErr server is not a member of the cluster
	JSClusterServerNotMemberErr ErrorIdentifier = 10044

	// JSClusterTagsErr tags placement not supported for operation
	JSClusterTagsErr ErrorIdentifier = 10011

	// JSClusterUnSupportFeatureErr not currently supported in clustered mode
	JSClusterUnSupportFeatureErr ErrorIdentifier = 10036

	// JSConsumerAlreadyExists action CREATE is used for a existing consumer with a different config (consumer already exists)
	JSConsumerAlreadyExists ErrorIdentifier = 10148

	// JSConsumerBadDurableNameErr durable name can not contain '.', '*', '>'
	JSConsumerBadDurableNameErr ErrorIdentifier = 10103

	// JSConsumerConfigRequiredErr consumer config required
	JSConsumerConfigRequiredErr ErrorIdentifier = 10078

	// JSConsumerCreateDurableAndNameMismatch Consumer Durable and Name have to be equal if both are provided
	JSConsumerCreateDurableAndNameMismatch ErrorIdentifier = 10132

	// JSConsumerCreateErrF General consumer creation failure string ({err})
	JSConsumerCreateErrF ErrorIdentifier = 10012

	// JSConsumerCreateFilterSubjectMismatchErr Consumer create request did not match filtered subject from create subject
	JSConsumerCreateFilterSubjectMismatchErr ErrorIdentifier = 10131

	// JSConsumerDeliverCycleErr consumer deliver subject forms a cycle
	JSConsumerDeliverCycleErr ErrorIdentifier = 10081

	// JSConsumerDeliverToWildcardsErr consumer deliver subject has wildcards
	JSConsumerDeliverToWildcardsErr ErrorIdentifier = 10079

	// JSConsumerDescriptionTooLongErrF consumer description is too long, maximum allowed is {max}
	JSConsumerDescriptionTooLongErrF ErrorIdentifier = 10107

	// JSConsumerDirectRequiresEphemeralErr consumer direct requires an ephemeral consumer
	JSConsumerDirectRequiresEphemeralErr ErrorIdentifier = 10091

	// JSConsumerDirectRequiresPushErr consumer direct requires a push based consumer
	JSConsumerDirectRequiresPushErr ErrorIdentifier = 10090

	// JSConsumerDoesNotExist action UPDATE is used for a nonexisting consumer (consumer does not exist)
	JSConsumerDoesNotExist ErrorIdentifier = 10149

	// JSConsumerDuplicateFilterSubjects consumer cannot have both FilterSubject and FilterSubjects specified
	JSConsumerDuplicateFilterSubjects ErrorIdentifier = 10136

	// JSConsumerDurableNameNotInSubjectErr consumer expected to be durable but no durable name set in subject
	JSConsumerDurableNameNotInSubjectErr ErrorIdentifier = 10016

	// JSConsumerDurableNameNotMatchSubjectErr consumer name in subject does not match durable name in request
	JSConsumerDurableNameNotMatchSubjectErr ErrorIdentifier = 10017

	// JSConsumerDurableNameNotSetErr consumer expected to be durable but a durable name was not set
	JSConsumerDurableNameNotSetErr ErrorIdentifier = 10018

	// JSConsumerEmptyFilter consumer filter in FilterSubjects cannot be empty
	JSConsumerEmptyFilter ErrorIdentifier = 10139

	// JSConsumerEphemeralWithDurableInSubjectErr consumer expected to be ephemeral but detected a durable name set in subject
	JSConsumerEphemeralWithDurableInSubjectErr ErrorIdentifier = 10019

	// JSConsumerEphemeralWithDurableNameErr consumer expected to be ephemeral but a durable name was set in request
	JSConsumerEphemeralWithDurableNameErr ErrorIdentifier = 10020

	// JSConsumerExistingActiveErr consumer already exists and is still active
	JSConsumerExistingActiveErr ErrorIdentifier = 10105

	// JSConsumerFCRequiresPushErr consumer flow control requires a push based consumer
	JSConsumerFCRequiresPushErr ErrorIdentifier = 10089

	// JSConsumerFilterNotSubsetErr consumer filter subject is not a valid subset of the interest subjects
	JSConsumerFilterNotSubsetErr ErrorIdentifier = 10093

	// JSConsumerHBRequiresPushErr consumer idle heartbeat requires a push based consumer
	JSConsumerHBRequiresPushErr ErrorIdentifier = 10088

	// JSConsumerInactiveThresholdExcess consumer inactive threshold exceeds system limit of {limit}
	JSConsumerInactiveThresholdExcess ErrorIdentifier = 10153

	// JSConsumerInvalidDeliverSubject invalid push consumer deliver subject
	JSConsumerInvalidDeliverSubject ErrorIdentifier = 10112

	// JSConsumerInvalidPolicyErrF Generic delivery policy error ({err})
	JSConsumerInvalidPolicyErrF ErrorIdentifier = 10094

	// JSConsumerInvalidSamplingErrF failed to parse consumer sampling configuration: {err}
	JSConsumerInvalidSamplingErrF ErrorIdentifier = 10095

	// JSConsumerMaxDeliverBackoffErr max deliver is required to be > length of backoff values
	JSConsumerMaxDeliverBackoffErr ErrorIdentifier = 10116

	// JSConsumerMaxPendingAckExcessErrF consumer max ack pending exceeds system limit of {limit}
	JSConsumerMaxPendingAckExcessErrF ErrorIdentifier = 10121

	// JSConsumerMaxPendingAckPolicyRequiredErr consumer requires ack policy for max ack pending
	JSConsumerMaxPendingAckPolicyRequiredErr ErrorIdentifier = 10082

	// JSConsumerMaxRequestBatchExceededF consumer max request batch exceeds server limit of {limit}
	JSConsumerMaxRequestBatchExceededF ErrorIdentifier = 10125

	// JSConsumerMaxRequestBatchNegativeErr consumer max request batch needs to be > 0
	JSConsumerMaxRequestBatchNegativeErr ErrorIdentifier = 10114

	// JSConsumerMaxRequestExpiresToSmall consumer max request expires needs to be >= 1ms
	JSConsumerMaxRequestExpiresToSmall ErrorIdentifier = 10115

	// JSConsumerMaxWaitingNegativeErr consumer max waiting needs to be positive
	JSConsumerMaxWaitingNegativeErr ErrorIdentifier = 10087

	// JSConsumerMetadataLengthErrF consumer metadata exceeds maximum size of {limit}
	JSConsumerMetadataLengthErrF ErrorIdentifier = 10135

	// JSConsumerMultipleFiltersNotAllowed consumer with multiple subject filters cannot use subject based API
	JSConsumerMultipleFiltersNotAllowed ErrorIdentifier = 10137

	// JSConsumerNameContainsPathSeparatorsErr Consumer name can not contain path separators
	JSConsumerNameContainsPathSeparatorsErr ErrorIdentifier = 10127

	// JSConsumerNameExistErr consumer name already in use
	JSConsumerNameExistErr ErrorIdentifier = 10013

	// JSConsumerNameTooLongErrF consumer name is too long, maximum allowed is {max}
	JSConsumerNameTooLongErrF ErrorIdentifier = 10102

	// JSConsumerNotFoundErr consumer not found
	JSConsumerNotFoundErr ErrorIdentifier = 10014

	// JSConsumerOfflineErr consumer is offline
	JSConsumerOfflineErr ErrorIdentifier = 10119

	// JSConsumerOnMappedErr consumer direct on a mapped consumer
	JSConsumerOnMappedErr ErrorIdentifier = 10092

	// JSConsumerOverlappingSubjectFilters consumer subject filters cannot overlap
	JSConsumerOverlappingSubjectFilters ErrorIdentifier = 10138

	// JSConsumerPullNotDurableErr consumer in pull mode requires a durable name
	JSConsumerPullNotDurableErr ErrorIdentifier = 10085

	// JSConsumerPullRequiresAckErr consumer in pull mode requires ack policy
	JSConsumerPullRequiresAckErr ErrorIdentifier = 10084

	// JSConsumerPullWithRateLimitErr consumer in pull mode can not have rate limit set
	JSConsumerPullWithRateLimitErr ErrorIdentifier = 10086

	// JSConsumerPushMaxWaitingErr consumer in push mode can not set max waiting
	JSConsumerPushMaxWaitingErr ErrorIdentifier = 10080

	// JSConsumerReplacementWithDifferentNameErr consumer replacement durable config not the same
	JSConsumerReplacementWithDifferentNameErr ErrorIdentifier = 10106

	// JSConsumerReplicasExceedsStream consumer config replica count exceeds parent stream
	JSConsumerReplicasExceedsStream ErrorIdentifier = 10126

	// JSConsumerReplicasShouldMatchStream consumer config replicas must match interest retention stream's replicas
	JSConsumerReplicasShouldMatchStream ErrorIdentifier = 10134

	// JSConsumerSmallHeartbeatErr consumer idle heartbeat needs to be >= 100ms
	JSConsumerSmallHeartbeatErr ErrorIdentifier = 10083

	// JSConsumerStoreFailedErrF error creating store for consumer: {err}
	JSConsumerStoreFailedErrF ErrorIdentifier = 10104

	// JSConsumerWQConsumerNotDeliverAllErr consumer must be deliver all on workqueue stream
	JSConsumerWQConsumerNotDeliverAllErr ErrorIdentifier = 10101

	// JSConsumerWQConsumerNotUniqueErr filtered consumer not unique on workqueue stream
	JSConsumerWQConsumerNotUniqueErr ErrorIdentifier = 10100

	// JSConsumerWQMultipleUnfilteredErr multiple non-filtered consumers not allowed on workqueue stream
	JSConsumerWQMultipleUnfilteredErr ErrorIdentifier = 10099

	// JSConsumerWQRequiresExplicitAckErr workqueue stream requires explicit ack
	JSConsumerWQRequiresExplicitAckErr ErrorIdentifier = 10098

	// JSConsumerWithFlowControlNeedsHeartbeats consumer with flow control also needs heartbeats
	JSConsumerWithFlowControlNeedsHeartbeats ErrorIdentifier = 10108

	// JSInsufficientResourcesErr insufficient resources
	JSInsufficientResourcesErr ErrorIdentifier = 10023

	// JSInvalidJSONErr invalid JSON
	JSInvalidJSONErr ErrorIdentifier = 10025

	// JSMaximumConsumersLimitErr maximum consumers limit reached
	JSMaximumConsumersLimitErr ErrorIdentifier = 10026

	// JSMaximumStreamsLimitErr maximum number of streams reached
	JSMaximumStreamsLimitErr ErrorIdentifier = 10027

	// JSMemoryResourcesExceededErr insufficient memory resources available
	JSMemoryResourcesExceededErr ErrorIdentifier = 10028

	// JSMirrorConsumerSetupFailedErrF generic mirror consumer setup failure string ({err})
	JSMirrorConsumerSetupFailedErrF ErrorIdentifier = 10029

	// JSMirrorInvalidStreamName mirrored stream name is invalid
	JSMirrorInvalidStreamName ErrorIdentifier = 10142

	// JSMirrorInvalidSubjectFilter mirror subject filter is invalid
	JSMirrorInvalidSubjectFilter ErrorIdentifier = 10151

	// JSMirrorMaxMessageSizeTooBigErr stream mirror must have max message size >= source
	JSMirrorMaxMessageSizeTooBigErr ErrorIdentifier = 10030

	// JSMirrorMultipleFiltersNotAllowed mirror with multiple subject transforms cannot also have a single subject filter
	JSMirrorMultipleFiltersNotAllowed ErrorIdentifier = 10150

	// JSMirrorOverlappingSubjectFilters mirror subject filters can not overlap
	JSMirrorOverlappingSubjectFilters ErrorIdentifier = 10152

	// JSMirrorWithFirstSeqErr stream mirrors can not have first sequence configured
	JSMirrorWithFirstSeqErr ErrorIdentifier = 10143

	// JSMirrorWithSourcesErr stream mirrors can not also contain other sources
	JSMirrorWithSourcesErr ErrorIdentifier = 10031

	// JSMirrorWithStartSeqAndTimeErr stream mirrors can not have both start seq and start time configured
	JSMirrorWithStartSeqAndTimeErr ErrorIdentifier = 10032

	// JSMirrorWithSubjectFiltersErr stream mirrors can not contain filtered subjects
	JSMirrorWithSubjectFiltersErr ErrorIdentifier = 10033

	// JSMirrorWithSubjectsErr stream mirrors can not contain subjects
	JSMirrorWithSubjectsErr ErrorIdentifier = 10034

	// JSNoAccountErr account not found
	JSNoAccountErr ErrorIdentifier = 10035

	// JSNoLimitsErr no JetStream default or applicable tiered limit present
	JSNoLimitsErr ErrorIdentifier = 10120

	// JSNoMessageFoundErr no message found
	JSNoMessageFoundErr ErrorIdentifier = 10037

	// JSNotEmptyRequestErr expected an empty request payload
	JSNotEmptyRequestErr ErrorIdentifier = 10038

	// JSNotEnabledErr JetStream not enabled
	JSNotEnabledErr ErrorIdentifier = 10076

	// JSNotEnabledForAccountErr JetStream not enabled for account
	JSNotEnabledForAccountErr ErrorIdentifier = 10039

	// JSPeerRemapErr peer remap failed
	JSPeerRemapErr ErrorIdentifier = 10075

	// JSRaftGeneralErrF General RAFT error string ({err})
	JSRaftGeneralErrF ErrorIdentifier = 10041

	// JSReplicasCountCannotBeNegative replicas count cannot be negative
	JSReplicasCountCannotBeNegative ErrorIdentifier = 10133

	// JSRestoreSubscribeFailedErrF JetStream unable to subscribe to restore snapshot {subject}: {err}
	JSRestoreSubscribeFailedErrF ErrorIdentifier = 10042

	// JSSequenceNotFoundErrF sequence {seq} not found
	JSSequenceNotFoundErrF ErrorIdentifier = 10043

	// JSSnapshotDeliverSubjectInvalidErr deliver subject not valid
	JSSnapshotDeliverSubjectInvalidErr ErrorIdentifier = 10015

	// JSSourceConsumerSetupFailedErrF General source consumer setup failure string ({err})
	JSSourceConsumerSetupFailedErrF ErrorIdentifier = 10045

	// JSSourceDuplicateDetected source stream, filter and transform (plus external if present) must form a unique combination (duplicate source configuration detected)
	JSSourceDuplicateDetected ErrorIdentifier = 10140

	// JSSourceInvalidStreamName sourced stream name is invalid
	JSSourceInvalidStreamName ErrorIdentifier = 10141

	// JSSourceInvalidSubjectFilter source subject filter is invalid
	JSSourceInvalidSubjectFilter ErrorIdentifier = 10145

	// JSSourceInvalidTransformDestination source transform destination is invalid
	JSSourceInvalidTransformDestination ErrorIdentifier = 10146

	// JSSourceMaxMessageSizeTooBigErr stream source must have max message size >= target
	JSSourceMaxMessageSizeTooBigErr ErrorIdentifier = 10046

	// JSSourceMultipleFiltersNotAllowed source with multiple subject transforms cannot also have a single subject filter
	JSSourceMultipleFiltersNotAllowed ErrorIdentifier = 10144

	// JSSourceOverlappingSubjectFilters source filters can not overlap
	JSSourceOverlappingSubjectFilters ErrorIdentifier = 10147

	// JSStorageResourcesExceededErr insufficient storage resources available
	JSStorageResourcesExceededErr ErrorIdentifier = 10047

	// JSStreamAssignmentErrF Generic stream assignment error string ({err})
	JSStreamAssignmentErrF ErrorIdentifier = 10048

	// JSStreamCreateErrF Generic stream creation error string ({err})
	JSStreamCreateErrF ErrorIdentifier = 10049

	// JSStreamDeleteErrF General stream deletion error string ({err})
	JSStreamDeleteErrF ErrorIdentifier = 10050

	// JSStreamExternalApiOverlapErrF stream external api prefix {prefix} must not overlap with {subject}
	JSStreamExternalApiOverlapErrF ErrorIdentifier = 10021

	// JSStreamExternalDelPrefixOverlapsErrF stream external delivery prefix {prefix} overlaps with stream subject {subject}
	JSStreamExternalDelPrefixOverlapsErrF ErrorIdentifier = 10022

	// JSStreamGeneralErrorF General stream failure string ({err})
	JSStreamGeneralErrorF ErrorIdentifier = 10051

	// JSStreamHeaderExceedsMaximumErr header size exceeds maximum allowed of 64k
	JSStreamHeaderExceedsMaximumErr ErrorIdentifier = 10097

	// JSStreamInfoMaxSubjectsErr subject details would exceed maximum allowed
	JSStreamInfoMaxSubjectsErr ErrorIdentifier = 10117

	// JSStreamInvalidConfigF Stream configuration validation error string ({err})
	JSStreamInvalidConfigF ErrorIdentifier = 10052

	// JSStreamInvalidErr stream not valid
	JSStreamInvalidErr ErrorIdentifier = 10096

	// JSStreamInvalidExternalDeliverySubjErrF stream external delivery prefix {prefix} must not contain wildcards
	JSStreamInvalidExternalDeliverySubjErrF ErrorIdentifier = 10024

	// JSStreamLimitsErrF General stream limits exceeded error string ({err})
	JSStreamLimitsErrF ErrorIdentifier = 10053

	// JSStreamMaxBytesRequired account requires a stream config to have max bytes set
	JSStreamMaxBytesRequired ErrorIdentifier = 10113

	// JSStreamMaxStreamBytesExceeded stream max bytes exceeds account limit max stream bytes
	JSStreamMaxStreamBytesExceeded ErrorIdentifier = 10122

	// JSStreamMessageExceedsMaximumErr message size exceeds maximum allowed
	JSStreamMessageExceedsMaximumErr ErrorIdentifier = 10054

	// JSStreamMirrorNotUpdatableErr stream mirror configuration can not be updated
	JSStreamMirrorNotUpdatableErr ErrorIdentifier = 10055

	// JSStreamMismatchErr stream name in subject does not match request
	JSStreamMismatchErr ErrorIdentifier = 10056

	// JSStreamMoveAndScaleErr can not move and scale a stream in a single update
	JSStreamMoveAndScaleErr ErrorIdentifier = 10123

	// JSStreamMoveInProgressF stream move already in progress: {msg}
	JSStreamMoveInProgressF ErrorIdentifier = 10124

	// JSStreamMoveNotInProgress stream move not in progress
	JSStreamMoveNotInProgress ErrorIdentifier = 10129

	// JSStreamMsgDeleteFailedF Generic message deletion failure error string ({err})
	JSStreamMsgDeleteFailedF ErrorIdentifier = 10057

	// JSStreamNameContainsPathSeparatorsErr Stream name can not contain path separators
	JSStreamNameContainsPathSeparatorsErr ErrorIdentifier = 10128

	// JSStreamNameExistErr stream name already in use with a different configuration
	JSStreamNameExistErr ErrorIdentifier = 10058

	// JSStreamNameExistRestoreFailedErr stream name already in use, cannot restore
	JSStreamNameExistRestoreFailedErr ErrorIdentifier = 10130

	// JSStreamNotFoundErr stream not found
	JSStreamNotFoundErr ErrorIdentifier = 10059

	// JSStreamNotMatchErr expected stream does not match
	JSStreamNotMatchErr ErrorIdentifier = 10060

	// JSStreamOfflineErr stream is offline
	JSStreamOfflineErr ErrorIdentifier = 10118

	// JSStreamPurgeFailedF Generic stream purge failure error string ({err})
	JSStreamPurgeFailedF ErrorIdentifier = 10110

	// JSStreamReplicasNotSupportedErr replicas > 1 not supported in non-clustered mode
	JSStreamReplicasNotSupportedErr ErrorIdentifier = 10074

	// JSStreamReplicasNotUpdatableErr Replicas configuration can not be updated
	JSStreamReplicasNotUpdatableErr ErrorIdentifier = 10061

	// JSStreamRestoreErrF restore failed: {err}
	JSStreamRestoreErrF ErrorIdentifier = 10062

	// JSStreamRollupFailedF Generic stream rollup failure error string ({err})
	JSStreamRollupFailedF ErrorIdentifier = 10111

	// JSStreamSealedErr invalid operation on sealed stream
	JSStreamSealedErr ErrorIdentifier = 10109

	// JSStreamSequenceNotMatchErr expected stream sequence does not match
	JSStreamSequenceNotMatchErr ErrorIdentifier = 10063

	// JSStreamSnapshotErrF snapshot failed: {err}
	JSStreamSnapshotErrF ErrorIdentifier = 10064

	// JSStreamStoreFailedF Generic error when storing a message failed ({err})
	JSStreamStoreFailedF ErrorIdentifier = 10077

	// JSStreamSubjectOverlapErr subjects overlap with an existing stream
	JSStreamSubjectOverlapErr ErrorIdentifier = 10065

	// JSStreamTemplateCreateErrF Generic template creation failed string ({err})
	JSStreamTemplateCreateErrF ErrorIdentifier = 10066

	// JSStreamTemplateDeleteErrF Generic stream template deletion failed error string ({err})
	JSStreamTemplateDeleteErrF ErrorIdentifier = 10067

	// JSStreamTemplateNotFoundErr template not found
	JSStreamTemplateNotFoundErr ErrorIdentifier = 10068

	// JSStreamUpdateErrF Generic stream update error string ({err})
	JSStreamUpdateErrF ErrorIdentifier = 10069

	// JSStreamWrongLastMsgIDErrF wrong last msg ID: {id}
	JSStreamWrongLastMsgIDErrF ErrorIdentifier = 10070

	// JSStreamWrongLastSequenceErrF wrong last sequence: {seq}
	JSStreamWrongLastSequenceErrF ErrorIdentifier = 10071

	// JSTempStorageFailedErr JetStream unable to open temp storage for restore
	JSTempStorageFailedErr ErrorIdentifier = 10072

	// JSTemplateNameNotMatchSubjectErr template name in subject does not match request
	JSTemplateNameNotMatchSubjectErr ErrorIdentifier = 10073
)

type ErrorOption added in v2.4.0

type ErrorOption func(*errOpts)

ErrorOption configures a NATS Error helper

func Unless added in v2.4.0

func Unless(err error) ErrorOption

Unless ensures that if err is a ApiErr that err will be returned rather than the one being created via the helper

type ErrorsData added in v2.3.0

type ErrorsData struct {
	Constant    string `json:"constant"`
	Code        int    `json:"code"`
	ErrCode     uint16 `json:"error_code"`
	Description string `json:"description"`
	Comment     string `json:"comment"`
	Help        string `json:"help"`
	URL         string `json:"url"`
	Deprecates  string `json:"deprecates"`
}

ErrorsData is the source data for generated errors as found in errors.json

type EventFilterOptions added in v2.2.0

type EventFilterOptions struct {
	Name    string   `json:"server_name,omitempty"` // filter by server name
	Cluster string   `json:"cluster,omitempty"`     // filter by cluster name
	Host    string   `json:"host,omitempty"`        // filter by host name
	Tags    []string `json:"tags,omitempty"`        // filter by tags (must match all tags)
	Domain  string   `json:"domain,omitempty"`      // filter by JS domain
}

Common filter options for system requests STATSZ VARZ SUBSZ CONNZ ROUTEZ GATEWAYZ LEAFZ

type ExpvarzEventOptions added in v2.10.15

type ExpvarzEventOptions struct {
	EventFilterOptions
}

In the context of system events, ExpvarzEventOptions are options passed to Expvarz

type ExpvarzStatus added in v2.10.15

type ExpvarzStatus struct {
	Memstats json.RawMessage `json:"memstats"`
	Cmdline  json.RawMessage `json:"cmdline"`
}

type ExtExport added in v2.2.0

type ExtExport struct {
	jwt.Export
	ApprovedAccounts []string             `json:"approved_accounts,omitempty"`
	RevokedAct       map[string]time.Time `json:"revoked_activations,omitempty"`
}

type ExtImport added in v2.2.0

type ExtImport struct {
	jwt.Import
	Invalid     bool                `json:"invalid"`
	Share       bool                `json:"share"`
	Tracking    bool                `json:"tracking"`
	TrackingHdr http.Header         `json:"tracking_header,omitempty"`
	Latency     *jwt.ServiceLatency `json:"latency,omitempty"`
	M1          *ServiceLatency     `json:"m1,omitempty"`
}

type ExtMap added in v2.2.0

type ExtMap map[string][]*MapDest

type ExtVrIssues added in v2.2.0

type ExtVrIssues struct {
	Description string `json:"description"`
	Blocking    bool   `json:"blocking"`
	Time        bool   `json:"time_check"`
}

type ExternalStream added in v2.2.0

type ExternalStream struct {
	ApiPrefix     string `json:"api"`
	DeliverPrefix string `json:"deliver"`
}

ExternalStream allows you to qualify access to a stream source in another account.

type FileConsumerInfo added in v2.2.0

type FileConsumerInfo struct {
	Created time.Time
	Name    string
	ConsumerConfig
}

File ConsumerInfo is used for creating consumer stores.

type FileStoreConfig added in v2.2.0

type FileStoreConfig struct {
	// Where the parent directory for all storage will be located.
	StoreDir string
	// BlockSize is the file block size. This also represents the maximum overhead size.
	BlockSize uint64
	// CacheExpire is how long with no activity until we expire the cache.
	CacheExpire time.Duration
	// SubjectStateExpire is how long with no activity until we expire a msg block's subject state.
	SubjectStateExpire time.Duration
	// SyncInterval is how often we sync to disk in the background.
	SyncInterval time.Duration
	// SyncAlways is when the stream should sync all data writes.
	SyncAlways bool
	// AsyncFlush allows async flush to batch write operations.
	AsyncFlush bool
	// Cipher is the cipher to use when encrypting.
	Cipher StoreCipher
	// Compression is the algorithm to use when compressing.
	Compression StoreCompression
	// contains filtered or unexported fields
}

type FileStreamInfo added in v2.2.0

type FileStreamInfo struct {
	Created time.Time
	StreamConfig
}

FileStreamInfo allows us to remember created time.

type GatewayInterestMode

type GatewayInterestMode byte

GatewayInterestMode represents an account interest mode for a gateway connection

const (
	// optimistic is the default mode where a cluster will send
	// to a gateway unless it is been told that there is no interest
	// (this is for plain subscribers only).
	Optimistic GatewayInterestMode = iota
	// transitioning is when a gateway has to send too many
	// no interest on subjects to the remote and decides that it is
	// now time to move to modeInterestOnly (this is on a per account
	// basis).
	Transitioning
	// interestOnly means that a cluster sends all it subscriptions
	// interest to the gateway, which in return does not send a message
	// unless it knows that there is explicit interest.
	InterestOnly
)

GatewayInterestMode values

func (GatewayInterestMode) String

func (im GatewayInterestMode) String() string

type GatewayOpts

type GatewayOpts struct {
	Name              string               `json:"name"`
	Host              string               `json:"addr,omitempty"`
	Port              int                  `json:"port,omitempty"`
	Username          string               `json:"-"`
	Password          string               `json:"-"`
	AuthTimeout       float64              `json:"auth_timeout,omitempty"`
	TLSConfig         *tls.Config          `json:"-"`
	TLSTimeout        float64              `json:"tls_timeout,omitempty"`
	TLSMap            bool                 `json:"-"`
	TLSCheckKnownURLs bool                 `json:"-"`
	TLSPinnedCerts    PinnedCertSet        `json:"-"`
	Advertise         string               `json:"advertise,omitempty"`
	ConnectRetries    int                  `json:"connect_retries,omitempty"`
	Gateways          []*RemoteGatewayOpts `json:"gateways,omitempty"`
	RejectUnknown     bool                 `json:"reject_unknown,omitempty"` // config got renamed to reject_unknown_cluster
	// contains filtered or unexported fields
}

GatewayOpts are options for gateways. NOTE: This structure is no longer used for monitoring endpoints and json tags are deprecated and may be removed in the future.

type GatewayOptsVarz

type GatewayOptsVarz struct {
	Name           string                  `json:"name,omitempty"`
	Host           string                  `json:"host,omitempty"`
	Port           int                     `json:"port,omitempty"`
	AuthTimeout    float64                 `json:"auth_timeout,omitempty"`
	TLSTimeout     float64                 `json:"tls_timeout,omitempty"`
	TLSRequired    bool                    `json:"tls_required,omitempty"`
	TLSVerify      bool                    `json:"tls_verify,omitempty"`
	Advertise      string                  `json:"advertise,omitempty"`
	ConnectRetries int                     `json:"connect_retries,omitempty"`
	Gateways       []RemoteGatewayOptsVarz `json:"gateways,omitempty"`
	RejectUnknown  bool                    `json:"reject_unknown,omitempty"` // config got renamed to reject_unknown_cluster
}

GatewayOptsVarz contains monitoring gateway information

type GatewayStat

type GatewayStat struct {
	ID         uint64    `json:"gwid"`
	Name       string    `json:"name"`
	Sent       DataStats `json:"sent"`
	Received   DataStats `json:"received"`
	NumInbound int       `json:"inbound_connections"`
}

GatewayStat holds gateway statistics.

type Gatewayz

type Gatewayz struct {
	ID               string                       `json:"server_id"`
	Now              time.Time                    `json:"now"`
	Name             string                       `json:"name,omitempty"`
	Host             string                       `json:"host,omitempty"`
	Port             int                          `json:"port,omitempty"`
	OutboundGateways map[string]*RemoteGatewayz   `json:"outbound_gateways"`
	InboundGateways  map[string][]*RemoteGatewayz `json:"inbound_gateways"`
}

Gatewayz represents detailed information on Gateways

type GatewayzEventOptions added in v2.2.0

type GatewayzEventOptions struct {
	GatewayzOptions
	EventFilterOptions
}

In the context of system events, GatewayzEventOptions are options passed to Gatewayz

type GatewayzOptions

type GatewayzOptions struct {
	// Name will output only remote gateways with this name
	Name string `json:"name"`

	// Accounts indicates if accounts with its interest should be included in the results.
	Accounts bool `json:"accounts"`

	// AccountName will limit the list of accounts to that account name (makes Accounts implicit)
	AccountName string `json:"account_name"`
}

GatewayzOptions are the options passed to Gatewayz()

type HealthStatus added in v2.7.1

type HealthStatus struct {
	Status     string         `json:"status"`
	StatusCode int            `json:"status_code,omitempty"`
	Error      string         `json:"error,omitempty"`
	Errors     []HealthzError `json:"errors,omitempty"`
}

type HealthZErrorType added in v2.10.0

type HealthZErrorType int
const (
	HealthzErrorConn HealthZErrorType = iota
	HealthzErrorBadRequest
	HealthzErrorJetStream
	HealthzErrorAccount
	HealthzErrorStream
	HealthzErrorConsumer
)

func (HealthZErrorType) MarshalJSON added in v2.10.0

func (t HealthZErrorType) MarshalJSON() ([]byte, error)

func (HealthZErrorType) String added in v2.10.0

func (t HealthZErrorType) String() string

func (*HealthZErrorType) UnmarshalJSON added in v2.10.0

func (t *HealthZErrorType) UnmarshalJSON(data []byte) error

type HealthzError added in v2.10.0

type HealthzError struct {
	Type     HealthZErrorType `json:"type"`
	Account  string           `json:"account,omitempty"`
	Stream   string           `json:"stream,omitempty"`
	Consumer string           `json:"consumer,omitempty"`
	Error    string           `json:"error,omitempty"`
}

type HealthzEventOptions added in v2.9.0

type HealthzEventOptions struct {
	HealthzOptions
	EventFilterOptions
}

In the context of system events, HealthzEventOptions are options passed to Healthz

type HealthzOptions added in v2.9.0

type HealthzOptions struct {
	// Deprecated: Use JSEnabledOnly instead
	JSEnabled     bool   `json:"js-enabled,omitempty"`
	JSEnabledOnly bool   `json:"js-enabled-only,omitempty"`
	JSServerOnly  bool   `json:"js-server-only,omitempty"`
	Account       string `json:"account,omitempty"`
	Stream        string `json:"stream,omitempty"`
	Consumer      string `json:"consumer,omitempty"`
	Details       bool   `json:"details,omitempty"`
}

HealthzOptions are options passed to Healthz

type Info

type Info struct {
	ID                string   `json:"server_id"`
	Name              string   `json:"server_name"`
	Version           string   `json:"version"`
	Proto             int      `json:"proto"`
	GitCommit         string   `json:"git_commit,omitempty"`
	GoVersion         string   `json:"go"`
	Host              string   `json:"host"`
	Port              int      `json:"port"`
	Headers           bool     `json:"headers"`
	AuthRequired      bool     `json:"auth_required,omitempty"`
	TLSRequired       bool     `json:"tls_required,omitempty"`
	TLSVerify         bool     `json:"tls_verify,omitempty"`
	TLSAvailable      bool     `json:"tls_available,omitempty"`
	MaxPayload        int32    `json:"max_payload"`
	JetStream         bool     `json:"jetstream,omitempty"`
	IP                string   `json:"ip,omitempty"`
	CID               uint64   `json:"client_id,omitempty"`
	ClientIP          string   `json:"client_ip,omitempty"`
	Nonce             string   `json:"nonce,omitempty"`
	Cluster           string   `json:"cluster,omitempty"`
	Dynamic           bool     `json:"cluster_dynamic,omitempty"`
	Domain            string   `json:"domain,omitempty"`
	ClientConnectURLs []string `json:"connect_urls,omitempty"`    // Contains URLs a client can connect to.
	WSConnectURLs     []string `json:"ws_connect_urls,omitempty"` // Contains URLs a ws client can connect to.
	LameDuckMode      bool     `json:"ldm,omitempty"`
	Compression       string   `json:"compression,omitempty"`

	// Route Specific
	Import        *SubjectPermission `json:"import,omitempty"`
	Export        *SubjectPermission `json:"export,omitempty"`
	LNOC          bool               `json:"lnoc,omitempty"`
	LNOCU         bool               `json:"lnocu,omitempty"`
	InfoOnConnect bool               `json:"info_on_connect,omitempty"` // When true the server will respond to CONNECT with an INFO
	ConnectInfo   bool               `json:"connect_info,omitempty"`    // When true this is the server INFO response to CONNECT
	RoutePoolSize int                `json:"route_pool_size,omitempty"`
	RoutePoolIdx  int                `json:"route_pool_idx,omitempty"`
	RouteAccount  string             `json:"route_account,omitempty"`
	RouteAccReqID string             `json:"route_acc_add_reqid,omitempty"`

	// Gateways Specific
	Gateway           string   `json:"gateway,omitempty"`             // Name of the origin Gateway (sent by gateway's INFO)
	GatewayURLs       []string `json:"gateway_urls,omitempty"`        // Gateway URLs in the originating cluster (sent by gateway's INFO)
	GatewayURL        string   `json:"gateway_url,omitempty"`         // Gateway URL on that server (sent by route's INFO)
	GatewayCmd        byte     `json:"gateway_cmd,omitempty"`         // Command code for the receiving server to know what to do
	GatewayCmdPayload []byte   `json:"gateway_cmd_payload,omitempty"` // Command payload when needed
	GatewayNRP        bool     `json:"gateway_nrp,omitempty"`         // Uses new $GNR. prefix for mapped replies
	GatewayIOM        bool     `json:"gateway_iom,omitempty"`         // Indicate that all accounts will be switched to InterestOnly mode "right away"

	// LeafNode Specific
	LeafNodeURLs  []string `json:"leafnode_urls,omitempty"`  // LeafNode URLs that the server can reconnect to.
	RemoteAccount string   `json:"remote_account,omitempty"` // Lets the other side know the remote account that they bind to.

	XKey string `json:"xkey,omitempty"` // Public server's x25519 key.
}

Info is the information sent to clients, routes, gateways, and leaf nodes, to help them understand information about this server.

type JSAPIAudit added in v2.2.0

type JSAPIAudit struct {
	TypedEvent
	Server   string      `json:"server"`
	Client   *ClientInfo `json:"client"`
	Subject  string      `json:"subject"`
	Request  string      `json:"request,omitempty"`
	Response string      `json:"response"`
	Domain   string      `json:"domain,omitempty"`
}

JSAPIAudit is an advisory about administrative actions taken on JetStream

type JSAPILimitReachedAdvisory added in v2.10.21

type JSAPILimitReachedAdvisory struct {
	TypedEvent
	Server  string `json:"server"`           // Server that created the event, name or ID
	Domain  string `json:"domain,omitempty"` // Domain the server belongs to
	Dropped int64  `json:"dropped"`          // How many messages did we drop from the queue
}

JSAPILimitReachedAdvisory is a advisory published when JetStream hits the queue length limit.

type JSApiAccountInfoResponse added in v2.2.0

type JSApiAccountInfoResponse struct {
	ApiResponse
	*JetStreamAccountStats
}

JSApiAccountInfoResponse reports back information on jetstream for this account.

type JSApiAccountPurgeResponse added in v2.9.0

type JSApiAccountPurgeResponse struct {
	ApiResponse
	Initiated bool `json:"initiated,omitempty"`
}

JSApiAccountPurgeResponse is the response to a purge request in the meta group.

type JSApiConsumerCreateResponse added in v2.2.0

type JSApiConsumerCreateResponse struct {
	ApiResponse
	*ConsumerInfo
}

type JSApiConsumerDeleteResponse added in v2.2.0

type JSApiConsumerDeleteResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

type JSApiConsumerGetNextRequest added in v2.2.0

type JSApiConsumerGetNextRequest struct {
	Expires   time.Duration `json:"expires,omitempty"`
	Batch     int           `json:"batch,omitempty"`
	MaxBytes  int           `json:"max_bytes,omitempty"`
	NoWait    bool          `json:"no_wait,omitempty"`
	Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
}

JSApiConsumerGetNextRequest is for getting next messages for pull based consumers.

type JSApiConsumerInfoResponse added in v2.2.0

type JSApiConsumerInfoResponse struct {
	ApiResponse
	*ConsumerInfo
}

type JSApiConsumerLeaderStepDownResponse added in v2.2.0

type JSApiConsumerLeaderStepDownResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiConsumerLeaderStepDownResponse is the response to a consumer leader stepdown request.

type JSApiConsumerListResponse added in v2.2.0

type JSApiConsumerListResponse struct {
	ApiResponse
	ApiPaged
	Consumers []*ConsumerInfo `json:"consumers"`
	Missing   []string        `json:"missing,omitempty"`
}

type JSApiConsumerNamesResponse added in v2.2.0

type JSApiConsumerNamesResponse struct {
	ApiResponse
	ApiPaged
	Consumers []string `json:"consumers"`
}

type JSApiConsumersRequest added in v2.2.0

type JSApiConsumersRequest struct {
	ApiPagedRequest
}

type JSApiLeaderStepDownResponse added in v2.2.0

type JSApiLeaderStepDownResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiLeaderStepDownResponse is the response to a meta leader stepdown request.

type JSApiLeaderStepdownRequest added in v2.2.0

type JSApiLeaderStepdownRequest struct {
	Placement *Placement `json:"placement,omitempty"`
}

JSApiLeaderStepdownRequest allows placement control over the meta leader placement.

type JSApiMetaServerRemoveRequest added in v2.2.0

type JSApiMetaServerRemoveRequest struct {
	// Server name of the peer to be removed.
	Server string `json:"peer"`
	// Peer ID of the peer to be removed. If specified this is used
	// instead of the server name.
	Peer string `json:"peer_id,omitempty"`
}

JSApiMetaServerRemoveRequest will remove a peer from the meta group.

type JSApiMetaServerRemoveResponse added in v2.2.0

type JSApiMetaServerRemoveResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiMetaServerRemoveResponse is the response to a peer removal request in the meta group.

type JSApiMetaServerStreamMoveRequest added in v2.9.0

type JSApiMetaServerStreamMoveRequest struct {
	// Server name of the peer to be evacuated.
	Server string `json:"server,omitempty"`
	// Cluster the server is in
	Cluster string `json:"cluster,omitempty"`
	// Domain the sever is in
	Domain string `json:"domain,omitempty"`
	// Ephemeral placement tags for the move
	Tags []string `json:"tags,omitempty"`
}

JSApiMetaServerStreamMoveRequest will move a stream on a server to another response to this will come as JSApiStreamUpdateResponse/JSApiStreamUpdateResponseType

type JSApiMsgDeleteRequest added in v2.2.0

type JSApiMsgDeleteRequest struct {
	Seq     uint64 `json:"seq"`
	NoErase bool   `json:"no_erase,omitempty"`
}

JSApiMsgDeleteRequest delete message request.

type JSApiMsgDeleteResponse added in v2.2.0

type JSApiMsgDeleteResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

type JSApiMsgGetRequest added in v2.2.0

type JSApiMsgGetRequest struct {
	Seq     uint64 `json:"seq,omitempty"`
	LastFor string `json:"last_by_subj,omitempty"`
	NextFor string `json:"next_by_subj,omitempty"`
}

JSApiMsgGetRequest get a message request.

type JSApiMsgGetResponse added in v2.2.0

type JSApiMsgGetResponse struct {
	ApiResponse
	Message *StoredMsg `json:"message,omitempty"`
}

type JSApiStreamCreateResponse added in v2.2.0

type JSApiStreamCreateResponse struct {
	ApiResponse
	*StreamInfo
	DidCreate bool `json:"did_create,omitempty"`
}

JSApiStreamCreateResponse stream creation.

type JSApiStreamDeleteResponse added in v2.2.0

type JSApiStreamDeleteResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiStreamDeleteResponse stream removal.

type JSApiStreamInfoRequest added in v2.2.2

type JSApiStreamInfoRequest struct {
	ApiPagedRequest
	DeletedDetails bool   `json:"deleted_details,omitempty"`
	SubjectsFilter string `json:"subjects_filter,omitempty"`
}

type JSApiStreamInfoResponse added in v2.2.0

type JSApiStreamInfoResponse struct {
	ApiResponse
	ApiPaged
	*StreamInfo
}

type JSApiStreamLeaderStepDownResponse added in v2.2.0

type JSApiStreamLeaderStepDownResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiStreamLeaderStepDownResponse is the response to a leader stepdown request.

type JSApiStreamListRequest added in v2.6.5

type JSApiStreamListRequest struct {
	ApiPagedRequest
	// These are filters that can be applied to the list.
	Subject string `json:"subject,omitempty"`
}

type JSApiStreamListResponse added in v2.2.0

type JSApiStreamListResponse struct {
	ApiResponse
	ApiPaged
	Streams []*StreamInfo `json:"streams"`
	Missing []string      `json:"missing,omitempty"`
}

JSApiStreamListResponse list of detailed stream information. A nil request is valid and means all streams.

type JSApiStreamNamesRequest added in v2.2.0

type JSApiStreamNamesRequest struct {
	ApiPagedRequest
	// These are filters that can be applied to the list.
	Subject string `json:"subject,omitempty"`
}

type JSApiStreamNamesResponse added in v2.2.0

type JSApiStreamNamesResponse struct {
	ApiResponse
	ApiPaged
	Streams []string `json:"streams"`
}

JSApiStreamNamesResponse list of streams. A nil request is valid and means all streams.

type JSApiStreamPurgeRequest added in v2.3.0

type JSApiStreamPurgeRequest struct {
	// Purge up to but not including sequence.
	Sequence uint64 `json:"seq,omitempty"`
	// Subject to match against messages for the purge command.
	Subject string `json:"filter,omitempty"`
	// Number of messages to keep.
	Keep uint64 `json:"keep,omitempty"`
}

JSApiStreamPurgeRequest is optional request information to the purge API. Subject will filter the purge request to only messages that match the subject, which can have wildcards. Sequence will purge up to but not including this sequence and can be combined with subject filtering. Keep will specify how many messages to keep. This can also be combined with subject filtering. Note that Sequence and Keep are mutually exclusive, so both can not be set at the same time.

type JSApiStreamPurgeResponse added in v2.2.0

type JSApiStreamPurgeResponse struct {
	ApiResponse
	Success bool   `json:"success,omitempty"`
	Purged  uint64 `json:"purged"`
}

type JSApiStreamRemovePeerRequest added in v2.2.0

type JSApiStreamRemovePeerRequest struct {
	// Server name of the peer to be removed.
	Peer string `json:"peer"`
}

JSApiStreamRemovePeerRequest is the required remove peer request.

type JSApiStreamRemovePeerResponse added in v2.2.0

type JSApiStreamRemovePeerResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

JSApiStreamRemovePeerResponse is the response to a remove peer request.

type JSApiStreamRestoreRequest added in v2.2.0

type JSApiStreamRestoreRequest struct {
	// Configuration of the given stream.
	Config StreamConfig `json:"config"`
	// Current State for the given stream.
	State StreamState `json:"state"`
}

JSApiStreamRestoreRequest is the required restore request.

type JSApiStreamRestoreResponse added in v2.2.0

type JSApiStreamRestoreResponse struct {
	ApiResponse
	// Subject to deliver the chunks to for the snapshot restore.
	DeliverSubject string `json:"deliver_subject"`
}

JSApiStreamRestoreResponse is the direct response to the restore request.

type JSApiStreamSnapshotRequest added in v2.2.0

type JSApiStreamSnapshotRequest struct {
	// Subject to deliver the chunks to for the snapshot.
	DeliverSubject string `json:"deliver_subject"`
	// Do not include consumers in the snapshot.
	NoConsumers bool `json:"no_consumers,omitempty"`
	// Optional chunk size preference.
	// Best to just let server select.
	ChunkSize int `json:"chunk_size,omitempty"`
	// Check all message's checksums prior to snapshot.
	CheckMsgs bool `json:"jsck,omitempty"`
}

type JSApiStreamSnapshotResponse added in v2.2.0

type JSApiStreamSnapshotResponse struct {
	ApiResponse
	// Configuration of the given stream.
	Config *StreamConfig `json:"config,omitempty"`
	// Current State for the given stream.
	State *StreamState `json:"state,omitempty"`
}

JSApiStreamSnapshotResponse is the direct response to the snapshot request.

type JSApiStreamTemplateCreateResponse added in v2.2.0

type JSApiStreamTemplateCreateResponse struct {
	ApiResponse
	*StreamTemplateInfo
}

JSApiStreamTemplateCreateResponse for creating templates.

type JSApiStreamTemplateDeleteResponse added in v2.2.0

type JSApiStreamTemplateDeleteResponse struct {
	ApiResponse
	Success bool `json:"success,omitempty"`
}

type JSApiStreamTemplateInfoResponse added in v2.2.0

type JSApiStreamTemplateInfoResponse struct {
	ApiResponse
	*StreamTemplateInfo
}

JSApiStreamTemplateInfoResponse for information about stream templates.

type JSApiStreamTemplateNamesResponse added in v2.2.0

type JSApiStreamTemplateNamesResponse struct {
	ApiResponse
	ApiPaged
	Templates []string `json:"streams"`
}

JSApiStreamTemplateNamesResponse list of templates

type JSApiStreamTemplatesRequest added in v2.2.0

type JSApiStreamTemplatesRequest struct {
	ApiPagedRequest
}

type JSApiStreamUpdateResponse added in v2.2.0

type JSApiStreamUpdateResponse struct {
	ApiResponse
	*StreamInfo
}

JSApiStreamUpdateResponse for updating a stream.

type JSConsumerAckMetric added in v2.2.0

type JSConsumerAckMetric struct {
	TypedEvent
	Stream      string `json:"stream"`
	Consumer    string `json:"consumer"`
	ConsumerSeq uint64 `json:"consumer_seq"`
	StreamSeq   uint64 `json:"stream_seq"`
	Delay       int64  `json:"ack_time"`
	Deliveries  uint64 `json:"deliveries"`
	Domain      string `json:"domain,omitempty"`
}

JSConsumerAckMetric is a metric published when a user acknowledges a message, the number of these that will be published is dependent on SampleFrequency

type JSConsumerActionAdvisory added in v2.2.0

type JSConsumerActionAdvisory struct {
	TypedEvent
	Stream   string             `json:"stream"`
	Consumer string             `json:"consumer"`
	Action   ActionAdvisoryType `json:"action"`
	Domain   string             `json:"domain,omitempty"`
}

JSConsumerActionAdvisory indicates that a consumer was created or deleted

type JSConsumerDeliveryExceededAdvisory added in v2.2.0

type JSConsumerDeliveryExceededAdvisory struct {
	TypedEvent
	Stream     string `json:"stream"`
	Consumer   string `json:"consumer"`
	StreamSeq  uint64 `json:"stream_seq"`
	Deliveries uint64 `json:"deliveries"`
	Domain     string `json:"domain,omitempty"`
}

JSConsumerDeliveryExceededAdvisory is an advisory informing that a message hit its MaxDeliver threshold and so might be a candidate for DLQ handling

type JSConsumerDeliveryNakAdvisory added in v2.8.2

type JSConsumerDeliveryNakAdvisory struct {
	TypedEvent
	Stream      string `json:"stream"`
	Consumer    string `json:"consumer"`
	ConsumerSeq uint64 `json:"consumer_seq"`
	StreamSeq   uint64 `json:"stream_seq"`
	Deliveries  uint64 `json:"deliveries"`
	Domain      string `json:"domain,omitempty"`
}

JSConsumerDeliveryNakAdvisory is an advisory informing that a message was naked by the consumer

type JSConsumerDeliveryTerminatedAdvisory added in v2.2.0

type JSConsumerDeliveryTerminatedAdvisory struct {
	TypedEvent
	Stream      string `json:"stream"`
	Consumer    string `json:"consumer"`
	ConsumerSeq uint64 `json:"consumer_seq"`
	StreamSeq   uint64 `json:"stream_seq"`
	Deliveries  uint64 `json:"deliveries"`
	Reason      string `json:"reason,omitempty"`
	Domain      string `json:"domain,omitempty"`
}

JSConsumerDeliveryTerminatedAdvisory is an advisory informing that a message was terminated by the consumer, so might be a candidate for DLQ handling

type JSConsumerLeaderElectedAdvisory added in v2.2.0

type JSConsumerLeaderElectedAdvisory struct {
	TypedEvent
	Account  string      `json:"account,omitempty"`
	Stream   string      `json:"stream"`
	Consumer string      `json:"consumer"`
	Leader   string      `json:"leader"`
	Replicas []*PeerInfo `json:"replicas"`
	Domain   string      `json:"domain,omitempty"`
}

JSConsumerLeaderElectedAdvisory indicates that a consumer has elected a new leader.

type JSConsumerQuorumLostAdvisory added in v2.2.0

type JSConsumerQuorumLostAdvisory struct {
	TypedEvent
	Account  string      `json:"account,omitempty"`
	Stream   string      `json:"stream"`
	Consumer string      `json:"consumer"`
	Replicas []*PeerInfo `json:"replicas"`
	Domain   string      `json:"domain,omitempty"`
}

JSConsumerQuorumLostAdvisory indicates that a consumer has lost quorum and is stalled.

type JSDomainLeaderElectedAdvisory added in v2.10.11

type JSDomainLeaderElectedAdvisory struct {
	TypedEvent
	Leader   string      `json:"leader"`
	Replicas []*PeerInfo `json:"replicas"`
	Cluster  string      `json:"cluster"`
	Domain   string      `json:"domain,omitempty"`
}

JSClusterLeaderElectedAdvisory indicates that a domain has elected a new leader.

type JSInfo added in v2.2.0

type JSInfo struct {
	ID       string          `json:"server_id"`
	Now      time.Time       `json:"now"`
	Disabled bool            `json:"disabled,omitempty"`
	Config   JetStreamConfig `json:"config,omitempty"`
	JetStreamStats
	Streams   int              `json:"streams"`
	Consumers int              `json:"consumers"`
	Messages  uint64           `json:"messages"`
	Bytes     uint64           `json:"bytes"`
	Meta      *MetaClusterInfo `json:"meta_cluster,omitempty"`

	// aggregate raft info
	AccountDetails []*AccountDetail `json:"account_details,omitempty"`
}

JSInfo has detailed information on JetStream.

type JSLimitOpts added in v2.8.0

type JSLimitOpts struct {
	MaxRequestBatch int
	MaxAckPending   int
	MaxHAAssets     int
	Duplicates      time.Duration
}

type JSPubAckResponse added in v2.2.0

type JSPubAckResponse struct {
	Error *ApiError `json:"error,omitempty"`
	*PubAck
}

JSPubAckResponse is a formal response to a publish operation.

func (*JSPubAckResponse) ToError added in v2.3.0

func (r *JSPubAckResponse) ToError() error

ToError checks if the response has a error and if it does converts it to an error avoiding the pitfalls described by https://yourbasic.org/golang/gotcha-why-nil-error-not-equal-nil/

type JSRestoreCompleteAdvisory added in v2.2.0

type JSRestoreCompleteAdvisory struct {
	TypedEvent
	Stream string      `json:"stream"`
	Start  time.Time   `json:"start"`
	End    time.Time   `json:"end"`
	Bytes  int64       `json:"bytes"`
	Client *ClientInfo `json:"client"`
	Domain string      `json:"domain,omitempty"`
}

JSRestoreCompleteAdvisory is an advisory sent after a snapshot is successfully started

type JSRestoreCreateAdvisory added in v2.2.0

type JSRestoreCreateAdvisory struct {
	TypedEvent
	Stream string      `json:"stream"`
	Client *ClientInfo `json:"client"`
	Domain string      `json:"domain,omitempty"`
}

JSRestoreCreateAdvisory is an advisory sent after a snapshot is successfully started

type JSServerOutOfSpaceAdvisory added in v2.2.0

type JSServerOutOfSpaceAdvisory struct {
	TypedEvent
	Server   string `json:"server"`
	ServerID string `json:"server_id"`
	Stream   string `json:"stream,omitempty"`
	Cluster  string `json:"cluster"`
	Domain   string `json:"domain,omitempty"`
}

JSServerOutOfSpaceAdvisory indicates that a stream has lost quorum and is stalled.

type JSServerRemovedAdvisory added in v2.2.0

type JSServerRemovedAdvisory struct {
	TypedEvent
	Server   string `json:"server"`
	ServerID string `json:"server_id"`
	Cluster  string `json:"cluster"`
	Domain   string `json:"domain,omitempty"`
}

JSServerRemovedAdvisory indicates that a stream has lost quorum and is stalled.

type JSSnapshotCompleteAdvisory added in v2.2.0

type JSSnapshotCompleteAdvisory struct {
	TypedEvent
	Stream string      `json:"stream"`
	Start  time.Time   `json:"start"`
	End    time.Time   `json:"end"`
	Client *ClientInfo `json:"client"`
	Domain string      `json:"domain,omitempty"`
}

JSSnapshotCompleteAdvisory is an advisory sent after a snapshot is successfully started

type JSSnapshotCreateAdvisory added in v2.2.0

type JSSnapshotCreateAdvisory struct {
	TypedEvent
	Stream string      `json:"stream"`
	State  StreamState `json:"state"`
	Client *ClientInfo `json:"client"`
	Domain string      `json:"domain,omitempty"`
}

JSSnapshotCreateAdvisory is an advisory sent after a snapshot is successfully started

type JSStreamActionAdvisory added in v2.2.0

type JSStreamActionAdvisory struct {
	TypedEvent
	Stream   string             `json:"stream"`
	Action   ActionAdvisoryType `json:"action"`
	Template string             `json:"template,omitempty"`
	Domain   string             `json:"domain,omitempty"`
}

JSStreamActionAdvisory indicates that a stream was created, edited or deleted

type JSStreamLeaderElectedAdvisory added in v2.2.0

type JSStreamLeaderElectedAdvisory struct {
	TypedEvent
	Account  string      `json:"account,omitempty"`
	Stream   string      `json:"stream"`
	Leader   string      `json:"leader"`
	Replicas []*PeerInfo `json:"replicas"`
	Domain   string      `json:"domain,omitempty"`
}

JSStreamLeaderElectedAdvisory indicates that a stream has elected a new leader.

type JSStreamQuorumLostAdvisory added in v2.2.0

type JSStreamQuorumLostAdvisory struct {
	TypedEvent
	Account  string      `json:"account,omitempty"`
	Stream   string      `json:"stream"`
	Replicas []*PeerInfo `json:"replicas"`
	Domain   string      `json:"domain,omitempty"`
}

JSStreamQuorumLostAdvisory indicates that a stream has lost quorum and is stalled.

type JSzOptions added in v2.2.0

type JSzOptions struct {
	Account          string `json:"account,omitempty"`
	Accounts         bool   `json:"accounts,omitempty"`
	Streams          bool   `json:"streams,omitempty"`
	Consumer         bool   `json:"consumer,omitempty"`
	Config           bool   `json:"config,omitempty"`
	LeaderOnly       bool   `json:"leader_only,omitempty"`
	Offset           int    `json:"offset,omitempty"`
	Limit            int    `json:"limit,omitempty"`
	RaftGroups       bool   `json:"raft,omitempty"`
	StreamLeaderOnly bool   `json:"stream_leader_only,omitempty"`
}

JSzOptions are options passed to Jsz

type JWTChanged added in v2.2.0

type JWTChanged func(publicKey string)

JWTChanged functions are called when the store file watcher notices a JWT changed

type JetStreamAPIStats added in v2.2.0

type JetStreamAPIStats struct {
	Total    uint64 `json:"total"`
	Errors   uint64 `json:"errors"`
	Inflight uint64 `json:"inflight,omitempty"`
}

type JetStreamAccountLimits added in v2.2.0

type JetStreamAccountLimits struct {
	MaxMemory            int64 `json:"max_memory"`
	MaxStore             int64 `json:"max_storage"`
	MaxStreams           int   `json:"max_streams"`
	MaxConsumers         int   `json:"max_consumers"`
	MaxAckPending        int   `json:"max_ack_pending"`
	MemoryMaxStreamBytes int64 `json:"memory_max_stream_bytes"`
	StoreMaxStreamBytes  int64 `json:"storage_max_stream_bytes"`
	MaxBytesRequired     bool  `json:"max_bytes_required"`
}

type JetStreamAccountStats added in v2.2.0

type JetStreamAccountStats struct {
	JetStreamTier                          // in case tiers are used, reflects totals with limits not set
	Domain        string                   `json:"domain,omitempty"`
	API           JetStreamAPIStats        `json:"api"`
	Tiers         map[string]JetStreamTier `json:"tiers,omitempty"` // indexed by tier name
}

JetStreamAccountStats returns current statistics about the account's JetStream usage.

type JetStreamConfig added in v2.2.0

type JetStreamConfig struct {
	MaxMemory    int64         `json:"max_memory"`
	MaxStore     int64         `json:"max_storage"`
	StoreDir     string        `json:"store_dir,omitempty"`
	SyncInterval time.Duration `json:"sync_interval,omitempty"`
	SyncAlways   bool          `json:"sync_always,omitempty"`
	Domain       string        `json:"domain,omitempty"`
	CompressOK   bool          `json:"compress_ok,omitempty"`
	UniqueTag    string        `json:"unique_tag,omitempty"`
}

JetStreamConfig determines this server's configuration. MaxMemory and MaxStore are in bytes.

type JetStreamStats added in v2.2.0

type JetStreamStats struct {
	Memory         uint64            `json:"memory"`
	Store          uint64            `json:"storage"`
	ReservedMemory uint64            `json:"reserved_memory"`
	ReservedStore  uint64            `json:"reserved_storage"`
	Accounts       int               `json:"accounts"`
	HAAssets       int               `json:"ha_assets"`
	API            JetStreamAPIStats `json:"api"`
}

Statistics about JetStream for this server.

type JetStreamTier added in v2.8.0

type JetStreamTier struct {
	Memory         uint64                 `json:"memory"`
	Store          uint64                 `json:"storage"`
	ReservedMemory uint64                 `json:"reserved_memory"`
	ReservedStore  uint64                 `json:"reserved_storage"`
	Streams        int                    `json:"streams"`
	Consumers      int                    `json:"consumers"`
	Limits         JetStreamAccountLimits `json:"limits"`
}

type JetStreamVarz added in v2.2.0

type JetStreamVarz struct {
	Config *JetStreamConfig `json:"config,omitempty"`
	Stats  *JetStreamStats  `json:"stats,omitempty"`
	Meta   *MetaClusterInfo `json:"meta,omitempty"`
}

JetStreamVarz contains basic runtime information about jetstream

type JszEventOptions added in v2.2.0

type JszEventOptions struct {
	JSzOptions
	EventFilterOptions
}

In the context of system events, JszEventOptions are options passed to Jsz

type KickClientReq added in v2.10.0

type KickClientReq struct {
	CID uint64 `json:"cid"`
}

type LDMClientReq added in v2.10.0

type LDMClientReq struct {
	CID uint64 `json:"cid"`
}

type LeafInfo added in v2.1.0

type LeafInfo struct {
	Name        string   `json:"name"`
	IsSpoke     bool     `json:"is_spoke"`
	Account     string   `json:"account"`
	IP          string   `json:"ip"`
	Port        int      `json:"port"`
	RTT         string   `json:"rtt,omitempty"`
	InMsgs      int64    `json:"in_msgs"`
	OutMsgs     int64    `json:"out_msgs"`
	InBytes     int64    `json:"in_bytes"`
	OutBytes    int64    `json:"out_bytes"`
	NumSubs     uint32   `json:"subscriptions"`
	Subs        []string `json:"subscriptions_list,omitempty"`
	Compression string   `json:"compression,omitempty"`
}

LeafInfo has detailed information on each remote leafnode connection.

type LeafNodeOpts

type LeafNodeOpts struct {
	Host              string        `json:"addr,omitempty"`
	Port              int           `json:"port,omitempty"`
	Username          string        `json:"-"`
	Password          string        `json:"-"`
	Nkey              string        `json:"-"`
	Account           string        `json:"-"`
	Users             []*User       `json:"-"`
	AuthTimeout       float64       `json:"auth_timeout,omitempty"`
	TLSConfig         *tls.Config   `json:"-"`
	TLSTimeout        float64       `json:"tls_timeout,omitempty"`
	TLSMap            bool          `json:"-"`
	TLSPinnedCerts    PinnedCertSet `json:"-"`
	TLSHandshakeFirst bool          `json:"-"`
	Advertise         string        `json:"-"`
	NoAdvertise       bool          `json:"-"`
	ReconnectInterval time.Duration `json:"-"`

	// Compression options
	Compression CompressionOpts `json:"-"`

	// For solicited connections to other clusters/superclusters.
	Remotes []*RemoteLeafOpts `json:"remotes,omitempty"`

	// This is the minimum version that is accepted for remote connections.
	// Note that since the server version in the CONNECT protocol was added
	// only starting at v2.8.0, any version below that will be rejected
	// (since empty version string in CONNECT would fail the "version at
	// least" test).
	MinVersion string
	// contains filtered or unexported fields
}

LeafNodeOpts are options for a given server to accept leaf node connections and/or connect to a remote cluster.

type LeafNodeOptsVarz

type LeafNodeOptsVarz struct {
	Host              string               `json:"host,omitempty"`
	Port              int                  `json:"port,omitempty"`
	AuthTimeout       float64              `json:"auth_timeout,omitempty"`
	TLSTimeout        float64              `json:"tls_timeout,omitempty"`
	TLSRequired       bool                 `json:"tls_required,omitempty"`
	TLSVerify         bool                 `json:"tls_verify,omitempty"`
	Remotes           []RemoteLeafOptsVarz `json:"remotes,omitempty"`
	TLSOCSPPeerVerify bool                 `json:"tls_ocsp_peer_verify,omitempty"`
}

LeafNodeOptsVarz contains monitoring leaf node information

type Leafz added in v2.1.0

type Leafz struct {
	ID       string      `json:"server_id"`
	Now      time.Time   `json:"now"`
	NumLeafs int         `json:"leafnodes"`
	Leafs    []*LeafInfo `json:"leafs"`
}

Leafz represents detailed information on Leafnodes.

type LeafzEventOptions added in v2.2.0

type LeafzEventOptions struct {
	LeafzOptions
	EventFilterOptions
}

In the context of system events, LeafzEventOptions are options passed to Leafz

type LeafzOptions added in v2.1.0

type LeafzOptions struct {
	// Subscriptions indicates that Leafz will return a leafnode's subscriptions
	Subscriptions bool   `json:"subscriptions"`
	Account       string `json:"account"`
}

LeafzOptions are options passed to Leafz

type LocalCache added in v2.9.21

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

LocalCache is a local file implementation of OCSPResponseCache

func (*LocalCache) Compress added in v2.9.21

func (c *LocalCache) Compress(buf []byte) ([]byte, error)

func (*LocalCache) Config added in v2.9.21

func (c *LocalCache) Config() *OCSPResponseCacheConfig

func (*LocalCache) Decompress added in v2.9.21

func (c *LocalCache) Decompress(buf []byte) ([]byte, error)

func (*LocalCache) Delete added in v2.9.21

func (c *LocalCache) Delete(key string, wasMiss bool, log *certidp.Log)

Delete removes a CA OCSP response from the OCSP peer cache matching the response fingerprint (a hash)

func (*LocalCache) Get added in v2.9.21

func (c *LocalCache) Get(key string, log *certidp.Log) []byte

Get returns a CA OCSP response from the OCSP peer cache matching the response fingerprint (a hash)

func (*LocalCache) Online added in v2.9.21

func (c *LocalCache) Online() bool

func (*LocalCache) Put added in v2.9.21

func (c *LocalCache) Put(key string, caResp *ocsp.Response, subj string, log *certidp.Log)

Put captures a CA OCSP response to the OCSP peer cache indexed by response fingerprint (a hash)

func (*LocalCache) Start added in v2.9.21

func (c *LocalCache) Start(s *Server)

Start initializes the configured OCSP peer cache, loads a saved cache from disk (if present), and initializes runtime statistics

func (*LocalCache) Stats added in v2.9.21

func (c *LocalCache) Stats() *OCSPResponseCacheStats

func (*LocalCache) Stop added in v2.9.21

func (c *LocalCache) Stop(s *Server)

func (*LocalCache) Type added in v2.9.21

func (c *LocalCache) Type() string

type Logger

type Logger interface {

	// Log a notice statement
	Noticef(format string, v ...any)

	// Log a warning statement
	Warnf(format string, v ...any)

	// Log a fatal error
	Fatalf(format string, v ...any)

	// Log an error
	Errorf(format string, v ...any)

	// Log a debug statement
	Debugf(format string, v ...any)

	// Log a trace statement
	Tracef(format string, v ...any)
}

Logger interface of the NATS Server

type LostStreamData added in v2.2.0

type LostStreamData struct {
	Msgs  []uint64 `json:"msgs"`
	Bytes uint64   `json:"bytes"`
}

LostStreamData indicates msgs that have been lost.

type MQTTOpts added in v2.2.0

type MQTTOpts struct {
	// The server will accept MQTT client connections on this hostname/IP.
	Host string
	// The server will accept MQTT client connections on this port.
	Port int

	// If no user name is provided when a client connects, will default to the
	// matching user from the global list of users in `Options.Users`.
	NoAuthUser string

	// Authentication section. If anything is configured in this section,
	// it will override the authorization configuration of regular clients.
	Username string
	Password string
	Token    string

	// JetStream domain mqtt is supposed to pick up
	JsDomain string

	// Number of replicas for MQTT streams.
	// Negative or 0 value means that the server(s) will pick a replica
	// number based on the known size of the cluster (but capped at 3).
	// Note that if an account was already connected, the stream's replica
	// count is not modified. Use the NATS CLI to update the count if desired.
	StreamReplicas int

	// Number of replicas for MQTT consumers.
	// Negative or 0 value means that there is no override and the consumer
	// will have the same replica factor that the stream it belongs to.
	// If a value is specified, it will require to be lower than the stream
	// replicas count (lower than StreamReplicas if specified, but also lower
	// than the automatic value determined by cluster size).
	// Note that existing consumers are not modified.
	//
	// UPDATE: This is no longer used while messages stream has interest policy retention
	// which requires consumer replica count to match the parent stream.
	ConsumerReplicas int

	// Indicate if the consumers should be created with memory storage.
	// Note that existing consumers are not modified.
	ConsumerMemoryStorage bool

	// If specified will have the system auto-cleanup the consumers after being
	// inactive for the specified amount of time.
	ConsumerInactiveThreshold time.Duration

	// Timeout for the authentication process.
	AuthTimeout float64

	// TLS configuration is required.
	TLSConfig *tls.Config
	// If true, map certificate values for authentication purposes.
	TLSMap bool
	// Timeout for the TLS handshake
	TLSTimeout float64
	// Set of allowable certificates
	TLSPinnedCerts PinnedCertSet

	// AckWait is the amount of time after which a QoS 1 or 2 message sent to a
	// client is redelivered as a DUPLICATE if the server has not received the
	// PUBACK on the original Packet Identifier. The same value applies to
	// PubRel redelivery. The value has to be positive. Zero will cause the
	// server to use the default value (30 seconds). Note that changes to this
	// option is applied only to new MQTT subscriptions (or sessions for
	// PubRels).
	AckWait time.Duration

	// MaxAckPending is the amount of QoS 1 and 2 messages (combined) the server
	// can send to a subscription without receiving any PUBACK for those
	// messages. The valid range is [0..65535].
	//
	// The total of subscriptions' MaxAckPending on a given session cannot
	// exceed 65535. Attempting to create a subscription that would bring the
	// total above the limit would result in the server returning 0x80 in the
	// SUBACK for this subscription.
	//
	// Due to how the NATS Server handles the MQTT "#" wildcard, each
	// subscription ending with "#" will use 2 times the MaxAckPending value.
	// Note that changes to this option is applied only to new subscriptions.
	MaxAckPending uint16
	// contains filtered or unexported fields
}

MQTTOpts are options for MQTT

type MQTTOptsVarz added in v2.8.0

type MQTTOptsVarz struct {
	Host              string        `json:"host,omitempty"`
	Port              int           `json:"port,omitempty"`
	NoAuthUser        string        `json:"no_auth_user,omitempty"`
	AuthTimeout       float64       `json:"auth_timeout,omitempty"`
	TLSMap            bool          `json:"tls_map,omitempty"`
	TLSTimeout        float64       `json:"tls_timeout,omitempty"`
	TLSPinnedCerts    []string      `json:"tls_pinned_certs,omitempty"`
	JsDomain          string        `json:"js_domain,omitempty"`
	AckWait           time.Duration `json:"ack_wait,omitempty"`
	MaxAckPending     uint16        `json:"max_ack_pending,omitempty"`
	TLSOCSPPeerVerify bool          `json:"tls_ocsp_peer_verify,omitempty"`
}

MQTTOptsVarz contains monitoring MQTT information

type MapDest added in v2.2.0

type MapDest struct {
	Subject string `json:"subject"`
	Weight  uint8  `json:"weight"`
	Cluster string `json:"cluster,omitempty"`
}

MapDest is for mapping published subjects for clients.

func NewMapDest added in v2.2.0

func NewMapDest(subject string, weight uint8) *MapDest

type MemAccResolver

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

MemAccResolver is a memory only resolver. Mostly for testing.

func (*MemAccResolver) Close added in v2.2.0

func (*MemAccResolver) Close()

func (*MemAccResolver) Fetch

func (m *MemAccResolver) Fetch(name string) (string, error)

Fetch will fetch the account jwt claims from the internal sync.Map.

func (*MemAccResolver) IsReadOnly added in v2.2.0

func (m *MemAccResolver) IsReadOnly() bool

func (*MemAccResolver) IsTrackingUpdate added in v2.2.0

func (*MemAccResolver) IsTrackingUpdate() bool

func (*MemAccResolver) Reload added in v2.2.0

func (*MemAccResolver) Reload() error

func (*MemAccResolver) Start added in v2.2.0

func (*MemAccResolver) Start(*Server) error

func (*MemAccResolver) Store

func (m *MemAccResolver) Store(name, jwt string) error

Store will store the account jwt claims in the internal sync.Map.

type MetaClusterInfo added in v2.6.2

type MetaClusterInfo struct {
	Name     string      `json:"name,omitempty"`
	Leader   string      `json:"leader,omitempty"`
	Peer     string      `json:"peer,omitempty"`
	Replicas []*PeerInfo `json:"replicas,omitempty"`
	Size     int         `json:"cluster_size"`
	Pending  int         `json:"pending"`
}

MetaClusterInfo shows information about the meta group.

type NkeyUser

type NkeyUser struct {
	Nkey                   string              `json:"user"`
	Issued                 int64               `json:"issued,omitempty"` // this is a copy of the issued at (iat) field in the jwt
	Permissions            *Permissions        `json:"permissions,omitempty"`
	Account                *Account            `json:"account,omitempty"`
	SigningKey             string              `json:"signing_key,omitempty"`
	AllowedConnectionTypes map[string]struct{} `json:"connection_types,omitempty"`
}

NkeyUser is for multiple nkey based users

type NoOpCache added in v2.9.21

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

NoOpCache is a no-op implementation of OCSPResponseCache

func (*NoOpCache) Config added in v2.9.21

func (c *NoOpCache) Config() *OCSPResponseCacheConfig

func (*NoOpCache) Delete added in v2.9.21

func (c *NoOpCache) Delete(_ string, _ bool, _ *certidp.Log)

func (*NoOpCache) Get added in v2.9.21

func (c *NoOpCache) Get(_ string, _ *certidp.Log) []byte

func (*NoOpCache) Online added in v2.9.21

func (c *NoOpCache) Online() bool

func (*NoOpCache) Put added in v2.9.21

func (c *NoOpCache) Put(_ string, _ *ocsp.Response, _ string, _ *certidp.Log)

func (*NoOpCache) Start added in v2.9.21

func (c *NoOpCache) Start(_ *Server)

func (*NoOpCache) Stats added in v2.9.21

func (c *NoOpCache) Stats() *OCSPResponseCacheStats

func (*NoOpCache) Stop added in v2.9.21

func (c *NoOpCache) Stop(_ *Server)

func (*NoOpCache) Type added in v2.9.21

func (c *NoOpCache) Type() string

type Number added in v2.9.17

type Number interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

type OCSPConfig added in v2.3.0

type OCSPConfig struct {
	// Mode defines the policy for OCSP stapling.
	Mode OCSPMode

	// OverrideURLs is the http URL endpoint used to get OCSP staples.
	OverrideURLs []string
}

OCSPConfig represents the options of OCSP stapling options.

type OCSPMode added in v2.3.0

type OCSPMode uint8
const (
	// OCSPModeAuto staples a status, only if "status_request" is set in cert.
	OCSPModeAuto OCSPMode = iota

	// OCSPModeAlways enforces OCSP stapling for certs and shuts down the server in
	// case a server is revoked or cannot get OCSP staples.
	OCSPModeAlways

	// OCSPModeNever disables OCSP stapling even if cert has Must-Staple flag.
	OCSPModeNever

	// OCSPModeMust honors the Must-Staple flag from a certificate but also causing shutdown
	// in case the certificate has been revoked.
	OCSPModeMust
)

type OCSPMonitor added in v2.3.0

type OCSPMonitor struct {
	Leaf   *x509.Certificate
	Issuer *x509.Certificate
	// contains filtered or unexported fields
}

OCSPMonitor monitors the state of a staple per certificate.

type OCSPPeerChainlinkInvalidEventMsg added in v2.9.21

type OCSPPeerChainlinkInvalidEventMsg struct {
	TypedEvent
	Link   certidp.CertInfo `json:"link"`
	Peer   certidp.CertInfo `json:"peer"`
	Server ServerInfo       `json:"server"`
	Reason string           `json:"reason"`
}

OCSPPeerChainlinkInvalidEventMsg is sent when a certificate (link) in a valid TLS chain is found to be OCSP invalid during a peer TLS handshake. A "peer" can be an inbound client connection or a leaf connection to a remote server. Peer and Link may be the same if the invalid cert was the peer's leaf cert

type OCSPPeerRejectEventMsg added in v2.9.21

type OCSPPeerRejectEventMsg struct {
	TypedEvent
	Kind   string           `json:"kind"`
	Peer   certidp.CertInfo `json:"peer"`
	Server ServerInfo       `json:"server"`
	Reason string           `json:"reason"`
}

OCSPPeerRejectEventMsg is sent when a peer TLS handshake is ultimately rejected due to OCSP invalidation. A "peer" can be an inbound client connection or a leaf connection to a remote server. Peer in event payload is always the peer's (TLS) leaf cert, which may or may be the invalid cert (See also OCSPPeerChainlinkInvalidEventMsg)

type OCSPResponseCache added in v2.9.21

type OCSPResponseCache interface {
	Put(key string, resp *ocsp.Response, subj string, log *certidp.Log)
	Get(key string, log *certidp.Log) []byte
	Delete(key string, miss bool, log *certidp.Log)
	Type() string
	Start(s *Server)
	Stop(s *Server)
	Online() bool
	Config() *OCSPResponseCacheConfig
	Stats() *OCSPResponseCacheStats
}

type OCSPResponseCacheConfig added in v2.9.21

type OCSPResponseCacheConfig struct {
	Type            OCSPResponseCacheType
	LocalStore      string
	PreserveRevoked bool
	SaveInterval    float64
}

func NewOCSPResponseCacheConfig added in v2.9.21

func NewOCSPResponseCacheConfig() *OCSPResponseCacheConfig

type OCSPResponseCacheItem added in v2.9.21

type OCSPResponseCacheItem struct {
	Subject     string                  `json:"subject,omitempty"`
	CachedAt    time.Time               `json:"cached_at"`
	RespStatus  certidp.StatusAssertion `json:"resp_status"`
	RespExpires time.Time               `json:"resp_expires,omitempty"`
	Resp        []byte                  `json:"resp"`
}

type OCSPResponseCacheStats added in v2.9.21

type OCSPResponseCacheStats struct {
	Responses int64 `json:"size"`
	Hits      int64 `json:"hits"`
	Misses    int64 `json:"misses"`
	Revokes   int64 `json:"revokes"`
	Goods     int64 `json:"goods"`
	Unknowns  int64 `json:"unknowns"`
}

type OCSPResponseCacheType added in v2.9.21

type OCSPResponseCacheType int
const (
	NONE OCSPResponseCacheType = iota + 1
	LOCAL
)

type OCSPResponseCacheVarz added in v2.9.21

type OCSPResponseCacheVarz struct {
	Type      string `json:"cache_type,omitempty"`
	Hits      int64  `json:"cache_hits,omitempty"`
	Misses    int64  `json:"cache_misses,omitempty"`
	Responses int64  `json:"cached_responses,omitempty"`
	Revokes   int64  `json:"cached_revoked_responses,omitempty"`
	Goods     int64  `json:"cached_good_responses,omitempty"`
	Unknowns  int64  `json:"cached_unknown_responses,omitempty"`
}

OCSPResponseCacheVarz contains OCSP response cache information

type Options

type Options struct {
	ConfigFile                 string        `json:"-"`
	ServerName                 string        `json:"server_name"`
	Host                       string        `json:"addr"`
	Port                       int           `json:"port"`
	DontListen                 bool          `json:"dont_listen"`
	ClientAdvertise            string        `json:"-"`
	Trace                      bool          `json:"-"`
	Debug                      bool          `json:"-"`
	TraceVerbose               bool          `json:"-"`
	NoLog                      bool          `json:"-"`
	NoSigs                     bool          `json:"-"`
	NoSublistCache             bool          `json:"-"`
	NoHeaderSupport            bool          `json:"-"`
	DisableShortFirstPing      bool          `json:"-"`
	Logtime                    bool          `json:"-"`
	LogtimeUTC                 bool          `json:"-"`
	MaxConn                    int           `json:"max_connections"`
	MaxSubs                    int           `json:"max_subscriptions,omitempty"`
	MaxSubTokens               uint8         `json:"-"`
	Nkeys                      []*NkeyUser   `json:"-"`
	Users                      []*User       `json:"-"`
	Accounts                   []*Account    `json:"-"`
	NoAuthUser                 string        `json:"-"`
	SystemAccount              string        `json:"-"`
	NoSystemAccount            bool          `json:"-"`
	Username                   string        `json:"-"`
	Password                   string        `json:"-"`
	Authorization              string        `json:"-"`
	AuthCallout                *AuthCallout  `json:"-"`
	PingInterval               time.Duration `json:"ping_interval"`
	MaxPingsOut                int           `json:"ping_max"`
	HTTPHost                   string        `json:"http_host"`
	HTTPPort                   int           `json:"http_port"`
	HTTPBasePath               string        `json:"http_base_path"`
	HTTPSPort                  int           `json:"https_port"`
	AuthTimeout                float64       `json:"auth_timeout"`
	MaxControlLine             int32         `json:"max_control_line"`
	MaxPayload                 int32         `json:"max_payload"`
	MaxPending                 int64         `json:"max_pending"`
	Cluster                    ClusterOpts   `json:"cluster,omitempty"`
	Gateway                    GatewayOpts   `json:"gateway,omitempty"`
	LeafNode                   LeafNodeOpts  `json:"leaf,omitempty"`
	JetStream                  bool          `json:"jetstream"`
	JetStreamMaxMemory         int64         `json:"-"`
	JetStreamMaxStore          int64         `json:"-"`
	JetStreamDomain            string        `json:"-"`
	JetStreamExtHint           string        `json:"-"`
	JetStreamKey               string        `json:"-"`
	JetStreamOldKey            string        `json:"-"`
	JetStreamCipher            StoreCipher   `json:"-"`
	JetStreamUniqueTag         string
	JetStreamLimits            JSLimitOpts
	JetStreamMaxCatchup        int64
	JetStreamRequestQueueLimit int64
	StoreDir                   string            `json:"-"`
	SyncInterval               time.Duration     `json:"-"`
	SyncAlways                 bool              `json:"-"`
	JsAccDefaultDomain         map[string]string `json:"-"` // account to domain name mapping
	Websocket                  WebsocketOpts     `json:"-"`
	MQTT                       MQTTOpts          `json:"-"`
	ProfPort                   int               `json:"-"`
	ProfBlockRate              int               `json:"-"`
	PidFile                    string            `json:"-"`
	PortsFileDir               string            `json:"-"`
	LogFile                    string            `json:"-"`
	LogSizeLimit               int64             `json:"-"`
	LogMaxFiles                int64             `json:"-"`
	Syslog                     bool              `json:"-"`
	RemoteSyslog               string            `json:"-"`
	Routes                     []*url.URL        `json:"-"`
	RoutesStr                  string            `json:"-"`
	TLSTimeout                 float64           `json:"tls_timeout"`
	TLS                        bool              `json:"-"`
	TLSVerify                  bool              `json:"-"`
	TLSMap                     bool              `json:"-"`
	TLSCert                    string            `json:"-"`
	TLSKey                     string            `json:"-"`
	TLSCaCert                  string            `json:"-"`
	TLSConfig                  *tls.Config       `json:"-"`
	TLSPinnedCerts             PinnedCertSet     `json:"-"`
	TLSRateLimit               int64             `json:"-"`
	// When set to true, the server will perform the TLS handshake before
	// sending the INFO protocol. For clients that are not configured
	// with a similar option, their connection will fail with some sort
	// of timeout or EOF error since they are expecting to receive an
	// INFO protocol first.
	TLSHandshakeFirst bool `json:"-"`
	// If TLSHandshakeFirst is true and this value is strictly positive,
	// the server will wait for that amount of time for the TLS handshake
	// to start before falling back to previous behavior of sending the
	// INFO protocol first. It allows for a mix of newer clients that can
	// require a TLS handshake first, and older clients that can't.
	TLSHandshakeFirstFallback time.Duration `json:"-"`
	AllowNonTLS               bool          `json:"-"`
	WriteDeadline             time.Duration `json:"-"`
	MaxClosedClients          int           `json:"-"`
	LameDuckDuration          time.Duration `json:"-"`
	LameDuckGracePeriod       time.Duration `json:"-"`

	// MaxTracedMsgLen is the maximum printable length for traced messages.
	MaxTracedMsgLen int `json:"-"`

	// Operating a trusted NATS server
	TrustedKeys              []string              `json:"-"`
	TrustedOperators         []*jwt.OperatorClaims `json:"-"`
	AccountResolver          AccountResolver       `json:"-"`
	AccountResolverTLSConfig *tls.Config           `json:"-"`

	// AlwaysEnableNonce will always present a nonce to new connections
	// typically used by custom Authentication implementations who embeds
	// the server and so not presented as a configuration option
	AlwaysEnableNonce bool

	CustomClientAuthentication Authentication `json:"-"`
	CustomRouterAuthentication Authentication `json:"-"`

	// CheckConfig configuration file syntax test was successful and exit.
	CheckConfig bool `json:"-"`

	// DisableJetStreamBanner will not print the ascii art on startup for JetStream enabled servers
	DisableJetStreamBanner bool `json:"-"`

	// ConnectErrorReports specifies the number of failed attempts
	// at which point server should report the failure of an initial
	// connection to a route, gateway or leaf node.
	// See DEFAULT_CONNECT_ERROR_REPORTS for default value.
	ConnectErrorReports int

	// ReconnectErrorReports is similar to ConnectErrorReports except
	// that this applies to reconnect events.
	ReconnectErrorReports int

	// Tags describing the server. They will be included in varz
	// and used as a filter criteria for some system requests.
	Tags jwt.TagList `json:"-"`

	// OCSPConfig enables OCSP Stapling in the server.
	OCSPConfig *OCSPConfig

	// OCSP Cache config enables next-gen cache for OCSP features
	OCSPCacheConfig *OCSPResponseCacheConfig
	// contains filtered or unexported fields
}

Options block for nats-server. NOTE: This structure is no longer used for monitoring endpoints and json tags are deprecated and may be removed in the future.

var FlagSnapshot *Options

FlagSnapshot captures the server options as specified by CLI flags at startup. This should not be modified once the server has started.

func ConfigureOptions

func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error)

ConfigureOptions accepts a flag set and augments it with NATS Server specific flags. On success, an options structure is returned configured based on the selected flags and/or configuration file. The command line options take precedence to the ones in the configuration file.

func MergeOptions

func MergeOptions(fileOpts, flagOpts *Options) *Options

MergeOptions will merge two options giving preference to the flagOpts if the item is present.

func ProcessConfigFile

func ProcessConfigFile(configFile string) (*Options, error)

ProcessConfigFile processes a configuration file. FIXME(dlc): A bit hacky

func (*Options) Clone

func (o *Options) Clone() *Options

Clone performs a deep copy of the Options struct, returning a new clone with all values copied.

func (*Options) ProcessConfigFile

func (o *Options) ProcessConfigFile(configFile string) error

ProcessConfigFile updates the Options structure with options present in the given configuration file. This version is convenient if one wants to set some default options and then override them with what is in the config file. For instance, this version allows you to do something such as:

opts := &Options{Debug: true} opts.ProcessConfigFile(myConfigFile)

If the config file contains "debug: false", after this call, opts.Debug would really be false. It would be impossible to achieve that with the non receiver ProcessConfigFile() version, since one would not know after the call if "debug" was not present or was present but set to false.

type Peer added in v2.2.0

type Peer struct {
	ID      string
	Current bool
	Last    time.Time
	Lag     uint64
}

type PeerInfo added in v2.2.0

type PeerInfo struct {
	Name    string        `json:"name"`
	Current bool          `json:"current"`
	Offline bool          `json:"offline,omitempty"`
	Active  time.Duration `json:"active"`
	Lag     uint64        `json:"lag,omitempty"`
	Peer    string        `json:"peer"`
	// contains filtered or unexported fields
}

PeerInfo shows information about all the peers in the cluster that are supporting the stream or consumer.

type Pending added in v2.2.0

type Pending struct {
	Sequence  uint64
	Timestamp int64
}

Represents a pending message for explicit ack or ack all. Sequence is the original consumer sequence.

type Permissions

type Permissions struct {
	Publish   *SubjectPermission  `json:"publish"`
	Subscribe *SubjectPermission  `json:"subscribe"`
	Response  *ResponsePermission `json:"responses,omitempty"`
}

Permissions are the allowed subjects on a per publish or subscribe basis.

type PinnedCertSet added in v2.2.5

type PinnedCertSet map[string]struct{}

PinnedCertSet is a set of lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo

type Placement added in v2.2.0

type Placement struct {
	Cluster string   `json:"cluster,omitempty"`
	Tags    []string `json:"tags,omitempty"`
}

Used to guide placement of streams and meta controllers in clustered JetStream.

type Ports

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

Ports describes URLs that the server can be contacted in

type ProfilezEventOptions added in v2.10.0

type ProfilezEventOptions struct {
	ProfilezOptions
	EventFilterOptions
}

In the context of system events, ProfilezEventOptions are options passed to Profilez

type ProfilezOptions added in v2.10.0

type ProfilezOptions struct {
	Name     string        `json:"name"`
	Debug    int           `json:"debug"`
	Duration time.Duration `json:"duration,omitempty"`
}

ProfilezOptions are options passed to Profilez

type ProfilezStatus added in v2.10.0

type ProfilezStatus struct {
	Profile []byte `json:"profile"`
	Error   string `json:"error"`
}

type PubAck added in v2.2.0

type PubAck struct {
	Stream    string `json:"stream"`
	Sequence  uint64 `json:"seq"`
	Domain    string `json:"domain,omitempty"`
	Duplicate bool   `json:"duplicate,omitempty"`
}

PubAck is the detail you get back from a publish to a stream that was successful. e.g. +OK {"stream": "Orders", "seq": 22}

type RaftConfig added in v2.2.0

type RaftConfig struct {
	Name     string
	Store    string
	Log      WAL
	Track    bool
	Observer bool
}

type RaftGroupDetail added in v2.9.15

type RaftGroupDetail struct {
	Name      string `json:"name"`
	RaftGroup string `json:"raft_group,omitempty"`
}

RaftGroupDetail shows information details about the Raft group.

type RaftNode added in v2.2.0

type RaftNode interface {
	Propose(entry []byte) error
	ProposeMulti(entries []*Entry) error
	ForwardProposal(entry []byte) error
	InstallSnapshot(snap []byte) error
	SendSnapshot(snap []byte) error
	NeedSnapshot() bool
	Applied(index uint64) (entries uint64, bytes uint64)
	State() RaftState
	Size() (entries, bytes uint64)
	Progress() (index, commit, applied uint64)
	Leader() bool
	Quorum() bool
	Current() bool
	Healthy() bool
	Term() uint64
	GroupLeader() string
	HadPreviousLeader() bool
	StepDown(preferred ...string) error
	SetObserver(isObserver bool)
	IsObserver() bool
	Campaign() error
	ID() string
	Group() string
	Peers() []*Peer
	UpdateKnownPeers(knownPeers []string)
	ProposeAddPeer(peer string) error
	ProposeRemovePeer(peer string) error
	AdjustClusterSize(csz int) error
	AdjustBootClusterSize(csz int) error
	ClusterSize() int
	ApplyQ() *ipQueue[*CommittedEntry]
	PauseApply() error
	ResumeApply()
	LeadChangeC() <-chan bool
	QuitC() <-chan struct{}
	Created() time.Time
	Stop()
	WaitForStop()
	Delete()
}

type RaftState added in v2.2.0

type RaftState uint8
const (
	Follower RaftState = iota
	Leader
	Candidate
	Closed
)

Allowable states for a NATS Consensus Group.

func (RaftState) String added in v2.2.0

func (state RaftState) String() string

type RaftzGroup added in v2.10.17

type RaftzGroup struct {
	ID            string                    `json:"id"`
	State         string                    `json:"state"`
	Size          int                       `json:"size"`
	QuorumNeeded  int                       `json:"quorum_needed"`
	Observer      bool                      `json:"observer,omitempty"`
	Paused        bool                      `json:"paused,omitempty"`
	Committed     uint64                    `json:"committed"`
	Applied       uint64                    `json:"applied"`
	CatchingUp    bool                      `json:"catching_up,omitempty"`
	Leader        string                    `json:"leader,omitempty"`
	EverHadLeader bool                      `json:"ever_had_leader"`
	Term          uint64                    `json:"term"`
	Vote          string                    `json:"voted_for,omitempty"`
	PTerm         uint64                    `json:"pterm"`
	PIndex        uint64                    `json:"pindex"`
	IPQPropLen    int                       `json:"ipq_proposal_len"`
	IPQEntryLen   int                       `json:"ipq_entry_len"`
	IPQRespLen    int                       `json:"ipq_resp_len"`
	IPQApplyLen   int                       `json:"ipq_apply_len"`
	WAL           StreamState               `json:"wal"`
	WALError      error                     `json:"wal_error,omitempty"`
	Peers         map[string]RaftzGroupPeer `json:"peers"`
}

type RaftzGroupPeer added in v2.10.17

type RaftzGroupPeer struct {
	Name                string `json:"name"`
	Known               bool   `json:"known"`
	LastReplicatedIndex uint64 `json:"last_replicated_index,omitempty"`
	LastSeen            string `json:"last_seen,omitempty"`
}

type RePublish added in v2.9.0

type RePublish struct {
	Source      string `json:"src,omitempty"`
	Destination string `json:"dest"`
	HeadersOnly bool   `json:"headers_only,omitempty"`
}

RePublish is for republishing messages once committed to a stream.

type RemoteGatewayOpts

type RemoteGatewayOpts struct {
	Name       string      `json:"name"`
	TLSConfig  *tls.Config `json:"-"`
	TLSTimeout float64     `json:"tls_timeout,omitempty"`
	URLs       []*url.URL  `json:"urls,omitempty"`
	// contains filtered or unexported fields
}

RemoteGatewayOpts are options for connecting to a remote gateway NOTE: This structure is no longer used for monitoring endpoints and json tags are deprecated and may be removed in the future.

type RemoteGatewayOptsVarz

type RemoteGatewayOptsVarz struct {
	Name       string   `json:"name"`
	TLSTimeout float64  `json:"tls_timeout,omitempty"`
	URLs       []string `json:"urls,omitempty"`
}

RemoteGatewayOptsVarz contains monitoring remote gateway information

type RemoteGatewayz

type RemoteGatewayz struct {
	IsConfigured bool               `json:"configured"`
	Connection   *ConnInfo          `json:"connection,omitempty"`
	Accounts     []*AccountGatewayz `json:"accounts,omitempty"`
}

RemoteGatewayz represents information about an outbound connection to a gateway

type RemoteLeafOpts

type RemoteLeafOpts struct {
	LocalAccount      string           `json:"local_account,omitempty"`
	NoRandomize       bool             `json:"-"`
	URLs              []*url.URL       `json:"urls,omitempty"`
	Credentials       string           `json:"-"`
	Nkey              string           `json:"-"`
	SignatureCB       SignatureHandler `json:"-"`
	TLS               bool             `json:"-"`
	TLSConfig         *tls.Config      `json:"-"`
	TLSTimeout        float64          `json:"tls_timeout,omitempty"`
	TLSHandshakeFirst bool             `json:"-"`
	Hub               bool             `json:"hub,omitempty"`
	DenyImports       []string         `json:"-"`
	DenyExports       []string         `json:"-"`

	// Compression options for this remote. Each remote could have a different
	// setting and also be different from the LeafNode options.
	Compression CompressionOpts `json:"-"`

	// When an URL has the "ws" (or "wss") scheme, then the server will initiate the
	// connection as a websocket connection. By default, the websocket frames will be
	// masked (as if this server was a websocket client to the remote server). The
	// NoMasking option will change this behavior and will send umasked frames.
	Websocket struct {
		Compression bool `json:"-"`
		NoMasking   bool `json:"-"`
	}

	// If we are clustered and our local account has JetStream, if apps are accessing
	// a stream or consumer leader through this LN and it gets dropped, the apps will
	// not be able to work. This tells the system to migrate the leaders away from this server.
	// This only changes leader for R>1 assets.
	JetStreamClusterMigrate bool `json:"jetstream_cluster_migrate,omitempty"`
	// contains filtered or unexported fields
}

RemoteLeafOpts are options for connecting to a remote server as a leaf node.

type RemoteLeafOptsVarz

type RemoteLeafOptsVarz struct {
	LocalAccount      string     `json:"local_account,omitempty"`
	TLSTimeout        float64    `json:"tls_timeout,omitempty"`
	URLs              []string   `json:"urls,omitempty"`
	Deny              *DenyRules `json:"deny,omitempty"`
	TLSOCSPPeerVerify bool       `json:"tls_ocsp_peer_verify,omitempty"`
}

RemoteLeafOptsVarz contains monitoring remote leaf node information

type ReplayPolicy added in v2.2.0

type ReplayPolicy int

ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.

const (
	// ReplayInstant will replay messages as fast as possible.
	ReplayInstant ReplayPolicy = iota
	// ReplayOriginal will maintain the same timing as the messages were received.
	ReplayOriginal
)

func (ReplayPolicy) MarshalJSON added in v2.2.0

func (rp ReplayPolicy) MarshalJSON() ([]byte, error)

func (ReplayPolicy) String added in v2.2.0

func (r ReplayPolicy) String() string

func (*ReplayPolicy) UnmarshalJSON added in v2.2.0

func (rp *ReplayPolicy) UnmarshalJSON(data []byte) error

type ResponsePermission added in v2.0.4

type ResponsePermission struct {
	MaxMsgs int           `json:"max"`
	Expires time.Duration `json:"ttl"`
}

ResponsePermission can be used to allow responses to any reply subject that is received on a valid subscription.

type RetentionPolicy added in v2.2.0

type RetentionPolicy int

RetentionPolicy determines how messages in a set are retained.

const (
	// LimitsPolicy (default) means that messages are retained until any given limit is reached.
	// This could be one of MaxMsgs, MaxBytes, or MaxAge.
	LimitsPolicy RetentionPolicy = iota
	// InterestPolicy specifies that when all known consumers have acknowledged a message it can be removed.
	InterestPolicy
	// WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed.
	WorkQueuePolicy
)

func (RetentionPolicy) MarshalJSON added in v2.2.0

func (rp RetentionPolicy) MarshalJSON() ([]byte, error)

func (RetentionPolicy) String added in v2.2.0

func (rp RetentionPolicy) String() string

func (*RetentionPolicy) UnmarshalJSON added in v2.2.0

func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error

type RouteInfo

type RouteInfo struct {
	Rid          uint64             `json:"rid"`
	RemoteID     string             `json:"remote_id"`
	RemoteName   string             `json:"remote_name"`
	DidSolicit   bool               `json:"did_solicit"`
	IsConfigured bool               `json:"is_configured"`
	IP           string             `json:"ip"`
	Port         int                `json:"port"`
	Start        time.Time          `json:"start"`
	LastActivity time.Time          `json:"last_activity"`
	RTT          string             `json:"rtt,omitempty"`
	Uptime       string             `json:"uptime"`
	Idle         string             `json:"idle"`
	Import       *SubjectPermission `json:"import,omitempty"`
	Export       *SubjectPermission `json:"export,omitempty"`
	Pending      int                `json:"pending_size"`
	InMsgs       int64              `json:"in_msgs"`
	OutMsgs      int64              `json:"out_msgs"`
	InBytes      int64              `json:"in_bytes"`
	OutBytes     int64              `json:"out_bytes"`
	NumSubs      uint32             `json:"subscriptions"`
	Subs         []string           `json:"subscriptions_list,omitempty"`
	SubsDetail   []SubDetail        `json:"subscriptions_list_detail,omitempty"`
	Account      string             `json:"account,omitempty"`
	Compression  string             `json:"compression,omitempty"`
}

RouteInfo has detailed information on a per connection basis.

type RoutePermissions

type RoutePermissions struct {
	Import *SubjectPermission `json:"import"`
	Export *SubjectPermission `json:"export"`
}

RoutePermissions are similar to user permissions but describe what a server can import/export from and to another server.

type RouteStat

type RouteStat struct {
	ID       uint64    `json:"rid"`
	Name     string    `json:"name,omitempty"`
	Sent     DataStats `json:"sent"`
	Received DataStats `json:"received"`
	Pending  int       `json:"pending"`
}

RouteStat holds route statistics.

type RouteType

type RouteType int

RouteType designates the router type

const (
	// This route we learned from speaking to other routes.
	Implicit RouteType = iota
	// This route was explicitly configured.
	Explicit
)

Type of Route

type Routez

type Routez struct {
	ID        string             `json:"server_id"`
	Name      string             `json:"server_name"`
	Now       time.Time          `json:"now"`
	Import    *SubjectPermission `json:"import,omitempty"`
	Export    *SubjectPermission `json:"export,omitempty"`
	NumRoutes int                `json:"num_routes"`
	Routes    []*RouteInfo       `json:"routes"`
}

Routez represents detailed information on current client connections.

type RoutezEventOptions added in v2.2.0

type RoutezEventOptions struct {
	RoutezOptions
	EventFilterOptions
}

In the context of system events, RoutezEventOptions are options passed to Routez

type RoutezOptions

type RoutezOptions struct {
	// Subscriptions indicates that Routez will return a route's subscriptions
	Subscriptions bool `json:"subscriptions"`
	// SubscriptionsDetail indicates if subscription details should be included in the results
	SubscriptionsDetail bool `json:"subscriptions_detail"`
}

RoutezOptions are options passed to Routez

type SequenceInfo added in v2.4.0

type SequenceInfo struct {
	Consumer uint64     `json:"consumer_seq"`
	Stream   uint64     `json:"stream_seq"`
	Last     *time.Time `json:"last_active,omitempty"`
}

SequenceInfo has both the consumer and the stream sequence and last activity.

type SequencePair added in v2.2.0

type SequencePair struct {
	Consumer uint64 `json:"consumer_seq"`
	Stream   uint64 `json:"stream_seq"`
}

SequencePair has both the consumer and the stream sequence. They point to same message.

type Server

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

Server is our main struct.

func New

func New(opts *Options) *Server

New will setup a new server struct after parsing the options. DEPRECATED: Use NewServer(opts)

func NewServer

func NewServer(opts *Options) (*Server, error)

NewServer will setup a new server struct after parsing the options. Could return an error if options can not be validated. The provided Options type should not be re-used afterwards. Either use Options.Clone() to pass a copy, or make a new one.

func (*Server) AcceptLoop

func (s *Server) AcceptLoop(clr chan struct{})

AcceptLoop is exported for easier testing.

func (*Server) AccountResolver

func (s *Server) AccountResolver() AccountResolver

AccountResolver returns the registered account resolver.

func (*Server) AccountStatz added in v2.9.0

func (s *Server) AccountStatz(opts *AccountStatzOptions) (*AccountStatz, error)

Leafz returns a AccountStatz structure containing summary information about accounts.

func (*Server) Accountz added in v2.2.0

func (s *Server) Accountz(optz *AccountzOptions) (*Accountz, error)

func (*Server) ActivePeers added in v2.2.0

func (s *Server) ActivePeers() (peers []string)

activePeers is used in bootstrapping raft groups like the JetStream meta controller.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr will return the net.Addr object for the current listener.

func (*Server) ClientURL added in v2.1.0

func (s *Server) ClientURL() string

ClientURL returns the URL used to connect clients. Helpful in testing when we designate a random client port (-1).

func (*Server) ClusterAddr

func (s *Server) ClusterAddr() *net.TCPAddr

ClusterAddr returns the net.Addr object for the route listener.

func (*Server) ClusterName added in v2.2.0

func (s *Server) ClusterName() string

clusterName returns our cluster name which could be dynamic.

func (*Server) ConfigTime

func (s *Server) ConfigTime() time.Time

ConfigTime will report the last time the server configuration was loaded.

func (*Server) ConfigureLogger

func (s *Server) ConfigureLogger()

ConfigureLogger configures and sets the logger for the server.

func (*Server) Connz

func (s *Server) Connz(opts *ConnzOptions) (*Connz, error)

Connz returns a Connz struct containing information about connections.

func (*Server) Debugf

func (s *Server) Debugf(format string, v ...any)

Debugf logs a debug statement

func (*Server) DisableJetStream added in v2.2.0

func (s *Server) DisableJetStream() error

DisableJetStream will turn off JetStream and signals in clustered mode to have the metacontroller remove us from the peer list.

func (*Server) DisconnectClientByID added in v2.10.0

func (s *Server) DisconnectClientByID(id uint64) error

DisconnectClientByID disconnects a client by connection ID

func (*Server) EnableJetStream added in v2.2.0

func (s *Server) EnableJetStream(config *JetStreamConfig) error

EnableJetStream will enable JetStream support on this server with the given configuration. A nil configuration will dynamically choose the limits and temporary file storage directory.

func (*Server) Errorc added in v2.1.6

func (s *Server) Errorc(ctx string, e error)

Error logs an error with a context

func (*Server) Errorf

func (s *Server) Errorf(format string, v ...any)

Errorf logs an error

func (*Server) Errors added in v2.1.6

func (s *Server) Errors(scope any, e error)

Error logs an error with a scope

func (*Server) Errorsc added in v2.1.6

func (s *Server) Errorsc(scope any, ctx string, e error)

Error logs an error with a scope and context

func (*Server) EventsEnabled

func (s *Server) EventsEnabled() bool

EventsEnabled will report if the server has internal events enabled via a defined system account.

func (*Server) Fatalf

func (s *Server) Fatalf(format string, v ...any)

Fatalf logs a fatal error

func (*Server) GatewayAddr

func (s *Server) GatewayAddr() *net.TCPAddr

GatewayAddr returns the net.Addr object for the gateway listener.

func (*Server) Gatewayz

func (s *Server) Gatewayz(opts *GatewayzOptions) (*Gatewayz, error)

Gatewayz returns a Gatewayz struct containing information about gateways.

func (*Server) GetClient

func (s *Server) GetClient(cid uint64) *client

GetClient will return the client associated with cid.

func (*Server) GetLeafNode

func (s *Server) GetLeafNode(cid uint64) *client

GetLeafNode returns the leafnode associated with the cid.

func (*Server) GlobalAccount added in v2.2.0

func (s *Server) GlobalAccount() *Account

GlobalAccount returns the global account. Default clients will use the global account.

func (*Server) HTTPHandler

func (s *Server) HTTPHandler() http.Handler

HTTPHandler returns the http.Handler object used to handle monitoring endpoints. It will return nil if the server is not configured for monitoring, or if the server has not been started yet (Server.Start()).

func (*Server) HandleAccountStatz added in v2.9.0

func (s *Server) HandleAccountStatz(w http.ResponseWriter, r *http.Request)

HandleAccountStatz process HTTP requests for statz information of all accounts.

func (*Server) HandleAccountz added in v2.2.0

func (s *Server) HandleAccountz(w http.ResponseWriter, r *http.Request)

HandleAccountz process HTTP requests for account information.

func (*Server) HandleConnz

func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request)

HandleConnz process HTTP requests for connection information.

func (*Server) HandleGatewayz

func (s *Server) HandleGatewayz(w http.ResponseWriter, r *http.Request)

HandleGatewayz process HTTP requests for route information.

func (*Server) HandleIPQueuesz added in v2.8.0

func (s *Server) HandleIPQueuesz(w http.ResponseWriter, r *http.Request)

func (*Server) HandleJsz added in v2.2.0

func (s *Server) HandleJsz(w http.ResponseWriter, r *http.Request)

HandleJsz process HTTP requests for jetstream information.

func (*Server) HandleLeafz added in v2.1.0

func (s *Server) HandleLeafz(w http.ResponseWriter, r *http.Request)

HandleLeafz process HTTP requests for leafnode information.

func (*Server) HandleRaftz added in v2.10.17

func (s *Server) HandleRaftz(w http.ResponseWriter, r *http.Request)

func (*Server) HandleRoot

func (s *Server) HandleRoot(w http.ResponseWriter, r *http.Request)

HandleRoot will show basic info and links to others handlers.

func (*Server) HandleRoutez

func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request)

HandleRoutez process HTTP requests for route information.

func (*Server) HandleStacksz

func (s *Server) HandleStacksz(w http.ResponseWriter, r *http.Request)

HandleStacksz processes HTTP requests for getting stacks

func (*Server) HandleSubsz

func (s *Server) HandleSubsz(w http.ResponseWriter, r *http.Request)

HandleSubsz processes HTTP requests for subjects stats.

func (*Server) HandleVarz

func (s *Server) HandleVarz(w http.ResponseWriter, r *http.Request)

HandleVarz will process HTTP requests for server information.

func (*Server) ID

func (s *Server) ID() string

ID returns the server's ID

func (*Server) InProcessConn added in v2.9.0

func (s *Server) InProcessConn() (net.Conn, error)

InProcessConn returns an in-process connection to the server, avoiding the need to use a TCP listener for local connectivity within the same process. This can be used regardless of the state of the DontListen option.

func (*Server) JetStreamClusterPeers added in v2.2.0

func (s *Server) JetStreamClusterPeers() []string

func (*Server) JetStreamConfig added in v2.2.0

func (s *Server) JetStreamConfig() *JetStreamConfig

JetStreamConfig will return the current config. Useful if the system created a dynamic configuration. A copy is returned.

func (*Server) JetStreamEnabled added in v2.2.0

func (s *Server) JetStreamEnabled() bool

JetStreamEnabled reports if jetstream is enabled for this server.

func (*Server) JetStreamEnabledForDomain added in v2.3.4

func (s *Server) JetStreamEnabledForDomain() bool

JetStreamEnabledForDomain will report if any servers have JetStream enabled within this domain.

func (*Server) JetStreamIsClustered added in v2.2.0

func (s *Server) JetStreamIsClustered() bool

func (*Server) JetStreamIsConsumerLeader added in v2.2.0

func (s *Server) JetStreamIsConsumerLeader(account, stream, consumer string) bool

func (*Server) JetStreamIsCurrent added in v2.2.0

func (s *Server) JetStreamIsCurrent() bool

func (*Server) JetStreamIsLeader added in v2.2.0

func (s *Server) JetStreamIsLeader() bool

func (*Server) JetStreamIsStreamAssigned added in v2.2.0

func (s *Server) JetStreamIsStreamAssigned(account, stream string) bool

func (*Server) JetStreamIsStreamCurrent added in v2.2.0

func (s *Server) JetStreamIsStreamCurrent(account, stream string) bool

func (*Server) JetStreamIsStreamLeader added in v2.2.0

func (s *Server) JetStreamIsStreamLeader(account, stream string) bool

func (*Server) JetStreamNumAccounts added in v2.2.0

func (s *Server) JetStreamNumAccounts() int

JetStreamNumAccounts returns the number of enabled accounts this server is tracking.

func (*Server) JetStreamReservedResources added in v2.2.0

func (s *Server) JetStreamReservedResources() (int64, int64, error)

JetStreamReservedResources returns the reserved resources if JetStream is enabled.

func (*Server) JetStreamSnapshotMeta added in v2.2.0

func (s *Server) JetStreamSnapshotMeta() error

func (*Server) JetStreamSnapshotStream added in v2.2.0

func (s *Server) JetStreamSnapshotStream(account, stream string) error

func (*Server) JetStreamStepdownConsumer added in v2.9.16

func (s *Server) JetStreamStepdownConsumer(account, stream, consumer string) error

func (*Server) JetStreamStepdownStream added in v2.2.0

func (s *Server) JetStreamStepdownStream(account, stream string) error

func (*Server) Jsz added in v2.2.0

func (s *Server) Jsz(opts *JSzOptions) (*JSInfo, error)

Jsz returns a Jsz structure containing information about JetStream.

func (*Server) JszAccount added in v2.2.0

func (s *Server) JszAccount(opts *JSzOptions) (*AccountDetail, error)

func (*Server) LDMClientByID added in v2.10.0

func (s *Server) LDMClientByID(id uint64) error

LDMClientByID sends a Lame Duck Mode info message to a client by connection ID

func (*Server) LameDuckShutdown added in v2.10.18

func (s *Server) LameDuckShutdown()

LameDuckShutdown will perform a lame duck shutdown of NATS, whereby the client listener is closed, existing client connections are kicked, Raft leaderships are transferred, JetStream is shutdown and then finally shutdown the the NATS Server itself. This function blocks and will not return until the NATS Server has completed the entire shutdown operation.

func (*Server) Leafz added in v2.1.0

func (s *Server) Leafz(opts *LeafzOptions) (*Leafz, error)

Leafz returns a Leafz structure containing information about leafnodes.

func (*Server) Logger added in v2.2.0

func (s *Server) Logger() Logger

Returns our current logger.

func (*Server) LookupAccount

func (s *Server) LookupAccount(name string) (*Account, error)

LookupAccount is a public function to return the account structure associated with name.

func (*Server) LookupOrRegisterAccount

func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool)

LookupOrRegisterAccount will return the given account if known or create a new entry.

func (*Server) MonitorAddr

func (s *Server) MonitorAddr() *net.TCPAddr

MonitorAddr will return the net.Addr object for the monitoring listener.

func (*Server) Name added in v2.2.0

func (s *Server) Name() string

Name returns the server's name. This will be the same as the ID if it was not set.

func (*Server) NewOCSPMonitor added in v2.3.0

func (srv *Server) NewOCSPMonitor(config *tlsConfigKind) (*tls.Config, *OCSPMonitor, error)

NewOCSPMonitor takes a TLS configuration then wraps it with the callbacks set for OCSP verification along with a monitor that will periodically fetch OCSP staples.

func (*Server) Node added in v2.2.0

func (s *Server) Node() string

Returns the node name for this server which is a hash of the server name.

func (*Server) NodeName added in v2.2.0

func (s *Server) NodeName() string

NodeName returns the node name for this server.

func (*Server) NonceRequired

func (s *Server) NonceRequired() bool

NonceRequired tells us if we should send a nonce.

func (*Server) Noticef

func (s *Server) Noticef(format string, v ...any)

Noticef logs a notice statement

func (*Server) NumActiveAccounts

func (s *Server) NumActiveAccounts() int32

NumActiveAccounts reports number of active accounts on this server.

func (*Server) NumClients

func (s *Server) NumClients() int

NumClients will report the number of registered clients.

func (*Server) NumLeafNodes

func (s *Server) NumLeafNodes() int

NumLeafNodes will report number of leaf node connections.

func (*Server) NumLoadedAccounts added in v2.1.2

func (s *Server) NumLoadedAccounts() int

NumLoadedAccounts returns the number of loaded accounts.

func (*Server) NumOutboundGateways

func (s *Server) NumOutboundGateways() int

NumOutboundGateways is public here mostly for testing.

func (*Server) NumRemotes

func (s *Server) NumRemotes() int

NumRemotes will report number of registered remotes.

func (*Server) NumRoutes

func (s *Server) NumRoutes() int

NumRoutes will report the number of registered routes.

func (*Server) NumSlowConsumers

func (s *Server) NumSlowConsumers() int64

NumSlowConsumers will report the number of slow consumers.

func (*Server) NumSlowConsumersClients added in v2.10.0

func (s *Server) NumSlowConsumersClients() uint64

NumSlowConsumersClients will report the number of slow consumers clients.

func (*Server) NumSlowConsumersGateways added in v2.10.0

func (s *Server) NumSlowConsumersGateways() uint64

NumSlowConsumersGateways will report the number of slow consumers leafs.

func (*Server) NumSlowConsumersLeafs added in v2.10.0

func (s *Server) NumSlowConsumersLeafs() uint64

NumSlowConsumersLeafs will report the number of slow consumers leafs.

func (*Server) NumSlowConsumersRoutes added in v2.10.0

func (s *Server) NumSlowConsumersRoutes() uint64

NumSlowConsumersRoutes will report the number of slow consumers routes.

func (*Server) NumSubscriptions

func (s *Server) NumSubscriptions() uint32

NumSubscriptions will report how many subscriptions are active.

func (*Server) PortsInfo

func (s *Server) PortsInfo(maxWait time.Duration) *Ports

PortsInfo attempts to resolve all the ports. If after maxWait the ports are not resolved, it returns nil. Otherwise it returns a Ports struct describing ports where the server can be contacted

func (*Server) ProfilerAddr

func (s *Server) ProfilerAddr() *net.TCPAddr

ProfilerAddr returns the net.Addr object for the profiler listener.

func (*Server) RateLimitDebugf added in v2.10.0

func (s *Server) RateLimitDebugf(format string, v ...any)

func (*Server) RateLimitWarnf added in v2.8.0

func (s *Server) RateLimitWarnf(format string, v ...any)

func (*Server) ReOpenLogFile

func (s *Server) ReOpenLogFile()

ReOpenLogFile if the logger is a file based logger, close and re-open the file. This allows for file rotation by 'mv'ing the file then signaling the process to trigger this function.

func (*Server) ReadyForConnections

func (s *Server) ReadyForConnections(dur time.Duration) bool

ReadyForConnections returns `true` if the server is ready to accept clients and, if routing is enabled, route connections. If after the duration `dur` the server is still not ready, returns `false`.

func (*Server) RegisterAccount

func (s *Server) RegisterAccount(name string) (*Account, error)

RegisterAccount will register an account. The account must be new or this call will fail.

func (*Server) Reload

func (s *Server) Reload() error

Reload reads the current configuration file and calls out to ReloadOptions to apply the changes. This returns an error if the server was not started with a config file or an option which doesn't support hot-swapping was changed.

func (*Server) ReloadOptions added in v2.3.4

func (s *Server) ReloadOptions(newOpts *Options) error

ReloadOptions applies any supported options from the provided Options type. This returns an error if an option which doesn't support hot-swapping was changed. The provided Options type should not be re-used afterwards. Either use Options.Clone() to pass a copy, or make a new one.

func (*Server) Routez

func (s *Server) Routez(routezOpts *RoutezOptions) (*Routez, error)

Routez returns a Routez struct containing information about routes.

func (*Server) Running added in v2.2.0

func (s *Server) Running() bool

Public version.

func (*Server) SetAccountResolver

func (s *Server) SetAccountResolver(ar AccountResolver)

SetAccountResolver will assign the account resolver.

func (*Server) SetDefaultSystemAccount added in v2.2.0

func (s *Server) SetDefaultSystemAccount() error

SetDefaultSystemAccount will create a default system account if one is not present.

func (*Server) SetLogger

func (s *Server) SetLogger(logger Logger, debugFlag, traceFlag bool)

SetLogger sets the logger of the server

func (*Server) SetLoggerV2 added in v2.1.6

func (s *Server) SetLoggerV2(logger Logger, debugFlag, traceFlag, sysTrace bool)

SetLogger sets the logger of the server

func (*Server) SetSystemAccount

func (s *Server) SetSystemAccount(accName string) error

SetSystemAccount will set the internal system account. If root operators are present it will also check validity.

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown will shutdown the server instance by kicking out the AcceptLoop and closing all associated clients.

func (*Server) Start

func (s *Server) Start()

Start up the server, this will not block.

WaitForShutdown can be used to block and wait for the server to shutdown properly if needed after calling s.Shutdown()

func (*Server) StartHTTPMonitoring

func (s *Server) StartHTTPMonitoring()

StartHTTPMonitoring will enable the HTTP monitoring port. DEPRECATED: Should use StartMonitoring.

func (*Server) StartHTTPSMonitoring

func (s *Server) StartHTTPSMonitoring()

StartHTTPSMonitoring will enable the HTTPS monitoring port. DEPRECATED: Should use StartMonitoring.

func (*Server) StartMonitoring

func (s *Server) StartMonitoring() error

StartMonitoring starts the HTTP or HTTPs server if needed.

func (*Server) StartProfiler

func (s *Server) StartProfiler()

StartProfiler is called to enable dynamic profiling.

func (*Server) StartRouting

func (s *Server) StartRouting(clientListenReady chan struct{})

StartRouting will start the accept loop on the cluster host:port and will actively try to connect to listed routes.

func (*Server) StoreDir added in v2.2.0

func (s *Server) StoreDir() string

StoreDir returns the current JetStream directory.

func (*Server) String added in v2.2.0

func (s *Server) String() string

func (*Server) Subsz

func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error)

Subsz returns a Subsz struct containing subjects statistics

func (*Server) SystemAccount

func (s *Server) SystemAccount() *Account

SystemAccount returns the system account if set.

func (*Server) Tracef

func (s *Server) Tracef(format string, v ...any)

Tracef logs a trace statement

func (*Server) TrackedRemoteServers added in v2.1.0

func (s *Server) TrackedRemoteServers() int

TrackedRemoteServers returns how many remote servers we are tracking from a system events perspective.

func (*Server) UpdateAccountClaims

func (s *Server) UpdateAccountClaims(a *Account, ac *jwt.AccountClaims)

UpdateAccountClaims will update an existing account with new claims. This will replace any exports or imports previously defined. Lock MUST NOT be held upon entry.

func (*Server) Varz

func (s *Server) Varz(varzOpts *VarzOptions) (*Varz, error)

Varz returns a Varz struct containing the server information.

func (*Server) WaitForShutdown added in v2.1.6

func (s *Server) WaitForShutdown()

WaitForShutdown will block until the server has been fully shutdown.

func (*Server) Warnf

func (s *Server) Warnf(format string, v ...any)

Warnf logs a warning error

type ServerAPIAccountzResponse added in v2.10.24

type ServerAPIAccountzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Accountz   `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIAccountzResponse is the response type for accountz

type ServerAPIConnzResponse added in v2.4.0

type ServerAPIConnzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Connz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIConnzResponse is the response type connz

type ServerAPIExpvarzResponse added in v2.10.24

type ServerAPIExpvarzResponse struct {
	Server *ServerInfo    `json:"server"`
	Data   *ExpvarzStatus `json:"data,omitempty"`
	Error  *ApiError      `json:"error,omitempty"`
}

ServerAPIExpvarzResponse is the response type for expvarz

type ServerAPIGatewayzResponse added in v2.10.24

type ServerAPIGatewayzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Gatewayz   `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIGatewayzResponse is the response type for gatewayz

type ServerAPIHealthzResponse added in v2.10.24

type ServerAPIHealthzResponse struct {
	Server *ServerInfo   `json:"server"`
	Data   *HealthStatus `json:"data,omitempty"`
	Error  *ApiError     `json:"error,omitempty"`
}

ServerAPIHealthzResponse is the response type for healthz

type ServerAPIJszResponse added in v2.10.24

type ServerAPIJszResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *JSInfo     `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIJszResponse is the response type for jsz

type ServerAPILeafzResponse added in v2.10.24

type ServerAPILeafzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Leafz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPILeafzResponse is the response type for leafz

type ServerAPIResponse added in v2.4.0

type ServerAPIResponse struct {
	Server *ServerInfo `json:"server"`
	Data   any         `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
	// contains filtered or unexported fields
}

ServerAPIResponse is the response type for the server API like varz, connz etc.

type ServerAPIRoutezResponse added in v2.10.24

type ServerAPIRoutezResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Routez     `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIRoutezResponse is the response type for routez

type ServerAPISubszResponse added in v2.10.24

type ServerAPISubszResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Subsz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPISubszResponse is the response type for subsz

type ServerAPIVarzResponse added in v2.10.24

type ServerAPIVarzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Varz       `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

ServerAPIVarzResponse is the response type for varz

type ServerCapability added in v2.10.0

type ServerCapability uint64

Type for our server capabilities.

const (
	JetStreamEnabled     ServerCapability = 1 << iota // Server had JetStream enabled.
	BinaryStreamSnapshot                              // New stream snapshot capability.
)

type ServerID added in v2.10.0

type ServerID struct {
	Name string `json:"name"`
	Host string `json:"host"`
	ID   string `json:"id"`
}

ServerID is basic static info for a server.

type ServerInfo

type ServerInfo struct {
	Name    string   `json:"name"`
	Host    string   `json:"host"`
	ID      string   `json:"id"`
	Cluster string   `json:"cluster,omitempty"`
	Domain  string   `json:"domain,omitempty"`
	Version string   `json:"ver"`
	Tags    []string `json:"tags,omitempty"`
	// Whether JetStream is enabled (deprecated in favor of the `ServerCapability`).
	JetStream bool `json:"jetstream"`
	// Generic capability flags
	Flags ServerCapability `json:"flags"`
	// Sequence and Time from the remote server for this message.
	Seq  uint64    `json:"seq"`
	Time time.Time `json:"time"`
}

ServerInfo identifies remote servers.

func (*ServerInfo) BinaryStreamSnapshot added in v2.10.0

func (si *ServerInfo) BinaryStreamSnapshot() bool

JetStreamEnabled indicates whether or not we have binary stream snapshot capbilities.

func (*ServerInfo) JetStreamEnabled added in v2.10.0

func (si *ServerInfo) JetStreamEnabled() bool

JetStreamEnabled indicates whether or not we have JetStream enabled.

func (*ServerInfo) SetBinaryStreamSnapshot added in v2.10.0

func (si *ServerInfo) SetBinaryStreamSnapshot()

Set binary stream snapshot capability.

func (*ServerInfo) SetJetStreamEnabled added in v2.10.0

func (si *ServerInfo) SetJetStreamEnabled()

Set JetStream capability.

type ServerStats

type ServerStats struct {
	Start            time.Time      `json:"start"`
	Mem              int64          `json:"mem"`
	Cores            int            `json:"cores"`
	CPU              float64        `json:"cpu"`
	Connections      int            `json:"connections"`
	TotalConnections uint64         `json:"total_connections"`
	ActiveAccounts   int            `json:"active_accounts"`
	NumSubs          uint32         `json:"subscriptions"`
	Sent             DataStats      `json:"sent"`
	Received         DataStats      `json:"received"`
	SlowConsumers    int64          `json:"slow_consumers"`
	Routes           []*RouteStat   `json:"routes,omitempty"`
	Gateways         []*GatewayStat `json:"gateways,omitempty"`
	ActiveServers    int            `json:"active_servers,omitempty"`
	JetStream        *JetStreamVarz `json:"jetstream,omitempty"`
}

ServerStats hold various statistics that we will periodically send out.

type ServerStatsMsg

type ServerStatsMsg struct {
	Server ServerInfo  `json:"server"`
	Stats  ServerStats `json:"statsz"`
}

ServerStatsMsg is sent periodically with stats updates.

type ServiceLatency added in v2.1.0

type ServiceLatency struct {
	TypedEvent
	Status         int           `json:"status"`
	Error          string        `json:"description,omitempty"`
	Requestor      *ClientInfo   `json:"requestor,omitempty"`
	Responder      *ClientInfo   `json:"responder,omitempty"`
	RequestHeader  http.Header   `json:"header,omitempty"` // only contains header(s) triggering the measurement
	RequestStart   time.Time     `json:"start"`
	ServiceLatency time.Duration `json:"service"`
	SystemLatency  time.Duration `json:"system"`
	TotalLatency   time.Duration `json:"total"`
}

ServiceLatency is the JSON message sent out in response to latency tracking for an accounts exported services. Additional client info is available in requestor and responder. Note that for a requestor, the only information shared by default is the RTT used to calculate the total latency. The requestor's account can designate to share the additional information in the service import.

func (*ServiceLatency) NATSTotalTime added in v2.2.0

func (m1 *ServiceLatency) NATSTotalTime() time.Duration

NATSTotalTime is a helper function that totals the NATS latencies.

type ServiceRespType added in v2.0.4

type ServiceRespType uint8

ServiceRespType represents the types of service request response types.

const (
	Singleton ServiceRespType = iota
	Streamed
	Chunked
)

Service response types. Defaults to a singleton.

func (ServiceRespType) String added in v2.0.4

func (rt ServiceRespType) String() string

String helper.

type SignatureHandler added in v2.9.0

type SignatureHandler func([]byte) (string, []byte, error)

SignatureHandler is used to sign a nonce from the server while authenticating with Nkeys. The callback should sign the nonce and return the JWT and the raw signature.

type SimpleState added in v2.3.0

type SimpleState struct {
	Msgs  uint64 `json:"messages"`
	First uint64 `json:"first_seq"`
	Last  uint64 `json:"last_seq"`
	// contains filtered or unexported fields
}

SimpleState for filtered subject specific state.

type SlowConsumersStats added in v2.10.0

type SlowConsumersStats struct {
	Clients  uint64 `json:"clients"`
	Routes   uint64 `json:"routes"`
	Gateways uint64 `json:"gateways"`
	Leafs    uint64 `json:"leafs"`
}

SlowConsumersStats contains information about the slow consumers from different type of connections.

type SnapshotResult added in v2.2.0

type SnapshotResult struct {
	Reader io.ReadCloser
	State  StreamState
}

SnapshotResult contains information about the snapshot.

type SortOpt

type SortOpt string

SortOpt is a helper type to sort clients

const (
	ByCid      SortOpt = "cid"        // By connection ID
	ByStart    SortOpt = "start"      // By connection start time, same as CID
	BySubs     SortOpt = "subs"       // By number of subscriptions
	ByPending  SortOpt = "pending"    // By amount of data in bytes waiting to be sent to client
	ByOutMsgs  SortOpt = "msgs_to"    // By number of messages sent
	ByInMsgs   SortOpt = "msgs_from"  // By number of messages received
	ByOutBytes SortOpt = "bytes_to"   // By amount of bytes sent
	ByInBytes  SortOpt = "bytes_from" // By amount of bytes received
	ByLast     SortOpt = "last"       // By the last activity
	ByIdle     SortOpt = "idle"       // By the amount of inactivity
	ByUptime   SortOpt = "uptime"     // By the amount of time connections exist
	ByStop     SortOpt = "stop"       // By the stop time for a closed connection
	ByReason   SortOpt = "reason"     // By the reason for a closed connection
	ByRTT      SortOpt = "rtt"        // By the round trip time
)

Possible sort options

func (SortOpt) IsValid

func (s SortOpt) IsValid() bool

IsValid determines if a sort option is valid

type StatszEventOptions added in v2.2.0

type StatszEventOptions struct {
	// No actual options yet
	EventFilterOptions
}

StatszEventOptions are options passed to Statsz

type StorageType added in v2.2.0

type StorageType int

StorageType determines how messages are stored for retention.

func (StorageType) MarshalJSON added in v2.2.0

func (st StorageType) MarshalJSON() ([]byte, error)

func (StorageType) String added in v2.2.0

func (st StorageType) String() string

func (*StorageType) UnmarshalJSON added in v2.2.0

func (st *StorageType) UnmarshalJSON(data []byte) error

type StorageUpdateHandler added in v2.2.0

type StorageUpdateHandler func(msgs, bytes int64, seq uint64, subj string)

Used to call back into the upper layers to report on changes in storage resources. For the cases where its a single message we will also supply sequence number and subject.

type StoreCipher added in v2.9.0

type StoreCipher int
const (
	ChaCha StoreCipher = iota
	AES
	NoCipher
)

func (StoreCipher) String added in v2.9.0

func (cipher StoreCipher) String() string

type StoreCompression added in v2.10.0

type StoreCompression uint8
const (
	NoCompression StoreCompression = iota
	S2Compression
)

func (StoreCompression) Compress added in v2.10.0

func (alg StoreCompression) Compress(buf []byte) ([]byte, error)

func (StoreCompression) Decompress added in v2.10.0

func (alg StoreCompression) Decompress(buf []byte) ([]byte, error)

func (StoreCompression) MarshalJSON added in v2.10.0

func (alg StoreCompression) MarshalJSON() ([]byte, error)

func (StoreCompression) String added in v2.10.0

func (alg StoreCompression) String() string

func (*StoreCompression) UnmarshalJSON added in v2.10.0

func (alg *StoreCompression) UnmarshalJSON(b []byte) error

type StoreMsg added in v2.8.0

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

StoreMsg is the stored message format for messages that are retained by the Store layer.

type StoredMsg added in v2.2.0

type StoredMsg struct {
	Subject  string    `json:"subject"`
	Sequence uint64    `json:"seq"`
	Header   []byte    `json:"hdrs,omitempty"`
	Data     []byte    `json:"data,omitempty"`
	Time     time.Time `json:"time"`
}

StoredMsg is for raw access to messages in a stream.

type StreamAlternate added in v2.8.0

type StreamAlternate struct {
	Name    string `json:"name"`
	Domain  string `json:"domain,omitempty"`
	Cluster string `json:"cluster"`
}

type StreamConfig added in v2.2.0

type StreamConfig struct {
	Name         string           `json:"name"`
	Description  string           `json:"description,omitempty"`
	Subjects     []string         `json:"subjects,omitempty"`
	Retention    RetentionPolicy  `json:"retention"`
	MaxConsumers int              `json:"max_consumers"`
	MaxMsgs      int64            `json:"max_msgs"`
	MaxBytes     int64            `json:"max_bytes"`
	MaxAge       time.Duration    `json:"max_age"`
	MaxMsgsPer   int64            `json:"max_msgs_per_subject"`
	MaxMsgSize   int32            `json:"max_msg_size,omitempty"`
	Discard      DiscardPolicy    `json:"discard"`
	Storage      StorageType      `json:"storage"`
	Replicas     int              `json:"num_replicas"`
	NoAck        bool             `json:"no_ack,omitempty"`
	Template     string           `json:"template_owner,omitempty"`
	Duplicates   time.Duration    `json:"duplicate_window,omitempty"`
	Placement    *Placement       `json:"placement,omitempty"`
	Mirror       *StreamSource    `json:"mirror,omitempty"`
	Sources      []*StreamSource  `json:"sources,omitempty"`
	Compression  StoreCompression `json:"compression"`
	FirstSeq     uint64           `json:"first_seq,omitempty"`

	// Allow applying a subject transform to incoming messages before doing anything else
	SubjectTransform *SubjectTransformConfig `json:"subject_transform,omitempty"`

	// Allow republish of the message after being sequenced and stored.
	RePublish *RePublish `json:"republish,omitempty"`

	// Allow higher performance, direct access to get individual messages. E.g. KeyValue
	AllowDirect bool `json:"allow_direct"`
	// Allow higher performance and unified direct access for mirrors as well.
	MirrorDirect bool `json:"mirror_direct"`

	// Allow KV like semantics to also discard new on a per subject basis
	DiscardNewPer bool `json:"discard_new_per_subject,omitempty"`

	// Sealed will seal a stream so no messages can get out or in.
	Sealed bool `json:"sealed"`
	// DenyDelete will restrict the ability to delete messages.
	DenyDelete bool `json:"deny_delete"`
	// DenyPurge will restrict the ability to purge messages.
	DenyPurge bool `json:"deny_purge"`
	// AllowRollup allows messages to be placed into the system and purge
	// all older messages using a special msg header.
	AllowRollup bool `json:"allow_rollup_hdrs"`

	// The following defaults will apply to consumers when created against
	// this stream, unless overridden manually.
	// TODO(nat): Can/should we name these better?
	ConsumerLimits StreamConsumerLimits `json:"consumer_limits"`

	// Metadata is additional metadata for the Stream.
	Metadata map[string]string `json:"metadata,omitempty"`
}

StreamConfig will determine the name, subjects and retention policy for a given stream. If subjects is empty the name will be used.

type StreamConsumerLimits added in v2.10.0

type StreamConsumerLimits struct {
	InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
	MaxAckPending     int           `json:"max_ack_pending,omitempty"`
}

type StreamDetail added in v2.2.0

type StreamDetail struct {
	Name               string              `json:"name"`
	Created            time.Time           `json:"created"`
	Cluster            *ClusterInfo        `json:"cluster,omitempty"`
	Config             *StreamConfig       `json:"config,omitempty"`
	State              StreamState         `json:"state,omitempty"`
	Consumer           []*ConsumerInfo     `json:"consumer_detail,omitempty"`
	Mirror             *StreamSourceInfo   `json:"mirror,omitempty"`
	Sources            []*StreamSourceInfo `json:"sources,omitempty"`
	RaftGroup          string              `json:"stream_raft_group,omitempty"`
	ConsumerRaftGroups []*RaftGroupDetail  `json:"consumer_raft_groups,omitempty"`
}

StreamDetail shows information about the stream state and its consumers.

type StreamInfo added in v2.2.0

type StreamInfo struct {
	Config     StreamConfig        `json:"config"`
	Created    time.Time           `json:"created"`
	State      StreamState         `json:"state"`
	Domain     string              `json:"domain,omitempty"`
	Cluster    *ClusterInfo        `json:"cluster,omitempty"`
	Mirror     *StreamSourceInfo   `json:"mirror,omitempty"`
	Sources    []*StreamSourceInfo `json:"sources,omitempty"`
	Alternates []StreamAlternate   `json:"alternates,omitempty"`
	// TimeStamp indicates when the info was gathered
	TimeStamp time.Time `json:"ts"`
}

StreamInfo shows config and current state for this stream.

type StreamReplicatedState added in v2.10.0

type StreamReplicatedState struct {
	Msgs     uint64
	Bytes    uint64
	FirstSeq uint64
	LastSeq  uint64
	Failed   uint64
	Deleted  DeleteBlocks
}

StreamReplicatedState represents what is encoded in a binary stream snapshot used for stream replication in an NRG.

func DecodeStreamState added in v2.10.0

func DecodeStreamState(buf []byte) (*StreamReplicatedState, error)

type StreamSource added in v2.2.0

type StreamSource struct {
	Name              string                   `json:"name"`
	OptStartSeq       uint64                   `json:"opt_start_seq,omitempty"`
	OptStartTime      *time.Time               `json:"opt_start_time,omitempty"`
	FilterSubject     string                   `json:"filter_subject,omitempty"`
	SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
	External          *ExternalStream          `json:"external,omitempty"`
	// contains filtered or unexported fields
}

StreamSource dictates how streams can source from other streams.

type StreamSourceInfo added in v2.2.0

type StreamSourceInfo struct {
	Name              string                   `json:"name"`
	External          *ExternalStream          `json:"external,omitempty"`
	Lag               uint64                   `json:"lag"`
	Active            time.Duration            `json:"active"`
	Error             *ApiError                `json:"error,omitempty"`
	FilterSubject     string                   `json:"filter_subject,omitempty"`
	SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
}

StreamSourceInfo shows information about an upstream stream source.

type StreamState added in v2.2.0

type StreamState struct {
	Msgs        uint64            `json:"messages"`
	Bytes       uint64            `json:"bytes"`
	FirstSeq    uint64            `json:"first_seq"`
	FirstTime   time.Time         `json:"first_ts"`
	LastSeq     uint64            `json:"last_seq"`
	LastTime    time.Time         `json:"last_ts"`
	NumSubjects int               `json:"num_subjects,omitempty"`
	Subjects    map[string]uint64 `json:"subjects,omitempty"`
	NumDeleted  int               `json:"num_deleted,omitempty"`
	Deleted     []uint64          `json:"deleted,omitempty"`
	Lost        *LostStreamData   `json:"lost,omitempty"`
	Consumers   int               `json:"consumer_count"`
}

StreamState is information about the given stream.

type StreamStore added in v2.2.0

type StreamStore interface {
	StoreMsg(subject string, hdr, msg []byte) (uint64, int64, error)
	StoreRawMsg(subject string, hdr, msg []byte, seq uint64, ts int64) error
	SkipMsg() uint64
	SkipMsgs(seq uint64, num uint64) error
	LoadMsg(seq uint64, sm *StoreMsg) (*StoreMsg, error)
	LoadNextMsg(filter string, wc bool, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error)
	LoadNextMsgMulti(sl *Sublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error)
	LoadLastMsg(subject string, sm *StoreMsg) (*StoreMsg, error)
	RemoveMsg(seq uint64) (bool, error)
	EraseMsg(seq uint64) (bool, error)
	Purge() (uint64, error)
	PurgeEx(subject string, seq, keep uint64) (uint64, error)
	Compact(seq uint64) (uint64, error)
	Truncate(seq uint64) error
	GetSeqFromTime(t time.Time) uint64
	FilteredState(seq uint64, subject string) SimpleState
	SubjectsState(filterSubject string) map[string]SimpleState
	SubjectsTotals(filterSubject string) map[string]uint64
	NumPending(sseq uint64, filter string, lastPerSubject bool) (total, validThrough uint64)
	NumPendingMulti(sseq uint64, sl *Sublist, lastPerSubject bool) (total, validThrough uint64)
	State() StreamState
	FastState(*StreamState)
	EncodedStreamState(failed uint64) (enc []byte, err error)
	SyncDeleted(dbs DeleteBlocks)
	Type() StorageType
	RegisterStorageUpdates(StorageUpdateHandler)
	UpdateConfig(cfg *StreamConfig) error
	Delete() error
	Stop() error
	ConsumerStore(name string, cfg *ConsumerConfig) (ConsumerStore, error)
	AddConsumer(o ConsumerStore) error
	RemoveConsumer(o ConsumerStore) error
	Snapshot(deadline time.Duration, includeConsumers, checkMsgs bool) (*SnapshotResult, error)
	Utilization() (total, reported uint64, err error)
}

type StreamTemplateConfig added in v2.2.0

type StreamTemplateConfig struct {
	Name       string        `json:"name"`
	Config     *StreamConfig `json:"config"`
	MaxStreams uint32        `json:"max_streams"`
}

StreamTemplateConfig allows a configuration to auto-create streams based on this template when a message is received that matches. Each new stream will use the config as the template config to create them.

type StreamTemplateInfo added in v2.2.0

type StreamTemplateInfo struct {
	Config  *StreamTemplateConfig `json:"config"`
	Streams []string              `json:"streams"`
}

StreamTemplateInfo

type SubDetail

type SubDetail struct {
	Account string `json:"account,omitempty"`
	Subject string `json:"subject"`
	Queue   string `json:"qgroup,omitempty"`
	Sid     string `json:"sid"`
	Msgs    int64  `json:"msgs"`
	Max     int64  `json:"max,omitempty"`
	Cid     uint64 `json:"cid"`
}

SubDetail is for verbose information for subscriptions.

type SubjectPermission

type SubjectPermission struct {
	Allow []string `json:"allow,omitempty"`
	Deny  []string `json:"deny,omitempty"`
}

SubjectPermission is an individual allow and deny struct for publish and subscribe authorizations.

type SubjectTransformConfig added in v2.10.0

type SubjectTransformConfig struct {
	Source      string `json:"src"`
	Destination string `json:"dest"`
}

SubjectTransformConfig is for applying a subject transform (to matching messages) before doing anything else when a new message is received

type SubjectTransformer added in v2.9.0

type SubjectTransformer interface {
	// TODO(dlc) - We could add in client here to allow for things like foo -> foo.$ACCOUNT
	Match(string) (string, error)
	TransformSubject(subject string) string
	TransformTokenizedSubject(tokens []string) string
}

SubjectTransformer transforms subjects using mappings

This API is not part of the public API and not subject to SemVer protections

type Sublist

type Sublist struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

A Sublist stores and efficiently retrieves subscriptions.

func NewSublist

func NewSublist(enableCache bool) *Sublist

NewSublist will create a default sublist with caching enabled per the flag.

func NewSublistNoCache

func NewSublistNoCache() *Sublist

NewSublistNoCache will create a default sublist with caching disabled.

func NewSublistWithCache added in v2.0.2

func NewSublistWithCache() *Sublist

NewSublistWithCache will create a default sublist with caching enabled.

func (*Sublist) All

func (s *Sublist) All(subs *[]*subscription)

All is used to collect all subscriptions.

func (*Sublist) CacheCount

func (s *Sublist) CacheCount() int

CacheCount returns the number of result sets in the cache.

func (*Sublist) CacheEnabled

func (s *Sublist) CacheEnabled() bool

CacheEnabled returns whether or not caching is enabled for this sublist.

func (*Sublist) ClearNotification added in v2.2.0

func (s *Sublist) ClearNotification(subject string, notify chan<- bool) bool

func (*Sublist) ClearQueueNotification added in v2.4.0

func (s *Sublist) ClearQueueNotification(subject, queue string, notify chan<- bool) bool

func (*Sublist) Count

func (s *Sublist) Count() uint32

Count returns the number of subscriptions.

func (*Sublist) HasInterest added in v2.10.15

func (s *Sublist) HasInterest(subject string) bool

HasInterest will return whether or not there is any interest in the subject. In cases where more detail is not required, this may be faster than Match.

func (*Sublist) Insert

func (s *Sublist) Insert(sub *subscription) error

Insert adds a subscription into the sublist

func (*Sublist) Match

func (s *Sublist) Match(subject string) *SublistResult

Match will match all entries to the literal subject. It will return a set of results for both normal and queue subscribers.

func (*Sublist) MatchBytes added in v2.10.19

func (s *Sublist) MatchBytes(subject []byte) *SublistResult

MatchBytes will match all entries to the literal subject. It will return a set of results for both normal and queue subscribers.

func (*Sublist) NumInterest added in v2.10.22

func (s *Sublist) NumInterest(subject string) (np, nq int)

NumInterest will return the number of subs/qsubs interested in the subject. In cases where more detail is not required, this may be faster than Match.

func (*Sublist) RegisterNotification added in v2.2.0

func (s *Sublist) RegisterNotification(subject string, notify chan<- bool) error

RegisterNotification will register for notifications when interest for the given subject changes. The subject must be a literal publish type subject. The notification is true for when the first interest for a subject is inserted, and false when all interest in the subject is removed. Note that this interest needs to be exact and that wildcards will not trigger the notifications. The sublist will not block when trying to send the notification. Its up to the caller to make sure the channel send will not block.

func (*Sublist) RegisterQueueNotification added in v2.4.0

func (s *Sublist) RegisterQueueNotification(subject, queue string, notify chan<- bool) error

func (*Sublist) Remove

func (s *Sublist) Remove(sub *subscription) error

Remove will remove a subscription.

func (*Sublist) RemoveBatch

func (s *Sublist) RemoveBatch(subs []*subscription) error

RemoveBatch will remove a list of subscriptions.

func (*Sublist) ReverseMatch added in v2.2.0

func (s *Sublist) ReverseMatch(subject string) *SublistResult

For a given subject (which may contain wildcards), this call returns all subscriptions that would match that subject. For instance, suppose that the sublist contains: foo.bar, foo.bar.baz and foo.baz, ReverseMatch("foo.*") would return foo.bar and foo.baz. This is used in situations where the sublist is likely to contain only literals and one wants to get all the subjects that would have been a match to a subscription on `subject`.

func (*Sublist) Stats

func (s *Sublist) Stats() *SublistStats

Stats will return a stats structure for the current state.

func (*Sublist) UpdateRemoteQSub

func (s *Sublist) UpdateRemoteQSub(sub *subscription)

UpdateRemoteQSub should be called when we update the weight of an existing remote queue sub.

type SublistResult

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

SublistResult is a result structure better optimized for queue subs.

type SublistStats

type SublistStats struct {
	NumSubs      uint32  `json:"num_subscriptions"`
	NumCache     uint32  `json:"num_cache"`
	NumInserts   uint64  `json:"num_inserts"`
	NumRemoves   uint64  `json:"num_removes"`
	NumMatches   uint64  `json:"num_matches"`
	CacheHitRate float64 `json:"cache_hit_rate"`
	MaxFanout    uint32  `json:"max_fanout"`
	AvgFanout    float64 `json:"avg_fanout"`
	// contains filtered or unexported fields
}

SublistStats are public stats for the sublist

type Subsz

type Subsz struct {
	ID  string    `json:"server_id"`
	Now time.Time `json:"now"`
	*SublistStats
	Total  int         `json:"total"`
	Offset int         `json:"offset"`
	Limit  int         `json:"limit"`
	Subs   []SubDetail `json:"subscriptions_list,omitempty"`
}

Subsz represents detail information on current connections.

type SubszEventOptions added in v2.2.0

type SubszEventOptions struct {
	SubszOptions
	EventFilterOptions
}

In the context of system events, SubzEventOptions are options passed to Subz

type SubszOptions

type SubszOptions struct {
	// Offset is used for pagination. Subsz() only returns connections starting at this
	// offset from the global results.
	Offset int `json:"offset"`

	// Limit is the maximum number of subscriptions that should be returned by Subsz().
	Limit int `json:"limit"`

	// Subscriptions indicates if subscription details should be included in the results.
	Subscriptions bool `json:"subscriptions"`

	// Filter based on this account name.
	Account string `json:"account,omitempty"`

	// Test the list against this subject. Needs to be literal since it signifies a publish subject.
	// We will only return subscriptions that would match if a message was sent to this subject.
	Test string `json:"test,omitempty"`
}

SubszOptions are the options passed to Subsz. As of now, there are no options defined.

type TLSCertPairOpt added in v2.10.8

type TLSCertPairOpt struct {
	CertFile string
	KeyFile  string
}

TLSCertPairOpt are the paths to a certificate and private key.

type TLSConfigOpts

type TLSConfigOpts struct {
	CertFile             string
	KeyFile              string
	CaFile               string
	Verify               bool
	Insecure             bool
	Map                  bool
	TLSCheckKnownURLs    bool
	HandshakeFirst       bool          // Indicate that the TLS handshake should occur first, before sending the INFO protocol.
	FallbackDelay        time.Duration // Where supported, indicates how long to wait for the handshake before falling back to sending the INFO protocol first.
	Timeout              float64
	RateLimit            int64
	Ciphers              []uint16
	CurvePreferences     []tls.CurveID
	PinnedCerts          PinnedCertSet
	CertStore            certstore.StoreType
	CertMatchBy          certstore.MatchByType
	CertMatch            string
	CertMatchSkipInvalid bool
	CaCertsMatch         []string
	OCSPPeerConfig       *certidp.OCSPPeerConfig
	Certificates         []*TLSCertPairOpt
	MinVersion           uint16
}

TLSConfigOpts holds the parsed tls config information, used with flag parsing

type TLSPeerCert added in v2.9.0

type TLSPeerCert struct {
	Subject          string `json:"subject,omitempty"`
	SubjectPKISha256 string `json:"spki_sha256,omitempty"`
	CertSha256       string `json:"cert_sha256,omitempty"`
}

TLSPeerCert contains basic information about a TLS peer certificate

type TemplateStore added in v2.2.0

type TemplateStore interface {
	Store(*streamTemplate) error
	Delete(*streamTemplate) error
}

TemplateStore stores templates.

type TypedEvent added in v2.2.0

type TypedEvent struct {
	Type string    `json:"type"`
	ID   string    `json:"id"`
	Time time.Time `json:"timestamp"`
}

TypedEvent is a event or advisory sent by the server that has nats type hints typically used for events that might be consumed by 3rd party event systems

type URLAccResolver

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

URLAccResolver implements an http fetcher.

func NewURLAccResolver

func NewURLAccResolver(url string) (*URLAccResolver, error)

NewURLAccResolver returns a new resolver for the given base URL.

func (*URLAccResolver) Close added in v2.2.0

func (*URLAccResolver) Close()

func (*URLAccResolver) Fetch

func (ur *URLAccResolver) Fetch(name string) (string, error)

Fetch will fetch the account jwt claims from the base url, appending the account name onto the end.

func (*URLAccResolver) IsReadOnly added in v2.2.0

func (*URLAccResolver) IsReadOnly() bool

func (*URLAccResolver) IsTrackingUpdate added in v2.2.0

func (*URLAccResolver) IsTrackingUpdate() bool

func (*URLAccResolver) Reload added in v2.2.0

func (*URLAccResolver) Reload() error

func (*URLAccResolver) Start added in v2.2.0

func (*URLAccResolver) Start(*Server) error

func (*URLAccResolver) Store

func (*URLAccResolver) Store(_, _ string) error

type User

type User struct {
	Username               string              `json:"user"`
	Password               string              `json:"password"`
	Permissions            *Permissions        `json:"permissions,omitempty"`
	Account                *Account            `json:"account,omitempty"`
	ConnectionDeadline     time.Time           `json:"connection_deadline,omitempty"`
	AllowedConnectionTypes map[string]struct{} `json:"connection_types,omitempty"`
}

User is for multiple accounts/users.

type UserInfo added in v2.10.0

type UserInfo struct {
	UserID      string        `json:"user"`
	Account     string        `json:"account"`
	Permissions *Permissions  `json:"permissions,omitempty"`
	Expires     time.Duration `json:"expires,omitempty"`
}

UserInfo returns basic information to a user about bound account and user permissions. For account information they will need to ping that separately, and this allows security controls on each subsystem if desired, e.g. account info, jetstream account info, etc.

type Varz

type Varz struct {
	ID                    string                 `json:"server_id"`
	Name                  string                 `json:"server_name"`
	Version               string                 `json:"version"`
	Proto                 int                    `json:"proto"`
	GitCommit             string                 `json:"git_commit,omitempty"`
	GoVersion             string                 `json:"go"`
	Host                  string                 `json:"host"`
	Port                  int                    `json:"port"`
	AuthRequired          bool                   `json:"auth_required,omitempty"`
	TLSRequired           bool                   `json:"tls_required,omitempty"`
	TLSVerify             bool                   `json:"tls_verify,omitempty"`
	TLSOCSPPeerVerify     bool                   `json:"tls_ocsp_peer_verify,omitempty"`
	IP                    string                 `json:"ip,omitempty"`
	ClientConnectURLs     []string               `json:"connect_urls,omitempty"`
	WSConnectURLs         []string               `json:"ws_connect_urls,omitempty"`
	MaxConn               int                    `json:"max_connections"`
	MaxSubs               int                    `json:"max_subscriptions,omitempty"`
	PingInterval          time.Duration          `json:"ping_interval"`
	MaxPingsOut           int                    `json:"ping_max"`
	HTTPHost              string                 `json:"http_host"`
	HTTPPort              int                    `json:"http_port"`
	HTTPBasePath          string                 `json:"http_base_path"`
	HTTPSPort             int                    `json:"https_port"`
	AuthTimeout           float64                `json:"auth_timeout"`
	MaxControlLine        int32                  `json:"max_control_line"`
	MaxPayload            int                    `json:"max_payload"`
	MaxPending            int64                  `json:"max_pending"`
	Cluster               ClusterOptsVarz        `json:"cluster,omitempty"`
	Gateway               GatewayOptsVarz        `json:"gateway,omitempty"`
	LeafNode              LeafNodeOptsVarz       `json:"leaf,omitempty"`
	MQTT                  MQTTOptsVarz           `json:"mqtt,omitempty"`
	Websocket             WebsocketOptsVarz      `json:"websocket,omitempty"`
	JetStream             JetStreamVarz          `json:"jetstream,omitempty"`
	TLSTimeout            float64                `json:"tls_timeout"`
	WriteDeadline         time.Duration          `json:"write_deadline"`
	Start                 time.Time              `json:"start"`
	Now                   time.Time              `json:"now"`
	Uptime                string                 `json:"uptime"`
	Mem                   int64                  `json:"mem"`
	Cores                 int                    `json:"cores"`
	MaxProcs              int                    `json:"gomaxprocs"`
	CPU                   float64                `json:"cpu"`
	Connections           int                    `json:"connections"`
	TotalConnections      uint64                 `json:"total_connections"`
	Routes                int                    `json:"routes"`
	Remotes               int                    `json:"remotes"`
	Leafs                 int                    `json:"leafnodes"`
	InMsgs                int64                  `json:"in_msgs"`
	OutMsgs               int64                  `json:"out_msgs"`
	InBytes               int64                  `json:"in_bytes"`
	OutBytes              int64                  `json:"out_bytes"`
	SlowConsumers         int64                  `json:"slow_consumers"`
	Subscriptions         uint32                 `json:"subscriptions"`
	HTTPReqStats          map[string]uint64      `json:"http_req_stats"`
	ConfigLoadTime        time.Time              `json:"config_load_time"`
	Tags                  jwt.TagList            `json:"tags,omitempty"`
	TrustedOperatorsJwt   []string               `json:"trusted_operators_jwt,omitempty"`
	TrustedOperatorsClaim []*jwt.OperatorClaims  `json:"trusted_operators_claim,omitempty"`
	SystemAccount         string                 `json:"system_account,omitempty"`
	PinnedAccountFail     uint64                 `json:"pinned_account_fails,omitempty"`
	OCSPResponseCache     *OCSPResponseCacheVarz `json:"ocsp_peer_cache,omitempty"`
	SlowConsumersStats    *SlowConsumersStats    `json:"slow_consumer_stats"`
}

Varz will output server information on the monitoring port at /varz.

type VarzEventOptions added in v2.2.0

type VarzEventOptions struct {
	VarzOptions
	EventFilterOptions
}

In the context of system events, VarzEventOptions are options passed to Varz

type VarzOptions

type VarzOptions struct{}

VarzOptions are the options passed to Varz(). Currently, there are no options defined.

type WAL added in v2.2.0

type WAL interface {
	Type() StorageType
	StoreMsg(subj string, hdr, msg []byte) (uint64, int64, error)
	LoadMsg(index uint64, sm *StoreMsg) (*StoreMsg, error)
	RemoveMsg(index uint64) (bool, error)
	Compact(index uint64) (uint64, error)
	Purge() (uint64, error)
	PurgeEx(subject string, seq, keep uint64) (uint64, error)
	Truncate(seq uint64) error
	State() StreamState
	FastState(*StreamState)
	Stop() error
	Delete() error
}

type WebsocketOpts added in v2.2.0

type WebsocketOpts struct {
	// The server will accept websocket client connections on this hostname/IP.
	Host string
	// The server will accept websocket client connections on this port.
	Port int
	// The host:port to advertise to websocket clients in the cluster.
	Advertise string

	// If no user name is provided when a client connects, will default to the
	// matching user from the global list of users in `Options.Users`.
	NoAuthUser string

	// Name of the cookie, which if present in WebSocket upgrade headers,
	// will be treated as JWT during CONNECT phase as long as
	// "jwt" specified in the CONNECT options is missing or empty.
	JWTCookie string

	// Authentication section. If anything is configured in this section,
	// it will override the authorization configuration of regular clients.
	Username string
	Password string
	Token    string

	// Timeout for the authentication process.
	AuthTimeout float64

	// By default the server will enforce the use of TLS. If no TLS configuration
	// is provided, you need to explicitly set NoTLS to true to allow the server
	// to start without TLS configuration. Note that if a TLS configuration is
	// present, this boolean is ignored and the server will run the Websocket
	// server with that TLS configuration.
	// Running without TLS is less secure since Websocket clients that use bearer
	// tokens will send them in clear. So this should not be used in production.
	NoTLS bool

	// TLS configuration is required.
	TLSConfig *tls.Config
	// If true, map certificate values for authentication purposes.
	TLSMap bool

	// When present, accepted client certificates (verify/verify_and_map) must be in this list
	TLSPinnedCerts PinnedCertSet

	// If true, the Origin header must match the request's host.
	SameOrigin bool

	// Only origins in this list will be accepted. If empty and
	// SameOrigin is false, any origin is accepted.
	AllowedOrigins []string

	// If set to true, the server will negotiate with clients
	// if compression can be used. If this is false, no compression
	// will be used (both in server and clients) since it has to
	// be negotiated between both endpoints
	Compression bool

	// Total time allowed for the server to read the client request
	// and write the response back to the client. This include the
	// time needed for the TLS Handshake.
	HandshakeTimeout time.Duration
	// contains filtered or unexported fields
}

WebsocketOpts are options for websocket

type WebsocketOptsVarz added in v2.8.0

type WebsocketOptsVarz struct {
	Host              string        `json:"host,omitempty"`
	Port              int           `json:"port,omitempty"`
	Advertise         string        `json:"advertise,omitempty"`
	NoAuthUser        string        `json:"no_auth_user,omitempty"`
	JWTCookie         string        `json:"jwt_cookie,omitempty"`
	HandshakeTimeout  time.Duration `json:"handshake_timeout,omitempty"`
	AuthTimeout       float64       `json:"auth_timeout,omitempty"`
	NoTLS             bool          `json:"no_tls,omitempty"`
	TLSMap            bool          `json:"tls_map,omitempty"`
	TLSPinnedCerts    []string      `json:"tls_pinned_certs,omitempty"`
	SameOrigin        bool          `json:"same_origin,omitempty"`
	AllowedOrigins    []string      `json:"allowed_origins,omitempty"`
	Compression       bool          `json:"compression,omitempty"`
	TLSOCSPPeerVerify bool          `json:"tls_ocsp_peer_verify,omitempty"`
}

WebsocketOptsVarz contains monitoring websocket information

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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