| 1 |
// Copyright 2019-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"encoding/binary" |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"math/bits" |
| 22 |
"os" |
| 23 |
"strings" |
| 24 |
"time" |
| 25 |
"unsafe" |
| 26 |
|
| 27 |
"github.com/nats-io/nats-server/v2/server/avl" |
| 28 |
"github.com/nats-io/nats-server/v2/server/gsl" |
| 29 |
) |
| 30 |
|
| 31 |
// StorageType determines how messages are stored for retention. |
| 32 |
type StorageType int |
| 33 |
|
| 34 |
const ( |
| 35 |
// File specifies on disk, designated by the JetStream config StoreDir. |
| 36 |
FileStorage = StorageType(22) |
| 37 |
// MemoryStorage specifies in memory only. |
| 38 |
MemoryStorage = StorageType(33) |
| 39 |
) |
| 40 |
|
| 41 |
var ( |
| 42 |
// ErrStoreClosed is returned when the store has been closed |
| 43 |
ErrStoreClosed = errors.New("store is closed") |
| 44 |
// ErrStoreMsgNotFound when message was not found but was expected to be. |
| 45 |
ErrStoreMsgNotFound = errors.New("no message found") |
| 46 |
// ErrStoreEOF is returned when message seq is greater than the last sequence. |
| 47 |
ErrStoreEOF = errors.New("stream store EOF") |
| 48 |
// ErrMaxMsgs is returned when we have discard new as a policy and we reached the message limit. |
| 49 |
ErrMaxMsgs = errors.New("maximum messages exceeded") |
| 50 |
// ErrMaxBytes is returned when we have discard new as a policy and we reached the bytes limit. |
| 51 |
ErrMaxBytes = errors.New("maximum bytes exceeded") |
| 52 |
// ErrMaxMsgsPerSubject is returned when we have discard new as a policy and we reached the message limit per subject. |
| 53 |
ErrMaxMsgsPerSubject = errors.New("maximum messages per subject exceeded") |
| 54 |
// ErrStoreSnapshotInProgress is returned when RemoveMsg or EraseMsg is called |
| 55 |
// while a snapshot is in progress. |
| 56 |
ErrStoreSnapshotInProgress = errors.New("snapshot in progress") |
| 57 |
// ErrMsgTooLarge is returned when a message is considered too large. |
| 58 |
ErrMsgTooLarge = errors.New("message too large") |
| 59 |
// ErrStoreWrongType is for when you access the wrong storage type. |
| 60 |
ErrStoreWrongType = errors.New("wrong storage type") |
| 61 |
// ErrNoAckPolicy is returned when trying to update a consumer's acks with no ack policy. |
| 62 |
ErrNoAckPolicy = errors.New("ack policy is none") |
| 63 |
// ErrSequenceMismatch is returned when storing a raw message and the expected sequence is wrong. |
| 64 |
ErrSequenceMismatch = errors.New("expected sequence does not match store") |
| 65 |
// ErrCorruptStreamState |
| 66 |
ErrCorruptStreamState = errors.New("stream state snapshot is corrupt") |
| 67 |
// ErrTooManyResults |
| 68 |
ErrTooManyResults = errors.New("too many matching results for request") |
| 69 |
// ErrStoreOldUpdate is returned when a consumer update is older than the current state. |
| 70 |
ErrStoreOldUpdate = errors.New("old update ignored") |
| 71 |
) |
| 72 |
|
| 73 |
// StoreMsg is the stored message format for messages that are retained by the Store layer. |
| 74 |
type StoreMsg struct { |
| 75 |
subj string |
| 76 |
hdr []byte |
| 77 |
msg []byte |
| 78 |
buf []byte |
| 79 |
seq uint64 |
| 80 |
ts int64 |
| 81 |
} |
| 82 |
|
| 83 |
// Used to call back into the upper layers to report on changes in storage resources. |
| 84 |
// For the cases where its a single message we will also supply sequence number and subject. |
| 85 |
type StorageUpdateHandler func(msgs, bytes int64, seq uint64, subj string) |
| 86 |
|
| 87 |
// Used to call back into the upper layers to remove a message. |
| 88 |
type StorageRemoveMsgHandler func(seq uint64) |
| 89 |
|
| 90 |
// Used to call back into the upper layers to process a JetStream message. |
| 91 |
// Will propose the message if the stream is replicated. |
| 92 |
type ProcessJetStreamMsgHandler func(*inMsg) |
| 93 |
|
| 94 |
type StreamStore interface { |
| 95 |
StoreMsg(subject string, hdr, msg []byte, ttl int64) (uint64, int64, error) |
| 96 |
StoreRawMsg(subject string, hdr, msg []byte, seq uint64, ts int64, ttl int64, discardNewCheck bool) error |
| 97 |
SkipMsg(seq uint64) (uint64, error) |
| 98 |
SkipMsgNoInterest(seq uint64) (uint64, error) |
| 99 |
SkipMsgs(seq uint64, num uint64) error |
| 100 |
FlushAllPending() error |
| 101 |
LoadMsg(seq uint64, sm *StoreMsg) (*StoreMsg, error) |
| 102 |
LoadNextMsg(filter string, wc bool, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) |
| 103 |
LoadNextMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) |
| 104 |
LoadLastMsg(subject string, sm *StoreMsg) (*StoreMsg, error) |
| 105 |
LoadPrevMsg(filter string, wc bool, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) |
| 106 |
LoadPrevMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) |
| 107 |
RemoveMsg(seq uint64) (bool, error) |
| 108 |
EraseMsg(seq uint64) (bool, error) |
| 109 |
Purge() (uint64, error) |
| 110 |
PurgeEx(subject string, seq, keep uint64) (uint64, error) |
| 111 |
Compact(seq uint64) (uint64, error) |
| 112 |
Truncate(seq uint64) error |
| 113 |
GetSeqFromTime(t time.Time) uint64 |
| 114 |
FilteredState(seq uint64, subject string) (SimpleState, error) |
| 115 |
SubjectsState(filterSubject string) map[string]SimpleState |
| 116 |
SubjectsTotals(filterSubject string) map[string]uint64 |
| 117 |
AllLastSeqs() ([]uint64, error) |
| 118 |
MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) |
| 119 |
MultiLastMsgs(filters []string, minSeq, maxSeq uint64, maxAllowed int, cb func(sm *StoreMsg, np uint64) bool) (uint64, uint64, error) |
| 120 |
SubjectForSeq(seq uint64) (string, error) |
| 121 |
NumPending(sseq uint64, filter string, lastPerSubject bool) (total, validThrough uint64, err error) |
| 122 |
NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPerSubject bool) (total, validThrough uint64, err error) |
| 123 |
State() StreamState |
| 124 |
FastState(*StreamState) |
| 125 |
EncodedStreamState(failed uint64) (enc []byte, err error) |
| 126 |
SyncDeleted(dbs DeleteBlocks) error |
| 127 |
Type() StorageType |
| 128 |
RegisterStorageUpdates(StorageUpdateHandler) |
| 129 |
RegisterStorageRemoveMsg(StorageRemoveMsgHandler) |
| 130 |
RegisterProcessJetStreamMsg(ProcessJetStreamMsgHandler) |
| 131 |
UpdateConfig(cfg *StreamConfig) error |
| 132 |
Delete(inline bool) error |
| 133 |
Stop() error |
| 134 |
ConsumerStore(name string, created time.Time, cfg *ConsumerConfig) (ConsumerStore, error) |
| 135 |
AddConsumer(o ConsumerStore) error |
| 136 |
RemoveConsumer(o ConsumerStore) error |
| 137 |
Snapshot(deadline time.Duration, includeConsumers, checkMsgs bool) (*SnapshotResult, error) |
| 138 |
Utilization() (total, reported uint64, err error) |
| 139 |
ResetState() |
| 140 |
} |
| 141 |
|
| 142 |
// RetentionPolicy determines how messages in a set are retained. |
| 143 |
type RetentionPolicy int |
| 144 |
|
| 145 |
const ( |
| 146 |
// LimitsPolicy (default) means that messages are retained until any given limit is reached. |
| 147 |
// This could be one of MaxMsgs, MaxBytes, or MaxAge. |
| 148 |
LimitsPolicy RetentionPolicy = iota |
| 149 |
// InterestPolicy specifies that when all known consumers have acknowledged a message it can be removed. |
| 150 |
InterestPolicy |
| 151 |
// WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed. |
| 152 |
WorkQueuePolicy |
| 153 |
) |
| 154 |
|
| 155 |
// Discard Policy determines how we proceed when limits of messages or bytes are hit. The default, DicscardOld will |
| 156 |
// remove older messages. DiscardNew will fail to store the new message. |
| 157 |
type DiscardPolicy int |
| 158 |
|
| 159 |
const ( |
| 160 |
// DiscardOld will remove older messages to return to the limits. |
| 161 |
DiscardOld = iota |
| 162 |
// DiscardNew will error on a StoreMsg call |
| 163 |
DiscardNew |
| 164 |
) |
| 165 |
|
| 166 |
// StreamState is information about the given stream. |
| 167 |
type StreamState struct { |
| 168 |
Msgs uint64 `json:"messages"` |
| 169 |
Bytes uint64 `json:"bytes"` |
| 170 |
FirstSeq uint64 `json:"first_seq"` |
| 171 |
FirstTime time.Time `json:"first_ts"` |
| 172 |
LastSeq uint64 `json:"last_seq"` |
| 173 |
LastTime time.Time `json:"last_ts"` |
| 174 |
NumSubjects int `json:"num_subjects,omitempty"` |
| 175 |
Subjects map[string]uint64 `json:"subjects,omitempty"` |
| 176 |
NumDeleted int `json:"num_deleted,omitempty"` |
| 177 |
Deleted []uint64 `json:"deleted,omitempty"` |
| 178 |
Lost *LostStreamData `json:"lost,omitempty"` |
| 179 |
Consumers int `json:"consumer_count"` |
| 180 |
} |
| 181 |
|
| 182 |
// SimpleState for filtered subject specific state. |
| 183 |
type SimpleState struct { |
| 184 |
Msgs uint64 `json:"messages"` |
| 185 |
First uint64 `json:"first_seq"` |
| 186 |
Last uint64 `json:"last_seq"` |
| 187 |
|
| 188 |
// Internal usage for when the first needs to be updated before use. |
| 189 |
firstNeedsUpdate bool |
| 190 |
// Internal usage for when the last needs to be updated before use. |
| 191 |
lastNeedsUpdate bool |
| 192 |
} |
| 193 |
|
| 194 |
// LostStreamData indicates msgs that have been lost. |
| 195 |
type LostStreamData struct { |
| 196 |
Msgs []uint64 `json:"msgs"` |
| 197 |
Bytes uint64 `json:"bytes"` |
| 198 |
} |
| 199 |
|
| 200 |
// SnapshotResult contains information about the snapshot. |
| 201 |
type SnapshotResult struct { |
| 202 |
Reader io.ReadCloser |
| 203 |
State StreamState |
| 204 |
errCh chan string |
| 205 |
} |
| 206 |
|
| 207 |
const ( |
| 208 |
// Magic is used to identify stream state encodings. |
| 209 |
streamStateMagic = uint8(42) |
| 210 |
// Version |
| 211 |
streamStateVersion = uint8(1) |
| 212 |
// Magic / Identifier for run length encodings. |
| 213 |
runLengthMagic = uint8(33) |
| 214 |
// Magic / Identifier for AVL seqsets. |
| 215 |
seqSetMagic = uint8(22) |
| 216 |
) |
| 217 |
|
| 218 |
// Interface for DeleteBlock. |
| 219 |
// These will be of three types: |
| 220 |
// 1. AVL seqsets. |
| 221 |
// 2. Run length encoding of a deleted range. |
| 222 |
// 3. Legacy []uint64 |
| 223 |
type DeleteBlock interface { |
| 224 |
State() (first, last, num uint64) |
| 225 |
Range(f func(uint64) bool) |
| 226 |
} |
| 227 |
|
| 228 |
type DeleteBlocks []DeleteBlock |
| 229 |
|
| 230 |
// StreamReplicatedState represents what is encoded in a binary stream snapshot used |
| 231 |
// for stream replication in an NRG. |
| 232 |
type StreamReplicatedState struct { |
| 233 |
Msgs uint64 |
| 234 |
Bytes uint64 |
| 235 |
FirstSeq uint64 |
| 236 |
LastSeq uint64 |
| 237 |
Failed uint64 |
| 238 |
Deleted DeleteBlocks |
| 239 |
} |
| 240 |
|
| 241 |
// Determine if this is an encoded stream state. |
| 242 |
func IsEncodedStreamState(buf []byte) bool { |
| 243 |
return len(buf) >= hdrLen && buf[0] == streamStateMagic && buf[1] == streamStateVersion |
| 244 |
} |
| 245 |
|
| 246 |
var ErrBadStreamStateEncoding = errors.New("bad stream state encoding") |
| 247 |
|
| 248 |
func DecodeStreamState(buf []byte) (*StreamReplicatedState, error) { |
| 249 |
ss := &StreamReplicatedState{} |
| 250 |
if len(buf) < hdrLen || buf[0] != streamStateMagic || buf[1] != streamStateVersion { |
| 251 |
return nil, ErrBadStreamStateEncoding |
| 252 |
} |
| 253 |
var bi = hdrLen |
| 254 |
|
| 255 |
readU64 := func() uint64 { |
| 256 |
if bi < 0 || bi >= len(buf) { |
| 257 |
bi = -1 |
| 258 |
return 0 |
| 259 |
} |
| 260 |
num, n := binary.Uvarint(buf[bi:]) |
| 261 |
if n <= 0 { |
| 262 |
bi = -1 |
| 263 |
return 0 |
| 264 |
} |
| 265 |
bi += n |
| 266 |
return num |
| 267 |
} |
| 268 |
|
| 269 |
parserFailed := func() bool { |
| 270 |
return bi < 0 |
| 271 |
} |
| 272 |
|
| 273 |
ss.Msgs = readU64() |
| 274 |
ss.Bytes = readU64() |
| 275 |
ss.FirstSeq = readU64() |
| 276 |
ss.LastSeq = readU64() |
| 277 |
ss.Failed = readU64() |
| 278 |
|
| 279 |
if parserFailed() { |
| 280 |
return nil, ErrCorruptStreamState |
| 281 |
} |
| 282 |
|
| 283 |
if numDeleted := readU64(); numDeleted > 0 { |
| 284 |
// If we have some deleted blocks. |
| 285 |
for l := len(buf); l > bi; { |
| 286 |
switch buf[bi] { |
| 287 |
case seqSetMagic: |
| 288 |
dmap, n, err := avl.Decode(buf[bi:]) |
| 289 |
if err != nil { |
| 290 |
return nil, ErrCorruptStreamState |
| 291 |
} |
| 292 |
bi += n |
| 293 |
ss.Deleted = append(ss.Deleted, dmap) |
| 294 |
case runLengthMagic: |
| 295 |
bi++ |
| 296 |
var rl DeleteRange |
| 297 |
rl.First = readU64() |
| 298 |
rl.Num = readU64() |
| 299 |
if parserFailed() { |
| 300 |
return nil, ErrCorruptStreamState |
| 301 |
} |
| 302 |
ss.Deleted = append(ss.Deleted, &rl) |
| 303 |
default: |
| 304 |
return nil, ErrCorruptStreamState |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
return ss, nil |
| 310 |
} |
| 311 |
|
| 312 |
// uvarintLen returns the number of bytes binary.PutUvarint/binary.AppendUvarint |
| 313 |
// write for v: ceil(bits/7), with v=0 taking one byte. |
| 314 |
func uvarintLen(v uint64) int { |
| 315 |
return (bits.Len64(v|1) + 6) / 7 |
| 316 |
} |
| 317 |
|
| 318 |
// runLengthEncodeLen returns the encoded size of a run-length delete record, |
| 319 |
// exactly matching what appendRunLength writes. |
| 320 |
func runLengthEncodeLen(first, num uint64) int { |
| 321 |
return 1 + uvarintLen(first) + uvarintLen(num) |
| 322 |
} |
| 323 |
|
| 324 |
// appendRunLength appends a run-length encoded delete record for num |
| 325 |
// deleted sequences starting at first. |
| 326 |
func appendRunLength(b []byte, first, num uint64) []byte { |
| 327 |
b = append(b, runLengthMagic) |
| 328 |
b = binary.AppendUvarint(b, first) |
| 329 |
b = binary.AppendUvarint(b, num) |
| 330 |
return b |
| 331 |
} |
| 332 |
|
| 333 |
// DeleteRange is a run length encoded delete range. |
| 334 |
type DeleteRange struct { |
| 335 |
First uint64 |
| 336 |
Num uint64 |
| 337 |
} |
| 338 |
|
| 339 |
func (dr *DeleteRange) State() (first, last, num uint64) { |
| 340 |
deletesAfterFirst := dr.Num |
| 341 |
if deletesAfterFirst > 0 { |
| 342 |
deletesAfterFirst-- |
| 343 |
} |
| 344 |
return dr.First, dr.First + deletesAfterFirst, dr.Num |
| 345 |
} |
| 346 |
|
| 347 |
// Range will range over all the deleted sequences represented by this block. |
| 348 |
func (dr *DeleteRange) Range(f func(uint64) bool) { |
| 349 |
for seq := dr.First; seq < dr.First+dr.Num; seq++ { |
| 350 |
if !f(seq) { |
| 351 |
return |
| 352 |
} |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
// Legacy []uint64 |
| 357 |
type DeleteSlice []uint64 |
| 358 |
|
| 359 |
func (ds DeleteSlice) State() (first, last, num uint64) { |
| 360 |
if len(ds) == 0 { |
| 361 |
return 0, 0, 0 |
| 362 |
} |
| 363 |
return ds[0], ds[len(ds)-1], uint64(len(ds)) |
| 364 |
} |
| 365 |
|
| 366 |
// Range will range over all the deleted sequences represented by this []uint64. |
| 367 |
func (ds DeleteSlice) Range(f func(uint64) bool) { |
| 368 |
for _, seq := range ds { |
| 369 |
if !f(seq) { |
| 370 |
return |
| 371 |
} |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
func (dbs DeleteBlocks) NumDeleted() (total uint64) { |
| 376 |
for _, db := range dbs { |
| 377 |
_, _, num := db.State() |
| 378 |
total += num |
| 379 |
} |
| 380 |
return total |
| 381 |
} |
| 382 |
|
| 383 |
// ConsumerStore stores state on consumers for streams. |
| 384 |
type ConsumerStore interface { |
| 385 |
SetStarting(sseq uint64) error |
| 386 |
UpdateStarting(sseq uint64) |
| 387 |
Reset(sseq uint64) error |
| 388 |
HasState() bool |
| 389 |
UpdateDelivered(dseq, sseq, dc uint64, ts int64) error |
| 390 |
UpdateAcks(dseq, sseq uint64) error |
| 391 |
RemoveRedeliveredBelow(seq uint64) |
| 392 |
UpdateConfig(cfg *ConsumerConfig) error |
| 393 |
Update(*ConsumerState) error |
| 394 |
ForceUpdate(*ConsumerState) error |
| 395 |
State() (*ConsumerState, error) |
| 396 |
BorrowState() (*ConsumerState, error) |
| 397 |
EncodedState() ([]byte, error) |
| 398 |
Type() StorageType |
| 399 |
Stop() error |
| 400 |
Delete() error |
| 401 |
StreamDelete() error |
| 402 |
} |
| 403 |
|
| 404 |
// SequencePair has both the consumer and the stream sequence. They point to same message. |
| 405 |
type SequencePair struct { |
| 406 |
Consumer uint64 `json:"consumer_seq"` |
| 407 |
Stream uint64 `json:"stream_seq"` |
| 408 |
} |
| 409 |
|
| 410 |
// ConsumerState represents a stored state for a consumer. |
| 411 |
type ConsumerState struct { |
| 412 |
// Delivered keeps track of last delivered sequence numbers for both the stream and the consumer. |
| 413 |
Delivered SequencePair `json:"delivered"` |
| 414 |
// AckFloor keeps track of the ack floors for both the stream and the consumer. |
| 415 |
AckFloor SequencePair `json:"ack_floor"` |
| 416 |
// These are both in stream sequence context. |
| 417 |
// Pending is for all messages pending and the timestamp for the delivered time. |
| 418 |
// This will only be present when the AckPolicy is ExplicitAck. |
| 419 |
Pending map[uint64]*Pending `json:"pending,omitempty"` |
| 420 |
// This is for messages that have been redelivered, so count > 1. |
| 421 |
Redelivered map[uint64]uint64 `json:"redelivered,omitempty"` |
| 422 |
} |
| 423 |
|
| 424 |
// Encode consumer state. |
| 425 |
func encodeConsumerState(state *ConsumerState) []byte { |
| 426 |
var hdr [seqsHdrSize]byte |
| 427 |
var buf []byte |
| 428 |
|
| 429 |
maxSize := seqsHdrSize |
| 430 |
if lp := len(state.Pending); lp > 0 { |
| 431 |
maxSize += lp*(3*binary.MaxVarintLen64) + binary.MaxVarintLen64 |
| 432 |
} |
| 433 |
if lr := len(state.Redelivered); lr > 0 { |
| 434 |
maxSize += lr*(2*binary.MaxVarintLen64) + binary.MaxVarintLen64 |
| 435 |
} |
| 436 |
if maxSize == seqsHdrSize { |
| 437 |
buf = hdr[:seqsHdrSize] |
| 438 |
} else { |
| 439 |
buf = make([]byte, maxSize) |
| 440 |
} |
| 441 |
|
| 442 |
// Write header |
| 443 |
buf[0] = magic |
| 444 |
buf[1] = 2 |
| 445 |
|
| 446 |
n := hdrLen |
| 447 |
n += binary.PutUvarint(buf[n:], state.AckFloor.Consumer) |
| 448 |
n += binary.PutUvarint(buf[n:], state.AckFloor.Stream) |
| 449 |
n += binary.PutUvarint(buf[n:], state.Delivered.Consumer) |
| 450 |
n += binary.PutUvarint(buf[n:], state.Delivered.Stream) |
| 451 |
n += binary.PutUvarint(buf[n:], uint64(len(state.Pending))) |
| 452 |
|
| 453 |
asflr := state.AckFloor.Stream |
| 454 |
adflr := state.AckFloor.Consumer |
| 455 |
|
| 456 |
// These are optional, but always write len. This is to avoid a truncate inline. |
| 457 |
if len(state.Pending) > 0 { |
| 458 |
// To save space we will use now rounded to seconds to be our base timestamp. |
| 459 |
mints := time.Now().Round(time.Second).Unix() |
| 460 |
// Write minimum timestamp we found from above. |
| 461 |
n += binary.PutVarint(buf[n:], mints) |
| 462 |
|
| 463 |
for k, v := range state.Pending { |
| 464 |
n += binary.PutUvarint(buf[n:], k-asflr) |
| 465 |
n += binary.PutUvarint(buf[n:], v.Sequence-adflr) |
| 466 |
// Downsample to seconds to save on space. |
| 467 |
// Subsecond resolution not needed for recovery etc. |
| 468 |
ts := v.Timestamp / int64(time.Second) |
| 469 |
n += binary.PutVarint(buf[n:], mints-ts) |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
// We always write the redelivered len. |
| 474 |
n += binary.PutUvarint(buf[n:], uint64(len(state.Redelivered))) |
| 475 |
|
| 476 |
// We expect these to be small. |
| 477 |
if len(state.Redelivered) > 0 { |
| 478 |
for k, v := range state.Redelivered { |
| 479 |
n += binary.PutUvarint(buf[n:], k-asflr) |
| 480 |
n += binary.PutUvarint(buf[n:], v) |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
return buf[:n] |
| 485 |
} |
| 486 |
|
| 487 |
// Represents a pending message for explicit ack or ack all. |
| 488 |
// Sequence is the original consumer sequence. |
| 489 |
type Pending struct { |
| 490 |
Sequence uint64 |
| 491 |
Timestamp int64 |
| 492 |
} |
| 493 |
|
| 494 |
const ( |
| 495 |
limitsPolicyJSONString = `"limits"` |
| 496 |
interestPolicyJSONString = `"interest"` |
| 497 |
workQueuePolicyJSONString = `"workqueue"` |
| 498 |
) |
| 499 |
|
| 500 |
var ( |
| 501 |
limitsPolicyJSONBytes = []byte(limitsPolicyJSONString) |
| 502 |
interestPolicyJSONBytes = []byte(interestPolicyJSONString) |
| 503 |
workQueuePolicyJSONBytes = []byte(workQueuePolicyJSONString) |
| 504 |
) |
| 505 |
|
| 506 |
func (rp RetentionPolicy) String() string { |
| 507 |
switch rp { |
| 508 |
case LimitsPolicy: |
| 509 |
return "Limits" |
| 510 |
case InterestPolicy: |
| 511 |
return "Interest" |
| 512 |
case WorkQueuePolicy: |
| 513 |
return "WorkQueue" |
| 514 |
default: |
| 515 |
return "Unknown Retention Policy" |
| 516 |
} |
| 517 |
} |
| 518 |
|
| 519 |
func (rp RetentionPolicy) MarshalJSON() ([]byte, error) { |
| 520 |
switch rp { |
| 521 |
case LimitsPolicy: |
| 522 |
return limitsPolicyJSONBytes, nil |
| 523 |
case InterestPolicy: |
| 524 |
return interestPolicyJSONBytes, nil |
| 525 |
case WorkQueuePolicy: |
| 526 |
return workQueuePolicyJSONBytes, nil |
| 527 |
default: |
| 528 |
return nil, fmt.Errorf("can not marshal %v", rp) |
| 529 |
} |
| 530 |
} |
| 531 |
|
| 532 |
func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error { |
| 533 |
switch string(data) { |
| 534 |
case limitsPolicyJSONString: |
| 535 |
*rp = LimitsPolicy |
| 536 |
case interestPolicyJSONString: |
| 537 |
*rp = InterestPolicy |
| 538 |
case workQueuePolicyJSONString: |
| 539 |
*rp = WorkQueuePolicy |
| 540 |
default: |
| 541 |
return fmt.Errorf("can not unmarshal %q", data) |
| 542 |
} |
| 543 |
return nil |
| 544 |
} |
| 545 |
|
| 546 |
func (dp DiscardPolicy) String() string { |
| 547 |
switch dp { |
| 548 |
case DiscardOld: |
| 549 |
return "DiscardOld" |
| 550 |
case DiscardNew: |
| 551 |
return "DiscardNew" |
| 552 |
default: |
| 553 |
return "Unknown Discard Policy" |
| 554 |
} |
| 555 |
} |
| 556 |
|
| 557 |
func (dp DiscardPolicy) MarshalJSON() ([]byte, error) { |
| 558 |
switch dp { |
| 559 |
case DiscardOld: |
| 560 |
return []byte(`"old"`), nil |
| 561 |
case DiscardNew: |
| 562 |
return []byte(`"new"`), nil |
| 563 |
default: |
| 564 |
return nil, fmt.Errorf("can not marshal %v", dp) |
| 565 |
} |
| 566 |
} |
| 567 |
|
| 568 |
func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error { |
| 569 |
switch strings.ToLower(string(data)) { |
| 570 |
case `"old"`: |
| 571 |
*dp = DiscardOld |
| 572 |
case `"new"`: |
| 573 |
*dp = DiscardNew |
| 574 |
default: |
| 575 |
return fmt.Errorf("can not unmarshal %q", data) |
| 576 |
} |
| 577 |
return nil |
| 578 |
} |
| 579 |
|
| 580 |
const ( |
| 581 |
memoryStorageJSONString = `"memory"` |
| 582 |
fileStorageJSONString = `"file"` |
| 583 |
) |
| 584 |
|
| 585 |
var ( |
| 586 |
memoryStorageJSONBytes = []byte(memoryStorageJSONString) |
| 587 |
fileStorageJSONBytes = []byte(fileStorageJSONString) |
| 588 |
) |
| 589 |
|
| 590 |
func (st StorageType) String() string { |
| 591 |
switch st { |
| 592 |
case MemoryStorage: |
| 593 |
return "Memory" |
| 594 |
case FileStorage: |
| 595 |
return "File" |
| 596 |
default: |
| 597 |
return "Unknown Storage Type" |
| 598 |
} |
| 599 |
} |
| 600 |
|
| 601 |
func (st StorageType) MarshalJSON() ([]byte, error) { |
| 602 |
switch st { |
| 603 |
case MemoryStorage: |
| 604 |
return memoryStorageJSONBytes, nil |
| 605 |
case FileStorage: |
| 606 |
return fileStorageJSONBytes, nil |
| 607 |
default: |
| 608 |
return nil, fmt.Errorf("can not marshal %v", st) |
| 609 |
} |
| 610 |
} |
| 611 |
|
| 612 |
func (st *StorageType) UnmarshalJSON(data []byte) error { |
| 613 |
switch string(data) { |
| 614 |
case memoryStorageJSONString: |
| 615 |
*st = MemoryStorage |
| 616 |
case fileStorageJSONString: |
| 617 |
*st = FileStorage |
| 618 |
default: |
| 619 |
return fmt.Errorf("can not unmarshal %q", data) |
| 620 |
} |
| 621 |
return nil |
| 622 |
} |
| 623 |
|
| 624 |
const ( |
| 625 |
ackNonePolicyJSONString = `"none"` |
| 626 |
ackAllPolicyJSONString = `"all"` |
| 627 |
ackExplicitPolicyJSONString = `"explicit"` |
| 628 |
ackFlowControlPolicyJSONString = `"flow_control"` |
| 629 |
) |
| 630 |
|
| 631 |
var ( |
| 632 |
ackNonePolicyJSONBytes = []byte(ackNonePolicyJSONString) |
| 633 |
ackAllPolicyJSONBytes = []byte(ackAllPolicyJSONString) |
| 634 |
ackExplicitPolicyJSONBytes = []byte(ackExplicitPolicyJSONString) |
| 635 |
ackFlowControlPolicyJSONBytes = []byte(ackFlowControlPolicyJSONString) |
| 636 |
) |
| 637 |
|
| 638 |
func (ap AckPolicy) MarshalJSON() ([]byte, error) { |
| 639 |
switch ap { |
| 640 |
case AckNone: |
| 641 |
return ackNonePolicyJSONBytes, nil |
| 642 |
case AckAll: |
| 643 |
return ackAllPolicyJSONBytes, nil |
| 644 |
case AckExplicit: |
| 645 |
return ackExplicitPolicyJSONBytes, nil |
| 646 |
case AckFlowControl: |
| 647 |
return ackFlowControlPolicyJSONBytes, nil |
| 648 |
default: |
| 649 |
return nil, fmt.Errorf("can not marshal %v", ap) |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
func (ap *AckPolicy) UnmarshalJSON(data []byte) error { |
| 654 |
switch string(data) { |
| 655 |
case ackNonePolicyJSONString: |
| 656 |
*ap = AckNone |
| 657 |
case ackAllPolicyJSONString: |
| 658 |
*ap = AckAll |
| 659 |
case ackExplicitPolicyJSONString: |
| 660 |
*ap = AckExplicit |
| 661 |
case ackFlowControlPolicyJSONString: |
| 662 |
*ap = AckFlowControl |
| 663 |
default: |
| 664 |
return fmt.Errorf("can not unmarshal %q", data) |
| 665 |
} |
| 666 |
return nil |
| 667 |
} |
| 668 |
|
| 669 |
const ( |
| 670 |
replayInstantPolicyJSONString = `"instant"` |
| 671 |
replayOriginalPolicyJSONString = `"original"` |
| 672 |
) |
| 673 |
|
| 674 |
var ( |
| 675 |
replayInstantPolicyJSONBytes = []byte(replayInstantPolicyJSONString) |
| 676 |
replayOriginalPolicyJSONBytes = []byte(replayOriginalPolicyJSONString) |
| 677 |
) |
| 678 |
|
| 679 |
func (rp ReplayPolicy) MarshalJSON() ([]byte, error) { |
| 680 |
switch rp { |
| 681 |
case ReplayInstant: |
| 682 |
return replayInstantPolicyJSONBytes, nil |
| 683 |
case ReplayOriginal: |
| 684 |
return replayOriginalPolicyJSONBytes, nil |
| 685 |
default: |
| 686 |
return nil, fmt.Errorf("can not marshal %v", rp) |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
func (rp *ReplayPolicy) UnmarshalJSON(data []byte) error { |
| 691 |
switch string(data) { |
| 692 |
case replayInstantPolicyJSONString: |
| 693 |
*rp = ReplayInstant |
| 694 |
case replayOriginalPolicyJSONString: |
| 695 |
*rp = ReplayOriginal |
| 696 |
default: |
| 697 |
return fmt.Errorf("can not unmarshal %q", data) |
| 698 |
} |
| 699 |
return nil |
| 700 |
} |
| 701 |
|
| 702 |
const ( |
| 703 |
deliverAllPolicyJSONString = `"all"` |
| 704 |
deliverLastPolicyJSONString = `"last"` |
| 705 |
deliverNewPolicyJSONString = `"new"` |
| 706 |
deliverByStartSequenceJSONString = `"by_start_sequence"` |
| 707 |
deliverByStartTimeJSONString = `"by_start_time"` |
| 708 |
deliverLastPerPolicyJSONString = `"last_per_subject"` |
| 709 |
deliverUndefinedJSONString = `"undefined"` |
| 710 |
) |
| 711 |
|
| 712 |
var ( |
| 713 |
deliverAllPolicyJSONBytes = []byte(deliverAllPolicyJSONString) |
| 714 |
deliverLastPolicyJSONBytes = []byte(deliverLastPolicyJSONString) |
| 715 |
deliverNewPolicyJSONBytes = []byte(deliverNewPolicyJSONString) |
| 716 |
deliverByStartSequenceJSONBytes = []byte(deliverByStartSequenceJSONString) |
| 717 |
deliverByStartTimeJSONBytes = []byte(deliverByStartTimeJSONString) |
| 718 |
deliverLastPerPolicyJSONBytes = []byte(deliverLastPerPolicyJSONString) |
| 719 |
deliverUndefinedJSONBytes = []byte(deliverUndefinedJSONString) |
| 720 |
) |
| 721 |
|
| 722 |
func (p *DeliverPolicy) UnmarshalJSON(data []byte) error { |
| 723 |
switch string(data) { |
| 724 |
case deliverAllPolicyJSONString, deliverUndefinedJSONString: |
| 725 |
*p = DeliverAll |
| 726 |
case deliverLastPolicyJSONString: |
| 727 |
*p = DeliverLast |
| 728 |
case deliverLastPerPolicyJSONString: |
| 729 |
*p = DeliverLastPerSubject |
| 730 |
case deliverNewPolicyJSONString: |
| 731 |
*p = DeliverNew |
| 732 |
case deliverByStartSequenceJSONString: |
| 733 |
*p = DeliverByStartSequence |
| 734 |
case deliverByStartTimeJSONString: |
| 735 |
*p = DeliverByStartTime |
| 736 |
default: |
| 737 |
return fmt.Errorf("can not unmarshal %q", data) |
| 738 |
} |
| 739 |
|
| 740 |
return nil |
| 741 |
} |
| 742 |
|
| 743 |
func (p DeliverPolicy) MarshalJSON() ([]byte, error) { |
| 744 |
switch p { |
| 745 |
case DeliverAll: |
| 746 |
return deliverAllPolicyJSONBytes, nil |
| 747 |
case DeliverLast: |
| 748 |
return deliverLastPolicyJSONBytes, nil |
| 749 |
case DeliverLastPerSubject: |
| 750 |
return deliverLastPerPolicyJSONBytes, nil |
| 751 |
case DeliverNew: |
| 752 |
return deliverNewPolicyJSONBytes, nil |
| 753 |
case DeliverByStartSequence: |
| 754 |
return deliverByStartSequenceJSONBytes, nil |
| 755 |
case DeliverByStartTime: |
| 756 |
return deliverByStartTimeJSONBytes, nil |
| 757 |
default: |
| 758 |
return deliverUndefinedJSONBytes, nil |
| 759 |
} |
| 760 |
} |
| 761 |
|
| 762 |
func isOutOfSpaceErr(err error) bool { |
| 763 |
return err != nil && (strings.Contains(err.Error(), "no space left")) |
| 764 |
} |
| 765 |
|
| 766 |
// For when our upper layer catchup detects its missing messages from the beginning of the stream. |
| 767 |
var errFirstSequenceMismatch = errors.New("first sequence mismatch") |
| 768 |
|
| 769 |
func isClusterResetErr(err error) bool { |
| 770 |
return err == errLastSeqMismatch || err == ErrStoreEOF || err == errFirstSequenceMismatch || errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries || err == errAlreadyLeader |
| 771 |
} |
| 772 |
|
| 773 |
// Copy all fields. |
| 774 |
func (smo *StoreMsg) copy(sm *StoreMsg) { |
| 775 |
if sm.buf != nil { |
| 776 |
sm.buf = sm.buf[:0] |
| 777 |
} |
| 778 |
sm.buf = append(sm.buf, smo.buf...) |
| 779 |
// We set cap on header in case someone wants to expand it. |
| 780 |
sm.hdr, sm.msg = sm.buf[:len(smo.hdr):len(smo.hdr)], sm.buf[len(smo.hdr):] |
| 781 |
sm.subj, sm.seq, sm.ts = smo.subj, smo.seq, smo.ts |
| 782 |
} |
| 783 |
|
| 784 |
// Clear all fields except underlying buffer but reset that if present to [:0]. |
| 785 |
func (sm *StoreMsg) clear() { |
| 786 |
if sm == nil { |
| 787 |
return |
| 788 |
} |
| 789 |
*sm = StoreMsg{_EMPTY_, nil, nil, sm.buf, 0, 0} |
| 790 |
if len(sm.buf) > 0 { |
| 791 |
sm.buf = sm.buf[:0] |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
// Note this will avoid a copy of the data used for the string, but it will also reference the existing slice's data pointer. |
| 796 |
// So this should be used sparingly when we know the encompassing byte slice's lifetime is the same. |
| 797 |
func bytesToString(b []byte) string { |
| 798 |
if len(b) == 0 { |
| 799 |
return _EMPTY_ |
| 800 |
} |
| 801 |
p := unsafe.SliceData(b) |
| 802 |
return unsafe.String(p, len(b)) |
| 803 |
} |
| 804 |
|
| 805 |
// Same in reverse. Used less often. |
| 806 |
func stringToBytes(s string) []byte { |
| 807 |
if len(s) == 0 { |
| 808 |
return nil |
| 809 |
} |
| 810 |
p := unsafe.StringData(s) |
| 811 |
b := unsafe.Slice(p, len(s)) |
| 812 |
return b |
| 813 |
} |
| 814 |
|
| 815 |
// Forces a copy of a string, for use in the case that you might have been passed a value when bytesToString was used, |
| 816 |
// but now you need a separate copy of it to store for longer-term use. |
| 817 |
func copyString(s string) string { |
| 818 |
b := make([]byte, len(s)) |
| 819 |
copy(b, s) |
| 820 |
return bytesToString(b) |
| 821 |
} |
| 822 |
|
| 823 |
func isPermissionError(err error) bool { |
| 824 |
return err != nil && os.IsPermission(err) |
| 825 |
} |