| 1 |
// Copyright 2022-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 jetstream |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"fmt" |
| 19 |
"time" |
| 20 |
) |
| 21 |
|
| 22 |
type pullOptFunc func(*consumeOpts) error |
| 23 |
|
| 24 |
func (fn pullOptFunc) configureConsume(opts *consumeOpts) error { |
| 25 |
return fn(opts) |
| 26 |
} |
| 27 |
|
| 28 |
func (fn pullOptFunc) configureMessages(opts *consumeOpts) error { |
| 29 |
return fn(opts) |
| 30 |
} |
| 31 |
|
| 32 |
// WithClientTrace enables request/response API calls tracing. |
| 33 |
func WithClientTrace(ct *ClientTrace) JetStreamOpt { |
| 34 |
return func(opts *JetStreamOptions) error { |
| 35 |
opts.ClientTrace = ct |
| 36 |
return nil |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// WithPublishAsyncErrHandler sets error handler for async message publish. |
| 41 |
func WithPublishAsyncErrHandler(cb MsgErrHandler) JetStreamOpt { |
| 42 |
return func(opts *JetStreamOptions) error { |
| 43 |
opts.publisherOpts.aecb = cb |
| 44 |
return nil |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
// WithPublishAsyncAckHandler sets an ack handler for async message publish, |
| 49 |
// invoked when a publish is successfully acked by the server. See |
| 50 |
// [MsgAckHandler] for constraints on the handler. |
| 51 |
func WithPublishAsyncAckHandler(cb MsgAckHandler) JetStreamOpt { |
| 52 |
return func(opts *JetStreamOptions) error { |
| 53 |
opts.publisherOpts.ackcb = cb |
| 54 |
return nil |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
// WithPublishAsyncMaxPending sets the maximum outstanding async publishes that |
| 59 |
// can be inflight at one time. |
| 60 |
func WithPublishAsyncMaxPending(max int) JetStreamOpt { |
| 61 |
return func(opts *JetStreamOptions) error { |
| 62 |
if max < 1 { |
| 63 |
return fmt.Errorf("%w: max ack pending should be >= 1", ErrInvalidOption) |
| 64 |
} |
| 65 |
opts.publisherOpts.maxpa = max |
| 66 |
return nil |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
// WithPublishAsyncTimeout sets the timeout for async message publish. |
| 71 |
// If not provided, timeout is disabled. |
| 72 |
func WithPublishAsyncTimeout(dur time.Duration) JetStreamOpt { |
| 73 |
return func(opts *JetStreamOptions) error { |
| 74 |
opts.publisherOpts.ackTimeout = dur |
| 75 |
return nil |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
// WithDefaultTimeout sets the default timeout for JetStream API requests. |
| 80 |
// It is used when context used for the request does not have a deadline set. |
| 81 |
// If not provided, a default of 5 seconds will be used. |
| 82 |
func WithDefaultTimeout(timeout time.Duration) JetStreamOpt { |
| 83 |
return func(opts *JetStreamOptions) error { |
| 84 |
if timeout <= 0 { |
| 85 |
return fmt.Errorf("%w: timeout value must be greater than 0", ErrInvalidOption) |
| 86 |
} |
| 87 |
opts.DefaultTimeout = timeout |
| 88 |
return nil |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
// WithPurgeSubject sets a specific subject for which messages on a stream will |
| 93 |
// be purged |
| 94 |
func WithPurgeSubject(subject string) StreamPurgeOpt { |
| 95 |
return func(req *StreamPurgeRequest) error { |
| 96 |
req.Subject = subject |
| 97 |
return nil |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
// WithPurgeSequence is used to set a specific sequence number up to which (but |
| 102 |
// not including) messages will be purged from a stream Can be combined with |
| 103 |
// [WithPurgeSubject] option, but not with [WithPurgeKeep] |
| 104 |
func WithPurgeSequence(sequence uint64) StreamPurgeOpt { |
| 105 |
return func(req *StreamPurgeRequest) error { |
| 106 |
if req.Keep != 0 { |
| 107 |
return fmt.Errorf("%w: both 'keep' and 'sequence' cannot be provided in purge request", ErrInvalidOption) |
| 108 |
} |
| 109 |
req.Sequence = sequence |
| 110 |
return nil |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
// WithPurgeKeep sets the number of messages to be kept in the stream after |
| 115 |
// purge. Can be combined with [WithPurgeSubject] option, but not with |
| 116 |
// [WithPurgeSequence] |
| 117 |
func WithPurgeKeep(keep uint64) StreamPurgeOpt { |
| 118 |
return func(req *StreamPurgeRequest) error { |
| 119 |
if req.Sequence != 0 { |
| 120 |
return fmt.Errorf("%w: both 'keep' and 'sequence' cannot be provided in purge request", ErrInvalidOption) |
| 121 |
} |
| 122 |
req.Keep = keep |
| 123 |
return nil |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
// WithGetMsgSubject sets the stream subject from which the message should be |
| 128 |
// retrieved. Server will return a first message with a seq >= to the input seq |
| 129 |
// that has the specified subject. |
| 130 |
func WithGetMsgSubject(subject string) GetMsgOpt { |
| 131 |
return func(req *apiMsgGetRequest) error { |
| 132 |
req.NextFor = subject |
| 133 |
return nil |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
// PullMaxMessages limits the number of messages to be buffered in the client. |
| 138 |
// If not provided, a default of 500 messages will be used. |
| 139 |
// This option is exclusive with PullMaxBytes. |
| 140 |
// |
| 141 |
// PullMaxMessages implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 142 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 143 |
type PullMaxMessages int |
| 144 |
|
| 145 |
func (max PullMaxMessages) configureConsume(opts *consumeOpts) error { |
| 146 |
if max <= 0 { |
| 147 |
return fmt.Errorf("%w: maxMessages size must be at least 1", ErrInvalidOption) |
| 148 |
} |
| 149 |
opts.MaxMessages = int(max) |
| 150 |
return nil |
| 151 |
} |
| 152 |
|
| 153 |
func (max PullMaxMessages) configureMessages(opts *consumeOpts) error { |
| 154 |
if max <= 0 { |
| 155 |
return fmt.Errorf("%w: maxMessages size must be at least 1", ErrInvalidOption) |
| 156 |
} |
| 157 |
opts.MaxMessages = int(max) |
| 158 |
return nil |
| 159 |
} |
| 160 |
|
| 161 |
type pullMaxMessagesWithBytesLimit struct { |
| 162 |
maxMessages int |
| 163 |
maxBytes int |
| 164 |
} |
| 165 |
|
| 166 |
// PullMaxMessagesWithBytesLimit limits the number of messages to be buffered |
| 167 |
// in the client. Additionally, it sets the maximum size a single fetch request |
| 168 |
// can have. Note that this will not limit the total size of messages buffered |
| 169 |
// in the client, but rather can serve as a way to limit what nats server will |
| 170 |
// have to internally buffer for a single fetch request. |
| 171 |
// |
| 172 |
// The byte limit should never be set to a value lower than the maximum message |
| 173 |
// size that can be expected from the server. If the byte limit is lower than |
| 174 |
// the maximum message size, the consumer will stall and not be able to consume |
| 175 |
// messages. |
| 176 |
// |
| 177 |
// This is an advanced option and should be used with caution. Most users should |
| 178 |
// use [PullMaxMessages] or [PullMaxBytes] instead. |
| 179 |
// |
| 180 |
// PullMaxMessagesWithBytesLimit implements both PullConsumeOpt and |
| 181 |
// PullMessagesOpt, allowing it to configure Consumer.Consume and Consumer.Messages. |
| 182 |
func PullMaxMessagesWithBytesLimit(maxMessages, byteLimit int) pullMaxMessagesWithBytesLimit { |
| 183 |
return pullMaxMessagesWithBytesLimit{maxMessages, byteLimit} |
| 184 |
} |
| 185 |
|
| 186 |
func (m pullMaxMessagesWithBytesLimit) configureConsume(opts *consumeOpts) error { |
| 187 |
if m.maxMessages <= 0 { |
| 188 |
return fmt.Errorf("%w: maxMessages size must be at least 1", ErrInvalidOption) |
| 189 |
} |
| 190 |
if m.maxBytes <= 0 { |
| 191 |
return fmt.Errorf("%w: maxBytes size must be at least 1", ErrInvalidOption) |
| 192 |
} |
| 193 |
if opts.MaxMessages > 0 { |
| 194 |
return fmt.Errorf("%w: maxMessages already set", ErrInvalidOption) |
| 195 |
} |
| 196 |
opts.MaxMessages = m.maxMessages |
| 197 |
opts.MaxBytes = m.maxBytes |
| 198 |
opts.LimitSize = true |
| 199 |
|
| 200 |
return nil |
| 201 |
} |
| 202 |
|
| 203 |
func (m pullMaxMessagesWithBytesLimit) configureMessages(opts *consumeOpts) error { |
| 204 |
if m.maxMessages <= 0 { |
| 205 |
return fmt.Errorf("%w: maxMessages size must be at least 1", ErrInvalidOption) |
| 206 |
} |
| 207 |
if m.maxBytes <= 0 { |
| 208 |
return fmt.Errorf("%w: maxBytes size must be at least 1", ErrInvalidOption) |
| 209 |
} |
| 210 |
if opts.MaxMessages > 0 { |
| 211 |
return fmt.Errorf("%w: maxMessages already set", ErrInvalidOption) |
| 212 |
} |
| 213 |
opts.MaxMessages = m.maxMessages |
| 214 |
opts.MaxBytes = m.maxBytes |
| 215 |
opts.LimitSize = true |
| 216 |
|
| 217 |
return nil |
| 218 |
} |
| 219 |
|
| 220 |
// PullExpiry sets timeout on a single pull request, waiting until at least one |
| 221 |
// message is available. |
| 222 |
// If not provided, a default of 30 seconds will be used. |
| 223 |
// |
| 224 |
// PullExpiry implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 225 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 226 |
type PullExpiry time.Duration |
| 227 |
|
| 228 |
func (exp PullExpiry) configureConsume(opts *consumeOpts) error { |
| 229 |
expiry := time.Duration(exp) |
| 230 |
if expiry < time.Second { |
| 231 |
return fmt.Errorf("%w: expires value must be at least 1s", ErrInvalidOption) |
| 232 |
} |
| 233 |
opts.Expires = expiry |
| 234 |
return nil |
| 235 |
} |
| 236 |
|
| 237 |
func (exp PullExpiry) configureMessages(opts *consumeOpts) error { |
| 238 |
expiry := time.Duration(exp) |
| 239 |
if expiry < time.Second { |
| 240 |
return fmt.Errorf("%w: expires value must be at least 1s", ErrInvalidOption) |
| 241 |
} |
| 242 |
opts.Expires = expiry |
| 243 |
return nil |
| 244 |
} |
| 245 |
|
| 246 |
// PullMaxBytes limits the number of bytes to be buffered in the client. |
| 247 |
// If not provided, the limit is not set (max messages will be used instead). |
| 248 |
// This option is exclusive with PullMaxMessages. |
| 249 |
// |
| 250 |
// The value should be set to a high enough value to accommodate the largest |
| 251 |
// message expected from the server. Note that it may not be sufficient to set |
| 252 |
// this value to the maximum message size, as this setting controls the client |
| 253 |
// buffer size, not the max bytes requested from the server within a single pull |
| 254 |
// request. If the value is set too low, the consumer will stall and not be able |
| 255 |
// to consume messages. |
| 256 |
// |
| 257 |
// PullMaxBytes implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 258 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 259 |
type PullMaxBytes int |
| 260 |
|
| 261 |
func (max PullMaxBytes) configureConsume(opts *consumeOpts) error { |
| 262 |
if max <= 0 { |
| 263 |
return fmt.Errorf("%w: max bytes must be greater than 0", ErrInvalidOption) |
| 264 |
} |
| 265 |
opts.MaxBytes = int(max) |
| 266 |
return nil |
| 267 |
} |
| 268 |
|
| 269 |
func (max PullMaxBytes) configureMessages(opts *consumeOpts) error { |
| 270 |
if max <= 0 { |
| 271 |
return fmt.Errorf("%w: max bytes must be greater than 0", ErrInvalidOption) |
| 272 |
} |
| 273 |
opts.MaxBytes = int(max) |
| 274 |
return nil |
| 275 |
} |
| 276 |
|
| 277 |
// PullThresholdMessages sets the message count on which consuming will trigger |
| 278 |
// new pull request to the server. Defaults to 50% of MaxMessages. |
| 279 |
// |
| 280 |
// PullThresholdMessages implements both PullConsumeOpt and PullMessagesOpt, |
| 281 |
// allowing it to configure Consumer.Consume and Consumer.Messages. |
| 282 |
type PullThresholdMessages int |
| 283 |
|
| 284 |
func (t PullThresholdMessages) configureConsume(opts *consumeOpts) error { |
| 285 |
opts.ThresholdMessages = int(t) |
| 286 |
return nil |
| 287 |
} |
| 288 |
|
| 289 |
func (t PullThresholdMessages) configureMessages(opts *consumeOpts) error { |
| 290 |
opts.ThresholdMessages = int(t) |
| 291 |
return nil |
| 292 |
} |
| 293 |
|
| 294 |
// PullThresholdBytes sets the byte count on which consuming will trigger |
| 295 |
// new pull request to the server. Defaults to 50% of MaxBytes (if set). |
| 296 |
// |
| 297 |
// PullThresholdBytes implements both PullConsumeOpt and PullMessagesOpt, |
| 298 |
// allowing it to configure Consumer.Consume and Consumer.Messages. |
| 299 |
type PullThresholdBytes int |
| 300 |
|
| 301 |
func (t PullThresholdBytes) configureConsume(opts *consumeOpts) error { |
| 302 |
opts.ThresholdBytes = int(t) |
| 303 |
return nil |
| 304 |
} |
| 305 |
|
| 306 |
func (t PullThresholdBytes) configureMessages(opts *consumeOpts) error { |
| 307 |
opts.ThresholdBytes = int(t) |
| 308 |
return nil |
| 309 |
} |
| 310 |
|
| 311 |
// PullMinPending sets the minimum number of messages that should be pending for |
| 312 |
// a consumer with PriorityPolicyOverflow to be considered for delivery. |
| 313 |
// If provided, PullPriorityGroup must be set as well and the consumer has to have |
| 314 |
// PriorityPolicy set to PriorityPolicyOverflow. |
| 315 |
// |
| 316 |
// PullMinPending implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 317 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 318 |
type PullMinPending int |
| 319 |
|
| 320 |
func (min PullMinPending) configureConsume(opts *consumeOpts) error { |
| 321 |
if min < 1 { |
| 322 |
return fmt.Errorf("%w: min pending should be more than 0", ErrInvalidOption) |
| 323 |
} |
| 324 |
opts.MinPending = int64(min) |
| 325 |
return nil |
| 326 |
} |
| 327 |
|
| 328 |
func (min PullMinPending) configureMessages(opts *consumeOpts) error { |
| 329 |
if min < 1 { |
| 330 |
return fmt.Errorf("%w: min pending should be more than 0", ErrInvalidOption) |
| 331 |
} |
| 332 |
opts.MinPending = int64(min) |
| 333 |
return nil |
| 334 |
} |
| 335 |
|
| 336 |
// PullMinAckPending sets the minimum number of pending acks that should be |
| 337 |
// present for a consumer with PriorityPolicyOverflow to be considered for |
| 338 |
// delivery. If provided, PullPriorityGroup must be set as well and the consumer |
| 339 |
// has to have PriorityPolicy set to PriorityPolicyOverflow. |
| 340 |
// |
| 341 |
// PullMinAckPending implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 342 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 343 |
type PullMinAckPending int |
| 344 |
|
| 345 |
func (min PullMinAckPending) configureConsume(opts *consumeOpts) error { |
| 346 |
if min < 1 { |
| 347 |
return fmt.Errorf("%w: min pending should be more than 0", ErrInvalidOption) |
| 348 |
} |
| 349 |
opts.MinAckPending = int64(min) |
| 350 |
return nil |
| 351 |
} |
| 352 |
|
| 353 |
func (min PullMinAckPending) configureMessages(opts *consumeOpts) error { |
| 354 |
if min < 1 { |
| 355 |
return fmt.Errorf("%w: min pending should be more than 0", ErrInvalidOption) |
| 356 |
} |
| 357 |
opts.MinAckPending = int64(min) |
| 358 |
return nil |
| 359 |
} |
| 360 |
|
| 361 |
// PullPrioritized sets the priority used when sending pull requests for consumer with |
| 362 |
// PriorityPolicyPrioritized. Lower values indicate higher priority (0 is the |
| 363 |
// highest priority). Maximum priority value is 9. |
| 364 |
// |
| 365 |
// If provided, PullPriorityGroup must be set as well and the consumer has to |
| 366 |
// have PriorityPolicy set to PriorityPolicyPrioritized. |
| 367 |
// |
| 368 |
// PullPrioritized implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 369 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 370 |
type PullPrioritized uint8 |
| 371 |
|
| 372 |
func (p PullPrioritized) configureConsume(opts *consumeOpts) error { |
| 373 |
opts.Priority = uint8(p) |
| 374 |
return nil |
| 375 |
} |
| 376 |
func (p PullPrioritized) configureMessages(opts *consumeOpts) error { |
| 377 |
opts.Priority = uint8(p) |
| 378 |
return nil |
| 379 |
} |
| 380 |
|
| 381 |
// PullPriorityGroup sets the priority group for a consumer. |
| 382 |
// It has to match one of the priority groups set on the consumer. |
| 383 |
// |
| 384 |
// PullPriorityGroup implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 385 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 386 |
type PullPriorityGroup string |
| 387 |
|
| 388 |
func (g PullPriorityGroup) configureConsume(opts *consumeOpts) error { |
| 389 |
opts.Group = string(g) |
| 390 |
return nil |
| 391 |
} |
| 392 |
|
| 393 |
func (g PullPriorityGroup) configureMessages(opts *consumeOpts) error { |
| 394 |
opts.Group = string(g) |
| 395 |
return nil |
| 396 |
} |
| 397 |
|
| 398 |
// PullHeartbeat sets the idle heartbeat duration for a pull subscription |
| 399 |
// If a client does not receive a heartbeat message from a stream for more |
| 400 |
// than the idle heartbeat setting, the subscription will be removed |
| 401 |
// and error will be passed to the message handler. |
| 402 |
// If not provided, a default PullExpiry / 2 will be used (capped at 30 seconds) |
| 403 |
// |
| 404 |
// PullHeartbeat implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 405 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 406 |
type PullHeartbeat time.Duration |
| 407 |
|
| 408 |
func (hb PullHeartbeat) configureConsume(opts *consumeOpts) error { |
| 409 |
hbTime := time.Duration(hb) |
| 410 |
if hbTime < 500*time.Millisecond || hbTime > 30*time.Second { |
| 411 |
return fmt.Errorf("%w: idle_heartbeat value must be within 500ms-30s range", ErrInvalidOption) |
| 412 |
} |
| 413 |
opts.Heartbeat = hbTime |
| 414 |
return nil |
| 415 |
} |
| 416 |
|
| 417 |
func (hb PullHeartbeat) configureMessages(opts *consumeOpts) error { |
| 418 |
hbTime := time.Duration(hb) |
| 419 |
if hbTime < 500*time.Millisecond || hbTime > 30*time.Second { |
| 420 |
return fmt.Errorf("%w: idle_heartbeat value must be within 500ms-30s range", ErrInvalidOption) |
| 421 |
} |
| 422 |
opts.Heartbeat = hbTime |
| 423 |
return nil |
| 424 |
} |
| 425 |
|
| 426 |
// StopAfter sets the number of messages after which the consumer is |
| 427 |
// automatically stopped and no more messages are pulled from the server. |
| 428 |
// |
| 429 |
// StopAfter implements both PullConsumeOpt and PullMessagesOpt, allowing |
| 430 |
// it to configure Consumer.Consume and Consumer.Messages. |
| 431 |
type StopAfter int |
| 432 |
|
| 433 |
func (nMsgs StopAfter) configureConsume(opts *consumeOpts) error { |
| 434 |
if nMsgs <= 0 { |
| 435 |
return fmt.Errorf("%w: auto stop after value cannot be less than 1", ErrInvalidOption) |
| 436 |
} |
| 437 |
opts.StopAfter = int(nMsgs) |
| 438 |
return nil |
| 439 |
} |
| 440 |
|
| 441 |
func (nMsgs StopAfter) configureMessages(opts *consumeOpts) error { |
| 442 |
if nMsgs <= 0 { |
| 443 |
return fmt.Errorf("%w: auto stop after value cannot be less than 1", ErrInvalidOption) |
| 444 |
} |
| 445 |
opts.StopAfter = int(nMsgs) |
| 446 |
return nil |
| 447 |
} |
| 448 |
|
| 449 |
// ConsumeErrHandler sets custom error handler invoked when an error was |
| 450 |
// encountered while consuming messages It will be invoked for both terminal |
| 451 |
// (Consumer Deleted, invalid request body) and non-terminal (e.g. missing |
| 452 |
// heartbeats) errors. |
| 453 |
type ConsumeErrHandler ConsumeErrHandlerFunc |
| 454 |
|
| 455 |
func (c ConsumeErrHandler) configureConsume(opts *consumeOpts) error { |
| 456 |
opts.ErrHandler = c |
| 457 |
return nil |
| 458 |
} |
| 459 |
|
| 460 |
func (c ConsumeErrHandler) configurePushConsume(opts *pushConsumeOpts) error { |
| 461 |
opts.ErrHandler = c |
| 462 |
return nil |
| 463 |
} |
| 464 |
|
| 465 |
// WithMessagesErrOnMissingHeartbeat sets whether a missing heartbeat error |
| 466 |
// should be reported when calling [MessagesContext.Next] (Default: true). |
| 467 |
func WithMessagesErrOnMissingHeartbeat(hbErr bool) PullMessagesOpt { |
| 468 |
return pullOptFunc(func(cfg *consumeOpts) error { |
| 469 |
cfg.ReportMissingHeartbeats = hbErr |
| 470 |
return nil |
| 471 |
}) |
| 472 |
} |
| 473 |
|
| 474 |
// FetchMinPending sets the minimum number of messages that should be pending for |
| 475 |
// a consumer with PriorityPolicyOverflow to be considered for delivery. |
| 476 |
// If provided, FetchPriorityGroup must be set as well and the consumer has to have |
| 477 |
// PriorityPolicy set to PriorityPolicyOverflow. |
| 478 |
func FetchMinPending(min int64) FetchOpt { |
| 479 |
return func(req *pullRequest) error { |
| 480 |
if min < 1 { |
| 481 |
return fmt.Errorf("%w: min pending should be more than 0", ErrInvalidOption) |
| 482 |
} |
| 483 |
req.MinPending = min |
| 484 |
return nil |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
// FetchMinAckPending sets the minimum number of pending acks that should be |
| 489 |
// present for a consumer with PriorityPolicyOverflow to be considered for |
| 490 |
// delivery. If provided, FetchPriorityGroup must be set as well and the consumer |
| 491 |
// has to have PriorityPolicy set to PriorityPolicyOverflow. |
| 492 |
func FetchMinAckPending(min int64) FetchOpt { |
| 493 |
return func(req *pullRequest) error { |
| 494 |
if min < 1 { |
| 495 |
return fmt.Errorf("%w: min ack pending should be more than 0", ErrInvalidOption) |
| 496 |
} |
| 497 |
req.MinAckPending = min |
| 498 |
return nil |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
// FetchPrioritized sets the priority used when sending fetch requests for consumer with |
| 503 |
// PriorityPolicyPrioritized. Lower values indicate higher priority (0 is the |
| 504 |
// highest priority). Maximum priority value is 9. |
| 505 |
// |
| 506 |
// If provided, FetchPriorityGroup must be set as well and the consumer has to |
| 507 |
// have PriorityPolicy set to PriorityPolicyPrioritized. |
| 508 |
func FetchPrioritized(priority uint8) FetchOpt { |
| 509 |
return func(req *pullRequest) error { |
| 510 |
req.Priority = priority |
| 511 |
return nil |
| 512 |
} |
| 513 |
} |
| 514 |
|
| 515 |
// FetchPriorityGroup sets the priority group for a consumer. |
| 516 |
// It has to match one of the priority groups set on the consumer. |
| 517 |
func FetchPriorityGroup(group string) FetchOpt { |
| 518 |
return func(req *pullRequest) error { |
| 519 |
req.Group = group |
| 520 |
return nil |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
// FetchMaxWait sets custom timeout for fetching predefined batch of messages. |
| 525 |
// |
| 526 |
// If not provided, a default of 30 seconds will be used. |
| 527 |
func FetchMaxWait(timeout time.Duration) FetchOpt { |
| 528 |
return func(req *pullRequest) error { |
| 529 |
if timeout <= 0 { |
| 530 |
return fmt.Errorf("%w: timeout value must be greater than 0", ErrInvalidOption) |
| 531 |
} |
| 532 |
req.Expires = timeout |
| 533 |
req.maxWaitSet = true |
| 534 |
return nil |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
// FetchHeartbeat sets custom heartbeat for individual fetch request. If a |
| 539 |
// client does not receive a heartbeat message from a stream for more than 2 |
| 540 |
// times the idle heartbeat setting, Fetch will return [ErrNoHeartbeat]. |
| 541 |
// |
| 542 |
// Heartbeat value has to be lower than FetchMaxWait / 2. |
| 543 |
// |
| 544 |
// If not provided, heartbeat will is set to 5s for requests with FetchMaxWait > 10s |
| 545 |
// and disabled otherwise. |
| 546 |
func FetchHeartbeat(hb time.Duration) FetchOpt { |
| 547 |
return func(req *pullRequest) error { |
| 548 |
if hb <= 0 { |
| 549 |
return fmt.Errorf("%w: timeout value must be greater than 0", ErrInvalidOption) |
| 550 |
} |
| 551 |
req.Heartbeat = hb |
| 552 |
return nil |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
// FetchContext sets a context for the Fetch operation. |
| 557 |
// The Fetch operation will be canceled if the context is canceled. |
| 558 |
// If the context has a deadline, it will be used to set expiry on pull request. |
| 559 |
func FetchContext(ctx context.Context) FetchOpt { |
| 560 |
return func(req *pullRequest) error { |
| 561 |
req.ctx = ctx |
| 562 |
|
| 563 |
// If context has a deadline, use it to set expiry |
| 564 |
if deadline, ok := ctx.Deadline(); ok { |
| 565 |
remaining := time.Until(deadline) |
| 566 |
if remaining <= 0 { |
| 567 |
return fmt.Errorf("%w: context deadline already exceeded", ErrInvalidOption) |
| 568 |
} |
| 569 |
// Use 90% of remaining time for server (capped at 1s) |
| 570 |
buffer := time.Duration(float64(remaining) * 0.1) |
| 571 |
if buffer > time.Second { |
| 572 |
buffer = time.Second |
| 573 |
} |
| 574 |
req.Expires = remaining - buffer |
| 575 |
} |
| 576 |
|
| 577 |
return nil |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
// WithDeletedDetails can be used to display the information about messages |
| 582 |
// deleted from a stream on a stream info request |
| 583 |
func WithDeletedDetails(deletedDetails bool) StreamInfoOpt { |
| 584 |
return func(req *streamInfoRequest) error { |
| 585 |
req.DeletedDetails = deletedDetails |
| 586 |
return nil |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
// WithSubjectFilter can be used to display the information about messages |
| 591 |
// stored on given subjects. |
| 592 |
// NOTE: if the subject filter matches over 100k |
| 593 |
// subjects, this will result in multiple requests to the server to retrieve all |
| 594 |
// the information, and all of the returned subjects will be kept in memory. |
| 595 |
func WithSubjectFilter(subject string) StreamInfoOpt { |
| 596 |
return func(req *streamInfoRequest) error { |
| 597 |
req.SubjectFilter = subject |
| 598 |
return nil |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
// WithStreamListSubject can be used to filter results of ListStreams and |
| 603 |
// StreamNames requests to only streams that have given subject in their |
| 604 |
// configuration. |
| 605 |
func WithStreamListSubject(subject string) StreamListOpt { |
| 606 |
return func(req *streamsRequest) error { |
| 607 |
req.Subject = subject |
| 608 |
return nil |
| 609 |
} |
| 610 |
} |
| 611 |
|
| 612 |
// WithMsgID sets the message ID used for deduplication. |
| 613 |
func WithMsgID(id string) PublishOpt { |
| 614 |
return func(opts *pubOpts) error { |
| 615 |
opts.id = id |
| 616 |
return nil |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
// WithMsgTTL sets per msg TTL. |
| 621 |
// Requires [StreamConfig.AllowMsgTTL] to be enabled. |
| 622 |
func WithMsgTTL(dur time.Duration) PublishOpt { |
| 623 |
return func(opts *pubOpts) error { |
| 624 |
opts.ttl = dur |
| 625 |
return nil |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
// WithExpectStream sets the expected stream the message should be published to. |
| 630 |
// If the message is published to a different stream server will reject the |
| 631 |
// message and publish will fail. |
| 632 |
func WithExpectStream(stream string) PublishOpt { |
| 633 |
return func(opts *pubOpts) error { |
| 634 |
opts.stream = stream |
| 635 |
return nil |
| 636 |
} |
| 637 |
} |
| 638 |
|
| 639 |
// WithExpectLastSequence sets the expected sequence number the last message |
| 640 |
// on a stream should have. If the last message has a different sequence number |
| 641 |
// server will reject the message and publish will fail. |
| 642 |
func WithExpectLastSequence(seq uint64) PublishOpt { |
| 643 |
return func(opts *pubOpts) error { |
| 644 |
opts.lastSeq = &seq |
| 645 |
return nil |
| 646 |
} |
| 647 |
} |
| 648 |
|
| 649 |
// WithExpectLastSequencePerSubject sets the expected sequence number the last |
| 650 |
// message on a subject the message is published to. If the last message on a |
| 651 |
// subject has a different sequence number server will reject the message and |
| 652 |
// publish will fail. |
| 653 |
func WithExpectLastSequencePerSubject(seq uint64) PublishOpt { |
| 654 |
return func(opts *pubOpts) error { |
| 655 |
opts.lastSubjectSeq = &seq |
| 656 |
return nil |
| 657 |
} |
| 658 |
} |
| 659 |
|
| 660 |
// WithExpectLastSequenceForSubject sets the sequence and subject for which the |
| 661 |
// last sequence number should be checked. If the last message on a subject |
| 662 |
// has a different sequence number server will reject the message and publish |
| 663 |
// will fail. |
| 664 |
func WithExpectLastSequenceForSubject(seq uint64, subject string) PublishOpt { |
| 665 |
return func(opts *pubOpts) error { |
| 666 |
if subject == "" { |
| 667 |
return fmt.Errorf("%w: subject cannot be empty", ErrInvalidOption) |
| 668 |
} |
| 669 |
opts.lastSubjectSeq = &seq |
| 670 |
opts.lastSubject = subject |
| 671 |
return nil |
| 672 |
} |
| 673 |
} |
| 674 |
|
| 675 |
// WithExpectLastMsgID sets the expected message ID the last message on a stream |
| 676 |
// should have. If the last message has a different message ID server will |
| 677 |
// reject the message and publish will fail. |
| 678 |
func WithExpectLastMsgID(id string) PublishOpt { |
| 679 |
return func(opts *pubOpts) error { |
| 680 |
opts.lastMsgID = id |
| 681 |
return nil |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
// WithRetryWait sets the retry wait time when ErrNoResponders is encountered. |
| 686 |
// Defaults to 250ms. |
| 687 |
func WithRetryWait(dur time.Duration) PublishOpt { |
| 688 |
return func(opts *pubOpts) error { |
| 689 |
if dur <= 0 { |
| 690 |
return fmt.Errorf("%w: retry wait should be more than 0", ErrInvalidOption) |
| 691 |
} |
| 692 |
opts.retryWait = dur |
| 693 |
return nil |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
// WithRetryAttempts sets the retry number of attempts when ErrNoResponders is |
| 698 |
// encountered. Defaults to 2 |
| 699 |
func WithRetryAttempts(num int) PublishOpt { |
| 700 |
return func(opts *pubOpts) error { |
| 701 |
if num < 0 { |
| 702 |
return fmt.Errorf("%w: retry attempts cannot be negative", ErrInvalidOption) |
| 703 |
} |
| 704 |
opts.retryAttempts = num |
| 705 |
return nil |
| 706 |
} |
| 707 |
} |
| 708 |
|
| 709 |
// WithStallWait sets the max wait when the producer becomes stall producing |
| 710 |
// messages. If a publish call is blocked for this long, ErrTooManyStalledMsgs |
| 711 |
// is returned. |
| 712 |
func WithStallWait(ttl time.Duration) PublishOpt { |
| 713 |
return func(opts *pubOpts) error { |
| 714 |
if ttl <= 0 { |
| 715 |
return fmt.Errorf("%w: stall wait should be more than 0", ErrInvalidOption) |
| 716 |
} |
| 717 |
opts.stallWait = ttl |
| 718 |
return nil |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
// Predefined schedule constants for use with [WithScheduleCron]. |
| 723 |
const ( |
| 724 |
ScheduleYearly = "@yearly" |
| 725 |
ScheduleMonthly = "@monthly" |
| 726 |
ScheduleWeekly = "@weekly" |
| 727 |
ScheduleDaily = "@daily" |
| 728 |
ScheduleHourly = "@hourly" |
| 729 |
) |
| 730 |
|
| 731 |
// WithScheduleAt schedules a message for one-time delivery at a specific time. |
| 732 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 733 |
func WithScheduleAt(t time.Time) PublishOpt { |
| 734 |
return func(opts *pubOpts) error { |
| 735 |
opts.schedule = "@at " + t.UTC().Format(time.RFC3339) |
| 736 |
return nil |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
// WithScheduleEvery schedules a message for repeated delivery at the given |
| 741 |
// interval. The minimum interval is 1 second. |
| 742 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 743 |
func WithScheduleEvery(d time.Duration) PublishOpt { |
| 744 |
return func(opts *pubOpts) error { |
| 745 |
if d < time.Second { |
| 746 |
return fmt.Errorf("%w: schedule interval must be at least 1s", ErrInvalidOption) |
| 747 |
} |
| 748 |
opts.schedule = "@every " + d.String() |
| 749 |
return nil |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
// WithScheduleCron schedules a message using a cron expression. |
| 754 |
// Accepts 6-field cron format (seconds minutes hours day-of-month month |
| 755 |
// day-of-week) or predefined schedules (e.g. [ScheduleHourly], |
| 756 |
// [ScheduleDaily]). |
| 757 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 758 |
func WithScheduleCron(expr string) PublishOpt { |
| 759 |
return func(opts *pubOpts) error { |
| 760 |
if expr == "" { |
| 761 |
return fmt.Errorf("%w: cron expression cannot be empty", ErrInvalidOption) |
| 762 |
} |
| 763 |
opts.schedule = expr |
| 764 |
return nil |
| 765 |
} |
| 766 |
} |
| 767 |
|
| 768 |
// WithScheduleTarget sets the subject where scheduled messages will be |
| 769 |
// delivered. |
| 770 |
// This option is required for scheduled messages. |
| 771 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 772 |
func WithScheduleTarget(subject string) PublishOpt { |
| 773 |
return func(opts *pubOpts) error { |
| 774 |
if subject == "" { |
| 775 |
return fmt.Errorf("%w: schedule target subject cannot be empty", ErrInvalidOption) |
| 776 |
} |
| 777 |
opts.scheduleTarget = subject |
| 778 |
return nil |
| 779 |
} |
| 780 |
} |
| 781 |
|
| 782 |
// WithScheduleSource instructs the scheduler to read the latest message |
| 783 |
// from the given subject and republish it on schedule. Used for data |
| 784 |
// sampling use cases. |
| 785 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 786 |
func WithScheduleSource(subject string) PublishOpt { |
| 787 |
return func(opts *pubOpts) error { |
| 788 |
if subject == "" { |
| 789 |
return fmt.Errorf("%w: schedule source subject cannot be empty", ErrInvalidOption) |
| 790 |
} |
| 791 |
opts.scheduleSource = subject |
| 792 |
return nil |
| 793 |
} |
| 794 |
} |
| 795 |
|
| 796 |
// WithScheduleTTL sets the TTL on messages generated by the scheduler. |
| 797 |
// Requires [StreamConfig.AllowMsgTTL] to be enabled on the stream. |
| 798 |
func WithScheduleTTL(d time.Duration) PublishOpt { |
| 799 |
return func(opts *pubOpts) error { |
| 800 |
if d <= 0 { |
| 801 |
return fmt.Errorf("%w: schedule TTL must be greater than 0", ErrInvalidOption) |
| 802 |
} |
| 803 |
opts.scheduleTTL = d.String() |
| 804 |
return nil |
| 805 |
} |
| 806 |
} |
| 807 |
|
| 808 |
// WithScheduleTTLNever marks messages generated by the scheduler as never |
| 809 |
// expiring. This overrides the stream's MaxAge for delivered messages. |
| 810 |
// Requires [StreamConfig.AllowMsgTTL] to be enabled on the stream. |
| 811 |
func WithScheduleTTLNever() PublishOpt { |
| 812 |
return func(opts *pubOpts) error { |
| 813 |
opts.scheduleTTL = "never" |
| 814 |
return nil |
| 815 |
} |
| 816 |
} |
| 817 |
|
| 818 |
// WithScheduleTimeZone sets the time zone for cron schedule expressions. |
| 819 |
// The zone must be a valid IANA time zone name (e.g., "America/New_York"). |
| 820 |
// Only valid with cron schedule expressions; the server will reject this |
| 821 |
// header if used with @at or @every schedules. |
| 822 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 823 |
func WithScheduleTimeZone(zone string) PublishOpt { |
| 824 |
return func(opts *pubOpts) error { |
| 825 |
if zone == "" { |
| 826 |
return fmt.Errorf("%w: schedule time zone cannot be empty", ErrInvalidOption) |
| 827 |
} |
| 828 |
opts.scheduleTZ = zone |
| 829 |
return nil |
| 830 |
} |
| 831 |
} |
| 832 |
|
| 833 |
// WithScheduleRollup sets a per-subject rollup on messages generated by the |
| 834 |
// scheduler, so each delivery purges the previous message on the target |
| 835 |
// subject. |
| 836 |
// Requires [StreamConfig.AllowMsgSchedules] to be enabled. |
| 837 |
func WithScheduleRollup() PublishOpt { |
| 838 |
return func(opts *pubOpts) error { |
| 839 |
opts.scheduleRollup = MsgRollupSubject |
| 840 |
return nil |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
type nextOptFunc func(*nextOpts) |
| 845 |
|
| 846 |
func (fn nextOptFunc) configureNext(opts *nextOpts) { |
| 847 |
fn(opts) |
| 848 |
} |
| 849 |
|
| 850 |
// NextMaxWait sets a timeout for the Next operation. |
| 851 |
// If the timeout is reached before a message is available, a timeout error is returned. |
| 852 |
func NextMaxWait(timeout time.Duration) NextOpt { |
| 853 |
return nextOptFunc(func(opts *nextOpts) { |
| 854 |
opts.timeout = timeout |
| 855 |
}) |
| 856 |
} |
| 857 |
|
| 858 |
// NextContext sets a context for the Next operation. |
| 859 |
// The Next operation will be canceled if the context is canceled. |
| 860 |
func NextContext(ctx context.Context) NextOpt { |
| 861 |
return nextOptFunc(func(opts *nextOpts) { |
| 862 |
opts.ctx = ctx |
| 863 |
}) |
| 864 |
} |