| 1 |
// Copyright 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 |
//go:build !skip_js_tests |
| 15 |
|
| 16 |
package server |
| 17 |
|
| 18 |
import ( |
| 19 |
"bytes" |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"math" |
| 24 |
"math/big" |
| 25 |
"strconv" |
| 26 |
"strings" |
| 27 |
"sync" |
| 28 |
"testing" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/klauspost/compress/s2" |
| 32 |
"github.com/nats-io/nats.go" |
| 33 |
) |
| 34 |
|
| 35 |
func TestJetStreamAtomicBatchPublish(t *testing.T) { |
| 36 |
test := func( |
| 37 |
t *testing.T, |
| 38 |
storage StorageType, |
| 39 |
retention RetentionPolicy, |
| 40 |
replicas int, |
| 41 |
) { |
| 42 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 43 |
defer c.shutdown() |
| 44 |
|
| 45 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 46 |
defer nc.Close() |
| 47 |
|
| 48 |
var pubAck JSPubAckResponse |
| 49 |
|
| 50 |
cfg := &StreamConfig{ |
| 51 |
Name: "TEST", |
| 52 |
Subjects: []string{"foo.*"}, |
| 53 |
Storage: storage, |
| 54 |
Retention: retention, |
| 55 |
Replicas: replicas, |
| 56 |
} |
| 57 |
|
| 58 |
_, err := jsStreamCreate(t, nc, cfg) |
| 59 |
require_NoError(t, err) |
| 60 |
|
| 61 |
m := nats.NewMsg("foo.0") |
| 62 |
m.Data = []byte("foo.0") |
| 63 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 64 |
|
| 65 |
// Publish with atomic publish disabled. |
| 66 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 67 |
require_NoError(t, err) |
| 68 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 69 |
require_NotNil(t, pubAck.Error) |
| 70 |
require_Error(t, pubAck.Error, NewJSAtomicPublishDisabledError()) |
| 71 |
|
| 72 |
// Enable atomic publish. |
| 73 |
cfg.AllowAtomicPublish = true |
| 74 |
_, err = jsStreamUpdate(t, nc, cfg) |
| 75 |
require_NoError(t, err) |
| 76 |
|
| 77 |
// Publish without batch sequence errors. |
| 78 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 79 |
require_NoError(t, err) |
| 80 |
pubAck = JSPubAckResponse{} |
| 81 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 82 |
require_Error(t, pubAck.Error, NewJSAtomicPublishMissingSeqError()) |
| 83 |
|
| 84 |
// Publish a batch, misses start. |
| 85 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 86 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 87 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 88 |
require_NoError(t, err) |
| 89 |
pubAck = JSPubAckResponse{} |
| 90 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 91 |
require_Error(t, pubAck.Error, NewJSAtomicPublishIncompleteBatchError()) |
| 92 |
|
| 93 |
// Publish a "batch" which immediately commits. |
| 94 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 95 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 96 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 97 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 98 |
require_NoError(t, err) |
| 99 |
pubAck = JSPubAckResponse{} |
| 100 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 101 |
require_Equal(t, pubAck.Sequence, 1) |
| 102 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 103 |
require_Equal(t, pubAck.BatchSize, 1) |
| 104 |
|
| 105 |
// Reset commit. |
| 106 |
m.Header.Del("Nats-Batch-Commit") |
| 107 |
|
| 108 |
// Publish a "batch" which has gaps. |
| 109 |
require_NoError(t, nc.PublishMsg(m)) |
| 110 |
m.Header.Set("Nats-Batch-Sequence", "3") |
| 111 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 112 |
require_NoError(t, err) |
| 113 |
pubAck = JSPubAckResponse{} |
| 114 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 115 |
require_Error(t, pubAck.Error, NewJSAtomicPublishIncompleteBatchError()) |
| 116 |
|
| 117 |
// Publish a batch of N messages. |
| 118 |
m.Header.Del("Nats-Batch-Commit") |
| 119 |
for seq, batch := uint64(1), uint64(5); seq <= batch; seq++ { |
| 120 |
m.Subject = fmt.Sprintf("foo.%d", seq) |
| 121 |
m.Data = []byte(m.Subject) |
| 122 |
m.Header.Set("Nats-Batch-Sequence", strconv.FormatUint(seq, 10)) |
| 123 |
// If not commit. |
| 124 |
if seq != batch { |
| 125 |
require_NoError(t, nc.PublishMsg(m)) |
| 126 |
continue |
| 127 |
} |
| 128 |
|
| 129 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 130 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 131 |
require_NoError(t, err) |
| 132 |
|
| 133 |
pubAck = JSPubAckResponse{} |
| 134 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 135 |
require_True(t, pubAck.Error == nil) |
| 136 |
require_Equal(t, pubAck.Sequence, 6) |
| 137 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 138 |
require_Equal(t, pubAck.BatchSize, 5) |
| 139 |
} |
| 140 |
|
| 141 |
// Validate stream contents. |
| 142 |
if retention != InterestPolicy { |
| 143 |
for i := 0; i < 6; i++ { |
| 144 |
rsm, err := js.GetMsg("TEST", uint64(i+1)) |
| 145 |
require_NoError(t, err) |
| 146 |
subj := fmt.Sprintf("foo.%d", i) |
| 147 |
require_Equal(t, rsm.Subject, subj) |
| 148 |
require_Equal(t, string(rsm.Data), subj) |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 154 |
for _, retention := range []RetentionPolicy{LimitsPolicy, InterestPolicy, WorkQueuePolicy} { |
| 155 |
for _, replicas := range []int{1, 3} { |
| 156 |
t.Run(fmt.Sprintf("%s/%s/R%d", storage, retention, replicas), func(t *testing.T) { |
| 157 |
test(t, storage, retention, replicas) |
| 158 |
}) |
| 159 |
} |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
func TestJetStreamAtomicBatchPublishEmptyAck(t *testing.T) { |
| 165 |
test := func( |
| 166 |
t *testing.T, |
| 167 |
storage StorageType, |
| 168 |
retention RetentionPolicy, |
| 169 |
replicas int, |
| 170 |
) { |
| 171 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 172 |
defer c.shutdown() |
| 173 |
|
| 174 |
nc := clientConnectToServer(t, c.randomServer()) |
| 175 |
defer nc.Close() |
| 176 |
|
| 177 |
var pubAck JSPubAckResponse |
| 178 |
|
| 179 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 180 |
Name: "TEST", |
| 181 |
Subjects: []string{"foo.*"}, |
| 182 |
Storage: storage, |
| 183 |
Retention: retention, |
| 184 |
Replicas: replicas, |
| 185 |
AllowAtomicPublish: true, |
| 186 |
}) |
| 187 |
require_NoError(t, err) |
| 188 |
|
| 189 |
// Publish a batch of N messages. |
| 190 |
for seq, batch := uint64(1), uint64(5); seq <= batch; seq++ { |
| 191 |
m := nats.NewMsg(fmt.Sprintf("foo.%d", seq)) |
| 192 |
m.Data = []byte(m.Subject) |
| 193 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 194 |
m.Header.Set("Nats-Batch-Sequence", strconv.FormatUint(seq, 10)) |
| 195 |
commit := seq == batch |
| 196 |
if commit { |
| 197 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 198 |
} |
| 199 |
|
| 200 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 201 |
require_NoError(t, err) |
| 202 |
// If not commit we should receive an empty ack for flow control. |
| 203 |
if !commit { |
| 204 |
require_Len(t, len(rmsg.Data), 0) |
| 205 |
continue |
| 206 |
} |
| 207 |
|
| 208 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 209 |
require_Equal(t, pubAck.Sequence, 5) |
| 210 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 211 |
require_Equal(t, pubAck.BatchSize, 5) |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 216 |
for _, retention := range []RetentionPolicy{LimitsPolicy, InterestPolicy, WorkQueuePolicy} { |
| 217 |
for _, replicas := range []int{1, 3} { |
| 218 |
t.Run(fmt.Sprintf("%s/%s/R%d", storage, retention, replicas), func(t *testing.T) { |
| 219 |
test(t, storage, retention, replicas) |
| 220 |
}) |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
func TestJetStreamAtomicBatchPublishCommitEob(t *testing.T) { |
| 227 |
test := func( |
| 228 |
t *testing.T, |
| 229 |
storage StorageType, |
| 230 |
retention RetentionPolicy, |
| 231 |
replicas int, |
| 232 |
) { |
| 233 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 234 |
defer c.shutdown() |
| 235 |
|
| 236 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 237 |
defer nc.Close() |
| 238 |
|
| 239 |
var pubAck JSPubAckResponse |
| 240 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 241 |
Name: "TEST", |
| 242 |
Subjects: []string{"foo"}, |
| 243 |
Storage: storage, |
| 244 |
Retention: retention, |
| 245 |
Replicas: replicas, |
| 246 |
AllowAtomicPublish: true, |
| 247 |
}) |
| 248 |
require_NoError(t, err) |
| 249 |
|
| 250 |
// A batch that immediately commits through EOB is an error. |
| 251 |
m := nats.NewMsg("foo") |
| 252 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 253 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 254 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 255 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 256 |
require_NoError(t, err) |
| 257 |
pubAck = JSPubAckResponse{} |
| 258 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 259 |
require_Error(t, pubAck.Error, NewJSAtomicPublishIncompleteBatchError()) |
| 260 |
|
| 261 |
m = nats.NewMsg("foo") |
| 262 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 263 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 264 |
require_NoError(t, nc.PublishMsg(m)) |
| 265 |
|
| 266 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 267 |
require_NoError(t, nc.PublishMsg(m)) |
| 268 |
|
| 269 |
m.Header.Set("Nats-Batch-Sequence", "3") |
| 270 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 271 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 272 |
require_NoError(t, err) |
| 273 |
pubAck = JSPubAckResponse{} |
| 274 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 275 |
require_True(t, pubAck.Error == nil) |
| 276 |
require_Equal(t, pubAck.Sequence, 2) |
| 277 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 278 |
require_Equal(t, pubAck.BatchSize, 2) |
| 279 |
|
| 280 |
// Validate stream contents. |
| 281 |
if retention != InterestPolicy { |
| 282 |
for seq := uint64(1); seq <= 2; seq++ { |
| 283 |
rsm, err := js.GetMsg("TEST", seq) |
| 284 |
require_NoError(t, err) |
| 285 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Id"), "uuid") |
| 286 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Sequence"), strconv.FormatUint(seq, 10)) |
| 287 |
// The last message should have the commit header set, even though the commit was done via EOB. |
| 288 |
if seq == 2 { |
| 289 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Commit"), "1") |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 296 |
for _, retention := range []RetentionPolicy{LimitsPolicy, InterestPolicy, WorkQueuePolicy} { |
| 297 |
for _, replicas := range []int{1, 3} { |
| 298 |
t.Run(fmt.Sprintf("%s/%s/R%d", storage, retention, replicas), func(t *testing.T) { |
| 299 |
test(t, storage, retention, replicas) |
| 300 |
}) |
| 301 |
} |
| 302 |
} |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
func TestJetStreamAtomicBatchPublishCommitEobMaxBatchSize(t *testing.T) { |
| 307 |
streamMaxAtomicBatchSize = 3 |
| 308 |
defer func() { |
| 309 |
streamMaxAtomicBatchSize = streamDefaultMaxAtomicBatchSize |
| 310 |
}() |
| 311 |
|
| 312 |
s := RunBasicJetStreamServer(t) |
| 313 |
defer s.Shutdown() |
| 314 |
|
| 315 |
nc := clientConnectToServer(t, s) |
| 316 |
defer nc.Close() |
| 317 |
|
| 318 |
cfg := &StreamConfig{ |
| 319 |
Name: "TEST", |
| 320 |
Subjects: []string{"foo"}, |
| 321 |
Storage: FileStorage, |
| 322 |
Retention: LimitsPolicy, |
| 323 |
Replicas: 1, |
| 324 |
AllowAtomicPublish: true, |
| 325 |
} |
| 326 |
_, err := jsStreamCreate(t, nc, cfg) |
| 327 |
require_NoError(t, err) |
| 328 |
|
| 329 |
var pubAck JSPubAckResponse |
| 330 |
|
| 331 |
// A batch of exactly the maximum size must be accepted when committed via an |
| 332 |
// "End Of Batch" marker, since the marker itself is not stored as part of the batch. |
| 333 |
for seq := 1; seq <= streamMaxAtomicBatchSize; seq++ { |
| 334 |
m := nats.NewMsg("foo") |
| 335 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 336 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(seq)) |
| 337 |
require_NoError(t, nc.PublishMsg(m)) |
| 338 |
} |
| 339 |
m := nats.NewMsg("foo") |
| 340 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 341 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(streamMaxAtomicBatchSize+1)) |
| 342 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 343 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 344 |
require_NoError(t, err) |
| 345 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 346 |
require_True(t, pubAck.Error == nil) |
| 347 |
require_Equal(t, pubAck.BatchSize, uint64(streamMaxAtomicBatchSize)) |
| 348 |
|
| 349 |
// One message over the maximum size must still be rejected when committed via EOB. |
| 350 |
for seq := 1; seq <= streamMaxAtomicBatchSize+1; seq++ { |
| 351 |
m = nats.NewMsg("foo") |
| 352 |
m.Header.Set("Nats-Batch-Id", "uuid2") |
| 353 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(seq)) |
| 354 |
require_NoError(t, nc.PublishMsg(m)) |
| 355 |
} |
| 356 |
m = nats.NewMsg("foo") |
| 357 |
m.Header.Set("Nats-Batch-Id", "uuid2") |
| 358 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(streamMaxAtomicBatchSize+2)) |
| 359 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 360 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 361 |
require_NoError(t, err) |
| 362 |
pubAck = JSPubAckResponse{} |
| 363 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 364 |
require_Error(t, pubAck.Error, NewJSAtomicPublishTooLargeBatchError(streamMaxAtomicBatchSize)) |
| 365 |
|
| 366 |
// An EOB commit marker for an unknown batch at sequence maxSize+1 means the batch |
| 367 |
// itself would have exactly maxSize messages, so it should be reported as incomplete |
| 368 |
// rather than too large. |
| 369 |
m = nats.NewMsg("foo") |
| 370 |
m.Header.Set("Nats-Batch-Id", "uuid3") |
| 371 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(streamMaxAtomicBatchSize+1)) |
| 372 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 373 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 374 |
require_NoError(t, err) |
| 375 |
pubAck = JSPubAckResponse{} |
| 376 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 377 |
require_Error(t, pubAck.Error, NewJSAtomicPublishIncompleteBatchError()) |
| 378 |
} |
| 379 |
|
| 380 |
func TestJetStreamAtomicBatchPublishLimits(t *testing.T) { |
| 381 |
streamMaxAtomicBatchInflightPerStream = 1 |
| 382 |
streamMaxAtomicBatchInflightTotal = 1 |
| 383 |
streamMaxAtomicBatchSize = 2 |
| 384 |
streamMaxBatchTimeout = 500 * time.Millisecond |
| 385 |
defer func() { |
| 386 |
streamMaxAtomicBatchInflightPerStream = streamDefaultMaxAtomicBatchInflightPerStream |
| 387 |
streamMaxAtomicBatchInflightTotal = streamDefaultMaxAtomicBatchInflightTotal |
| 388 |
streamMaxAtomicBatchSize = streamDefaultMaxAtomicBatchSize |
| 389 |
streamMaxBatchTimeout = streamDefaultMaxBatchTimeout |
| 390 |
}() |
| 391 |
|
| 392 |
test := func(t *testing.T, replicas int) { |
| 393 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 394 |
defer c.shutdown() |
| 395 |
|
| 396 |
nc := clientConnectToServer(t, c.randomServer()) |
| 397 |
defer nc.Close() |
| 398 |
|
| 399 |
var pubAck JSPubAckResponse |
| 400 |
|
| 401 |
cfg := &StreamConfig{ |
| 402 |
Name: "FOO", |
| 403 |
Subjects: []string{"foo"}, |
| 404 |
Storage: FileStorage, |
| 405 |
Retention: LimitsPolicy, |
| 406 |
Replicas: replicas, |
| 407 |
AllowAtomicPublish: true, |
| 408 |
} |
| 409 |
_, err := jsStreamCreate(t, nc, cfg) |
| 410 |
require_NoError(t, err) |
| 411 |
|
| 412 |
// For testing total server-wide maximum inflight batches. |
| 413 |
cfg = &StreamConfig{ |
| 414 |
Name: "BAR", |
| 415 |
Subjects: []string{"bar"}, |
| 416 |
Storage: FileStorage, |
| 417 |
Retention: LimitsPolicy, |
| 418 |
Replicas: replicas, |
| 419 |
AllowAtomicPublish: true, |
| 420 |
} |
| 421 |
_, err = jsStreamCreate(t, nc, cfg) |
| 422 |
require_NoError(t, err) |
| 423 |
|
| 424 |
// A batch ID must not exceed the maximum length. |
| 425 |
for _, length := range []int{64, 65} { |
| 426 |
longBatchId := strings.Repeat("A", length) |
| 427 |
m := nats.NewMsg("foo") |
| 428 |
m.Header.Set("Nats-Batch-Id", longBatchId) |
| 429 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 430 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 431 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 432 |
require_NoError(t, err) |
| 433 |
pubAck = JSPubAckResponse{} |
| 434 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 435 |
if length <= 64 { |
| 436 |
require_True(t, pubAck.Error == nil) |
| 437 |
} else { |
| 438 |
require_NotNil(t, pubAck.Error) |
| 439 |
require_Error(t, pubAck.Error, NewJSAtomicPublishInvalidBatchIDError()) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
// One batch is inflight. |
| 444 |
m := nats.NewMsg("foo") |
| 445 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 446 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 447 |
require_NoError(t, nc.PublishMsg(m)) |
| 448 |
|
| 449 |
// Another batch moves over the threshold and batch is denied. |
| 450 |
m = nats.NewMsg("foo") |
| 451 |
m.Header.Set("Nats-Batch-Id", "exceeds_threshold") |
| 452 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 453 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 454 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 455 |
require_NoError(t, err) |
| 456 |
pubAck = JSPubAckResponse{} |
| 457 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 458 |
require_Error(t, pubAck.Error, NewJSAtomicPublishTooManyInflightError()) |
| 459 |
|
| 460 |
// Another batch on a different stream moves over the server-wide threshold and batch is denied. |
| 461 |
m = nats.NewMsg("bar") |
| 462 |
m.Header.Set("Nats-Batch-Id", "bar") |
| 463 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 464 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 465 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 466 |
require_NoError(t, err) |
| 467 |
pubAck = JSPubAckResponse{} |
| 468 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 469 |
require_Error(t, pubAck.Error, NewJSAtomicPublishTooManyInflightError()) |
| 470 |
|
| 471 |
// The first batch should now time out. |
| 472 |
sl := c.streamLeader(globalAccountName, "FOO") |
| 473 |
mset, err := sl.globalAccount().lookupStream("FOO") |
| 474 |
require_NoError(t, err) |
| 475 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 476 |
mset.mu.RLock() |
| 477 |
batches := mset.batches |
| 478 |
mset.mu.RUnlock() |
| 479 |
if batches == nil { |
| 480 |
return errors.New("batches not found") |
| 481 |
} |
| 482 |
batches.mu.Lock() |
| 483 |
groups := len(batches.atomic) |
| 484 |
batches.mu.Unlock() |
| 485 |
if groups != 0 { |
| 486 |
return fmt.Errorf("expected 0 groups, got %d", groups) |
| 487 |
} |
| 488 |
return nil |
| 489 |
}) |
| 490 |
|
| 491 |
// Publishing to the batch should also error since it timed out. |
| 492 |
m = nats.NewMsg("foo") |
| 493 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 494 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 495 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 496 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 497 |
require_NoError(t, err) |
| 498 |
pubAck = JSPubAckResponse{} |
| 499 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 500 |
require_Error(t, pubAck.Error, NewJSAtomicPublishIncompleteBatchError()) |
| 501 |
|
| 502 |
// Batch should be rejected if going over the max batch size. |
| 503 |
for _, size := range []int{streamMaxAtomicBatchSize, streamMaxAtomicBatchSize + 1} { |
| 504 |
for i := range size { |
| 505 |
seq := i + 1 |
| 506 |
m = nats.NewMsg("foo") |
| 507 |
m.Header.Set("Nats-Batch-Id", "exceeds_threshold") |
| 508 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(seq)) |
| 509 |
commit := seq == size |
| 510 |
if !commit { |
| 511 |
require_NoError(t, nc.PublishMsg(m)) |
| 512 |
continue |
| 513 |
} |
| 514 |
|
| 515 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 516 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 517 |
require_NoError(t, err) |
| 518 |
pubAck = JSPubAckResponse{} |
| 519 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 520 |
if size <= streamMaxAtomicBatchSize { |
| 521 |
require_True(t, pubAck.Error == nil) |
| 522 |
require_Equal(t, pubAck.BatchSize, uint64(size)) |
| 523 |
} else { |
| 524 |
require_Error(t, pubAck.Error, NewJSAtomicPublishTooLargeBatchError(streamMaxAtomicBatchSize)) |
| 525 |
} |
| 526 |
} |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
t.Run("R1", func(t *testing.T) { test(t, 1) }) |
| 531 |
t.Run("R3", func(t *testing.T) { test(t, 3) }) |
| 532 |
} |
| 533 |
|
| 534 |
func TestJetStreamAtomicBatchPublishDedupeNotAllowed(t *testing.T) { |
| 535 |
test := func( |
| 536 |
t *testing.T, |
| 537 |
nc *nats.Conn, |
| 538 |
js nats.JetStreamContext, |
| 539 |
storage StorageType, |
| 540 |
retention RetentionPolicy, |
| 541 |
replicas int, |
| 542 |
) { |
| 543 |
cfg := &StreamConfig{ |
| 544 |
Name: "TEST", |
| 545 |
Retention: retention, |
| 546 |
Subjects: []string{"foo"}, |
| 547 |
Replicas: replicas, |
| 548 |
Storage: storage, |
| 549 |
AllowAtomicPublish: true, |
| 550 |
} |
| 551 |
|
| 552 |
_, err := jsStreamCreate(t, nc, cfg) |
| 553 |
require_NoError(t, err) |
| 554 |
|
| 555 |
_, err = js.Publish("foo", nil, nats.MsgId("pre-existing")) |
| 556 |
require_NoError(t, err) |
| 557 |
|
| 558 |
var pubAck JSPubAckResponse |
| 559 |
m := nats.NewMsg("foo") |
| 560 |
m.Header.Set("Nats-Msg-Id", "pre-existing") |
| 561 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 562 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 563 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 564 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 565 |
require_NoError(t, err) |
| 566 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 567 |
require_NotNil(t, pubAck.Error) |
| 568 |
require_Error(t, pubAck.Error, NewJSAtomicPublishContainsDuplicateMessageError()) |
| 569 |
|
| 570 |
m = nats.NewMsg("foo") |
| 571 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 572 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 573 |
m.Header.Set("Nats-Msg-Id", "msgId1") |
| 574 |
require_NoError(t, nc.PublishMsg(m)) |
| 575 |
|
| 576 |
pubAck = JSPubAckResponse{} |
| 577 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 578 |
m.Header.Set("Nats-Msg-Id", "msgId2") |
| 579 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 580 |
rmsg, err = nc.RequestMsg(m, time.Second) |
| 581 |
require_NoError(t, err) |
| 582 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 583 |
require_True(t, pubAck.Error == nil) |
| 584 |
require_Equal(t, pubAck.BatchSize, 2) |
| 585 |
require_Equal(t, pubAck.Sequence, 3) |
| 586 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 587 |
} |
| 588 |
|
| 589 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 590 |
for _, retention := range []RetentionPolicy{LimitsPolicy, InterestPolicy, WorkQueuePolicy} { |
| 591 |
for _, replicas := range []int{1, 3} { |
| 592 |
t.Run(fmt.Sprintf("%s/%s/R%d", storage, retention, replicas), func(t *testing.T) { |
| 593 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 594 |
defer c.shutdown() |
| 595 |
|
| 596 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 597 |
defer nc.Close() |
| 598 |
|
| 599 |
test(t, nc, js, storage, retention, replicas) |
| 600 |
}) |
| 601 |
} |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
func TestJetStreamAtomicBatchPublishSourceAndMirror(t *testing.T) { |
| 607 |
test := func(t *testing.T, replicas int) { |
| 608 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 609 |
defer c.shutdown() |
| 610 |
|
| 611 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 612 |
defer nc.Close() |
| 613 |
|
| 614 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 615 |
Name: "TEST", |
| 616 |
Subjects: []string{"foo"}, |
| 617 |
Storage: FileStorage, |
| 618 |
AllowAtomicPublish: true, |
| 619 |
Replicas: replicas, |
| 620 |
}) |
| 621 |
require_NoError(t, err) |
| 622 |
|
| 623 |
for seq := uint64(1); seq <= 3; seq++ { |
| 624 |
m := nats.NewMsg("foo") |
| 625 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 626 |
m.Header.Set("Nats-Batch-Sequence", strconv.FormatUint(seq, 10)) |
| 627 |
commit := seq == 3 |
| 628 |
if !commit { |
| 629 |
require_NoError(t, nc.PublishMsg(m)) |
| 630 |
continue |
| 631 |
} |
| 632 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 633 |
|
| 634 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 635 |
require_NoError(t, err) |
| 636 |
var pubAck JSPubAckResponse |
| 637 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 638 |
require_Equal(t, pubAck.Sequence, 3) |
| 639 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 640 |
require_Equal(t, pubAck.BatchSize, 3) |
| 641 |
} |
| 642 |
|
| 643 |
require_NoError(t, js.DeleteMsg("TEST", 2)) |
| 644 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 645 |
return checkState(t, c, globalAccountName, "TEST") |
| 646 |
}) |
| 647 |
|
| 648 |
// Mirror can source batched messages but can't do atomic batching itself. |
| 649 |
_, err = jsStreamCreate(t, nc, &StreamConfig{ |
| 650 |
Name: "M-no-batch", |
| 651 |
Storage: FileStorage, |
| 652 |
Mirror: &StreamSource{Name: "TEST"}, |
| 653 |
Replicas: replicas, |
| 654 |
AllowAtomicPublish: true, |
| 655 |
}) |
| 656 |
require_Error(t, err, NewJSMirrorWithAtomicPublishError()) |
| 657 |
|
| 658 |
_, err = js.AddStream(&nats.StreamConfig{ |
| 659 |
Name: "M", |
| 660 |
Mirror: &nats.StreamSource{Name: "TEST"}, |
| 661 |
Replicas: replicas, |
| 662 |
}) |
| 663 |
require_NoError(t, err) |
| 664 |
|
| 665 |
_, err = jsStreamCreate(t, nc, &StreamConfig{ |
| 666 |
Name: "S", |
| 667 |
Storage: FileStorage, |
| 668 |
Sources: []*StreamSource{{Name: "TEST"}}, |
| 669 |
Replicas: replicas, |
| 670 |
AllowAtomicPublish: true, |
| 671 |
}) |
| 672 |
require_NoError(t, err) |
| 673 |
|
| 674 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 675 |
for _, name := range []string{"M", "S"} { |
| 676 |
if si, err := js.StreamInfo(name); err != nil { |
| 677 |
return err |
| 678 |
} else if si.State.Msgs != 2 { |
| 679 |
return fmt.Errorf("expected 2 messages for stream %q, got %d", name, si.State.Msgs) |
| 680 |
} |
| 681 |
} |
| 682 |
return nil |
| 683 |
}) |
| 684 |
|
| 685 |
// Ensure the batching headers were removed when ingested into the source/mirror. |
| 686 |
rsm, err := js.GetMsg("M", 1) |
| 687 |
require_NoError(t, err) |
| 688 |
require_Len(t, len(rsm.Header), 0) |
| 689 |
|
| 690 |
rsm, err = js.GetMsg("M", 3) |
| 691 |
require_NoError(t, err) |
| 692 |
require_Len(t, len(rsm.Header), 0) |
| 693 |
|
| 694 |
rsm, err = js.GetMsg("S", 1) |
| 695 |
require_NoError(t, err) |
| 696 |
require_Len(t, len(rsm.Header), 1) |
| 697 |
require_Equal(t, rsm.Header.Get(JSStreamSource), "TEST 1 > > foo") |
| 698 |
|
| 699 |
rsm, err = js.GetMsg("S", 2) |
| 700 |
require_NoError(t, err) |
| 701 |
require_Len(t, len(rsm.Header), 1) |
| 702 |
require_Equal(t, rsm.Header.Get(JSStreamSource), "TEST 3 > > foo") |
| 703 |
} |
| 704 |
|
| 705 |
t.Run("R1", func(t *testing.T) { test(t, 1) }) |
| 706 |
t.Run("R3", func(t *testing.T) { test(t, 3) }) |
| 707 |
} |
| 708 |
|
| 709 |
func TestJetStreamAtomicBatchPublishCleanup(t *testing.T) { |
| 710 |
const ( |
| 711 |
Disable = iota |
| 712 |
StepDown |
| 713 |
Delete |
| 714 |
Commit |
| 715 |
) |
| 716 |
|
| 717 |
test := func(t *testing.T, mode int) { |
| 718 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 719 |
defer c.shutdown() |
| 720 |
|
| 721 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 722 |
defer nc.Close() |
| 723 |
|
| 724 |
cfg := &StreamConfig{ |
| 725 |
Name: "TEST", |
| 726 |
Subjects: []string{"foo"}, |
| 727 |
Storage: FileStorage, |
| 728 |
AllowAtomicPublish: false, |
| 729 |
Replicas: 3, |
| 730 |
} |
| 731 |
_, err := jsStreamCreate(t, nc, cfg) |
| 732 |
require_NoError(t, err) |
| 733 |
|
| 734 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 735 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 736 |
require_NoError(t, err) |
| 737 |
mset.mu.RLock() |
| 738 |
batches := mset.batches |
| 739 |
mset.mu.RUnlock() |
| 740 |
require_True(t, batches == nil) |
| 741 |
|
| 742 |
// Enabling doesn't need to populate the batching state. |
| 743 |
cfg.AllowAtomicPublish = true |
| 744 |
_, err = jsStreamUpdate(t, nc, cfg) |
| 745 |
require_NoError(t, err) |
| 746 |
mset.mu.RLock() |
| 747 |
batches = mset.batches |
| 748 |
mset.mu.RUnlock() |
| 749 |
require_True(t, batches == nil) |
| 750 |
|
| 751 |
// Publish a partial batch that needs to be cleaned up. |
| 752 |
m := nats.NewMsg("foo") |
| 753 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 754 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 755 |
require_NoError(t, nc.PublishMsg(m)) |
| 756 |
|
| 757 |
// Publish another batch that commits, state should be cleaned up by default. |
| 758 |
m.Header.Set("Nats-Batch-Id", "commit") |
| 759 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 760 |
_, err = js.PublishMsg(m) |
| 761 |
require_NoError(t, err) |
| 762 |
|
| 763 |
mset.mu.RLock() |
| 764 |
batches = mset.batches |
| 765 |
mset.mu.RUnlock() |
| 766 |
require_NotNil(t, batches) |
| 767 |
batches.mu.Lock() |
| 768 |
groups := len(batches.atomic) |
| 769 |
b := batches.atomic["uuid"] |
| 770 |
batches.mu.Unlock() |
| 771 |
require_Len(t, groups, 1) |
| 772 |
require_NotNil(t, b) |
| 773 |
store := b.store |
| 774 |
require_Equal(t, store.State().Msgs, 1) |
| 775 |
|
| 776 |
// Should fully clean up the in-progress batch. |
| 777 |
switch mode { |
| 778 |
case Disable: |
| 779 |
cfg.AllowAtomicPublish = false |
| 780 |
_, err = jsStreamUpdate(t, nc, cfg) |
| 781 |
require_NoError(t, err) |
| 782 |
case StepDown: |
| 783 |
require_NoError(t, sl.JetStreamStepdownStream(globalAccountName, "TEST")) |
| 784 |
case Delete: |
| 785 |
require_NoError(t, mset.delete()) |
| 786 |
case Commit: |
| 787 |
m = nats.NewMsg("foo") |
| 788 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 789 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 790 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 791 |
_, err = js.PublishMsg(m) |
| 792 |
require_NoError(t, err) |
| 793 |
} |
| 794 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 795 |
mset.mu.RLock() |
| 796 |
batches = mset.batches |
| 797 |
mset.mu.RUnlock() |
| 798 |
if batches != nil { |
| 799 |
if mode != Commit { |
| 800 |
return fmt.Errorf("expected no batches") |
| 801 |
} |
| 802 |
batches.mu.Lock() |
| 803 |
groups = len(batches.atomic) |
| 804 |
batches.mu.Unlock() |
| 805 |
if groups > 0 { |
| 806 |
return fmt.Errorf("expected 0 groups, got %d", groups) |
| 807 |
} |
| 808 |
} |
| 809 |
if msgs := store.State().Msgs; msgs != 0 { |
| 810 |
return fmt.Errorf("expected 0 messages, got %d", msgs) |
| 811 |
} |
| 812 |
return nil |
| 813 |
}) |
| 814 |
} |
| 815 |
|
| 816 |
t.Run("Disable", func(t *testing.T) { test(t, Disable) }) |
| 817 |
t.Run("StepDown", func(t *testing.T) { test(t, StepDown) }) |
| 818 |
t.Run("Delete", func(t *testing.T) { test(t, Delete) }) |
| 819 |
t.Run("Commit", func(t *testing.T) { test(t, Commit) }) |
| 820 |
} |
| 821 |
|
| 822 |
func TestJetStreamAtomicBatchPublishConfigOpts(t *testing.T) { |
| 823 |
// Defaults. |
| 824 |
require_Equal(t, streamMaxBatchTimeout, 10*time.Second) |
| 825 |
require_Equal(t, streamMaxAtomicBatchInflightPerStream, 50) |
| 826 |
require_Equal(t, streamMaxAtomicBatchInflightTotal, 1000) |
| 827 |
require_Equal(t, streamMaxAtomicBatchSize, 1000) |
| 828 |
require_Equal(t, streamMaxFastBatchInflightPerStream, 1000) |
| 829 |
require_Equal(t, streamMaxFastBatchInflightTotal, 50_000) |
| 830 |
|
| 831 |
batchingConf := ` |
| 832 |
listen: 127.0.0.1:-1 |
| 833 |
jetstream { |
| 834 |
store_dir: %q |
| 835 |
limits { |
| 836 |
batch { |
| 837 |
max_inflight_per_stream: %d |
| 838 |
max_inflight_total: %d |
| 839 |
max_msgs: %d |
| 840 |
timeout: %s |
| 841 |
} |
| 842 |
} |
| 843 |
}` |
| 844 |
|
| 845 |
cf := createConfFile(t, []byte(fmt.Sprintf(batchingConf, t.TempDir(), 10, 20, 100, "5s"))) |
| 846 |
s, _ := RunServerWithConfig(cf) |
| 847 |
defer s.Shutdown() |
| 848 |
|
| 849 |
opts := s.getOpts() |
| 850 |
require_Equal(t, opts.JetStreamLimits.MaxBatchInflightPerStream, 10) |
| 851 |
require_Equal(t, opts.JetStreamLimits.MaxBatchInflightTotal, 20) |
| 852 |
require_Equal(t, opts.JetStreamLimits.MaxBatchSize, 100) |
| 853 |
require_Equal(t, opts.JetStreamLimits.MaxBatchTimeout, 5*time.Second) |
| 854 |
|
| 855 |
// Reloading is not supported, that would potentially mean dropping random batches when lowering limits. |
| 856 |
changeCurrentConfigContentWithNewContent(t, cf, []byte(fmt.Sprintf(batchingConf, t.TempDir(), 20, 40, 200, "10s"))) |
| 857 |
require_Error(t, s.Reload(), fmt.Errorf("config reload not supported for JetStreamLimits")) |
| 858 |
} |
| 859 |
|
| 860 |
func TestJetStreamAtomicBatchPublishDenyHeaders(t *testing.T) { |
| 861 |
test := func(t *testing.T, replicas int) { |
| 862 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 863 |
defer c.shutdown() |
| 864 |
|
| 865 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 866 |
defer nc.Close() |
| 867 |
|
| 868 |
cfg := &StreamConfig{ |
| 869 |
Name: "TEST", |
| 870 |
Subjects: []string{"foo"}, |
| 871 |
Storage: FileStorage, |
| 872 |
AllowAtomicPublish: true, |
| 873 |
Replicas: replicas, |
| 874 |
} |
| 875 |
_, err := jsStreamCreate(t, nc, cfg) |
| 876 |
require_NoError(t, err) |
| 877 |
|
| 878 |
// We might support these headers later on, but for now error. |
| 879 |
for key, value := range map[string]string{ |
| 880 |
"Nats-Expected-Last-Msg-Id": "msgId", |
| 881 |
} { |
| 882 |
t.Run(key, func(t *testing.T) { |
| 883 |
m := nats.NewMsg("foo") |
| 884 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 885 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 886 |
m.Header.Set(key, value) |
| 887 |
require_NoError(t, nc.PublishMsg(m)) |
| 888 |
|
| 889 |
m = nats.NewMsg("foo") |
| 890 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 891 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 892 |
m.Header.Set("Nats-Batch-Commit", "eob") |
| 893 |
_, err = js.PublishMsg(m) |
| 894 |
require_Error(t, err, NewJSAtomicPublishUnsupportedHeaderBatchError(key)) |
| 895 |
}) |
| 896 |
} |
| 897 |
} |
| 898 |
|
| 899 |
t.Run("R1", func(t *testing.T) { test(t, 1) }) |
| 900 |
t.Run("R3", func(t *testing.T) { test(t, 3) }) |
| 901 |
} |
| 902 |
|
| 903 |
func TestJetStreamAtomicBatchPublishStageAndCommit(t *testing.T) { |
| 904 |
type BatchItem struct { |
| 905 |
subject string |
| 906 |
rsubject string |
| 907 |
header nats.Header |
| 908 |
msg []byte |
| 909 |
err error |
| 910 |
} |
| 911 |
|
| 912 |
type BatchTest struct { |
| 913 |
title string |
| 914 |
allowRollup bool |
| 915 |
denyPurge bool |
| 916 |
allowTTL bool |
| 917 |
allowMsgCounter bool |
| 918 |
allowMsgSchedules bool |
| 919 |
discardNew bool |
| 920 |
discardNewPerSubj bool |
| 921 |
init func(mset *stream) |
| 922 |
batch []BatchItem |
| 923 |
validate func(mset *stream, commit bool) |
| 924 |
} |
| 925 |
|
| 926 |
tests := []BatchTest{ |
| 927 |
{ |
| 928 |
title: "dedupe-distinct", |
| 929 |
batch: []BatchItem{ |
| 930 |
{subject: "foo", header: nats.Header{JSMsgId: {"foo"}}}, |
| 931 |
{subject: "bar", header: nats.Header{JSMsgId: {"bar"}}}, |
| 932 |
}, |
| 933 |
validate: func(mset *stream, commit bool) { |
| 934 |
require_Equal(t, mset.checkMsgId("foo") != nil, commit) |
| 935 |
require_Equal(t, mset.checkMsgId("bar") != nil, commit) |
| 936 |
}, |
| 937 |
}, |
| 938 |
{ |
| 939 |
title: "dedupe", |
| 940 |
init: func(mset *stream) { |
| 941 |
mset.storeMsgId(&ddentry{id: "foo", seq: 0, ts: time.Now().UnixNano()}) |
| 942 |
}, |
| 943 |
batch: []BatchItem{ |
| 944 |
{subject: "foo", header: nats.Header{JSMsgId: {"foo"}}, err: errMsgIdDuplicate}, |
| 945 |
}, |
| 946 |
validate: func(mset *stream, commit bool) { |
| 947 |
require_NotNil(t, mset.checkMsgId("foo")) |
| 948 |
}, |
| 949 |
}, |
| 950 |
{ |
| 951 |
title: "dedupe-staged", |
| 952 |
batch: []BatchItem{ |
| 953 |
{subject: "foo", header: nats.Header{JSMsgId: {"foo"}}}, |
| 954 |
{subject: "foo", header: nats.Header{JSMsgId: {"foo"}}, err: errMsgIdDuplicate}, |
| 955 |
}, |
| 956 |
validate: func(mset *stream, commit bool) { |
| 957 |
require_Equal(t, mset.checkMsgId("foo") != nil, commit) |
| 958 |
}, |
| 959 |
}, |
| 960 |
{ |
| 961 |
title: "counter-single", |
| 962 |
allowMsgCounter: true, |
| 963 |
batch: []BatchItem{ |
| 964 |
{subject: "foo", header: nats.Header{JSMessageIncr: {"1"}}}, |
| 965 |
}, |
| 966 |
validate: func(mset *stream, commit bool) { |
| 967 |
if !commit { |
| 968 |
require_True(t, mset.clusteredCounterTotal["foo"] == nil) |
| 969 |
} else { |
| 970 |
counter := mset.clusteredCounterTotal["foo"] |
| 971 |
require_NotNil(t, counter) |
| 972 |
require_Equal(t, counter.ops, 1) |
| 973 |
require_Equal(t, counter.total.String(), "1") |
| 974 |
} |
| 975 |
}, |
| 976 |
}, |
| 977 |
{ |
| 978 |
title: "counter-multiple", |
| 979 |
allowMsgCounter: true, |
| 980 |
batch: []BatchItem{ |
| 981 |
{subject: "foo", header: nats.Header{JSMessageIncr: {"1"}}}, |
| 982 |
{subject: "foo", header: nats.Header{JSMessageIncr: {"2"}}}, |
| 983 |
}, |
| 984 |
validate: func(mset *stream, commit bool) { |
| 985 |
if !commit { |
| 986 |
require_True(t, mset.clusteredCounterTotal["foo"] == nil) |
| 987 |
} else { |
| 988 |
counter := mset.clusteredCounterTotal["foo"] |
| 989 |
require_NotNil(t, counter) |
| 990 |
require_Equal(t, counter.ops, 2) |
| 991 |
require_Equal(t, counter.total.String(), "3") |
| 992 |
} |
| 993 |
}, |
| 994 |
}, |
| 995 |
{ |
| 996 |
title: "counter-pre-init", |
| 997 |
allowMsgCounter: true, |
| 998 |
init: func(mset *stream) { |
| 999 |
mset.clusteredCounterTotal = map[string]*msgCounterRunningTotal{ |
| 1000 |
"foo": {total: big.NewInt(1), ops: 1}, |
| 1001 |
} |
| 1002 |
}, |
| 1003 |
batch: []BatchItem{ |
| 1004 |
{subject: "foo", header: nats.Header{JSMessageIncr: {"2"}}}, |
| 1005 |
}, |
| 1006 |
validate: func(mset *stream, commit bool) { |
| 1007 |
counter := mset.clusteredCounterTotal["foo"] |
| 1008 |
require_NotNil(t, counter) |
| 1009 |
if !commit { |
| 1010 |
require_Equal(t, counter.ops, 1) |
| 1011 |
require_Equal(t, counter.total.String(), "1") |
| 1012 |
} else { |
| 1013 |
require_Equal(t, counter.ops, 2) |
| 1014 |
require_Equal(t, counter.total.String(), "3") |
| 1015 |
} |
| 1016 |
}, |
| 1017 |
}, |
| 1018 |
{ |
| 1019 |
title: "msg-schedules-disabled", |
| 1020 |
allowMsgSchedules: false, |
| 1021 |
batch: []BatchItem{ |
| 1022 |
{ |
| 1023 |
subject: "foo", |
| 1024 |
header: nats.Header{JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}}, |
| 1025 |
err: NewJSMessageSchedulesDisabledError(), |
| 1026 |
}, |
| 1027 |
{ |
| 1028 |
subject: "foo", |
| 1029 |
header: nats.Header{JSSchedulePattern: {"disabled"}}, |
| 1030 |
err: NewJSMessageSchedulesDisabledError(), |
| 1031 |
}, |
| 1032 |
}, |
| 1033 |
}, |
| 1034 |
{ |
| 1035 |
title: "msg-schedules-ttl-disabled", |
| 1036 |
allowMsgSchedules: true, |
| 1037 |
batch: []BatchItem{ |
| 1038 |
{ |
| 1039 |
subject: "foo", |
| 1040 |
header: nats.Header{ |
| 1041 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1042 |
JSScheduleTTL: {"1s"}, |
| 1043 |
}, |
| 1044 |
err: errMsgTTLDisabled, |
| 1045 |
}, |
| 1046 |
}, |
| 1047 |
}, |
| 1048 |
{ |
| 1049 |
title: "msg-schedules-ttl-invalid", |
| 1050 |
allowMsgSchedules: true, |
| 1051 |
allowTTL: true, |
| 1052 |
batch: []BatchItem{ |
| 1053 |
{ |
| 1054 |
subject: "foo", |
| 1055 |
header: nats.Header{ |
| 1056 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1057 |
JSScheduleTTL: {"invalid"}, |
| 1058 |
}, |
| 1059 |
err: NewJSMessageSchedulesTTLInvalidError(), |
| 1060 |
}, |
| 1061 |
}, |
| 1062 |
}, |
| 1063 |
{ |
| 1064 |
title: "msg-schedules-rollup-invalid", |
| 1065 |
allowMsgSchedules: true, |
| 1066 |
batch: []BatchItem{ |
| 1067 |
{ |
| 1068 |
subject: "foo", |
| 1069 |
header: nats.Header{ |
| 1070 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1071 |
JSScheduleRollup: {"invalid"}, |
| 1072 |
}, |
| 1073 |
err: NewJSMessageSchedulesRollupInvalidError(), |
| 1074 |
}, |
| 1075 |
}, |
| 1076 |
}, |
| 1077 |
{ |
| 1078 |
title: "msg-schedules-invalid-schedule", |
| 1079 |
allowMsgSchedules: true, |
| 1080 |
batch: []BatchItem{ |
| 1081 |
{ |
| 1082 |
subject: "foo", |
| 1083 |
header: nats.Header{JSSchedulePattern: {"invalid"}}, |
| 1084 |
err: NewJSMessageSchedulesPatternInvalidError(), |
| 1085 |
}, |
| 1086 |
}, |
| 1087 |
}, |
| 1088 |
{ |
| 1089 |
title: "msg-schedules-invalid-time-zone", |
| 1090 |
allowMsgSchedules: true, |
| 1091 |
batch: []BatchItem{ |
| 1092 |
{ |
| 1093 |
subject: "foo", |
| 1094 |
header: nats.Header{ |
| 1095 |
JSSchedulePattern: {"0 * * * * *"}, |
| 1096 |
JSScheduleTimeZone: {"Not/A/Zone"}, |
| 1097 |
}, |
| 1098 |
err: NewJSMessageSchedulesTimeZoneInvalidError(), |
| 1099 |
}, |
| 1100 |
}, |
| 1101 |
}, |
| 1102 |
{ |
| 1103 |
title: "msg-schedules-empty-time-zone", |
| 1104 |
allowMsgSchedules: true, |
| 1105 |
batch: []BatchItem{ |
| 1106 |
{ |
| 1107 |
subject: "foo", |
| 1108 |
header: nats.Header{ |
| 1109 |
JSSchedulePattern: {"0 * * * * *"}, |
| 1110 |
JSScheduleTimeZone: {""}, |
| 1111 |
}, |
| 1112 |
err: NewJSMessageSchedulesTimeZoneInvalidError(), |
| 1113 |
}, |
| 1114 |
}, |
| 1115 |
}, |
| 1116 |
{ |
| 1117 |
title: "msg-schedules-target-mismatch", |
| 1118 |
allowMsgSchedules: true, |
| 1119 |
batch: []BatchItem{ |
| 1120 |
{ |
| 1121 |
subject: "foo", |
| 1122 |
header: nats.Header{ |
| 1123 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1124 |
JSScheduleTarget: {"not.matching"}, |
| 1125 |
}, |
| 1126 |
err: NewJSMessageSchedulesTargetInvalidError(), |
| 1127 |
}, |
| 1128 |
}, |
| 1129 |
}, |
| 1130 |
{ |
| 1131 |
title: "msg-schedules-target-must-be-literal", |
| 1132 |
allowMsgSchedules: true, |
| 1133 |
batch: []BatchItem{ |
| 1134 |
{ |
| 1135 |
subject: "foo", |
| 1136 |
header: nats.Header{ |
| 1137 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1138 |
JSScheduleTarget: {"foo.*"}, |
| 1139 |
}, |
| 1140 |
err: NewJSMessageSchedulesTargetInvalidError(), |
| 1141 |
}, |
| 1142 |
}, |
| 1143 |
}, |
| 1144 |
{ |
| 1145 |
title: "msg-schedules-target-must-be-unique", |
| 1146 |
allowMsgSchedules: true, |
| 1147 |
batch: []BatchItem{ |
| 1148 |
{ |
| 1149 |
subject: "foo", |
| 1150 |
header: nats.Header{ |
| 1151 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1152 |
JSScheduleTarget: {"foo"}, |
| 1153 |
}, |
| 1154 |
err: NewJSMessageSchedulesTargetInvalidError(), |
| 1155 |
}, |
| 1156 |
}, |
| 1157 |
}, |
| 1158 |
{ |
| 1159 |
title: "msg-schedules-rollup-disabled", |
| 1160 |
allowMsgSchedules: true, |
| 1161 |
batch: []BatchItem{ |
| 1162 |
{ |
| 1163 |
subject: "foo", |
| 1164 |
header: nats.Header{ |
| 1165 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1166 |
JSScheduleTarget: {"bar"}, |
| 1167 |
JSMsgRollup: {JSMsgRollupSubject}, |
| 1168 |
}, |
| 1169 |
err: errors.New("rollup not permitted"), |
| 1170 |
}, |
| 1171 |
}, |
| 1172 |
}, |
| 1173 |
{ |
| 1174 |
title: "msg-schedules", |
| 1175 |
allowMsgSchedules: true, |
| 1176 |
allowRollup: true, |
| 1177 |
batch: []BatchItem{ |
| 1178 |
{ |
| 1179 |
subject: "foo", |
| 1180 |
header: nats.Header{ |
| 1181 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1182 |
JSScheduleTarget: {"baz"}, |
| 1183 |
}, |
| 1184 |
}, |
| 1185 |
{ |
| 1186 |
subject: "bar", |
| 1187 |
header: nats.Header{ |
| 1188 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1189 |
JSScheduleTarget: {"baz"}, |
| 1190 |
JSMsgRollup: {JSMsgRollupSubject}, |
| 1191 |
}, |
| 1192 |
}, |
| 1193 |
}, |
| 1194 |
}, |
| 1195 |
{ |
| 1196 |
title: "msg-schedules-purge-staged-not-schedule", |
| 1197 |
allowMsgSchedules: true, |
| 1198 |
allowRollup: true, |
| 1199 |
batch: []BatchItem{ |
| 1200 |
{subject: "foo"}, |
| 1201 |
{ |
| 1202 |
subject: "bar", |
| 1203 |
header: nats.Header{ |
| 1204 |
JSScheduleNext: {JSScheduleNextPurge}, |
| 1205 |
JSScheduler: {"foo"}, |
| 1206 |
}, |
| 1207 |
err: NewJSMessageSchedulesSchedulerInvalidError(), |
| 1208 |
}, |
| 1209 |
}, |
| 1210 |
}, |
| 1211 |
{ |
| 1212 |
title: "msg-schedules-purge-staged-schedule", |
| 1213 |
allowMsgSchedules: true, |
| 1214 |
allowRollup: true, |
| 1215 |
batch: []BatchItem{ |
| 1216 |
{ |
| 1217 |
subject: "foo", |
| 1218 |
header: nats.Header{ |
| 1219 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1220 |
JSScheduleTarget: {"baz"}, |
| 1221 |
}, |
| 1222 |
}, |
| 1223 |
{ |
| 1224 |
subject: "bar", |
| 1225 |
header: nats.Header{ |
| 1226 |
JSScheduleNext: {JSScheduleNextPurge}, |
| 1227 |
JSScheduler: {"foo"}, |
| 1228 |
}, |
| 1229 |
}, |
| 1230 |
}, |
| 1231 |
validate: func(mset *stream, commit bool) { |
| 1232 |
if !commit { |
| 1233 |
return |
| 1234 |
} |
| 1235 |
require_NotNil(t, mset.inflight["foo"]) |
| 1236 |
require_True(t, mset.inflight["foo"].schedule) |
| 1237 |
}, |
| 1238 |
}, |
| 1239 |
{ |
| 1240 |
title: "msg-schedules-purge-staged-overwritten", |
| 1241 |
allowMsgSchedules: true, |
| 1242 |
allowRollup: true, |
| 1243 |
batch: []BatchItem{ |
| 1244 |
{ |
| 1245 |
subject: "foo", |
| 1246 |
header: nats.Header{ |
| 1247 |
JSSchedulePattern: {"@at 1970-01-01T00:00:00Z"}, |
| 1248 |
JSScheduleTarget: {"baz"}, |
| 1249 |
}, |
| 1250 |
}, |
| 1251 |
{subject: "foo"}, |
| 1252 |
{ |
| 1253 |
subject: "bar", |
| 1254 |
header: nats.Header{ |
| 1255 |
JSScheduleNext: {JSScheduleNextPurge}, |
| 1256 |
JSScheduler: {"foo"}, |
| 1257 |
}, |
| 1258 |
err: NewJSMessageSchedulesSchedulerInvalidError(), |
| 1259 |
}, |
| 1260 |
}, |
| 1261 |
}, |
| 1262 |
{ |
| 1263 |
title: "msg-schedules-purge-inflight-not-schedule", |
| 1264 |
allowMsgSchedules: true, |
| 1265 |
allowRollup: true, |
| 1266 |
init: func(mset *stream) { |
| 1267 |
mset.inflight = map[string]*inflightSubjectRunningTotal{ |
| 1268 |
"foo": {bytes: 10, ops: 1, schedule: false}, |
| 1269 |
} |
| 1270 |
}, |
| 1271 |
batch: []BatchItem{ |
| 1272 |
{ |
| 1273 |
subject: "bar", |
| 1274 |
header: nats.Header{ |
| 1275 |
JSScheduleNext: {JSScheduleNextPurge}, |
| 1276 |
JSScheduler: {"foo"}, |
| 1277 |
}, |
| 1278 |
err: NewJSMessageSchedulesSchedulerInvalidError(), |
| 1279 |
}, |
| 1280 |
}, |
| 1281 |
}, |
| 1282 |
{ |
| 1283 |
title: "msg-schedules-purge-inflight-schedule", |
| 1284 |
allowMsgSchedules: true, |
| 1285 |
allowRollup: true, |
| 1286 |
init: func(mset *stream) { |
| 1287 |
mset.inflight = map[string]*inflightSubjectRunningTotal{ |
| 1288 |
"foo": {bytes: 10, ops: 1, schedule: true}, |
| 1289 |
} |
| 1290 |
}, |
| 1291 |
batch: []BatchItem{ |
| 1292 |
{ |
| 1293 |
subject: "bar", |
| 1294 |
header: nats.Header{ |
| 1295 |
JSScheduleNext: {JSScheduleNextPurge}, |
| 1296 |
JSScheduler: {"foo"}, |
| 1297 |
}, |
| 1298 |
}, |
| 1299 |
}, |
| 1300 |
}, |
| 1301 |
{ |
| 1302 |
title: "discard-new", |
| 1303 |
discardNew: true, |
| 1304 |
batch: []BatchItem{ |
| 1305 |
{subject: "foo1"}, |
| 1306 |
{subject: "foo2"}, |
| 1307 |
}, |
| 1308 |
validate: func(mset *stream, commit bool) { |
| 1309 |
if !commit { |
| 1310 |
require_Len(t, len(mset.inflight), 0) |
| 1311 |
} else { |
| 1312 |
require_Len(t, len(mset.inflight), 2) |
| 1313 |
require_Equal(t, *mset.inflight["foo1"], inflightSubjectRunningTotal{bytes: 20, ops: 1}) |
| 1314 |
require_Equal(t, *mset.inflight["foo2"], inflightSubjectRunningTotal{bytes: 20, ops: 1}) |
| 1315 |
} |
| 1316 |
}, |
| 1317 |
}, |
| 1318 |
{ |
| 1319 |
title: "discard-new-max-msgs", |
| 1320 |
discardNew: true, |
| 1321 |
batch: []BatchItem{ |
| 1322 |
{subject: "foo"}, |
| 1323 |
{subject: "foo"}, |
| 1324 |
{subject: "foo", err: ErrMaxMsgs}, |
| 1325 |
}, |
| 1326 |
validate: func(mset *stream, commit bool) { |
| 1327 |
if !commit { |
| 1328 |
require_Len(t, len(mset.inflight), 0) |
| 1329 |
} else { |
| 1330 |
require_Len(t, len(mset.inflight), 1) |
| 1331 |
require_Equal(t, *mset.inflight["foo"], inflightSubjectRunningTotal{bytes: 19 * 3, ops: 3}) |
| 1332 |
} |
| 1333 |
}, |
| 1334 |
}, |
| 1335 |
{ |
| 1336 |
title: "discard-new-max-bytes", |
| 1337 |
discardNew: true, |
| 1338 |
batch: []BatchItem{ |
| 1339 |
{subject: "foo1", msg: bytes.Repeat([]byte("A"), 10)}, |
| 1340 |
{subject: "foo2", msg: bytes.Repeat([]byte("A"), 11), err: ErrMaxBytes}, |
| 1341 |
}, |
| 1342 |
validate: func(mset *stream, commit bool) { |
| 1343 |
if !commit { |
| 1344 |
require_Len(t, len(mset.inflight), 0) |
| 1345 |
} else { |
| 1346 |
require_Len(t, len(mset.inflight), 2) |
| 1347 |
require_Equal(t, *mset.inflight["foo1"], inflightSubjectRunningTotal{bytes: 30, ops: 1}) |
| 1348 |
require_Equal(t, *mset.inflight["foo2"], inflightSubjectRunningTotal{bytes: 31, ops: 1}) |
| 1349 |
} |
| 1350 |
}, |
| 1351 |
}, |
| 1352 |
{ |
| 1353 |
title: "discard-new-max-msgs-per-subj", |
| 1354 |
discardNew: true, |
| 1355 |
discardNewPerSubj: true, |
| 1356 |
batch: []BatchItem{ |
| 1357 |
{subject: "foo"}, |
| 1358 |
}, |
| 1359 |
validate: func(mset *stream, commit bool) { |
| 1360 |
if !commit { |
| 1361 |
require_Len(t, len(mset.inflight), 0) |
| 1362 |
} else { |
| 1363 |
require_Len(t, len(mset.inflight), 1) |
| 1364 |
require_Equal(t, *mset.inflight["foo"], inflightSubjectRunningTotal{bytes: 19, ops: 1}) |
| 1365 |
} |
| 1366 |
}, |
| 1367 |
}, |
| 1368 |
{ |
| 1369 |
title: "discard-new-max-msgs-per-subj-duplicate", |
| 1370 |
discardNew: true, |
| 1371 |
discardNewPerSubj: true, |
| 1372 |
batch: []BatchItem{ |
| 1373 |
{subject: "foo"}, |
| 1374 |
{subject: "foo", err: ErrMaxMsgsPerSubject}, |
| 1375 |
}, |
| 1376 |
validate: func(mset *stream, commit bool) { |
| 1377 |
require_Len(t, len(mset.inflight), 0) |
| 1378 |
}, |
| 1379 |
}, |
| 1380 |
{ |
| 1381 |
title: "discard-new-max-msgs-per-subj-inflight", |
| 1382 |
discardNew: true, |
| 1383 |
discardNewPerSubj: true, |
| 1384 |
init: func(mset *stream) { |
| 1385 |
mset.inflight = map[string]*inflightSubjectRunningTotal{"foo": {bytes: 123, ops: 1}} |
| 1386 |
}, |
| 1387 |
batch: []BatchItem{ |
| 1388 |
{subject: "foo", err: ErrMaxMsgsPerSubject}, |
| 1389 |
}, |
| 1390 |
validate: func(mset *stream, commit bool) { |
| 1391 |
require_Len(t, len(mset.inflight), 1) |
| 1392 |
require_Equal(t, *mset.inflight["foo"], inflightSubjectRunningTotal{bytes: 123, ops: 1}) |
| 1393 |
}, |
| 1394 |
}, |
| 1395 |
{ |
| 1396 |
title: "discard-new-max-msgs-per-subj-pre-existing", |
| 1397 |
discardNew: true, |
| 1398 |
discardNewPerSubj: true, |
| 1399 |
init: func(mset *stream) { |
| 1400 |
_, _, err := mset.store.StoreMsg("foo", nil, nil, 0) |
| 1401 |
require_NoError(t, err) |
| 1402 |
}, |
| 1403 |
batch: []BatchItem{ |
| 1404 |
{subject: "foo", err: ErrMaxMsgsPerSubject}, |
| 1405 |
}, |
| 1406 |
validate: func(mset *stream, commit bool) { |
| 1407 |
require_Len(t, len(mset.inflight), 0) |
| 1408 |
}, |
| 1409 |
}, |
| 1410 |
{ |
| 1411 |
title: "expect-last-seq", |
| 1412 |
batch: []BatchItem{ |
| 1413 |
{subject: "foo", header: nats.Header{JSExpectedLastSeq: {"0"}}}, |
| 1414 |
{subject: "bar"}, |
| 1415 |
}, |
| 1416 |
}, |
| 1417 |
{ |
| 1418 |
title: "expect-last-seq-not-first", |
| 1419 |
batch: []BatchItem{ |
| 1420 |
{subject: "foo"}, |
| 1421 |
{subject: "bar", header: nats.Header{JSExpectedLastSeq: {"0"}}, err: errors.New("last sequence mismatch")}, |
| 1422 |
}, |
| 1423 |
}, |
| 1424 |
{ |
| 1425 |
title: "expect-last-seq-invalid-first", |
| 1426 |
batch: []BatchItem{ |
| 1427 |
{subject: "foo", header: nats.Header{JSExpectedLastSeq: {"1"}}, err: errors.New("last sequence mismatch: 1 vs 0")}, |
| 1428 |
}, |
| 1429 |
}, |
| 1430 |
{ |
| 1431 |
title: "expect-last-seq-invalid", |
| 1432 |
batch: []BatchItem{ |
| 1433 |
{subject: "foo", header: nats.Header{JSExpectedLastSeq: {"0"}}}, |
| 1434 |
{subject: "bar", header: nats.Header{JSExpectedLastSeq: {"0"}}, err: errors.New("last sequence mismatch: 0 vs 1")}, |
| 1435 |
}, |
| 1436 |
}, |
| 1437 |
{ |
| 1438 |
title: "expect-per-subj-simple", |
| 1439 |
batch: []BatchItem{ |
| 1440 |
{subject: "foo", header: nats.Header{JSExpectedLastSubjSeq: {"0"}}}, |
| 1441 |
{subject: "bar", header: nats.Header{JSExpectedLastSubjSeq: {"0"}}}, |
| 1442 |
}, |
| 1443 |
validate: func(mset *stream, commit bool) { |
| 1444 |
if !commit { |
| 1445 |
require_Len(t, len(mset.expectedPerSubjectSequence), 0) |
| 1446 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 0) |
| 1447 |
} else { |
| 1448 |
require_Len(t, len(mset.expectedPerSubjectSequence), 2) |
| 1449 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 2) |
| 1450 |
require_Equal(t, mset.expectedPerSubjectSequence[0], "foo") |
| 1451 |
require_Equal(t, mset.expectedPerSubjectSequence[1], "bar") |
| 1452 |
} |
| 1453 |
}, |
| 1454 |
}, |
| 1455 |
{ |
| 1456 |
title: "expect-per-subj-redundant-in-batch", |
| 1457 |
batch: []BatchItem{ |
| 1458 |
{ |
| 1459 |
subject: "foo", |
| 1460 |
header: nats.Header{JSExpectedLastSubjSeq: {"0"}}, |
| 1461 |
}, |
| 1462 |
// Would normally fail the batch, recognize in-process. |
| 1463 |
{ |
| 1464 |
subject: "foo", |
| 1465 |
header: nats.Header{JSExpectedLastSubjSeq: {"1"}}, |
| 1466 |
err: errors.New("last sequence by subject mismatch: 1 vs 0"), |
| 1467 |
}, |
| 1468 |
// Redundant expected check results in an error. The subject 'foo' is also updated in the batch. |
| 1469 |
{ |
| 1470 |
subject: "foo", |
| 1471 |
header: nats.Header{JSExpectedLastSubjSeq: {"0"}}, |
| 1472 |
err: errors.New("last sequence by subject mismatch"), |
| 1473 |
}, |
| 1474 |
}, |
| 1475 |
validate: func(mset *stream, commit bool) { |
| 1476 |
if !commit { |
| 1477 |
require_Len(t, len(mset.expectedPerSubjectSequence), 0) |
| 1478 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 0) |
| 1479 |
} else { |
| 1480 |
require_Len(t, len(mset.expectedPerSubjectSequence), 1) |
| 1481 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 1) |
| 1482 |
require_Equal(t, mset.expectedPerSubjectSequence[0], "foo") |
| 1483 |
} |
| 1484 |
}, |
| 1485 |
}, |
| 1486 |
{ |
| 1487 |
title: "expect-per-subj-dupe-in-change", |
| 1488 |
batch: []BatchItem{ |
| 1489 |
{subject: "foo", header: nats.Header{JSExpectedLastSubjSeq: {"0"}, JSExpectedLastSubjSeqSubj: {"baz"}}}, |
| 1490 |
{subject: "bar", header: nats.Header{JSExpectedLastSubjSeq: {"0"}, JSExpectedLastSubjSeqSubj: {"baz"}}}, |
| 1491 |
}, |
| 1492 |
validate: func(mset *stream, commit bool) { |
| 1493 |
if !commit { |
| 1494 |
require_Len(t, len(mset.expectedPerSubjectSequence), 0) |
| 1495 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 0) |
| 1496 |
} else { |
| 1497 |
require_Len(t, len(mset.expectedPerSubjectSequence), 1) |
| 1498 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 1) |
| 1499 |
require_Equal(t, mset.expectedPerSubjectSequence[1], "baz") |
| 1500 |
} |
| 1501 |
}, |
| 1502 |
}, |
| 1503 |
{ |
| 1504 |
title: "expect-per-subj-not-first", |
| 1505 |
batch: []BatchItem{ |
| 1506 |
{subject: "foo"}, |
| 1507 |
// Mismatch because only the first 'foo' can have the expected check. |
| 1508 |
{ |
| 1509 |
subject: "foo", |
| 1510 |
header: nats.Header{JSExpectedLastSubjSeq: {"0"}}, |
| 1511 |
err: errors.New("last sequence by subject mismatch"), |
| 1512 |
}, |
| 1513 |
// Mismatch because only the first 'foo' can have the expected check. |
| 1514 |
{ |
| 1515 |
subject: "bar", |
| 1516 |
header: nats.Header{JSExpectedLastSubjSeq: {"0"}, JSExpectedLastSubjSeqSubj: {"foo"}}, |
| 1517 |
err: errors.New("last sequence by subject mismatch"), |
| 1518 |
}, |
| 1519 |
}, |
| 1520 |
}, |
| 1521 |
{ |
| 1522 |
title: "expect-per-subj-in-process", |
| 1523 |
init: func(mset *stream) { |
| 1524 |
mset.expectedPerSubjectInProcess = map[string]struct{}{"foo": {}} |
| 1525 |
}, |
| 1526 |
batch: []BatchItem{ |
| 1527 |
{subject: "foo", header: nats.Header{JSExpectedLastSubjSeq: {"10"}}, err: errors.New("last sequence by subject mismatch")}, |
| 1528 |
}, |
| 1529 |
validate: func(mset *stream, commit bool) { |
| 1530 |
require_Len(t, len(mset.expectedPerSubjectSequence), 0) |
| 1531 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 1) |
| 1532 |
}, |
| 1533 |
}, |
| 1534 |
{ |
| 1535 |
title: "expect-per-subj-inflight", |
| 1536 |
init: func(mset *stream) { |
| 1537 |
mset.inflight = map[string]*inflightSubjectRunningTotal{"bar": {bytes: 33, ops: 1}} |
| 1538 |
}, |
| 1539 |
batch: []BatchItem{ |
| 1540 |
{subject: "foo", header: nats.Header{JSExpectedLastSubjSeq: {"10"}, JSExpectedLastSubjSeqSubj: {"bar"}}, err: errors.New("last sequence by subject mismatch")}, |
| 1541 |
}, |
| 1542 |
validate: func(mset *stream, commit bool) { |
| 1543 |
require_Len(t, len(mset.expectedPerSubjectSequence), 0) |
| 1544 |
require_Len(t, len(mset.expectedPerSubjectInProcess), 0) |
| 1545 |
require_Len(t, len(mset.inflight), 1) |
| 1546 |
}, |
| 1547 |
}, |
| 1548 |
{ |
| 1549 |
title: "rollup-deny-purge", |
| 1550 |
allowRollup: true, |
| 1551 |
denyPurge: true, |
| 1552 |
batch: []BatchItem{ |
| 1553 |
{subject: "foo", header: nats.Header{JSMsgRollup: {JSMsgRollupSubject}}, err: errors.New("rollup not permitted")}, |
| 1554 |
}, |
| 1555 |
}, |
| 1556 |
{ |
| 1557 |
title: "rollup-invalid", |
| 1558 |
allowRollup: true, |
| 1559 |
denyPurge: false, |
| 1560 |
batch: []BatchItem{ |
| 1561 |
{subject: "foo", header: nats.Header{JSMsgRollup: {"invalid"}}, err: fmt.Errorf("rollup value invalid: %q", "invalid")}, |
| 1562 |
}, |
| 1563 |
}, |
| 1564 |
{ |
| 1565 |
title: "rollup-all-first", |
| 1566 |
allowRollup: true, |
| 1567 |
denyPurge: false, |
| 1568 |
batch: []BatchItem{ |
| 1569 |
{subject: "foo", header: nats.Header{JSMsgRollup: {JSMsgRollupAll}}}, |
| 1570 |
}, |
| 1571 |
}, |
| 1572 |
{ |
| 1573 |
title: "rollup-all-not-first", |
| 1574 |
allowRollup: true, |
| 1575 |
denyPurge: false, |
| 1576 |
batch: []BatchItem{ |
| 1577 |
{subject: "foo"}, |
| 1578 |
{subject: "bar", header: nats.Header{JSMsgRollup: {JSMsgRollupAll}}, err: errors.New("batch rollup all invalid")}, |
| 1579 |
}, |
| 1580 |
}, |
| 1581 |
{ |
| 1582 |
title: "rollup-sub-unique", |
| 1583 |
allowRollup: true, |
| 1584 |
denyPurge: false, |
| 1585 |
batch: []BatchItem{ |
| 1586 |
{subject: "foo", header: nats.Header{JSMsgRollup: {JSMsgRollupSubject}}}, |
| 1587 |
{subject: "bar", header: nats.Header{JSMsgRollup: {JSMsgRollupSubject}}}, |
| 1588 |
}, |
| 1589 |
}, |
| 1590 |
{ |
| 1591 |
title: "rollup-sub-overlap", |
| 1592 |
allowRollup: true, |
| 1593 |
denyPurge: false, |
| 1594 |
batch: []BatchItem{ |
| 1595 |
{subject: "foo", header: nats.Header{JSMsgRollup: {JSMsgRollupSubject}}}, |
| 1596 |
{subject: "foo", header: nats.Header{JSMsgRollup: {JSMsgRollupSubject}}, err: errors.New("batch rollup sub invalid")}, |
| 1597 |
}, |
| 1598 |
}, |
| 1599 |
{ |
| 1600 |
title: "subject-transform", |
| 1601 |
batch: []BatchItem{ |
| 1602 |
{subject: "bar", rsubject: "foo"}, |
| 1603 |
{subject: "bar"}, |
| 1604 |
}, |
| 1605 |
validate: func(mset *stream, commit bool) { |
| 1606 |
if !commit { |
| 1607 |
require_Len(t, len(mset.inflight), 0) |
| 1608 |
} else { |
| 1609 |
require_Len(t, len(mset.inflight), 1) |
| 1610 |
require_Equal(t, *mset.inflight["bar"], inflightSubjectRunningTotal{bytes: 38, ops: 2}) |
| 1611 |
require_Len(t, len(mset.inflightTransform), 1) |
| 1612 |
require_Equal(t, mset.inflightTransform[0], "bar") |
| 1613 |
} |
| 1614 |
}, |
| 1615 |
}, |
| 1616 |
} |
| 1617 |
|
| 1618 |
for _, test := range tests { |
| 1619 |
t.Run(test.title, func(t *testing.T) { |
| 1620 |
s := RunBasicJetStreamServer(t) |
| 1621 |
defer s.Shutdown() |
| 1622 |
|
| 1623 |
nc := clientConnectToServer(t, s) |
| 1624 |
defer nc.Close() |
| 1625 |
|
| 1626 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 1627 |
Name: "TEST", |
| 1628 |
Storage: MemoryStorage, |
| 1629 |
AllowAtomicPublish: true, |
| 1630 |
Subjects: []string{"foo", "bar", "baz"}, |
| 1631 |
}) |
| 1632 |
require_NoError(t, err) |
| 1633 |
|
| 1634 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 1635 |
require_NoError(t, err) |
| 1636 |
|
| 1637 |
if test.init != nil { |
| 1638 |
test.init(mset) |
| 1639 |
} |
| 1640 |
|
| 1641 |
var ( |
| 1642 |
discard DiscardPolicy |
| 1643 |
discardNewPer bool |
| 1644 |
maxMsgs int64 = -1 |
| 1645 |
maxMsgsPer int64 = -1 |
| 1646 |
maxBytes int64 = -1 |
| 1647 |
) |
| 1648 |
if test.discardNew { |
| 1649 |
discard, maxMsgs, maxBytes = DiscardNew, 2, 60 |
| 1650 |
} |
| 1651 |
if test.discardNewPerSubj { |
| 1652 |
require_True(t, test.discardNew) |
| 1653 |
discardNewPer, maxMsgs, maxBytes, maxMsgsPer = true, -1, -1, 1 |
| 1654 |
} |
| 1655 |
|
| 1656 |
diff := &batchStagedDiff{} |
| 1657 |
mset.clMu.Lock() |
| 1658 |
defer mset.clMu.Unlock() |
| 1659 |
var hadError bool |
| 1660 |
for _, m := range test.batch { |
| 1661 |
var hdr []byte |
| 1662 |
for key, values := range m.header { |
| 1663 |
for _, value := range values { |
| 1664 |
hdr = genHeader(hdr, key, value) |
| 1665 |
} |
| 1666 |
} |
| 1667 |
// Potential subject transform. |
| 1668 |
rsubject := m.subject |
| 1669 |
if m.rsubject != _EMPTY_ { |
| 1670 |
rsubject = m.rsubject |
| 1671 |
} |
| 1672 |
_, _, _, _, err = checkMsgHeadersPreClusteredProposal(diff, mset, m.subject, rsubject, hdr, m.msg, false, "TEST", nil, test.allowRollup, test.denyPurge, test.allowTTL, test.allowMsgCounter, test.allowMsgSchedules, discard, discardNewPer, -1, maxMsgs, maxMsgsPer, maxBytes) |
| 1673 |
if m.err != nil { |
| 1674 |
require_Error(t, err, m.err) |
| 1675 |
} else if err != nil { |
| 1676 |
require_NoError(t, err) |
| 1677 |
} |
| 1678 |
if err != nil { |
| 1679 |
hadError = true |
| 1680 |
} |
| 1681 |
if test.validate != nil { |
| 1682 |
test.validate(mset, false) |
| 1683 |
} |
| 1684 |
mset.clseq++ |
| 1685 |
} |
| 1686 |
if test.validate != nil && !hadError { |
| 1687 |
diff.commit(mset) |
| 1688 |
test.validate(mset, true) |
| 1689 |
} |
| 1690 |
}) |
| 1691 |
} |
| 1692 |
} |
| 1693 |
|
| 1694 |
func TestJetStreamCounterNullSourcesHeaderDoesNotPanic(t *testing.T) { |
| 1695 |
s := RunBasicJetStreamServer(t) |
| 1696 |
defer s.Shutdown() |
| 1697 |
|
| 1698 |
nc, js := jsClientConnect(t, s) |
| 1699 |
defer nc.Close() |
| 1700 |
|
| 1701 |
// Origin counter stream that will be sourced in below. |
| 1702 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 1703 |
Name: "O1", |
| 1704 |
Subjects: []string{"foo.*"}, |
| 1705 |
Storage: MemoryStorage, |
| 1706 |
AllowMsgCounter: true, |
| 1707 |
}) |
| 1708 |
require_NoError(t, err) |
| 1709 |
|
| 1710 |
m := nats.NewMsg("foo.1") |
| 1711 |
m.Header.Set(JSMessageIncr, "5") |
| 1712 |
_, err = js.PublishMsg(m) |
| 1713 |
require_NoError(t, err) |
| 1714 |
|
| 1715 |
_, err = jsStreamCreate(t, nc, &StreamConfig{ |
| 1716 |
Name: "M", |
| 1717 |
Subjects: []string{"foo"}, |
| 1718 |
Storage: MemoryStorage, |
| 1719 |
AllowMsgCounter: true, |
| 1720 |
}) |
| 1721 |
require_NoError(t, err) |
| 1722 |
|
| 1723 |
// A sources header holding a JSON `null` for the origin stream is stored |
| 1724 |
// verbatim, and decodes back into a present key with a nil inner map. |
| 1725 |
m = nats.NewMsg("foo") |
| 1726 |
m.Header.Set(JSMessageIncr, "1") |
| 1727 |
m.Header.Set(JSMessageCounterSources, `{"O1":null}`) |
| 1728 |
_, err = js.PublishMsg(m) |
| 1729 |
require_NoError(t, err) |
| 1730 |
|
| 1731 |
mset, err := s.globalAccount().lookupStream("M") |
| 1732 |
require_NoError(t, err) |
| 1733 |
var smv StoreMsg |
| 1734 |
sm, err := mset.store.LoadLastMsg("foo", &smv) |
| 1735 |
require_NoError(t, err) |
| 1736 |
require_Equal(t, string(sliceHeader(JSMessageCounterSources, sm.hdr)), `{"O1":null}`) |
| 1737 |
|
| 1738 |
// That stored record reached through the pre-clustered proposal path. The |
| 1739 |
// sourced message has to record its count, which used to be a write into |
| 1740 |
// the nil inner map. |
| 1741 |
hdr := genHeader(nil, JSMessageIncr, "5") |
| 1742 |
hdr = genHeader(hdr, JSStreamSource, "O1 1 > > foo.1") |
| 1743 |
diff := &batchStagedDiff{} |
| 1744 |
mset.clMu.Lock() |
| 1745 |
_, _, _, _, err = checkMsgHeadersPreClusteredProposal(diff, mset, "foo", "foo", hdr, []byte(`{"val":"5"}`), true, "M", nil, false, false, false, true, false, DiscardOld, false, -1, -1, -1, -1) |
| 1746 |
mset.clMu.Unlock() |
| 1747 |
require_NoError(t, err) |
| 1748 |
require_Equal(t, diff.counter["foo"].sources["O1"]["foo.1"], "5") |
| 1749 |
|
| 1750 |
// And now the same through the regular sourcing path. |
| 1751 |
_, err = jsStreamUpdate(t, nc, &StreamConfig{ |
| 1752 |
Name: "M", |
| 1753 |
Subjects: []string{"foo"}, |
| 1754 |
Sources: []*StreamSource{{ |
| 1755 |
Name: "O1", |
| 1756 |
SubjectTransforms: []SubjectTransformConfig{{Source: "foo.*", Destination: "foo"}}, |
| 1757 |
}}, |
| 1758 |
Storage: MemoryStorage, |
| 1759 |
AllowMsgCounter: true, |
| 1760 |
}) |
| 1761 |
require_NoError(t, err) |
| 1762 |
|
| 1763 |
checkFor(t, 5*time.Second, 50*time.Millisecond, func() error { |
| 1764 |
si, err := js.StreamInfo("M") |
| 1765 |
if err != nil { |
| 1766 |
return err |
| 1767 |
} |
| 1768 |
if si.State.Msgs != 2 { |
| 1769 |
return fmt.Errorf("expected 2 messages, got %d", si.State.Msgs) |
| 1770 |
} |
| 1771 |
return nil |
| 1772 |
}) |
| 1773 |
|
| 1774 |
// The counter aggregated the sourced increment, and the sources header was |
| 1775 |
// rewritten with a usable inner map. |
| 1776 |
rsm, err := js.GetMsg("M", 2) |
| 1777 |
require_NoError(t, err) |
| 1778 |
var count CounterValue |
| 1779 |
require_NoError(t, json.Unmarshal(rsm.Data, &count)) |
| 1780 |
require_Equal(t, count.Value, "6") |
| 1781 |
var sources CounterSources |
| 1782 |
require_NoError(t, json.Unmarshal([]byte(rsm.Header.Get(JSMessageCounterSources)), &sources)) |
| 1783 |
require_Equal(t, sources["O1"]["foo.1"], "5") |
| 1784 |
} |
| 1785 |
|
| 1786 |
func TestJetStreamCounterStagingDoesNotCorruptCommittedTotal(t *testing.T) { |
| 1787 |
s := RunBasicJetStreamServer(t) |
| 1788 |
defer s.Shutdown() |
| 1789 |
|
| 1790 |
nc := clientConnectToServer(t, s) |
| 1791 |
defer nc.Close() |
| 1792 |
|
| 1793 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 1794 |
Name: "TEST", |
| 1795 |
Storage: MemoryStorage, |
| 1796 |
AllowAtomicPublish: true, |
| 1797 |
Subjects: []string{"foo"}, |
| 1798 |
}) |
| 1799 |
require_NoError(t, err) |
| 1800 |
|
| 1801 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 1802 |
require_NoError(t, err) |
| 1803 |
|
| 1804 |
// Committed total of 2, built via Add so the big.Int has spare backing-array |
| 1805 |
// capacity that a shallow copy would share (and an in-place Add corrupt). |
| 1806 |
committed := new(big.Int) |
| 1807 |
committed.Add(big.NewInt(1), big.NewInt(1)) |
| 1808 |
committedSources := CounterSources{"S1": {"foo": "2"}} |
| 1809 |
mset.clusteredCounterTotal = map[string]*msgCounterRunningTotal{ |
| 1810 |
"foo": {total: committed, sources: committedSources, ops: 1}, |
| 1811 |
} |
| 1812 |
|
| 1813 |
// Stage an increment without committing the diff; this must not mutate the |
| 1814 |
// committed total. |
| 1815 |
hdr := genHeader(nil, JSMessageIncr, "3") |
| 1816 |
hdr = genHeader(hdr, JSStreamSource, "S1 1 > > foo") |
| 1817 |
msg := []byte(`{"val":"5"}`) |
| 1818 |
diff := &batchStagedDiff{} |
| 1819 |
mset.clMu.Lock() |
| 1820 |
_, _, _, _, err = checkMsgHeadersPreClusteredProposal(diff, mset, "foo", "foo", hdr, msg, true, "TEST", nil, false, false, false, true, false, DiscardOld, false, -1, -1, -1, -1) |
| 1821 |
mset.clMu.Unlock() |
| 1822 |
require_NoError(t, err) |
| 1823 |
|
| 1824 |
// Staged total reflects the increment (2+3=5). |
| 1825 |
require_Equal(t, diff.counter["foo"].total.String(), "5") |
| 1826 |
// Committed total and sources are untouched. |
| 1827 |
require_Equal(t, mset.clusteredCounterTotal["foo"].total.String(), "2") |
| 1828 |
require_Equal(t, mset.clusteredCounterTotal["foo"].ops, 1) |
| 1829 |
require_Equal(t, mset.clusteredCounterTotal["foo"].sources["S1"]["foo"], "2") |
| 1830 |
} |
| 1831 |
|
| 1832 |
func TestJetStreamAtomicBatchPublishHighLevelRollback(t *testing.T) { |
| 1833 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 1834 |
defer c.shutdown() |
| 1835 |
|
| 1836 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 1837 |
defer nc.Close() |
| 1838 |
|
| 1839 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 1840 |
Name: "TEST", |
| 1841 |
Subjects: []string{"foo"}, |
| 1842 |
Replicas: 3, |
| 1843 |
Storage: FileStorage, |
| 1844 |
Retention: InterestPolicy, |
| 1845 |
MaxMsgs: 1, |
| 1846 |
}) |
| 1847 |
require_NoError(t, err) |
| 1848 |
|
| 1849 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 1850 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 1851 |
require_NoError(t, err) |
| 1852 |
|
| 1853 |
requireEmpty := func() { |
| 1854 |
mset.ddMu.Lock() |
| 1855 |
ddarr, ddmap := len(mset.ddarr), len(mset.ddmap) |
| 1856 |
mset.ddMu.Unlock() |
| 1857 |
require_Len(t, ddarr, 0) |
| 1858 |
require_Len(t, ddmap, 0) |
| 1859 |
|
| 1860 |
mset.clMu.Lock() |
| 1861 |
inflight, subjSeq, subjInProcess := len(mset.inflight), len(mset.expectedPerSubjectSequence), len(mset.expectedPerSubjectInProcess) |
| 1862 |
mset.clMu.Unlock() |
| 1863 |
require_Len(t, inflight, 0) |
| 1864 |
require_Len(t, subjSeq, 0) |
| 1865 |
require_Len(t, subjInProcess, 0) |
| 1866 |
} |
| 1867 |
requireEmpty() |
| 1868 |
|
| 1869 |
m := nats.NewMsg("foo") |
| 1870 |
m.Header.Set("Nats-Msg-Id", "dedupe") |
| 1871 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence", "1") |
| 1872 |
_, err = js.PublishMsg(m) |
| 1873 |
require_Error(t, err, NewJSStreamWrongLastSequenceError(0)) |
| 1874 |
requireEmpty() |
| 1875 |
} |
| 1876 |
|
| 1877 |
func TestJetStreamAtomicBatchPublishExpectedPerSubject(t *testing.T) { |
| 1878 |
type TestKind int |
| 1879 |
const ( |
| 1880 |
OnlyFirst TestKind = iota |
| 1881 |
Redundant |
| 1882 |
NotFirst |
| 1883 |
) |
| 1884 |
|
| 1885 |
test := func(t *testing.T, kind TestKind) { |
| 1886 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 1887 |
defer c.shutdown() |
| 1888 |
|
| 1889 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 1890 |
defer nc.Close() |
| 1891 |
|
| 1892 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 1893 |
Name: "TEST", |
| 1894 |
Subjects: []string{"foo"}, |
| 1895 |
Storage: FileStorage, |
| 1896 |
Replicas: 3, |
| 1897 |
AllowAtomicPublish: true, |
| 1898 |
}) |
| 1899 |
require_NoError(t, err) |
| 1900 |
|
| 1901 |
_, err = js.Publish("foo", nil) |
| 1902 |
require_NoError(t, err) |
| 1903 |
|
| 1904 |
m := nats.NewMsg("foo") |
| 1905 |
if kind != NotFirst { |
| 1906 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence", "1") |
| 1907 |
} |
| 1908 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 1909 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 1910 |
require_NoError(t, nc.PublishMsg(m)) |
| 1911 |
|
| 1912 |
var pubAck JSPubAckResponse |
| 1913 |
|
| 1914 |
// Redundant expected headers are okay, as long as they reflect the state prior to the batch. |
| 1915 |
m = nats.NewMsg("foo") |
| 1916 |
if kind == Redundant || kind == NotFirst { |
| 1917 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence", "1") |
| 1918 |
} |
| 1919 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 1920 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 1921 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 1922 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 1923 |
require_NoError(t, err) |
| 1924 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 1925 |
if kind == Redundant || kind == NotFirst { |
| 1926 |
require_NotNil(t, pubAck.Error) |
| 1927 |
require_Error(t, pubAck.Error, NewJSStreamWrongLastSequenceConstantError()) |
| 1928 |
return |
| 1929 |
} |
| 1930 |
require_True(t, pubAck.Error == nil) |
| 1931 |
require_Equal(t, pubAck.Sequence, 3) |
| 1932 |
require_Equal(t, pubAck.BatchSize, 2) |
| 1933 |
|
| 1934 |
// The first message still contains the expected headers. |
| 1935 |
rsm, err := js.GetMsg("TEST", 2) |
| 1936 |
require_NoError(t, err) |
| 1937 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Id"), "uuid") |
| 1938 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Sequence"), "1") |
| 1939 |
require_Equal(t, rsm.Header.Get("Nats-Expected-Last-Subject-Sequence"), "1") |
| 1940 |
|
| 1941 |
// The second message doesn't have the expected headers, as the condition was already checked |
| 1942 |
// and seems inconsistent when getting the message afterward. |
| 1943 |
rsm, err = js.GetMsg("TEST", 3) |
| 1944 |
require_NoError(t, err) |
| 1945 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Id"), "uuid") |
| 1946 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Sequence"), "2") |
| 1947 |
require_Equal(t, rsm.Header.Get("Nats-Expected-Last-Subject-Sequence"), _EMPTY_) |
| 1948 |
} |
| 1949 |
|
| 1950 |
t.Run("single", func(t *testing.T) { test(t, OnlyFirst) }) |
| 1951 |
t.Run("redundant", func(t *testing.T) { test(t, Redundant) }) |
| 1952 |
t.Run("not-first", func(t *testing.T) { test(t, NotFirst) }) |
| 1953 |
} |
| 1954 |
|
| 1955 |
func TestJetStreamAtomicBatchPublishCounterSingleServer(t *testing.T) { |
| 1956 |
test := func(t *testing.T, storage StorageType) { |
| 1957 |
s := RunBasicJetStreamServer(t) |
| 1958 |
defer s.Shutdown() |
| 1959 |
|
| 1960 |
nc, js := jsClientConnect(t, s) |
| 1961 |
defer nc.Close() |
| 1962 |
|
| 1963 |
cfg := &StreamConfig{ |
| 1964 |
Name: "TEST", |
| 1965 |
Subjects: []string{"foo"}, |
| 1966 |
Storage: storage, |
| 1967 |
Retention: LimitsPolicy, |
| 1968 |
Replicas: 1, |
| 1969 |
AllowAtomicPublish: true, |
| 1970 |
AllowMsgCounter: true, |
| 1971 |
} |
| 1972 |
_, err := jsStreamCreate(t, nc, cfg) |
| 1973 |
require_NoError(t, err) |
| 1974 |
|
| 1975 |
// Publish an atomic batch of two counter increments. |
| 1976 |
m := nats.NewMsg("foo") |
| 1977 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 1978 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 1979 |
m.Header.Set("Nats-Incr", "1") |
| 1980 |
require_NoError(t, nc.PublishMsg(m)) |
| 1981 |
|
| 1982 |
m = nats.NewMsg("foo") |
| 1983 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 1984 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 1985 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 1986 |
m.Header.Set("Nats-Incr", "2") |
| 1987 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 1988 |
require_NoError(t, err) |
| 1989 |
|
| 1990 |
var pubAck JSPubAckResponse |
| 1991 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 1992 |
require_True(t, pubAck.Error == nil) |
| 1993 |
require_Equal(t, pubAck.Sequence, 2) |
| 1994 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 1995 |
require_Equal(t, pubAck.BatchSize, 2) |
| 1996 |
|
| 1997 |
// The stored messages must contain the rewritten counter payloads. |
| 1998 |
rsm, err := js.GetMsg("TEST", 1) |
| 1999 |
require_NoError(t, err) |
| 2000 |
require_Equal(t, string(rsm.Data), `{"val":"1"}`) |
| 2001 |
rsm, err = js.GetMsg("TEST", 2) |
| 2002 |
require_NoError(t, err) |
| 2003 |
require_Equal(t, string(rsm.Data), `{"val":"3"}`) |
| 2004 |
|
| 2005 |
// The counter must not be broken, a normal increment should still work. |
| 2006 |
m = nats.NewMsg("foo") |
| 2007 |
m.Header.Set("Nats-Incr", "5") |
| 2008 |
pa, err := js.PublishMsg(m) |
| 2009 |
require_NoError(t, err) |
| 2010 |
require_Equal(t, pa.Sequence, 3) |
| 2011 |
rsm, err = js.GetMsg("TEST", 3) |
| 2012 |
require_NoError(t, err) |
| 2013 |
require_Equal(t, string(rsm.Data), `{"val":"8"}`) |
| 2014 |
} |
| 2015 |
|
| 2016 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 2017 |
t.Run(storage.String(), func(t *testing.T) { |
| 2018 |
test(t, storage) |
| 2019 |
}) |
| 2020 |
} |
| 2021 |
} |
| 2022 |
|
| 2023 |
func TestJetStreamAtomicBatchPublishSingleServerRecovery(t *testing.T) { |
| 2024 |
s := RunBasicJetStreamServer(t) |
| 2025 |
defer s.Shutdown() |
| 2026 |
|
| 2027 |
nc := clientConnectToServer(t, s) |
| 2028 |
defer nc.Close() |
| 2029 |
|
| 2030 |
cfg := &StreamConfig{ |
| 2031 |
Name: "TEST", |
| 2032 |
Subjects: []string{"foo"}, |
| 2033 |
Storage: FileStorage, |
| 2034 |
Retention: LimitsPolicy, |
| 2035 |
Replicas: 1, |
| 2036 |
AllowAtomicPublish: true, |
| 2037 |
} |
| 2038 |
_, err := jsStreamCreate(t, nc, cfg) |
| 2039 |
require_NoError(t, err) |
| 2040 |
|
| 2041 |
// Manually construct and store a batch, so it doesn't immediately commit. |
| 2042 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 2043 |
require_NoError(t, err) |
| 2044 |
mset.mu.Lock() |
| 2045 |
batches := &batching{} |
| 2046 |
mset.batches = batches |
| 2047 |
jsa := mset.jsa |
| 2048 |
mset.mu.Unlock() |
| 2049 |
jsa.mu.RLock() |
| 2050 |
storeDir := jsa.storeDir |
| 2051 |
jsa.mu.RUnlock() |
| 2052 |
batches.mu.Lock() |
| 2053 |
b, err := batches.newAtomicBatch(mset, "uuid", 1, FileStorage, storeDir, "TEST") |
| 2054 |
if err != nil { |
| 2055 |
batches.mu.Unlock() |
| 2056 |
require_NoError(t, err) |
| 2057 |
} |
| 2058 |
hdr1 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2059 |
hdr1 = genHeader(hdr1, "Nats-Batch-Sequence", "1") |
| 2060 |
_, _, err = b.store.StoreMsg("foo", hdr1, nil, 0) |
| 2061 |
if err != nil { |
| 2062 |
batches.mu.Unlock() |
| 2063 |
require_NoError(t, err) |
| 2064 |
} |
| 2065 |
|
| 2066 |
hdr2 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2067 |
hdr2 = genHeader(hdr2, "Nats-Batch-Sequence", "2") |
| 2068 |
hdr2 = genHeader(hdr2, "Nats-Batch-Commit", "1") |
| 2069 |
_, _, err = b.store.StoreMsg("foo", hdr2, nil, 0) |
| 2070 |
if err != nil { |
| 2071 |
batches.mu.Unlock() |
| 2072 |
require_NoError(t, err) |
| 2073 |
} |
| 2074 |
abandonReason := b.readyForCommit() |
| 2075 |
batches.mu.Unlock() |
| 2076 |
require_True(t, abandonReason == nil) |
| 2077 |
|
| 2078 |
// Simulate the first message of the batch is committed. |
| 2079 |
err = mset.processJetStreamMsg("foo", _EMPTY_, hdr1, nil, 0, 0, nil, false, true) |
| 2080 |
require_NoError(t, err) |
| 2081 |
|
| 2082 |
// Simulate a hard kill, upon recovery the rest of the batch should be applied. |
| 2083 |
port := s.opts.Port |
| 2084 |
sd := s.StoreDir() |
| 2085 |
nc.Close() |
| 2086 |
s.Shutdown() |
| 2087 |
s = RunJetStreamServerOnPort(port, sd) |
| 2088 |
defer s.Shutdown() |
| 2089 |
|
| 2090 |
mset, err = s.globalAccount().lookupStream("TEST") |
| 2091 |
require_NoError(t, err) |
| 2092 |
state := mset.state() |
| 2093 |
require_Equal(t, state.Msgs, 2) |
| 2094 |
require_Equal(t, state.FirstSeq, 1) |
| 2095 |
require_Equal(t, state.LastSeq, 2) |
| 2096 |
|
| 2097 |
for seq := state.FirstSeq; seq <= state.LastSeq; seq++ { |
| 2098 |
sm, err := mset.getMsg(seq) |
| 2099 |
require_NoError(t, err) |
| 2100 |
require_Equal(t, string(getHeader("Nats-Batch-Id", sm.Header)), "uuid") |
| 2101 |
require_Equal(t, string(getHeader("Nats-Batch-Sequence", sm.Header)), strconv.FormatUint(seq, 10)) |
| 2102 |
// The last message should have the commit header set. |
| 2103 |
if seq == state.LastSeq { |
| 2104 |
require_Equal(t, string(getHeader("Nats-Batch-Commit", sm.Header)), "1") |
| 2105 |
} |
| 2106 |
} |
| 2107 |
} |
| 2108 |
|
| 2109 |
func TestJetStreamAtomicBatchPublishSingleServerRecoveryCommitEob(t *testing.T) { |
| 2110 |
s := RunBasicJetStreamServer(t) |
| 2111 |
defer s.Shutdown() |
| 2112 |
|
| 2113 |
nc := clientConnectToServer(t, s) |
| 2114 |
defer nc.Close() |
| 2115 |
|
| 2116 |
cfg := &StreamConfig{ |
| 2117 |
Name: "TEST", |
| 2118 |
Subjects: []string{"foo"}, |
| 2119 |
Storage: FileStorage, |
| 2120 |
Retention: LimitsPolicy, |
| 2121 |
Replicas: 1, |
| 2122 |
AllowAtomicPublish: true, |
| 2123 |
} |
| 2124 |
_, err := jsStreamCreate(t, nc, cfg) |
| 2125 |
require_NoError(t, err) |
| 2126 |
|
| 2127 |
// Manually construct and store a batch, so it doesn't immediately commit. |
| 2128 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 2129 |
require_NoError(t, err) |
| 2130 |
mset.mu.Lock() |
| 2131 |
batches := &batching{} |
| 2132 |
mset.batches = batches |
| 2133 |
jsa := mset.jsa |
| 2134 |
mset.mu.Unlock() |
| 2135 |
jsa.mu.RLock() |
| 2136 |
storeDir := jsa.storeDir |
| 2137 |
jsa.mu.RUnlock() |
| 2138 |
batches.mu.Lock() |
| 2139 |
b, err := batches.newAtomicBatch(mset, "uuid", 1, FileStorage, storeDir, "TEST") |
| 2140 |
if err != nil { |
| 2141 |
batches.mu.Unlock() |
| 2142 |
require_NoError(t, err) |
| 2143 |
} |
| 2144 |
hdr1 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2145 |
hdr1 = genHeader(hdr1, "Nats-Batch-Sequence", "1") |
| 2146 |
_, _, err = b.store.StoreMsg("foo", hdr1, nil, 0) |
| 2147 |
if err != nil { |
| 2148 |
batches.mu.Unlock() |
| 2149 |
require_NoError(t, err) |
| 2150 |
} |
| 2151 |
|
| 2152 |
hdr2 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2153 |
hdr2 = genHeader(hdr2, "Nats-Batch-Sequence", "2") |
| 2154 |
_, _, err = b.store.StoreMsg("foo", hdr2, nil, 0) |
| 2155 |
if err != nil { |
| 2156 |
batches.mu.Unlock() |
| 2157 |
require_NoError(t, err) |
| 2158 |
} |
| 2159 |
|
| 2160 |
hdr3 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2161 |
hdr3 = genHeader(hdr3, "Nats-Batch-Sequence", "3") |
| 2162 |
hdr3 = genHeader(hdr3, "Nats-Batch-Commit", "eob") |
| 2163 |
_, _, err = b.store.StoreMsg("foo", hdr3, nil, 0) |
| 2164 |
if err != nil { |
| 2165 |
batches.mu.Unlock() |
| 2166 |
require_NoError(t, err) |
| 2167 |
} |
| 2168 |
abandonReason := b.readyForCommit() |
| 2169 |
batches.mu.Unlock() |
| 2170 |
require_True(t, abandonReason == nil) |
| 2171 |
|
| 2172 |
// Simulate the first message of the batch is committed. |
| 2173 |
err = mset.processJetStreamMsg("foo", _EMPTY_, hdr1, nil, 0, 0, nil, false, true) |
| 2174 |
require_NoError(t, err) |
| 2175 |
|
| 2176 |
// Simulate a hard kill, upon recovery the rest of the batch should be applied. |
| 2177 |
port := s.opts.Port |
| 2178 |
sd := s.StoreDir() |
| 2179 |
nc.Close() |
| 2180 |
s.Shutdown() |
| 2181 |
s = RunJetStreamServerOnPort(port, sd) |
| 2182 |
defer s.Shutdown() |
| 2183 |
|
| 2184 |
mset, err = s.globalAccount().lookupStream("TEST") |
| 2185 |
require_NoError(t, err) |
| 2186 |
state := mset.state() |
| 2187 |
require_Equal(t, state.Msgs, 2) |
| 2188 |
require_Equal(t, state.FirstSeq, 1) |
| 2189 |
require_Equal(t, state.LastSeq, 2) |
| 2190 |
|
| 2191 |
for seq := state.FirstSeq; seq <= state.LastSeq; seq++ { |
| 2192 |
sm, err := mset.getMsg(seq) |
| 2193 |
require_NoError(t, err) |
| 2194 |
require_Equal(t, string(getHeader("Nats-Batch-Id", sm.Header)), "uuid") |
| 2195 |
require_Equal(t, string(getHeader("Nats-Batch-Sequence", sm.Header)), strconv.FormatUint(seq, 10)) |
| 2196 |
// The last message should have the commit header set, even though the commit was done via EOB. |
| 2197 |
if seq == state.LastSeq { |
| 2198 |
require_Equal(t, string(getHeader("Nats-Batch-Commit", sm.Header)), "1") |
| 2199 |
} |
| 2200 |
} |
| 2201 |
} |
| 2202 |
|
| 2203 |
func TestJetStreamAtomicBatchPublishEncode(t *testing.T) { |
| 2204 |
test := func(t *testing.T, commit bool, compress bool) { |
| 2205 |
ts := time.Now().UnixNano() |
| 2206 |
hdr := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2207 |
hdr = genHeader(hdr, "Nats-Batch-Sequence", "1") |
| 2208 |
msg := []byte("A") |
| 2209 |
if compress { |
| 2210 |
msg = bytes.Repeat(msg, compressThreshold) |
| 2211 |
} |
| 2212 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", "reply", hdr, msg, 1, ts, false, "uuid", 1, commit) |
| 2213 |
|
| 2214 |
buf, op := esm[1:], entryOp(esm[0]) |
| 2215 |
if commit { |
| 2216 |
require_Equal(t, op, batchCommitMsgOp) |
| 2217 |
} else { |
| 2218 |
require_Equal(t, op, batchMsgOp) |
| 2219 |
} |
| 2220 |
|
| 2221 |
batchId, batchSeq, op, mbuf, err := decodeBatchMsg(buf) |
| 2222 |
require_NoError(t, err) |
| 2223 |
require_Equal(t, batchId, "uuid") |
| 2224 |
require_Equal(t, batchSeq, 1) |
| 2225 |
if compress { |
| 2226 |
require_Equal(t, op, compressedStreamMsgOp) |
| 2227 |
mbuf, err = s2.Decode(nil, mbuf) |
| 2228 |
require_NoError(t, err) |
| 2229 |
} else { |
| 2230 |
require_Equal(t, op, streamMsgOp) |
| 2231 |
} |
| 2232 |
|
| 2233 |
subject, reply, dhdr, dmsg, lseq, dts, sourced, err := decodeStreamMsg(mbuf) |
| 2234 |
require_NoError(t, err) |
| 2235 |
require_Equal(t, subject, "foo") |
| 2236 |
require_Equal(t, reply, "reply") |
| 2237 |
require_True(t, bytes.Equal(dhdr, hdr)) |
| 2238 |
require_True(t, bytes.Equal(dmsg, msg)) |
| 2239 |
require_Equal(t, lseq, 1) |
| 2240 |
require_Equal(t, dts, ts) |
| 2241 |
require_False(t, sourced) |
| 2242 |
} |
| 2243 |
|
| 2244 |
t.Run("normal", func(t *testing.T) { test(t, false, false) }) |
| 2245 |
t.Run("normal-compress", func(t *testing.T) { test(t, false, true) }) |
| 2246 |
t.Run("commit", func(t *testing.T) { test(t, true, false) }) |
| 2247 |
t.Run("commit-compress", func(t *testing.T) { test(t, true, true) }) |
| 2248 |
} |
| 2249 |
|
| 2250 |
// Test a batch within a single proposal, optionally combined with messages unrelated |
| 2251 |
// to the batch but within the same proposal. |
| 2252 |
func TestJetStreamAtomicBatchPublishProposeOne(t *testing.T) { |
| 2253 |
test := func(t *testing.T, combined bool) { |
| 2254 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2255 |
defer c.shutdown() |
| 2256 |
|
| 2257 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2258 |
defer nc.Close() |
| 2259 |
|
| 2260 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2261 |
Name: "TEST", |
| 2262 |
Subjects: []string{"foo"}, |
| 2263 |
Storage: FileStorage, |
| 2264 |
Replicas: 3, |
| 2265 |
AllowAtomicPublish: true, |
| 2266 |
}) |
| 2267 |
require_NoError(t, err) |
| 2268 |
|
| 2269 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2270 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2271 |
require_NoError(t, err) |
| 2272 |
|
| 2273 |
pubAck, err := js.Publish("foo", nil) |
| 2274 |
require_NoError(t, err) |
| 2275 |
require_Equal(t, pubAck.Sequence, 1) |
| 2276 |
|
| 2277 |
var entries []*Entry |
| 2278 |
|
| 2279 |
mset.clMu.Lock() |
| 2280 |
if combined { |
| 2281 |
esm := encodeStreamMsg("foo", _EMPTY_, nil, nil, mset.clseq, 0, false) |
| 2282 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2283 |
mset.clseq++ |
| 2284 |
} |
| 2285 |
|
| 2286 |
msg := []byte("hello") |
| 2287 |
hdr := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2288 |
hdr = setHeader("Nats-Batch-Sequence", "1", hdr) |
| 2289 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", 1, false) |
| 2290 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2291 |
mset.clseq++ |
| 2292 |
|
| 2293 |
hdr = setHeader("Nats-Batch-Sequence", "2", hdr) |
| 2294 |
hdr = setHeader("Nats-Batch-Commit", "1", hdr) |
| 2295 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", 2, true) |
| 2296 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2297 |
mset.clseq++ |
| 2298 |
|
| 2299 |
if combined { |
| 2300 |
esm = encodeStreamMsg("foo", _EMPTY_, nil, nil, mset.clseq, 0, false) |
| 2301 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2302 |
mset.clseq++ |
| 2303 |
} |
| 2304 |
mset.clMu.Unlock() |
| 2305 |
n := mset.raftNode().(*raft) |
| 2306 |
n.sendAppendEntry(entries) |
| 2307 |
|
| 2308 |
pubAck, err = js.Publish("foo", nil) |
| 2309 |
require_NoError(t, err) |
| 2310 |
if combined { |
| 2311 |
require_Equal(t, pubAck.Sequence, 6) |
| 2312 |
} else { |
| 2313 |
require_Equal(t, pubAck.Sequence, 4) |
| 2314 |
} |
| 2315 |
} |
| 2316 |
|
| 2317 |
t.Run("single", func(t *testing.T) { test(t, false) }) |
| 2318 |
t.Run("combined", func(t *testing.T) { test(t, true) }) |
| 2319 |
} |
| 2320 |
|
| 2321 |
// Test a batch spanning multiple proposals, optionally combined with messages unrelated |
| 2322 |
// to the batch but within the same first/last proposal. |
| 2323 |
func TestJetStreamAtomicBatchPublishProposeMultiple(t *testing.T) { |
| 2324 |
test := func(t *testing.T, partial bool, combined bool) { |
| 2325 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2326 |
defer c.shutdown() |
| 2327 |
|
| 2328 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2329 |
defer nc.Close() |
| 2330 |
|
| 2331 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2332 |
Name: "TEST", |
| 2333 |
Subjects: []string{"foo"}, |
| 2334 |
Storage: FileStorage, |
| 2335 |
Replicas: 3, |
| 2336 |
AllowAtomicPublish: true, |
| 2337 |
}) |
| 2338 |
require_NoError(t, err) |
| 2339 |
|
| 2340 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2341 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2342 |
require_NoError(t, err) |
| 2343 |
|
| 2344 |
pubAck, err := js.Publish("foo", nil) |
| 2345 |
require_NoError(t, err) |
| 2346 |
require_Equal(t, pubAck.Sequence, 1) |
| 2347 |
|
| 2348 |
var entries []*Entry |
| 2349 |
mset.clMu.Lock() |
| 2350 |
hdr := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2351 |
hdr = genHeader(hdr, "Nats-Batch-Sequence", "1") |
| 2352 |
msg := []byte("hello") |
| 2353 |
if combined { |
| 2354 |
esm := encodeStreamMsg("foo", _EMPTY_, nil, nil, mset.clseq, 0, false) |
| 2355 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2356 |
mset.clseq++ |
| 2357 |
} |
| 2358 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", 1, false) |
| 2359 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2360 |
mset.clseq++ |
| 2361 |
mset.clMu.Unlock() |
| 2362 |
n := mset.raftNode().(*raft) |
| 2363 |
n.sendAppendEntry(entries) |
| 2364 |
|
| 2365 |
mset.clMu.Lock() |
| 2366 |
hdr = setHeader("Nats-Batch-Sequence", "2", hdr) |
| 2367 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", 2, false) |
| 2368 |
mset.clseq++ |
| 2369 |
mset.clMu.Unlock() |
| 2370 |
n.sendAppendEntry([]*Entry{newEntry(EntryNormal, esm)}) |
| 2371 |
|
| 2372 |
entries = nil |
| 2373 |
mset.clMu.Lock() |
| 2374 |
if !partial { |
| 2375 |
hdr = setHeader("Nats-Batch-Sequence", "3", hdr) |
| 2376 |
hdr = genHeader(hdr, "Nats-Batch-Commit", "1") |
| 2377 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", 3, true) |
| 2378 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2379 |
mset.clseq++ |
| 2380 |
} |
| 2381 |
if combined { |
| 2382 |
esm = encodeStreamMsg("foo", _EMPTY_, nil, nil, mset.clseq, 0, false) |
| 2383 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2384 |
mset.clseq++ |
| 2385 |
} |
| 2386 |
mset.clMu.Unlock() |
| 2387 |
n.sendAppendEntry(entries) |
| 2388 |
|
| 2389 |
pubAck, err = js.Publish("foo", nil) |
| 2390 |
require_NoError(t, err) |
| 2391 |
expectedSeq := uint64(2) |
| 2392 |
if !partial { |
| 2393 |
expectedSeq += 3 |
| 2394 |
} |
| 2395 |
if combined { |
| 2396 |
expectedSeq += 2 |
| 2397 |
} |
| 2398 |
require_Equal(t, pubAck.Sequence, expectedSeq) |
| 2399 |
} |
| 2400 |
|
| 2401 |
t.Run("partial", func(t *testing.T) { test(t, true, false) }) |
| 2402 |
t.Run("partial-combined", func(t *testing.T) { test(t, true, true) }) |
| 2403 |
t.Run("full", func(t *testing.T) { test(t, false, false) }) |
| 2404 |
t.Run("full-combined", func(t *testing.T) { test(t, false, true) }) |
| 2405 |
} |
| 2406 |
|
| 2407 |
// Test a batch that was only partially proposed. |
| 2408 |
func TestJetStreamAtomicBatchPublishProposeOnePartialBatch(t *testing.T) { |
| 2409 |
maxEntries := 3 |
| 2410 |
for i := range maxEntries + 1 { |
| 2411 |
t.Run(fmt.Sprintf("I-%d", i), func(t *testing.T) { |
| 2412 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2413 |
defer c.shutdown() |
| 2414 |
|
| 2415 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2416 |
defer nc.Close() |
| 2417 |
|
| 2418 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2419 |
Name: "TEST", |
| 2420 |
Subjects: []string{"foo"}, |
| 2421 |
Storage: FileStorage, |
| 2422 |
Replicas: 3, |
| 2423 |
AllowAtomicPublish: true, |
| 2424 |
}) |
| 2425 |
require_NoError(t, err) |
| 2426 |
|
| 2427 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2428 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2429 |
require_NoError(t, err) |
| 2430 |
|
| 2431 |
pubAck, err := js.Publish("foo", nil) |
| 2432 |
require_NoError(t, err) |
| 2433 |
require_Equal(t, pubAck.Sequence, 1) |
| 2434 |
|
| 2435 |
var entries []*Entry |
| 2436 |
mset.clMu.Lock() |
| 2437 |
msg := []byte("hello") |
| 2438 |
hdr := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 2439 |
for j := range 3 { |
| 2440 |
// Skip if indices equal. |
| 2441 |
if i == j { |
| 2442 |
continue |
| 2443 |
} |
| 2444 |
bseq := uint64(j + 1) |
| 2445 |
hdr = setHeader("Nats-Batch-Sequence", strconv.FormatUint(bseq, 10), hdr) |
| 2446 |
commit := bseq == uint64(maxEntries) |
| 2447 |
if commit { |
| 2448 |
hdr = setHeader("Nats-Batch-Commit", "1", hdr) |
| 2449 |
} |
| 2450 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, "uuid", bseq, commit) |
| 2451 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2452 |
mset.clseq++ |
| 2453 |
} |
| 2454 |
mset.clMu.Unlock() |
| 2455 |
n := mset.raftNode().(*raft) |
| 2456 |
n.sendAppendEntry(entries) |
| 2457 |
|
| 2458 |
pubAck, err = js.Publish("foo", nil) |
| 2459 |
require_NoError(t, err) |
| 2460 |
expectedSeq := uint64(2) |
| 2461 |
if i >= maxEntries { |
| 2462 |
expectedSeq += uint64(maxEntries) |
| 2463 |
} |
| 2464 |
require_Equal(t, pubAck.Sequence, expectedSeq) |
| 2465 |
}) |
| 2466 |
} |
| 2467 |
} |
| 2468 |
|
| 2469 |
// Test multiple sequential batches, the first batch is partially proposed. |
| 2470 |
func TestJetStreamAtomicBatchPublishProposeMultiplePartialBatches(t *testing.T) { |
| 2471 |
test := func(t *testing.T, batchSize int, retry bool) { |
| 2472 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2473 |
defer c.shutdown() |
| 2474 |
|
| 2475 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2476 |
defer nc.Close() |
| 2477 |
|
| 2478 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2479 |
Name: "TEST", |
| 2480 |
Subjects: []string{"foo"}, |
| 2481 |
Storage: FileStorage, |
| 2482 |
Replicas: 3, |
| 2483 |
AllowAtomicPublish: true, |
| 2484 |
}) |
| 2485 |
require_NoError(t, err) |
| 2486 |
|
| 2487 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2488 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2489 |
require_NoError(t, err) |
| 2490 |
|
| 2491 |
pubAck, err := js.Publish("foo", nil) |
| 2492 |
require_NoError(t, err) |
| 2493 |
require_Equal(t, pubAck.Sequence, 1) |
| 2494 |
|
| 2495 |
batchId1, batchId2 := "ID_1", "ID_2" |
| 2496 |
if retry { |
| 2497 |
batchId1, batchId2 = "uuid", "uuid" |
| 2498 |
} |
| 2499 |
|
| 2500 |
var entries []*Entry |
| 2501 |
mset.clMu.Lock() |
| 2502 |
msg := []byte("hello") |
| 2503 |
hdr := genHeader(nil, "Nats-Batch-Id", batchId1) |
| 2504 |
hdr = setHeader("Nats-Batch-Sequence", "1", hdr) |
| 2505 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, batchId1, 1, false) |
| 2506 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2507 |
mset.clseq++ |
| 2508 |
|
| 2509 |
for j := range batchSize { |
| 2510 |
bseq := uint64(j + 1) |
| 2511 |
hdr = genHeader(nil, "Nats-Batch-Id", batchId2) |
| 2512 |
hdr = setHeader("Nats-Batch-Sequence", strconv.FormatUint(bseq, 10), hdr) |
| 2513 |
commit := bseq == uint64(batchSize) |
| 2514 |
if commit { |
| 2515 |
hdr = setHeader("Nats-Batch-Commit", "1", hdr) |
| 2516 |
} |
| 2517 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, msg, mset.clseq, 0, false, batchId2, bseq, commit) |
| 2518 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2519 |
mset.clseq++ |
| 2520 |
} |
| 2521 |
mset.clMu.Unlock() |
| 2522 |
n := mset.raftNode().(*raft) |
| 2523 |
n.sendAppendEntry(entries) |
| 2524 |
|
| 2525 |
pubAck, err = js.Publish("foo", nil) |
| 2526 |
require_NoError(t, err) |
| 2527 |
require_Equal(t, pubAck.Sequence, uint64(2+batchSize)) |
| 2528 |
|
| 2529 |
// Validate the stream only committed the full batch. |
| 2530 |
rsm, err := js.GetMsg("TEST", 1) |
| 2531 |
require_NoError(t, err) |
| 2532 |
require_True(t, rsm.Header.Get("Nats-Batch-Id") == _EMPTY_) |
| 2533 |
for j := range batchSize { |
| 2534 |
rsm, err = js.GetMsg("TEST", uint64(2+j)) |
| 2535 |
require_NoError(t, err) |
| 2536 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Id"), batchId2) |
| 2537 |
require_Equal(t, rsm.Header.Get("Nats-Batch-Sequence"), strconv.Itoa(j+1)) |
| 2538 |
} |
| 2539 |
rsm, err = js.GetMsg("TEST", uint64(2+batchSize)) |
| 2540 |
require_NoError(t, err) |
| 2541 |
require_True(t, rsm.Header.Get("Nats-Batch-Id") == _EMPTY_) |
| 2542 |
|
| 2543 |
mset.clMu.Lock() |
| 2544 |
clfs := mset.clfs |
| 2545 |
mset.clMu.Unlock() |
| 2546 |
require_Equal(t, clfs, 1) |
| 2547 |
} |
| 2548 |
for _, retry := range []bool{false, true} { |
| 2549 |
for i := range 2 { |
| 2550 |
batchSize := i + 1 |
| 2551 |
title := fmt.Sprintf("B-%d", batchSize) |
| 2552 |
if retry { |
| 2553 |
title += "/Retry" |
| 2554 |
} else { |
| 2555 |
title += "/NoRetry" |
| 2556 |
} |
| 2557 |
t.Run(title, func(t *testing.T) { |
| 2558 |
test(t, batchSize, retry) |
| 2559 |
}) |
| 2560 |
} |
| 2561 |
} |
| 2562 |
} |
| 2563 |
|
| 2564 |
// Test a continuous flow of batches spanning multiple append entries can still move applied up. |
| 2565 |
// Also, test a server can become leader if the previous leader left it with a partial batch. |
| 2566 |
func TestJetStreamAtomicBatchPublishContinuousBatchesStillMoveAppliedUp(t *testing.T) { |
| 2567 |
test := func(t *testing.T, largePayload bool) { |
| 2568 |
var payload []byte |
| 2569 |
if largePayload { |
| 2570 |
// Create a large payload that can be easily compressed. |
| 2571 |
payload = make([]byte, 2*compressThreshold) |
| 2572 |
} |
| 2573 |
|
| 2574 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2575 |
defer c.shutdown() |
| 2576 |
|
| 2577 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2578 |
defer nc.Close() |
| 2579 |
|
| 2580 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2581 |
Name: "TEST", |
| 2582 |
Subjects: []string{"foo"}, |
| 2583 |
Storage: FileStorage, |
| 2584 |
Replicas: 3, |
| 2585 |
AllowAtomicPublish: true, |
| 2586 |
}) |
| 2587 |
require_NoError(t, err) |
| 2588 |
|
| 2589 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2590 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2591 |
require_NoError(t, err) |
| 2592 |
|
| 2593 |
pubAck, err := js.Publish("foo", nil) |
| 2594 |
require_NoError(t, err) |
| 2595 |
require_Equal(t, pubAck.Sequence, 1) |
| 2596 |
|
| 2597 |
n := mset.raftNode().(*raft) |
| 2598 |
index, commit, applied := n.Progress() |
| 2599 |
|
| 2600 |
// The first batch spans two append entries, but commits. |
| 2601 |
mset.clMu.Lock() |
| 2602 |
hdr := genHeader(nil, "Nats-Batch-Id", "ID_1") |
| 2603 |
hdr = setHeader("Nats-Batch-Sequence", "1", hdr) |
| 2604 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, payload, mset.clseq, 0, false, "ID_1", 1, false) |
| 2605 |
mset.clseq++ |
| 2606 |
mset.clMu.Unlock() |
| 2607 |
n.sendAppendEntry([]*Entry{newEntry(EntryNormal, esm)}) |
| 2608 |
|
| 2609 |
var entries []*Entry |
| 2610 |
mset.clMu.Lock() |
| 2611 |
hdr = genHeader(nil, "Nats-Batch-Id", "ID_1") |
| 2612 |
hdr = setHeader("Nats-Batch-Sequence", "2", hdr) |
| 2613 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, payload, mset.clseq, 0, false, "ID_1", 2, false) |
| 2614 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2615 |
mset.clseq++ |
| 2616 |
|
| 2617 |
hdr = genHeader(nil, "Nats-Batch-Id", "ID_1") |
| 2618 |
hdr = setHeader("Nats-Batch-Sequence", "3", hdr) |
| 2619 |
hdr = setHeader("Nats-Batch-Commit", "1", hdr) |
| 2620 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, payload, mset.clseq, 0, false, "ID_1", 3, true) |
| 2621 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2622 |
mset.clseq++ |
| 2623 |
|
| 2624 |
// The second batch doesn't commit. |
| 2625 |
hdr = genHeader(nil, "Nats-Batch-Id", "ID_2") |
| 2626 |
hdr = setHeader("Nats-Batch-Sequence", "1", hdr) |
| 2627 |
esm = encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, payload, mset.clseq, 0, false, "ID_2", 1, false) |
| 2628 |
mset.clseq++ |
| 2629 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2630 |
mset.clMu.Unlock() |
| 2631 |
n.sendAppendEntry(entries) |
| 2632 |
|
| 2633 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2634 |
n.RLock() |
| 2635 |
nindex, ncommit, processed, napplied := n.pindex, n.commit, n.processed, n.applied |
| 2636 |
n.RUnlock() |
| 2637 |
if nindex == index { |
| 2638 |
return errors.New("index not updated") |
| 2639 |
} else if ncommit == commit { |
| 2640 |
return errors.New("commit not updated") |
| 2641 |
} else if napplied == applied { |
| 2642 |
return errors.New("applied not updated") |
| 2643 |
} else if napplied == ncommit { |
| 2644 |
return errors.New("applied should not be able to equal commit yet") |
| 2645 |
} else if processed != ncommit { |
| 2646 |
return errors.New("must have processed all commits") |
| 2647 |
} |
| 2648 |
return checkState(t, c, globalAccountName, "TEST") |
| 2649 |
}) |
| 2650 |
|
| 2651 |
// Followers are now stranded with a partial batch, one needs to become leader |
| 2652 |
// and have the batch be rejected since it was partially proposed. |
| 2653 |
sl.Shutdown() |
| 2654 |
c.waitOnStreamLeader(globalAccountName, "TEST") |
| 2655 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2656 |
return checkState(t, c, globalAccountName, "TEST") |
| 2657 |
}) |
| 2658 |
|
| 2659 |
// Confirm the last batch gets rejected, and we are still able to publish with quorum. |
| 2660 |
pubAck, err = js.Publish("foo", nil) |
| 2661 |
require_NoError(t, err) |
| 2662 |
require_Equal(t, pubAck.Sequence, 5) |
| 2663 |
|
| 2664 |
c.restartServer(sl) |
| 2665 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2666 |
return checkState(t, c, globalAccountName, "TEST") |
| 2667 |
}) |
| 2668 |
|
| 2669 |
// Publish again, now with all servers online. |
| 2670 |
pubAck, err = js.Publish("foo", nil) |
| 2671 |
require_NoError(t, err) |
| 2672 |
require_Equal(t, pubAck.Sequence, 6) |
| 2673 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2674 |
return checkState(t, c, globalAccountName, "TEST") |
| 2675 |
}) |
| 2676 |
} |
| 2677 |
|
| 2678 |
t.Run("Normal", func(t *testing.T) { test(t, false) }) |
| 2679 |
t.Run("Compressed", func(t *testing.T) { test(t, true) }) |
| 2680 |
} |
| 2681 |
|
| 2682 |
// Test a batch that's committed but only partially applied, and the server gets hard killed. |
| 2683 |
// Upon recovery the server should skip the messages that were already applied but store the |
| 2684 |
// messages that weren't applied yet. |
| 2685 |
func TestJetStreamAtomicBatchPublishPartiallyAppliedBatchOnRecovery(t *testing.T) { |
| 2686 |
test := func(t *testing.T, largePayload bool) { |
| 2687 |
var payload []byte |
| 2688 |
expectedOp := streamMsgOp |
| 2689 |
if largePayload { |
| 2690 |
// Create a large payload that can be easily compressed. |
| 2691 |
payload = make([]byte, 2*compressThreshold) |
| 2692 |
expectedOp = compressedStreamMsgOp |
| 2693 |
} |
| 2694 |
|
| 2695 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2696 |
defer c.shutdown() |
| 2697 |
|
| 2698 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2699 |
defer nc.Close() |
| 2700 |
|
| 2701 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 2702 |
Name: "TEST", |
| 2703 |
Subjects: []string{"foo"}, |
| 2704 |
Storage: FileStorage, |
| 2705 |
Replicas: 3, |
| 2706 |
AllowAtomicPublish: true, |
| 2707 |
}) |
| 2708 |
require_NoError(t, err) |
| 2709 |
|
| 2710 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 2711 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 2712 |
require_NoError(t, err) |
| 2713 |
|
| 2714 |
pubAck, err := js.Publish("foo", nil) |
| 2715 |
require_NoError(t, err) |
| 2716 |
require_Equal(t, pubAck.Sequence, 1) |
| 2717 |
|
| 2718 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2719 |
return checkState(t, c, globalAccountName, "TEST") |
| 2720 |
}) |
| 2721 |
|
| 2722 |
// Pause applies on all followers. |
| 2723 |
for _, s := range c.servers { |
| 2724 |
if s == sl { |
| 2725 |
continue |
| 2726 |
} |
| 2727 |
fmset, err := s.globalAccount().lookupStream("TEST") |
| 2728 |
require_NoError(t, err) |
| 2729 |
require_NoError(t, fmset.raftNode().PauseApply()) |
| 2730 |
} |
| 2731 |
|
| 2732 |
// Publish a batch. |
| 2733 |
var entries []*Entry |
| 2734 |
mset.clMu.Lock() |
| 2735 |
for seq := uint64(1); seq <= 4; seq++ { |
| 2736 |
batchCommit := seq == 4 |
| 2737 |
hdr := genHeader(nil, "Nats-Batch-Id", "ID") |
| 2738 |
hdr = genHeader(hdr, "Nats-Batch-Sequence", strconv.FormatUint(seq, 10)) |
| 2739 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr, payload, mset.clseq, 0, false, "ID", seq, batchCommit) |
| 2740 |
if _, _, bop, _, err := decodeBatchMsg(esm[1:]); err != nil || bop != expectedOp { |
| 2741 |
mset.clMu.Unlock() |
| 2742 |
t.Fatalf("Unexpected batch op %v: %v", bop, err) |
| 2743 |
} |
| 2744 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 2745 |
mset.clseq++ |
| 2746 |
} |
| 2747 |
mset.clMu.Unlock() |
| 2748 |
|
| 2749 |
// Wait for the leader to have applied the batch, so the next |
| 2750 |
// publish informs the followers that it can be committed. |
| 2751 |
n := mset.raftNode().(*raft) |
| 2752 |
_, _, applied := n.Progress() |
| 2753 |
n.sendAppendEntry(entries) |
| 2754 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2755 |
_, _, napplied := n.Progress() |
| 2756 |
if applied == napplied { |
| 2757 |
return errors.New("batch hasn't been applied yet") |
| 2758 |
} |
| 2759 |
return nil |
| 2760 |
}) |
| 2761 |
|
| 2762 |
// Publish so the commit moves up on all servers. |
| 2763 |
pubAck, err = js.Publish("foo", nil) |
| 2764 |
require_NoError(t, err) |
| 2765 |
require_Equal(t, pubAck.Sequence, 6) |
| 2766 |
|
| 2767 |
// Simulate this follower only partially applied the batch and then got hard killed. |
| 2768 |
rs := c.randomNonStreamLeader(globalAccountName, "TEST") |
| 2769 |
mset, err = rs.globalAccount().lookupStream("TEST") |
| 2770 |
require_NoError(t, err) |
| 2771 |
|
| 2772 |
ts := time.Now().UnixNano() |
| 2773 |
hdr := genHeader(nil, "Nats-Batch-Id", "ID") |
| 2774 |
hdr = genHeader(hdr, "Nats-Batch-Sequence", "1") |
| 2775 |
require_NoError(t, mset.store.StoreRawMsg("foo", hdr, nil, 2, ts, 0, false)) |
| 2776 |
|
| 2777 |
hdr = genHeader(nil, "Nats-Batch-Id", "ID") |
| 2778 |
hdr = genHeader(hdr, "Nats-Batch-Sequence", "2") |
| 2779 |
require_NoError(t, mset.store.StoreRawMsg("foo", hdr, nil, 3, ts, 0, false)) |
| 2780 |
|
| 2781 |
// Unpause applies on the remaining follower. |
| 2782 |
for _, s := range c.servers { |
| 2783 |
if s == sl || s == rs { |
| 2784 |
continue |
| 2785 |
} |
| 2786 |
fmset, err := s.globalAccount().lookupStream("TEST") |
| 2787 |
require_NoError(t, err) |
| 2788 |
fmset.raftNode().ResumeApply() |
| 2789 |
} |
| 2790 |
|
| 2791 |
// Restart the "hard killed" follower, should apply the remainder of the batch upon recovery. |
| 2792 |
rs.Shutdown() |
| 2793 |
c.restartServer(rs) |
| 2794 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 2795 |
return checkState(t, c, globalAccountName, "TEST") |
| 2796 |
}) |
| 2797 |
} |
| 2798 |
|
| 2799 |
t.Run("Normal", func(t *testing.T) { test(t, false) }) |
| 2800 |
t.Run("Compressed", func(t *testing.T) { test(t, true) }) |
| 2801 |
} |
| 2802 |
|
| 2803 |
func TestJetStreamRollupIsolatedRead(t *testing.T) { |
| 2804 |
const ( |
| 2805 |
DirectGet = iota |
| 2806 |
DirectBatchGet |
| 2807 |
DirectMultiGet |
| 2808 |
Consumer |
| 2809 |
) |
| 2810 |
|
| 2811 |
test := func(t *testing.T, mode int) { |
| 2812 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 2813 |
defer c.shutdown() |
| 2814 |
|
| 2815 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 2816 |
defer nc.Close() |
| 2817 |
|
| 2818 |
_, err := js.AddStream(&nats.StreamConfig{ |
| 2819 |
Name: "TEST", |
| 2820 |
Subjects: []string{"foo.*"}, |
| 2821 |
AllowRollup: true, |
| 2822 |
Replicas: 3, |
| 2823 |
}) |
| 2824 |
require_NoError(t, err) |
| 2825 |
|
| 2826 |
rs := c.randomNonStreamLeader(globalAccountName, "TEST") |
| 2827 |
mset, err := rs.globalAccount().lookupStream("TEST") |
| 2828 |
require_NoError(t, err) |
| 2829 |
|
| 2830 |
// Reconnect to the selected server. |
| 2831 |
nc.Close() |
| 2832 |
nc, js = jsClientConnect(t, rs) |
| 2833 |
defer nc.Close() |
| 2834 |
|
| 2835 |
m := nats.NewMsg("foo.0") |
| 2836 |
pubAck, err := js.PublishMsg(m) |
| 2837 |
require_NoError(t, err) |
| 2838 |
require_Equal(t, pubAck.Sequence, 1) |
| 2839 |
|
| 2840 |
// mset.processJetStreamMsg will first store the new message, then update dedupe state, and then do the rollup. |
| 2841 |
// We block the replica such that it can store the new message but can't do the rollup yet. |
| 2842 |
// A read should wait for the rollup to complete. |
| 2843 |
mset.ddMu.Lock() |
| 2844 |
m.Subject = "foo.1" |
| 2845 |
m.Header.Set(JSMsgRollup, JSMsgRollupAll) |
| 2846 |
m.Header.Set(JSMsgId, "msgId") |
| 2847 |
_, _ = js.PublishMsg(m) |
| 2848 |
err = checkForErr(2*time.Second, 200*time.Millisecond, func() error { |
| 2849 |
var state StreamState |
| 2850 |
mset.store.FastState(&state) |
| 2851 |
if state.LastSeq != 2 { |
| 2852 |
return fmt.Errorf("expected last seq 2, got: %d", state.LastSeq) |
| 2853 |
} |
| 2854 |
return nil |
| 2855 |
}) |
| 2856 |
if err != nil { |
| 2857 |
mset.ddMu.Unlock() |
| 2858 |
require_NoError(t, err) |
| 2859 |
} |
| 2860 |
|
| 2861 |
// We're now subscribing and going to do a request, while the write is still halfway. |
| 2862 |
sub, err := nc.SubscribeSync("reply") |
| 2863 |
if err != nil { |
| 2864 |
mset.ddMu.Unlock() |
| 2865 |
require_NoError(t, err) |
| 2866 |
} |
| 2867 |
defer sub.Drain() |
| 2868 |
if err = nc.Flush(); err != nil { |
| 2869 |
mset.ddMu.Unlock() |
| 2870 |
require_NoError(t, err) |
| 2871 |
} |
| 2872 |
|
| 2873 |
// Run two goroutines, one will unblock the first write after a short sleep, |
| 2874 |
// the second will do the read/consumer request. |
| 2875 |
var ( |
| 2876 |
ready sync.WaitGroup |
| 2877 |
run sync.WaitGroup |
| 2878 |
cleanup sync.WaitGroup |
| 2879 |
) |
| 2880 |
ready.Add(2) |
| 2881 |
run.Add(1) |
| 2882 |
cleanup.Add(1) |
| 2883 |
go func() { |
| 2884 |
ready.Done() |
| 2885 |
defer cleanup.Done() |
| 2886 |
run.Wait() |
| 2887 |
time.Sleep(250 * time.Millisecond) |
| 2888 |
mset.ddMu.Unlock() |
| 2889 |
}() |
| 2890 |
go func() { |
| 2891 |
ready.Done() |
| 2892 |
run.Wait() |
| 2893 |
switch mode { |
| 2894 |
case DirectGet: |
| 2895 |
mset.getDirectRequest(&JSApiMsgGetRequest{LastFor: "foo.0"}, "reply") |
| 2896 |
case DirectBatchGet: |
| 2897 |
mset.getDirectRequest(&JSApiMsgGetRequest{NextFor: "foo.*", Batch: 2}, "reply") |
| 2898 |
case DirectMultiGet: |
| 2899 |
mset.getDirectRequest(&JSApiMsgGetRequest{MultiLastFor: []string{"foo.*"}, Batch: 2}, "reply") |
| 2900 |
case Consumer: |
| 2901 |
mset.addConsumer(&ConsumerConfig{DeliverSubject: "reply", Direct: true}) |
| 2902 |
} |
| 2903 |
}() |
| 2904 |
|
| 2905 |
// Wait for both to be ready, then run both of them. |
| 2906 |
ready.Wait() |
| 2907 |
run.Done() |
| 2908 |
|
| 2909 |
msg, err := sub.NextMsg(time.Second) |
| 2910 |
// Make sure cleanup has happened before validating. |
| 2911 |
cleanup.Wait() |
| 2912 |
require_NoError(t, err) |
| 2913 |
if mode == DirectGet { |
| 2914 |
require_Equal(t, msg.Header.Get("Status"), "404") |
| 2915 |
} else if mode != Consumer { |
| 2916 |
require_Equal(t, msg.Header.Get(JSNumPending), "0") |
| 2917 |
require_Equal(t, msg.Header.Get(JSSequence), "2") |
| 2918 |
} else { |
| 2919 |
require_True(t, strings.HasPrefix(msg.Reply, jsAckPre)) |
| 2920 |
sseq, _, _, _, pending := ackReplyInfo(msg.Reply) |
| 2921 |
require_Equal(t, pending, 0) |
| 2922 |
require_Equal(t, sseq, 2) |
| 2923 |
} |
| 2924 |
} |
| 2925 |
|
| 2926 |
t.Run("DirectGet", func(t *testing.T) { test(t, DirectGet) }) |
| 2927 |
t.Run("DirectBatchGet", func(t *testing.T) { test(t, DirectBatchGet) }) |
| 2928 |
t.Run("DirectMultiGet", func(t *testing.T) { test(t, DirectMultiGet) }) |
| 2929 |
t.Run("Consumer", func(t *testing.T) { test(t, Consumer) }) |
| 2930 |
} |
| 2931 |
|
| 2932 |
func TestJetStreamAtomicBatchPublishAdvisories(t *testing.T) { |
| 2933 |
templ := ` |
| 2934 |
listen: 127.0.0.1:-1 |
| 2935 |
server_name: %s |
| 2936 |
jetstream: { |
| 2937 |
max_mem_store: 2GB |
| 2938 |
max_file_store: 2GB |
| 2939 |
store_dir: '%s' |
| 2940 |
limits { |
| 2941 |
batch { |
| 2942 |
timeout: 2s |
| 2943 |
} |
| 2944 |
} |
| 2945 |
} |
| 2946 |
|
| 2947 |
leaf { |
| 2948 |
listen: 127.0.0.1:-1 |
| 2949 |
} |
| 2950 |
|
| 2951 |
cluster { |
| 2952 |
name: %s |
| 2953 |
listen: 127.0.0.1:%d |
| 2954 |
routes = [%s] |
| 2955 |
} |
| 2956 |
|
| 2957 |
# For access to system account. |
| 2958 |
accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } } |
| 2959 |
` |
| 2960 |
test := func(t *testing.T, replicas int) { |
| 2961 |
c := createJetStreamClusterWithTemplate(t, templ, "R3S", 3) |
| 2962 |
defer c.shutdown() |
| 2963 |
|
| 2964 |
nc := clientConnectToServer(t, c.randomServer()) |
| 2965 |
defer nc.Close() |
| 2966 |
|
| 2967 |
cfg := &StreamConfig{ |
| 2968 |
Name: "TEST", |
| 2969 |
Subjects: []string{"foo"}, |
| 2970 |
Replicas: replicas, |
| 2971 |
Storage: FileStorage, |
| 2972 |
AllowAtomicPublish: true, |
| 2973 |
} |
| 2974 |
|
| 2975 |
_, err := jsStreamCreate(t, nc, cfg) |
| 2976 |
require_NoError(t, err) |
| 2977 |
|
| 2978 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.*", JSAdvisoryStreamBatchAbandonedPre)) |
| 2979 |
require_NoError(t, err) |
| 2980 |
defer sub.Drain() |
| 2981 |
require_NoError(t, nc.Flush()) |
| 2982 |
|
| 2983 |
// Should receive an advisory if gaps are detected. |
| 2984 |
m := nats.NewMsg("foo") |
| 2985 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 2986 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 2987 |
require_NoError(t, nc.PublishMsg(m)) |
| 2988 |
m.Header.Set("Nats-Batch-Sequence", "3") |
| 2989 |
require_NoError(t, nc.PublishMsg(m)) |
| 2990 |
|
| 2991 |
msg, err := sub.NextMsg(time.Second) |
| 2992 |
require_NoError(t, err) |
| 2993 |
var advisory JSStreamBatchAbandonedAdvisory |
| 2994 |
require_NoError(t, json.Unmarshal(msg.Data, &advisory)) |
| 2995 |
require_Equal(t, advisory.BatchId, "uuid") |
| 2996 |
require_Equal(t, advisory.Reason, BatchIncomplete) |
| 2997 |
|
| 2998 |
// Should receive an advisory if the batch is too large. |
| 2999 |
count := 1002 |
| 3000 |
for seq := 1; seq <= count; seq++ { |
| 3001 |
m = nats.NewMsg("foo") |
| 3002 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3003 |
m.Header.Set("Nats-Batch-Sequence", strconv.Itoa(seq)) |
| 3004 |
if seq != count { |
| 3005 |
require_NoError(t, nc.PublishMsg(m)) |
| 3006 |
continue |
| 3007 |
} |
| 3008 |
var pubAck JSPubAckResponse |
| 3009 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 3010 |
rmsg, err := nc.RequestMsg(m, time.Second) |
| 3011 |
require_NoError(t, err) |
| 3012 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3013 |
require_NotNil(t, pubAck.Error) |
| 3014 |
require_Error(t, pubAck.Error, NewJSAtomicPublishTooLargeBatchError(streamDefaultMaxAtomicBatchSize)) |
| 3015 |
} |
| 3016 |
|
| 3017 |
msg, err = sub.NextMsg(time.Second) |
| 3018 |
require_NoError(t, err) |
| 3019 |
advisory = JSStreamBatchAbandonedAdvisory{} |
| 3020 |
require_NoError(t, json.Unmarshal(msg.Data, &advisory)) |
| 3021 |
require_Equal(t, advisory.BatchId, "uuid") |
| 3022 |
require_Equal(t, advisory.Reason, BatchLarge) |
| 3023 |
|
| 3024 |
// Should receive an advisory if the batch times out and is abandoned. |
| 3025 |
m = nats.NewMsg("foo") |
| 3026 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3027 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3028 |
require_NoError(t, nc.PublishMsg(m)) |
| 3029 |
|
| 3030 |
msg, err = sub.NextMsg(3 * time.Second) |
| 3031 |
require_NoError(t, err) |
| 3032 |
advisory = JSStreamBatchAbandonedAdvisory{} |
| 3033 |
require_NoError(t, json.Unmarshal(msg.Data, &advisory)) |
| 3034 |
require_Equal(t, advisory.BatchId, "uuid") |
| 3035 |
require_Equal(t, advisory.Reason, BatchTimeout) |
| 3036 |
|
| 3037 |
// Should receive an advisory if the batch has an unsupported required API level. |
| 3038 |
m = nats.NewMsg("foo") |
| 3039 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3040 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3041 |
m.Header.Set("Nats-Required-Api-Level", strconv.Itoa(math.MaxInt)) |
| 3042 |
require_NoError(t, nc.PublishMsg(m)) |
| 3043 |
|
| 3044 |
msg, err = sub.NextMsg(3 * time.Second) |
| 3045 |
require_NoError(t, err) |
| 3046 |
advisory = JSStreamBatchAbandonedAdvisory{} |
| 3047 |
require_NoError(t, json.Unmarshal(msg.Data, &advisory)) |
| 3048 |
require_Equal(t, advisory.BatchId, "uuid") |
| 3049 |
require_Equal(t, advisory.Reason, BatchRequirementsNotMet) |
| 3050 |
} |
| 3051 |
|
| 3052 |
for _, replicas := range []int{1, 3} { |
| 3053 |
t.Run(fmt.Sprintf("R%d", replicas), func(t *testing.T) { |
| 3054 |
test(t, replicas) |
| 3055 |
}) |
| 3056 |
} |
| 3057 |
} |
| 3058 |
|
| 3059 |
func TestJetStreamAtomicBatchPublishExpectedSeq(t *testing.T) { |
| 3060 |
s := RunBasicJetStreamServer(t) |
| 3061 |
defer s.Shutdown() |
| 3062 |
|
| 3063 |
nc, js := jsClientConnect(t, s) |
| 3064 |
defer nc.Close() |
| 3065 |
|
| 3066 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3067 |
Name: "TEST", |
| 3068 |
Subjects: []string{"foo"}, |
| 3069 |
Storage: FileStorage, |
| 3070 |
AllowAtomicPublish: true, |
| 3071 |
}) |
| 3072 |
require_NoError(t, err) |
| 3073 |
|
| 3074 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 3075 |
require_NoError(t, err) |
| 3076 |
|
| 3077 |
clseqAndClfs := func() (uint64, uint64) { |
| 3078 |
mset.clMu.Lock() |
| 3079 |
defer mset.clMu.Unlock() |
| 3080 |
return mset.clseq, mset.clfs |
| 3081 |
} |
| 3082 |
|
| 3083 |
clseq, clfs := clseqAndClfs() |
| 3084 |
require_Equal(t, clseq, 0) |
| 3085 |
require_Equal(t, clfs, 0) |
| 3086 |
|
| 3087 |
_, err = js.Publish("foo", []byte("hello")) |
| 3088 |
require_NoError(t, err) |
| 3089 |
|
| 3090 |
clseq, clfs = clseqAndClfs() |
| 3091 |
require_Equal(t, clseq, 0) |
| 3092 |
require_Equal(t, clfs, 0) |
| 3093 |
|
| 3094 |
// test expect last seq for standalone publish |
| 3095 |
_, err = js.Publish("foo", []byte("hello"), nats.ExpectLastSequence(1)) |
| 3096 |
require_NoError(t, err) |
| 3097 |
|
| 3098 |
clseq, clfs = clseqAndClfs() |
| 3099 |
require_Equal(t, clseq, 0) |
| 3100 |
require_Equal(t, clfs, 0) |
| 3101 |
|
| 3102 |
// now do a single msg batch with expect last seq |
| 3103 |
m := nats.NewMsg("foo") |
| 3104 |
m.Header.Set("Nats-Expected-Last-Sequence", "2") |
| 3105 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3106 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3107 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 3108 |
resp, err := nc.RequestMsg(m, time.Second) |
| 3109 |
require_NoError(t, err) |
| 3110 |
|
| 3111 |
var pubAck JSPubAckResponse |
| 3112 |
require_NoError(t, json.Unmarshal(resp.Data, &pubAck)) |
| 3113 |
if pubAck.Error != nil { |
| 3114 |
t.Fatalf("Commit error: %v", pubAck.Error) |
| 3115 |
} |
| 3116 |
require_Equal(t, pubAck.Sequence, 3) |
| 3117 |
require_Equal(t, pubAck.BatchSize, 1) |
| 3118 |
|
| 3119 |
clseq, clfs = clseqAndClfs() |
| 3120 |
require_Equal(t, clseq, 0) |
| 3121 |
require_Equal(t, clfs, 0) |
| 3122 |
} |
| 3123 |
|
| 3124 |
// Test two different batches within the same append entry. |
| 3125 |
func TestJetStreamAtomicBatchPublishPartialBatchInSharedAppendEntry(t *testing.T) { |
| 3126 |
test := func(t *testing.T, commit bool) { |
| 3127 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 3128 |
defer c.shutdown() |
| 3129 |
|
| 3130 |
nc := clientConnectToServer(t, c.randomServer()) |
| 3131 |
defer nc.Close() |
| 3132 |
|
| 3133 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3134 |
Name: "TEST", |
| 3135 |
Subjects: []string{"foo"}, |
| 3136 |
Storage: FileStorage, |
| 3137 |
Replicas: 3, |
| 3138 |
AllowAtomicPublish: true, |
| 3139 |
}) |
| 3140 |
require_NoError(t, err) |
| 3141 |
|
| 3142 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 3143 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 3144 |
require_NoError(t, err) |
| 3145 |
|
| 3146 |
js := sl.getJetStream() |
| 3147 |
esm1 := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, nil, []byte("b1"), 0, 0, false, "b1", 1, false) |
| 3148 |
esm2 := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, nil, []byte("b2"), 1, 0, false, "b2", 1, commit) |
| 3149 |
ce := newCommittedEntry(2, []*Entry{ |
| 3150 |
newEntry(EntryNormal, esm1), |
| 3151 |
newEntry(EntryNormal, esm2), |
| 3152 |
}) |
| 3153 |
batch := &batchApply{} |
| 3154 |
_, err = js.applyStreamEntries(mset, mset.raftNode(), ce, false, batch) |
| 3155 |
require_NoError(t, err) |
| 3156 |
entryStart, maxApplied := batch.entryStart, batch.maxApplied |
| 3157 |
|
| 3158 |
if !commit { |
| 3159 |
require_Equal(t, entryStart, 1) |
| 3160 |
require_Equal(t, maxApplied, 1) |
| 3161 |
return |
| 3162 |
} |
| 3163 |
require_Equal(t, entryStart, 0) |
| 3164 |
require_Equal(t, maxApplied, 0) |
| 3165 |
require_Equal(t, mset.lastSeq(), 1) |
| 3166 |
|
| 3167 |
var smv StoreMsg |
| 3168 |
sm, err := mset.store.LoadMsg(1, &smv) |
| 3169 |
require_NoError(t, err) |
| 3170 |
require_Equal(t, string(sm.buf), "b2") |
| 3171 |
} |
| 3172 |
|
| 3173 |
t.Run("NoCommit", func(t *testing.T) { test(t, false) }) |
| 3174 |
t.Run("Commit", func(t *testing.T) { test(t, true) }) |
| 3175 |
} |
| 3176 |
|
| 3177 |
func TestJetStreamAtomicBatchPublishCatchupMarkerMidBatch(t *testing.T) { |
| 3178 |
s := RunBasicJetStreamServer(t) |
| 3179 |
defer s.Shutdown() |
| 3180 |
|
| 3181 |
nc := clientConnectToServer(t, s) |
| 3182 |
defer nc.Close() |
| 3183 |
|
| 3184 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3185 |
Name: "TEST", |
| 3186 |
Subjects: []string{"foo"}, |
| 3187 |
Storage: MemoryStorage, |
| 3188 |
Replicas: 1, |
| 3189 |
AllowAtomicPublish: true, |
| 3190 |
}) |
| 3191 |
require_NoError(t, err) |
| 3192 |
|
| 3193 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 3194 |
require_NoError(t, err) |
| 3195 |
js := mset.js |
| 3196 |
require_True(t, js != nil) |
| 3197 |
|
| 3198 |
// Non-zero timestamp so apply does not treat these as skip/no-op messages. |
| 3199 |
ts := time.Now().UnixNano() |
| 3200 |
|
| 3201 |
// 1) Apply the start of an atomic batch (seq 1, no commit). The batch |
| 3202 |
// becomes "in progress" and this CommittedEntry is buffered. |
| 3203 |
hdr1 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 3204 |
hdr1 = genHeader(hdr1, "Nats-Batch-Sequence", "1") |
| 3205 |
esm1 := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr1, []byte("hello"), 0, ts, false, "uuid", 1, false) |
| 3206 |
ce1 := newCommittedEntry(1, []*Entry{newEntry(EntryNormal, esm1)}) |
| 3207 |
batch := &batchApply{} |
| 3208 |
_, err = js.applyStreamEntries(mset, mset.raftNode(), ce1, false, batch) |
| 3209 |
require_NoError(t, err) |
| 3210 |
|
| 3211 |
// Confirm the batch is in progress. |
| 3212 |
require_True(t, batch.id != _EMPTY_) |
| 3213 |
|
| 3214 |
// 2) A Raft-level catchup starts mid-batch. This pushes a marker entry with |
| 3215 |
// Type==EntryCatchup and Data==nil (see raft.sendCatchupSignal). The |
| 3216 |
// in-progress batch must remain intact and buffer this marker. |
| 3217 |
catchupCE := newCommittedEntry(0, []*Entry{{EntryCatchup, nil}}) |
| 3218 |
_, err = js.applyStreamEntries(mset, mset.raftNode(), catchupCE, false, batch) |
| 3219 |
require_NoError(t, err) |
| 3220 |
|
| 3221 |
// 3) Apply the batch commit (seq 2). The replay loop must skip the buffered |
| 3222 |
// EntryCatchup marker instead of decoding it and commit the full batch. |
| 3223 |
hdr2 := genHeader(nil, "Nats-Batch-Id", "uuid") |
| 3224 |
hdr2 = genHeader(hdr2, "Nats-Batch-Sequence", "2") |
| 3225 |
hdr2 = genHeader(hdr2, "Nats-Batch-Commit", "1") |
| 3226 |
esm2 := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, hdr2, []byte("world"), 1, ts, false, "uuid", 2, true) |
| 3227 |
ce2 := newCommittedEntry(2, []*Entry{newEntry(EntryNormal, esm2)}) |
| 3228 |
|
| 3229 |
// A regression would panic on entry.Data[1:] while holding mset.mu and batch.mu. |
| 3230 |
// Recover and release the locks so the deferred shutdown does not deadlock. |
| 3231 |
var panicked any |
| 3232 |
func() { |
| 3233 |
defer func() { panicked = recover() }() |
| 3234 |
_, err = js.applyStreamEntries(mset, mset.raftNode(), ce2, false, batch) |
| 3235 |
}() |
| 3236 |
if panicked != nil { |
| 3237 |
mset.mu.Unlock() |
| 3238 |
t.Fatalf("applyStreamEntries panicked committing a batch with a buffered EntryCatchup entry: %v", panicked) |
| 3239 |
} |
| 3240 |
require_NoError(t, err) |
| 3241 |
|
| 3242 |
// The full batch committed: both messages must be present. |
| 3243 |
state := mset.state() |
| 3244 |
require_Equal(t, state.Msgs, 2) |
| 3245 |
require_Equal(t, state.FirstSeq, 1) |
| 3246 |
require_Equal(t, state.LastSeq, 2) |
| 3247 |
} |
| 3248 |
|
| 3249 |
func TestJetStreamAtomicBatchPublishRejectPartialBatchOnLeaderChange(t *testing.T) { |
| 3250 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 3251 |
defer c.shutdown() |
| 3252 |
|
| 3253 |
nc := clientConnectToServer(t, c.randomServer()) |
| 3254 |
defer nc.Close() |
| 3255 |
|
| 3256 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3257 |
Name: "TEST", |
| 3258 |
Subjects: []string{"foo"}, |
| 3259 |
Storage: FileStorage, |
| 3260 |
Replicas: 3, |
| 3261 |
AllowAtomicPublish: true, |
| 3262 |
}) |
| 3263 |
require_NoError(t, err) |
| 3264 |
|
| 3265 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 3266 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 3267 |
require_NoError(t, err) |
| 3268 |
|
| 3269 |
// Propose a partial batch that doesn't commit. |
| 3270 |
var entries []*Entry |
| 3271 |
for i := range uint64(10) { |
| 3272 |
esm := encodeStreamMsgAllowCompressAndBatch("foo", _EMPTY_, nil, nil, i, 0, false, "b", i+1, false) |
| 3273 |
entries = append(entries, newEntry(EntryNormal, esm)) |
| 3274 |
} |
| 3275 |
n := mset.raftNode() |
| 3276 |
require_NoError(t, n.ProposeMulti(n.Term(), entries)) |
| 3277 |
|
| 3278 |
// Wait for all servers to have received and populated the partial batch. |
| 3279 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 3280 |
var pindexMax uint64 |
| 3281 |
for _, s := range c.servers { |
| 3282 |
mset2, err := s.globalAccount().lookupStream("TEST") |
| 3283 |
if err != nil { |
| 3284 |
return err |
| 3285 |
} |
| 3286 |
rn := mset2.raftNode().(*raft) |
| 3287 |
rn.RLock() |
| 3288 |
prop, pindex, processed := rn.prop.len(), rn.pindex, rn.processed |
| 3289 |
rn.RUnlock() |
| 3290 |
if prop > 0 { |
| 3291 |
return fmt.Errorf("still has inflight proposals") |
| 3292 |
} else if pindex != processed { |
| 3293 |
return fmt.Errorf("pindex %d != processed %d", pindex, processed) |
| 3294 |
} else if pindexMax == 0 { |
| 3295 |
pindexMax = pindex |
| 3296 |
} else if pindex != pindexMax { |
| 3297 |
return fmt.Errorf("pindex %d != max %d", pindex, pindexMax) |
| 3298 |
} |
| 3299 |
|
| 3300 |
} |
| 3301 |
return nil |
| 3302 |
}) |
| 3303 |
|
| 3304 |
// Trigger a leader change and ensure the CLFS gets accounted for. |
| 3305 |
require_NoError(t, n.StepDown()) |
| 3306 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 3307 |
for _, s := range c.servers { |
| 3308 |
mset, err = s.globalAccount().lookupStream("TEST") |
| 3309 |
if err != nil { |
| 3310 |
return err |
| 3311 |
} |
| 3312 |
if clfs := mset.getCLFS(); clfs != 10 { |
| 3313 |
return fmt.Errorf("expected clfs to be 10, got: %d", clfs) |
| 3314 |
} |
| 3315 |
} |
| 3316 |
return nil |
| 3317 |
}) |
| 3318 |
} |
| 3319 |
|
| 3320 |
func TestJetStreamAtomicBatchPublishPersistModeAsync(t *testing.T) { |
| 3321 |
s := RunBasicJetStreamServer(t) |
| 3322 |
defer s.Shutdown() |
| 3323 |
|
| 3324 |
nc := clientConnectToServer(t, s) |
| 3325 |
defer nc.Close() |
| 3326 |
|
| 3327 |
cfg := &StreamConfig{ |
| 3328 |
Name: "TEST", |
| 3329 |
Subjects: []string{"foo"}, |
| 3330 |
Storage: FileStorage, |
| 3331 |
Replicas: 1, |
| 3332 |
AllowAtomicPublish: true, |
| 3333 |
PersistMode: AsyncPersistMode, |
| 3334 |
} |
| 3335 |
_, err := jsStreamCreate(t, nc, cfg) |
| 3336 |
require_Error(t, err, NewJSStreamInvalidConfigError(fmt.Errorf("async persist mode is not supported with atomic batch publish"))) |
| 3337 |
} |
| 3338 |
|
| 3339 |
func TestJetStreamAtomicBatchPublishExpectedLastSubjectSequence(t *testing.T) { |
| 3340 |
s := RunBasicJetStreamServer(t) |
| 3341 |
defer s.Shutdown() |
| 3342 |
|
| 3343 |
nc, js := jsClientConnect(t, s) |
| 3344 |
defer nc.Close() |
| 3345 |
|
| 3346 |
cfg := &StreamConfig{ |
| 3347 |
Name: "TEST", |
| 3348 |
Subjects: []string{"foo.*"}, |
| 3349 |
Storage: FileStorage, |
| 3350 |
Replicas: 1, |
| 3351 |
AllowAtomicPublish: true, |
| 3352 |
} |
| 3353 |
_, err := jsStreamCreate(t, nc, cfg) |
| 3354 |
require_NoError(t, err) |
| 3355 |
|
| 3356 |
_, err = js.Publish("foo.A", nil) |
| 3357 |
require_NoError(t, err) |
| 3358 |
_, err = js.Publish("foo.B", nil) |
| 3359 |
require_NoError(t, err) |
| 3360 |
|
| 3361 |
m := nats.NewMsg("foo.A") |
| 3362 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3363 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3364 |
m.Header.Set("Nats-Expected-Last-Sequence", "2") |
| 3365 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence", "1") |
| 3366 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence-Subject", "foo.A") |
| 3367 |
msg, err := nc.RequestMsg(m, time.Second) |
| 3368 |
require_NoError(t, err) |
| 3369 |
require_Len(t, len(msg.Data), 0) // Empty ack. |
| 3370 |
|
| 3371 |
m = nats.NewMsg("foo.B") |
| 3372 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3373 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 3374 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 3375 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence", "2") |
| 3376 |
m.Header.Set("Nats-Expected-Last-Subject-Sequence-Subject", "foo.B") |
| 3377 |
msg, err = nc.RequestMsg(m, time.Second) |
| 3378 |
require_NoError(t, err) |
| 3379 |
var resp JSPubAckResponse |
| 3380 |
require_NoError(t, json.Unmarshal(msg.Data, &resp)) |
| 3381 |
require_True(t, resp.Error == nil) |
| 3382 |
require_Equal(t, resp.PubAck.Sequence, 4) |
| 3383 |
require_Equal(t, resp.PubAck.BatchId, "uuid") |
| 3384 |
require_Equal(t, resp.PubAck.BatchSize, 2) |
| 3385 |
} |
| 3386 |
|
| 3387 |
func TestJetStreamAtomicBatchPublishExpectedLastSubjectSequenceOwnership(t *testing.T) { |
| 3388 |
s := RunBasicJetStreamServer(t) |
| 3389 |
defer s.Shutdown() |
| 3390 |
|
| 3391 |
nc, js := jsClientConnect(t, s) |
| 3392 |
defer nc.Close() |
| 3393 |
|
| 3394 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3395 |
Name: "EVENTS", |
| 3396 |
Subjects: []string{"events.>"}, |
| 3397 |
Storage: MemoryStorage, |
| 3398 |
Replicas: 1, |
| 3399 |
AllowAtomicPublish: true, |
| 3400 |
}) |
| 3401 |
require_NoError(t, err) |
| 3402 |
|
| 3403 |
entry := "diary.entry_BBBBBBBBBBBBBBBBBBBBBBBB" |
| 3404 |
oldDay := "diary-day.day_CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" |
| 3405 |
targetDay := "diary-day.day_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" |
| 3406 |
mutation := "mutation.mut_DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" |
| 3407 |
entities := make([]string, 19) |
| 3408 |
for i := range entities { |
| 3409 |
entities[i] = fmt.Sprintf("seed.entity_%02d", i+1) |
| 3410 |
} |
| 3411 |
entities[10], entities[17], entities[18] = targetDay, entry, oldDay |
| 3412 |
for i, entity := range entities { |
| 3413 |
ack, err := js.Publish("events."+entity+".balance", nil) |
| 3414 |
require_NoError(t, err) |
| 3415 |
require_Equal(t, ack.Sequence, uint64(i+1)) |
| 3416 |
} |
| 3417 |
|
| 3418 |
batchEntities := []string{entry, oldDay, targetDay, mutation} |
| 3419 |
expected := []uint64{18, 19, 11, 0} |
| 3420 |
for i, entity := range batchEntities { |
| 3421 |
m := nats.NewMsg("events." + entity + ".balance") |
| 3422 |
m.Header.Set(JSExpectedLastSubjSeqSubj, "events."+entity+".*") |
| 3423 |
m.Header.Set(JSExpectedLastSubjSeq, strconv.FormatUint(expected[i], 10)) |
| 3424 |
m.Header.Set(JSBatchId, "uuid") |
| 3425 |
m.Header.Set(JSBatchSeq, strconv.Itoa(i+1)) |
| 3426 |
if i == len(batchEntities)-1 { |
| 3427 |
m.Header.Set(JSBatchCommit, "1") |
| 3428 |
msg, err := nc.RequestMsg(m, time.Second) |
| 3429 |
require_NoError(t, err) |
| 3430 |
var resp JSPubAckResponse |
| 3431 |
require_NoError(t, json.Unmarshal(msg.Data, &resp)) |
| 3432 |
if resp.Error != nil { |
| 3433 |
t.Fatalf("commit error: %v", resp.Error) |
| 3434 |
} |
| 3435 |
require_Equal(t, resp.PubAck.Sequence, uint64(23)) |
| 3436 |
require_Equal(t, resp.PubAck.BatchId, "uuid") |
| 3437 |
require_Equal(t, resp.PubAck.BatchSize, 4) |
| 3438 |
} else if i == 0 { |
| 3439 |
msg, err := nc.RequestMsg(m, time.Second) |
| 3440 |
require_NoError(t, err) |
| 3441 |
require_Len(t, len(msg.Data), 0) |
| 3442 |
} else { |
| 3443 |
require_NoError(t, nc.PublishMsg(m)) |
| 3444 |
} |
| 3445 |
} |
| 3446 |
} |
| 3447 |
|
| 3448 |
func TestJetStreamAtomicBatchPublishCommitUnsupported(t *testing.T) { |
| 3449 |
s := RunBasicJetStreamServer(t) |
| 3450 |
defer s.Shutdown() |
| 3451 |
|
| 3452 |
nc := clientConnectToServer(t, s) |
| 3453 |
defer nc.Close() |
| 3454 |
|
| 3455 |
cfg := &StreamConfig{ |
| 3456 |
Name: "TEST", |
| 3457 |
Subjects: []string{"foo"}, |
| 3458 |
Storage: MemoryStorage, |
| 3459 |
Replicas: 1, |
| 3460 |
AllowAtomicPublish: true, |
| 3461 |
} |
| 3462 |
_, err := jsStreamCreate(t, nc, cfg) |
| 3463 |
require_NoError(t, err) |
| 3464 |
|
| 3465 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 3466 |
require_NoError(t, err) |
| 3467 |
|
| 3468 |
var resp JSPubAckResponse |
| 3469 |
for _, unsupportedCommit := range []string{"", "unsupported", "0"} { |
| 3470 |
m := nats.NewMsg("foo") |
| 3471 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3472 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3473 |
_, err = nc.RequestMsg(m, time.Second) |
| 3474 |
require_NoError(t, err) |
| 3475 |
|
| 3476 |
m.Header.Set("Nats-Batch-Sequence", "2") |
| 3477 |
m.Header.Set("Nats-Batch-Commit", unsupportedCommit) |
| 3478 |
msg, err := nc.RequestMsg(m, time.Second) |
| 3479 |
require_NoError(t, err) |
| 3480 |
resp = JSPubAckResponse{} |
| 3481 |
require_NoError(t, json.Unmarshal(msg.Data, &resp)) |
| 3482 |
require_True(t, resp.Error != nil) |
| 3483 |
require_Error(t, resp.Error, NewJSAtomicPublishInvalidBatchCommitError()) |
| 3484 |
|
| 3485 |
// Confirm no batches are left. |
| 3486 |
mset.mu.RLock() |
| 3487 |
batches := mset.batches |
| 3488 |
mset.mu.RUnlock() |
| 3489 |
batches.mu.Lock() |
| 3490 |
groups := len(batches.atomic) |
| 3491 |
batches.mu.Unlock() |
| 3492 |
require_Len(t, groups, 0) |
| 3493 |
} |
| 3494 |
|
| 3495 |
// The required API level should allow the batch to be rejected. |
| 3496 |
m := nats.NewMsg("foo") |
| 3497 |
m.Header.Set("Nats-Batch-Id", "uuid") |
| 3498 |
m.Header.Set("Nats-Batch-Sequence", "1") |
| 3499 |
m.Header.Set("Nats-Batch-Commit", "1") |
| 3500 |
m.Header.Set("Nats-Required-Api-Level", strconv.Itoa(math.MaxInt)) |
| 3501 |
msg, err := nc.RequestMsg(m, time.Second) |
| 3502 |
require_NoError(t, err) |
| 3503 |
resp = JSPubAckResponse{} |
| 3504 |
require_NoError(t, json.Unmarshal(msg.Data, &resp)) |
| 3505 |
require_True(t, resp.Error != nil) |
| 3506 |
require_Error(t, resp.Error, NewJSRequiredApiLevelError()) |
| 3507 |
|
| 3508 |
// If required API level check passes, the header should be stripped. |
| 3509 |
m.Header.Set("Nats-Required-Api-Level", "0") |
| 3510 |
msg, err = nc.RequestMsg(m, time.Second) |
| 3511 |
require_NoError(t, err) |
| 3512 |
resp = JSPubAckResponse{} |
| 3513 |
require_NoError(t, json.Unmarshal(msg.Data, &resp)) |
| 3514 |
require_True(t, resp.Error == nil) |
| 3515 |
require_Equal(t, resp.PubAck.Sequence, 1) |
| 3516 |
|
| 3517 |
sm, err := mset.getMsg(1) |
| 3518 |
require_NoError(t, err) |
| 3519 |
require_Len(t, len(sliceHeader(JSRequiredApiLevel, sm.Header)), 0) |
| 3520 |
} |
| 3521 |
|
| 3522 |
func TestJetStreamAtomicPublishGetBatchSequence(t *testing.T) { |
| 3523 |
for _, tc := range []struct { |
| 3524 |
name string |
| 3525 |
hdr []byte |
| 3526 |
seq uint64 |
| 3527 |
exists bool |
| 3528 |
}{ |
| 3529 |
{"missing", nil, 0, false}, |
| 3530 |
{"empty-value", genHeader(nil, JSBatchSeq, ""), 0, false}, |
| 3531 |
{"valid", genHeader(nil, JSBatchSeq, "42"), 42, true}, |
| 3532 |
{"non-numeric", genHeader(nil, JSBatchSeq, "abc"), 0, false}, |
| 3533 |
{"negative", genHeader(nil, JSBatchSeq, "-1"), 0, false}, |
| 3534 |
{"overflow", genHeader(nil, JSBatchSeq, "18446744073709551616"), 0, false}, |
| 3535 |
} { |
| 3536 |
t.Run(tc.name, func(t *testing.T) { |
| 3537 |
seq, exists := getBatchSequence(tc.hdr) |
| 3538 |
require_Equal(t, seq, tc.seq) |
| 3539 |
require_Equal(t, exists, tc.exists) |
| 3540 |
}) |
| 3541 |
} |
| 3542 |
} |
| 3543 |
|
| 3544 |
func generateFastBatchReply(inbox string, batchId string, batchSeq uint64, flow uint16, gap string, op int) string { |
| 3545 |
return fmt.Sprintf("%s.%s.%d.%s.%d.%d.$FI", inbox, batchId, flow, gap, batchSeq, op) |
| 3546 |
} |
| 3547 |
|
| 3548 |
func TestJetStreamFastBatchPublish(t *testing.T) { |
| 3549 |
test := func( |
| 3550 |
t *testing.T, |
| 3551 |
storage StorageType, |
| 3552 |
retention RetentionPolicy, |
| 3553 |
replicas int, |
| 3554 |
) { |
| 3555 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 3556 |
defer c.shutdown() |
| 3557 |
|
| 3558 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 3559 |
defer nc.Close() |
| 3560 |
|
| 3561 |
cfg := &StreamConfig{ |
| 3562 |
Name: "TEST", |
| 3563 |
Subjects: []string{"foo.*"}, |
| 3564 |
Storage: storage, |
| 3565 |
Retention: retention, |
| 3566 |
Replicas: replicas, |
| 3567 |
} |
| 3568 |
|
| 3569 |
_, err := jsStreamCreate(t, nc, cfg) |
| 3570 |
require_NoError(t, err) |
| 3571 |
|
| 3572 |
inbox := nats.NewInbox() |
| 3573 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 3574 |
require_NoError(t, err) |
| 3575 |
defer sub.Drain() |
| 3576 |
|
| 3577 |
m := nats.NewMsg("foo.0") |
| 3578 |
m.Reply = generateFastBatchReply(inbox, "uuid", 0, 0, FastBatchGapFail, FastBatchOpStart) |
| 3579 |
m.Data = []byte("foo.0") |
| 3580 |
|
| 3581 |
// Publish with batch publish disabled. |
| 3582 |
require_NoError(t, nc.PublishMsg(m)) |
| 3583 |
rmsg, err := sub.NextMsg(time.Second) |
| 3584 |
require_NoError(t, err) |
| 3585 |
var pubAck JSPubAckResponse |
| 3586 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3587 |
require_NotNil(t, pubAck.Error) |
| 3588 |
require_Error(t, pubAck.Error, NewJSBatchPublishDisabledError()) |
| 3589 |
|
| 3590 |
// Enable batch publish. |
| 3591 |
cfg.AllowBatchPublish = true |
| 3592 |
_, err = jsStreamUpdate(t, nc, cfg) |
| 3593 |
require_NoError(t, err) |
| 3594 |
|
| 3595 |
// Publish with incorrect batch sequence errors. |
| 3596 |
m.Reply = generateFastBatchReply(inbox, "uuid", 0, 0, FastBatchGapFail, FastBatchOpStart) |
| 3597 |
require_NoError(t, nc.PublishMsg(m)) |
| 3598 |
rmsg, err = sub.NextMsg(time.Second) |
| 3599 |
require_NoError(t, err) |
| 3600 |
pubAck = JSPubAckResponse{} |
| 3601 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3602 |
require_NotNil(t, pubAck.Error) |
| 3603 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidPatternError()) |
| 3604 |
|
| 3605 |
// A batch that immediately commits through EOB is an error. |
| 3606 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapFail, FastBatchOpCommitEob) |
| 3607 |
require_NoError(t, nc.PublishMsg(m)) |
| 3608 |
rmsg, err = sub.NextMsg(time.Second) |
| 3609 |
require_NoError(t, err) |
| 3610 |
pubAck = JSPubAckResponse{} |
| 3611 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3612 |
require_NotNil(t, pubAck.Error) |
| 3613 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidPatternError()) |
| 3614 |
|
| 3615 |
// A batch ID must not exceed the maximum length. |
| 3616 |
longBatchId := strings.Repeat("A", 65) |
| 3617 |
m.Reply = generateFastBatchReply(inbox, longBatchId, 1, 0, FastBatchGapFail, FastBatchOpStart) |
| 3618 |
require_NoError(t, nc.PublishMsg(m)) |
| 3619 |
rmsg, err = sub.NextMsg(time.Second) |
| 3620 |
require_NoError(t, err) |
| 3621 |
pubAck = JSPubAckResponse{} |
| 3622 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3623 |
require_NotNil(t, pubAck.Error) |
| 3624 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidBatchIDError()) |
| 3625 |
|
| 3626 |
// Publish a batch, misses start. |
| 3627 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 0, FastBatchGapFail, FastBatchOpAppend) |
| 3628 |
require_NoError(t, nc.PublishMsg(m)) |
| 3629 |
rmsg, err = sub.NextMsg(time.Second) |
| 3630 |
require_NoError(t, err) |
| 3631 |
pubAck = JSPubAckResponse{} |
| 3632 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3633 |
require_Error(t, pubAck.Error, NewJSBatchPublishUnknownBatchIDError()) |
| 3634 |
|
| 3635 |
// Publish a "batch" which immediately commits. |
| 3636 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 3637 |
require_NoError(t, nc.PublishMsg(m)) |
| 3638 |
// The PubAck comes in immediately without an intermediate BatchFlowAck. |
| 3639 |
rmsg, err = sub.NextMsg(time.Second) |
| 3640 |
require_NoError(t, err) |
| 3641 |
pubAck = JSPubAckResponse{} |
| 3642 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3643 |
require_Equal(t, pubAck.Sequence, 1) |
| 3644 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 3645 |
require_Equal(t, pubAck.BatchSize, 1) |
| 3646 |
|
| 3647 |
// Publish a batch of N messages. |
| 3648 |
for seq, batch := uint64(1), uint64(5); seq <= batch; seq++ { |
| 3649 |
m.Subject = fmt.Sprintf("foo.%d", seq) |
| 3650 |
m.Data = []byte(m.Subject) |
| 3651 |
if seq == batch { |
| 3652 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpCommit) |
| 3653 |
} else if seq == 1 { |
| 3654 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpStart) |
| 3655 |
} else { |
| 3656 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpAppend) |
| 3657 |
} |
| 3658 |
require_NoError(t, nc.PublishMsg(m)) |
| 3659 |
|
| 3660 |
// Can already pre-check receiving the first flow control message. |
| 3661 |
if seq == 1 { |
| 3662 |
rmsg, err = sub.NextMsg(time.Second) |
| 3663 |
require_NoError(t, err) |
| 3664 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"ack\",")) |
| 3665 |
var batchFlowAck BatchFlowAck |
| 3666 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3667 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 3668 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 3669 |
} |
| 3670 |
} |
| 3671 |
// Should receive the PubAck upon commit. |
| 3672 |
rmsg, err = sub.NextMsg(time.Second) |
| 3673 |
require_NoError(t, err) |
| 3674 |
pubAck = JSPubAckResponse{} |
| 3675 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3676 |
require_Equal(t, pubAck.Sequence, 6) |
| 3677 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 3678 |
require_Equal(t, pubAck.BatchSize, 5) |
| 3679 |
|
| 3680 |
// Validate stream contents. |
| 3681 |
if retention != InterestPolicy { |
| 3682 |
for i := 0; i < 6; i++ { |
| 3683 |
rsm, err := js.GetMsg("TEST", uint64(i+1)) |
| 3684 |
require_NoError(t, err) |
| 3685 |
subj := fmt.Sprintf("foo.%d", i) |
| 3686 |
require_Equal(t, rsm.Subject, subj) |
| 3687 |
require_Equal(t, string(rsm.Data), subj) |
| 3688 |
} |
| 3689 |
} |
| 3690 |
} |
| 3691 |
|
| 3692 |
for _, storage := range []StorageType{FileStorage, MemoryStorage} { |
| 3693 |
for _, retention := range []RetentionPolicy{LimitsPolicy, InterestPolicy, WorkQueuePolicy} { |
| 3694 |
for _, replicas := range []int{1, 3} { |
| 3695 |
t.Run(fmt.Sprintf("%s/%s/R%d", storage, retention, replicas), func(t *testing.T) { |
| 3696 |
test(t, storage, retention, replicas) |
| 3697 |
}) |
| 3698 |
} |
| 3699 |
} |
| 3700 |
} |
| 3701 |
} |
| 3702 |
|
| 3703 |
func TestJetStreamFastBatchPublishGapDetection(t *testing.T) { |
| 3704 |
test := func( |
| 3705 |
t *testing.T, |
| 3706 |
replicas int, |
| 3707 |
gapMode string, |
| 3708 |
) { |
| 3709 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 3710 |
defer c.shutdown() |
| 3711 |
|
| 3712 |
nc := clientConnectToServer(t, c.randomServer()) |
| 3713 |
defer nc.Close() |
| 3714 |
|
| 3715 |
var batchFlowAck BatchFlowAck |
| 3716 |
var pubAck JSPubAckResponse |
| 3717 |
|
| 3718 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3719 |
Name: "TEST", |
| 3720 |
Subjects: []string{"foo"}, |
| 3721 |
Storage: FileStorage, |
| 3722 |
Replicas: replicas, |
| 3723 |
AllowBatchPublish: true, |
| 3724 |
}) |
| 3725 |
require_NoError(t, err) |
| 3726 |
|
| 3727 |
inbox := nats.NewInbox() |
| 3728 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 3729 |
require_NoError(t, err) |
| 3730 |
defer sub.Drain() |
| 3731 |
|
| 3732 |
m := nats.NewMsg("foo") |
| 3733 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, gapMode, FastBatchOpStart) |
| 3734 |
require_NoError(t, nc.PublishMsg(m)) |
| 3735 |
rmsg, err := sub.NextMsg(time.Second) |
| 3736 |
require_NoError(t, err) |
| 3737 |
|
| 3738 |
if gapMode == "unknown" { |
| 3739 |
pubAck = JSPubAckResponse{} |
| 3740 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3741 |
require_NotNil(t, pubAck.Error) |
| 3742 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidPatternError()) |
| 3743 |
return |
| 3744 |
} |
| 3745 |
|
| 3746 |
batchFlowAck = BatchFlowAck{} |
| 3747 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3748 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 3749 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 3750 |
|
| 3751 |
// Now a message is missed and a gap should be detected. |
| 3752 |
m.Reply = generateFastBatchReply(inbox, "uuid", 3, 0, gapMode, FastBatchOpAppend) |
| 3753 |
require_NoError(t, nc.PublishMsg(m)) |
| 3754 |
rmsg, err = sub.NextMsg(time.Second) |
| 3755 |
require_NoError(t, err) |
| 3756 |
|
| 3757 |
// There will always be a flow control message with the missed sequences. |
| 3758 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"gap\",")) |
| 3759 |
var batchFlowGap BatchFlowGap |
| 3760 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 3761 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 2) |
| 3762 |
require_Equal(t, batchFlowGap.CurrentSequence, 3) |
| 3763 |
|
| 3764 |
switch gapMode { |
| 3765 |
case FastBatchGapFail: |
| 3766 |
// By default, if a gap is detected, the batch is rejected. |
| 3767 |
// A PubAck is returned with the data that has been persisted up to that point. |
| 3768 |
rmsg, err = sub.NextMsg(time.Second) |
| 3769 |
require_NoError(t, err) |
| 3770 |
pubAck = JSPubAckResponse{} |
| 3771 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3772 |
require_Equal(t, pubAck.Sequence, 1) |
| 3773 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 3774 |
require_Equal(t, pubAck.BatchSize, 1) |
| 3775 |
case FastBatchGapOk: |
| 3776 |
// If a gap is ok, the batch will continue to function. |
| 3777 |
// An EOB commit should get us the PubAck for the third message. |
| 3778 |
m.Reply = generateFastBatchReply(inbox, "uuid", 4, 0, gapMode, FastBatchOpCommitEob) |
| 3779 |
require_NoError(t, nc.PublishMsg(m)) |
| 3780 |
rmsg, err = sub.NextMsg(time.Second) |
| 3781 |
require_NoError(t, err) |
| 3782 |
pubAck = JSPubAckResponse{} |
| 3783 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3784 |
require_Equal(t, pubAck.Sequence, 2) |
| 3785 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 3786 |
require_Equal(t, pubAck.BatchSize, 3) |
| 3787 |
default: |
| 3788 |
t.Fatalf("unexpected gap mode: %q", gapMode) |
| 3789 |
} |
| 3790 |
} |
| 3791 |
|
| 3792 |
for _, replicas := range []int{1, 3} { |
| 3793 |
for _, gapMode := range []string{"fail", "ok", "unknown"} { |
| 3794 |
t.Run(fmt.Sprintf("R%d/%s", replicas, gapMode), func(t *testing.T) { |
| 3795 |
test(t, replicas, gapMode) |
| 3796 |
}) |
| 3797 |
} |
| 3798 |
} |
| 3799 |
} |
| 3800 |
|
| 3801 |
func TestJetStreamFastBatchPublishMaxUint64SequenceRejected(t *testing.T) { |
| 3802 |
test := func(t *testing.T, commitEob bool) { |
| 3803 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 3804 |
defer c.shutdown() |
| 3805 |
|
| 3806 |
nc := clientConnectToServer(t, c.randomServer()) |
| 3807 |
defer nc.Close() |
| 3808 |
|
| 3809 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3810 |
Name: "TEST", |
| 3811 |
Subjects: []string{"foo"}, |
| 3812 |
Storage: FileStorage, |
| 3813 |
Replicas: 1, |
| 3814 |
AllowBatchPublish: true, |
| 3815 |
}) |
| 3816 |
require_NoError(t, err) |
| 3817 |
|
| 3818 |
inbox := nats.NewInbox() |
| 3819 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 3820 |
require_NoError(t, err) |
| 3821 |
defer sub.Drain() |
| 3822 |
|
| 3823 |
m := nats.NewMsg("foo") |
| 3824 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 1, FastBatchGapOk, FastBatchOpStart) |
| 3825 |
require_NoError(t, nc.PublishMsg(m)) |
| 3826 |
rmsg, err := sub.NextMsg(time.Second) |
| 3827 |
require_NoError(t, err) |
| 3828 |
|
| 3829 |
var batchFlowAck BatchFlowAck |
| 3830 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3831 |
require_Equal(t, batchFlowAck.Messages, 1) |
| 3832 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 3833 |
|
| 3834 |
rmsg, err = sub.NextMsg(time.Second) |
| 3835 |
require_NoError(t, err) |
| 3836 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"ack\",")) |
| 3837 |
batchFlowAck = BatchFlowAck{} |
| 3838 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3839 |
require_Equal(t, batchFlowAck.Messages, 1) |
| 3840 |
require_Equal(t, batchFlowAck.Sequence, 1) |
| 3841 |
|
| 3842 |
m.Reply = generateFastBatchReply(inbox, "uuid", math.MaxUint64-1, 1, FastBatchGapOk, FastBatchOpAppend) |
| 3843 |
require_NoError(t, nc.PublishMsg(m)) |
| 3844 |
rmsg, err = sub.NextMsg(time.Second) |
| 3845 |
require_NoError(t, err) |
| 3846 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"gap\",")) |
| 3847 |
var batchFlowGap BatchFlowGap |
| 3848 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 3849 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 2) |
| 3850 |
require_Equal(t, batchFlowGap.CurrentSequence, uint64(math.MaxUint64-1)) |
| 3851 |
|
| 3852 |
rmsg, err = sub.NextMsg(time.Second) |
| 3853 |
require_NoError(t, err) |
| 3854 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"ack\",")) |
| 3855 |
batchFlowAck = BatchFlowAck{} |
| 3856 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3857 |
require_Equal(t, batchFlowAck.Messages, 1) |
| 3858 |
require_Equal(t, batchFlowAck.Sequence, uint64(math.MaxUint64-1)) |
| 3859 |
|
| 3860 |
// math.MaxUint64 must be rejected so b.lseq cannot be jumped to a value |
| 3861 |
// where the next b.lseq++ would wrap to zero. |
| 3862 |
opCommit := FastBatchOpCommit |
| 3863 |
if commitEob { |
| 3864 |
opCommit = FastBatchOpCommitEob |
| 3865 |
} |
| 3866 |
m.Reply = generateFastBatchReply(inbox, "uuid", math.MaxUint64, 1, FastBatchGapOk, opCommit) |
| 3867 |
require_NoError(t, nc.PublishMsg(m)) |
| 3868 |
|
| 3869 |
rmsg, err = sub.NextMsg(time.Second) |
| 3870 |
require_NoError(t, err) |
| 3871 |
var pubAck JSPubAckResponse |
| 3872 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3873 |
require_NotNil(t, pubAck.Error) |
| 3874 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidPatternError()) |
| 3875 |
} |
| 3876 |
|
| 3877 |
t.Run("Commit", func(t *testing.T) { test(t, false) }) |
| 3878 |
t.Run("CommitEob", func(t *testing.T) { test(t, true) }) |
| 3879 |
} |
| 3880 |
|
| 3881 |
func TestJetStreamFastBatchPublishFlowControl(t *testing.T) { |
| 3882 |
templ := ` |
| 3883 |
listen: 127.0.0.1:-1 |
| 3884 |
server_name: %s |
| 3885 |
jetstream: { |
| 3886 |
max_mem_store: 2GB |
| 3887 |
max_file_store: 2GB |
| 3888 |
store_dir: '%s' |
| 3889 |
limits { |
| 3890 |
batch { |
| 3891 |
timeout: 750ms |
| 3892 |
} |
| 3893 |
} |
| 3894 |
} |
| 3895 |
|
| 3896 |
leaf { |
| 3897 |
listen: 127.0.0.1:-1 |
| 3898 |
} |
| 3899 |
|
| 3900 |
cluster { |
| 3901 |
name: %s |
| 3902 |
listen: 127.0.0.1:%d |
| 3903 |
routes = [%s] |
| 3904 |
} |
| 3905 |
|
| 3906 |
# For access to system account. |
| 3907 |
accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } } |
| 3908 |
` |
| 3909 |
|
| 3910 |
test := func(t *testing.T, replicas int) { |
| 3911 |
c := createJetStreamClusterWithTemplate(t, templ, "R3S", 3) |
| 3912 |
defer c.shutdown() |
| 3913 |
|
| 3914 |
nc := clientConnectToServer(t, c.randomServer()) |
| 3915 |
defer nc.Close() |
| 3916 |
|
| 3917 |
var batchFlowAck BatchFlowAck |
| 3918 |
var pubAck JSPubAckResponse |
| 3919 |
|
| 3920 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 3921 |
Name: "TEST", |
| 3922 |
Subjects: []string{"foo"}, |
| 3923 |
Storage: FileStorage, |
| 3924 |
Replicas: replicas, |
| 3925 |
AllowBatchPublish: true, |
| 3926 |
}) |
| 3927 |
require_NoError(t, err) |
| 3928 |
|
| 3929 |
inbox := nats.NewInbox() |
| 3930 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 3931 |
require_NoError(t, err) |
| 3932 |
defer sub.Drain() |
| 3933 |
|
| 3934 |
m := nats.NewMsg("foo") |
| 3935 |
lseq := uint64(5) |
| 3936 |
for seq := uint64(1); seq <= lseq; seq++ { |
| 3937 |
if seq == lseq { |
| 3938 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpCommit) |
| 3939 |
} else if seq == 1 { |
| 3940 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpStart) |
| 3941 |
} else { |
| 3942 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpAppend) |
| 3943 |
} |
| 3944 |
require_NoError(t, nc.PublishMsg(m)) |
| 3945 |
|
| 3946 |
if seq == 1 || seq%2 == 0 { |
| 3947 |
rmsg, err := sub.NextMsg(time.Second) |
| 3948 |
require_NoError(t, err) |
| 3949 |
batchFlowAck = BatchFlowAck{} |
| 3950 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 3951 |
if seq > 1 { |
| 3952 |
require_Equal(t, batchFlowAck.Sequence, seq) |
| 3953 |
} else { |
| 3954 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 3955 |
} |
| 3956 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 3957 |
} else if seq == lseq { |
| 3958 |
rmsg, err := sub.NextMsg(time.Second) |
| 3959 |
require_NoError(t, err) |
| 3960 |
pubAck = JSPubAckResponse{} |
| 3961 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 3962 |
require_Equal(t, pubAck.Sequence, 5) |
| 3963 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 3964 |
require_Equal(t, pubAck.BatchSize, 5) |
| 3965 |
} |
| 3966 |
|
| 3967 |
// Sleep between messages such that we'll go over the batch timeout. |
| 3968 |
// New messages being received should receive the timer. |
| 3969 |
time.Sleep(250 * time.Millisecond) |
| 3970 |
} |
| 3971 |
} |
| 3972 |
|
| 3973 |
for _, replicas := range []int{1, 3} { |
| 3974 |
t.Run(fmt.Sprintf("R%d", replicas), func(t *testing.T) { |
| 3975 |
test(t, replicas) |
| 3976 |
}) |
| 3977 |
} |
| 3978 |
} |
| 3979 |
|
| 3980 |
func TestJetStreamFastBatchInitAckMessages(t *testing.T) { |
| 3981 |
batches := &batching{} |
| 3982 |
mset := &stream{srv: &Server{opts: &Options{}}} |
| 3983 |
stopTimer := func(b *fastBatch) { b.timer.Stop() } |
| 3984 |
|
| 3985 |
// First batch, alone in the map: should get full window clamped to client max. |
| 3986 |
b1 := batches.newFastBatch(mset, "b1", false, 1000) |
| 3987 |
stopTimer(b1) |
| 3988 |
require_Equal(t, b1.ackMessages, 500) |
| 3989 |
|
| 3990 |
// Second concurrent batch: must start at 1 to coordinate with sibling. |
| 3991 |
b2 := batches.newFastBatch(mset, "b2", false, 1000) |
| 3992 |
stopTimer(b2) |
| 3993 |
require_Equal(t, b2.ackMessages, 1) |
| 3994 |
|
| 3995 |
// Resetting b1 while b2 still exists: also throttled to 1. |
| 3996 |
b1.timer.Reset(time.Hour) // Need to reset, otherwise below is a noop. |
| 3997 |
batches.fastBatchReset(mset, "b1", b1) |
| 3998 |
stopTimer(b1) |
| 3999 |
require_Equal(t, b1.ackMessages, 1) |
| 4000 |
|
| 4001 |
// Remove the sibling; a reset now returns to the full window. |
| 4002 |
stopTimer(b2) |
| 4003 |
delete(batches.fast, "b2") |
| 4004 |
batches.fastBatchInit(b1) |
| 4005 |
require_Equal(t, b1.ackMessages, 500) |
| 4006 |
|
| 4007 |
// A client-specified max below 500 is respected. |
| 4008 |
stopTimer(b1) |
| 4009 |
delete(batches.fast, "b1") |
| 4010 |
b3 := batches.newFastBatch(mset, "b3", false, 50) |
| 4011 |
stopTimer(b3) |
| 4012 |
require_Equal(t, b3.ackMessages, 50) |
| 4013 |
|
| 4014 |
// And throttled to 1 when a sibling is present. |
| 4015 |
b4 := batches.newFastBatch(mset, "b4", false, 50) |
| 4016 |
stopTimer(b4) |
| 4017 |
require_Equal(t, b4.ackMessages, 1) |
| 4018 |
} |
| 4019 |
|
| 4020 |
func TestJetStreamFastBatchPublishSourceAndMirror(t *testing.T) { |
| 4021 |
test := func(t *testing.T, replicas int) { |
| 4022 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4023 |
defer c.shutdown() |
| 4024 |
|
| 4025 |
nc, js := jsClientConnect(t, c.randomServer()) |
| 4026 |
defer nc.Close() |
| 4027 |
|
| 4028 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4029 |
Name: "TEST", |
| 4030 |
Subjects: []string{"foo"}, |
| 4031 |
Storage: FileStorage, |
| 4032 |
AllowBatchPublish: true, |
| 4033 |
Replicas: replicas, |
| 4034 |
}) |
| 4035 |
require_NoError(t, err) |
| 4036 |
|
| 4037 |
for seq := uint64(1); seq <= 3; seq++ { |
| 4038 |
m := nats.NewMsg("foo") |
| 4039 |
if seq == 1 { |
| 4040 |
m.Reply = generateFastBatchReply("", "uuid", seq, 10, FastBatchGapFail, FastBatchOpStart) |
| 4041 |
} else { |
| 4042 |
m.Reply = generateFastBatchReply("", "uuid", seq, 10, FastBatchGapFail, FastBatchOpAppend) |
| 4043 |
} |
| 4044 |
commit := seq == 3 |
| 4045 |
if !commit { |
| 4046 |
require_NoError(t, nc.PublishMsg(m)) |
| 4047 |
continue |
| 4048 |
} |
| 4049 |
|
| 4050 |
inbox := nats.NewInbox() |
| 4051 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4052 |
require_NoError(t, err) |
| 4053 |
defer sub.Drain() |
| 4054 |
|
| 4055 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 10, FastBatchGapFail, FastBatchOpCommit) |
| 4056 |
require_NoError(t, nc.PublishMsg(m)) |
| 4057 |
rmsg, err := sub.NextMsg(time.Second) |
| 4058 |
require_NoError(t, err) |
| 4059 |
var pubAck JSPubAckResponse |
| 4060 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4061 |
require_Equal(t, pubAck.Sequence, 3) |
| 4062 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4063 |
require_Equal(t, pubAck.BatchSize, 3) |
| 4064 |
} |
| 4065 |
|
| 4066 |
require_NoError(t, js.DeleteMsg("TEST", 2)) |
| 4067 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 4068 |
return checkState(t, c, globalAccountName, "TEST") |
| 4069 |
}) |
| 4070 |
|
| 4071 |
// Mirror can source batched messages but can't do fast batching itself. |
| 4072 |
_, err = jsStreamCreate(t, nc, &StreamConfig{ |
| 4073 |
Name: "M-no-batch", |
| 4074 |
Storage: FileStorage, |
| 4075 |
Mirror: &StreamSource{Name: "TEST"}, |
| 4076 |
Replicas: replicas, |
| 4077 |
AllowBatchPublish: true, |
| 4078 |
}) |
| 4079 |
require_Error(t, err, NewJSMirrorWithBatchPublishError()) |
| 4080 |
|
| 4081 |
_, err = js.AddStream(&nats.StreamConfig{ |
| 4082 |
Name: "M", |
| 4083 |
Mirror: &nats.StreamSource{Name: "TEST"}, |
| 4084 |
Replicas: replicas, |
| 4085 |
}) |
| 4086 |
require_NoError(t, err) |
| 4087 |
|
| 4088 |
_, err = jsStreamCreate(t, nc, &StreamConfig{ |
| 4089 |
Name: "S", |
| 4090 |
Storage: FileStorage, |
| 4091 |
Sources: []*StreamSource{{Name: "TEST"}}, |
| 4092 |
Replicas: replicas, |
| 4093 |
AllowBatchPublish: true, |
| 4094 |
}) |
| 4095 |
require_NoError(t, err) |
| 4096 |
|
| 4097 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 4098 |
for _, name := range []string{"M", "S"} { |
| 4099 |
if si, err := js.StreamInfo(name); err != nil { |
| 4100 |
return err |
| 4101 |
} else if si.State.Msgs != 2 { |
| 4102 |
return fmt.Errorf("expected 2 messages for stream %q, got %d", name, si.State.Msgs) |
| 4103 |
} |
| 4104 |
} |
| 4105 |
return nil |
| 4106 |
}) |
| 4107 |
|
| 4108 |
// Ensure the batching headers were removed when ingested into the source/mirror. |
| 4109 |
rsm, err := js.GetMsg("M", 1) |
| 4110 |
require_NoError(t, err) |
| 4111 |
require_Len(t, len(rsm.Header), 0) |
| 4112 |
|
| 4113 |
rsm, err = js.GetMsg("M", 3) |
| 4114 |
require_NoError(t, err) |
| 4115 |
require_Len(t, len(rsm.Header), 0) |
| 4116 |
|
| 4117 |
rsm, err = js.GetMsg("S", 1) |
| 4118 |
require_NoError(t, err) |
| 4119 |
require_Len(t, len(rsm.Header), 1) |
| 4120 |
require_Equal(t, rsm.Header.Get(JSStreamSource), "TEST 1 > > foo") |
| 4121 |
|
| 4122 |
rsm, err = js.GetMsg("S", 2) |
| 4123 |
require_NoError(t, err) |
| 4124 |
require_Len(t, len(rsm.Header), 1) |
| 4125 |
require_Equal(t, rsm.Header.Get(JSStreamSource), "TEST 3 > > foo") |
| 4126 |
} |
| 4127 |
|
| 4128 |
t.Run("R1", func(t *testing.T) { test(t, 1) }) |
| 4129 |
t.Run("R3", func(t *testing.T) { test(t, 3) }) |
| 4130 |
} |
| 4131 |
|
| 4132 |
func TestJetStreamFastBatchPublishDuplicates(t *testing.T) { |
| 4133 |
test := func(t *testing.T, replicas int) { |
| 4134 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4135 |
defer c.shutdown() |
| 4136 |
|
| 4137 |
nc := clientConnectToServer(t, c.randomServer()) |
| 4138 |
defer nc.Close() |
| 4139 |
|
| 4140 |
var batchFlowAck BatchFlowAck |
| 4141 |
var pubAck JSPubAckResponse |
| 4142 |
|
| 4143 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4144 |
Name: "TEST", |
| 4145 |
Subjects: []string{"foo"}, |
| 4146 |
Storage: FileStorage, |
| 4147 |
Replicas: replicas, |
| 4148 |
AllowBatchPublish: true, |
| 4149 |
}) |
| 4150 |
require_NoError(t, err) |
| 4151 |
|
| 4152 |
inbox := nats.NewInbox() |
| 4153 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4154 |
require_NoError(t, err) |
| 4155 |
defer sub.Drain() |
| 4156 |
|
| 4157 |
// Simulate storing a duplicate message. |
| 4158 |
msgId := "msgId" |
| 4159 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 4160 |
require_NotNil(t, sl) |
| 4161 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 4162 |
require_NoError(t, err) |
| 4163 |
dseq := uint64(1) |
| 4164 |
// If replicated, we simulate it being proposed still. |
| 4165 |
if replicas > 1 { |
| 4166 |
dseq = 0 |
| 4167 |
} |
| 4168 |
mset.storeMsgId(&ddentry{msgId, dseq, 0}) |
| 4169 |
|
| 4170 |
// Publish a "batch" which immediately commits. |
| 4171 |
m := nats.NewMsg("foo") |
| 4172 |
m.Header.Set(JSMsgId, msgId) |
| 4173 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 4174 |
require_NoError(t, nc.PublishMsg(m)) |
| 4175 |
// The PubAck comes in immediately without an intermediate BatchFlowAck. |
| 4176 |
rmsg, err := sub.NextMsg(time.Second) |
| 4177 |
require_NoError(t, err) |
| 4178 |
pubAck = JSPubAckResponse{} |
| 4179 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4180 |
if replicas == 1 { |
| 4181 |
require_True(t, pubAck.Error == nil) |
| 4182 |
require_Equal(t, pubAck.Sequence, 1) |
| 4183 |
require_True(t, pubAck.Duplicate) |
| 4184 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4185 |
require_Equal(t, pubAck.BatchSize, 1) |
| 4186 |
} else { |
| 4187 |
require_True(t, pubAck.Error != nil) |
| 4188 |
require_Equal(t, pubAck.Error.Error(), NewJSStreamDuplicateMessageConflictError().Error()) |
| 4189 |
} |
| 4190 |
mset.mu.RLock() |
| 4191 |
batches := mset.batches |
| 4192 |
batches.mu.Lock() |
| 4193 |
fastBatches := len(mset.batches.fast) |
| 4194 |
batches.mu.Unlock() |
| 4195 |
mset.mu.RUnlock() |
| 4196 |
require_Len(t, fastBatches, 0) |
| 4197 |
|
| 4198 |
// Flow setting so we get one flow control message below. |
| 4199 |
flow := uint16(3) |
| 4200 |
|
| 4201 |
// Publish a batch of N messages that are all duplicates, we expect |
| 4202 |
// to receive both a flow control message and PubAck. |
| 4203 |
for seq, batch := uint64(1), uint64(5); seq <= batch; seq++ { |
| 4204 |
if seq == batch { |
| 4205 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, flow, FastBatchGapFail, FastBatchOpCommit) |
| 4206 |
} else if seq == 1 { |
| 4207 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, flow, FastBatchGapFail, FastBatchOpStart) |
| 4208 |
} else { |
| 4209 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, flow, FastBatchGapFail, FastBatchOpAppend) |
| 4210 |
} |
| 4211 |
require_NoError(t, nc.PublishMsg(m)) |
| 4212 |
|
| 4213 |
// Can already pre-check receiving the first flow control message. |
| 4214 |
if seq == 1 { |
| 4215 |
rmsg, err = sub.NextMsg(time.Second) |
| 4216 |
require_NoError(t, err) |
| 4217 |
batchFlowAck = BatchFlowAck{} |
| 4218 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4219 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 4220 |
require_Equal(t, batchFlowAck.Messages, flow) |
| 4221 |
} |
| 4222 |
|
| 4223 |
// Expect one flow control message for this batch. |
| 4224 |
if seq%uint64(flow) == 0 { |
| 4225 |
rmsg, err = sub.NextMsg(time.Second) |
| 4226 |
require_NoError(t, err) |
| 4227 |
batchFlowAck = BatchFlowAck{} |
| 4228 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4229 |
require_Equal(t, batchFlowAck.Sequence, 3) |
| 4230 |
require_Equal(t, batchFlowAck.Messages, flow) |
| 4231 |
} |
| 4232 |
} |
| 4233 |
// Should receive the PubAck upon commit. |
| 4234 |
rmsg, err = sub.NextMsg(time.Second) |
| 4235 |
require_NoError(t, err) |
| 4236 |
pubAck = JSPubAckResponse{} |
| 4237 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4238 |
require_True(t, pubAck.Error == nil) |
| 4239 |
require_Equal(t, pubAck.Sequence, 0) |
| 4240 |
require_False(t, pubAck.Duplicate) |
| 4241 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4242 |
require_Equal(t, pubAck.BatchSize, 5) |
| 4243 |
|
| 4244 |
mset.mu.RLock() |
| 4245 |
batches = mset.batches |
| 4246 |
batches.mu.Lock() |
| 4247 |
fastBatches = len(mset.batches.fast) |
| 4248 |
batches.mu.Unlock() |
| 4249 |
mset.mu.RUnlock() |
| 4250 |
require_Len(t, fastBatches, 0) |
| 4251 |
} |
| 4252 |
|
| 4253 |
for _, replicas := range []int{1, 3} { |
| 4254 |
t.Run(fmt.Sprintf("R%d", replicas), func(t *testing.T) { |
| 4255 |
test(t, replicas) |
| 4256 |
}) |
| 4257 |
} |
| 4258 |
} |
| 4259 |
|
| 4260 |
func TestJetStreamFastBatchPublishDuplicatesCluster(t *testing.T) { |
| 4261 |
s := RunBasicJetStreamServer(t) |
| 4262 |
defer s.Shutdown() |
| 4263 |
|
| 4264 |
nc := clientConnectToServer(t, s) |
| 4265 |
defer nc.Close() |
| 4266 |
|
| 4267 |
var batchFlowAck BatchFlowAck |
| 4268 |
var pubAck JSPubAckResponse |
| 4269 |
|
| 4270 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4271 |
Name: "TEST", |
| 4272 |
Subjects: []string{"foo"}, |
| 4273 |
Storage: FileStorage, |
| 4274 |
AllowBatchPublish: true, |
| 4275 |
}) |
| 4276 |
require_NoError(t, err) |
| 4277 |
|
| 4278 |
inbox := nats.NewInbox() |
| 4279 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4280 |
require_NoError(t, err) |
| 4281 |
defer sub.Drain() |
| 4282 |
|
| 4283 |
msgId := "msgId" |
| 4284 |
m := nats.NewMsg("foo") |
| 4285 |
m.Header.Set(JSMsgId, msgId) |
| 4286 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 4, FastBatchGapFail, FastBatchOpStart) |
| 4287 |
require_NoError(t, nc.PublishMsg(m)) |
| 4288 |
rmsg, err := sub.NextMsg(time.Second) |
| 4289 |
require_NoError(t, err) |
| 4290 |
batchFlowAck = BatchFlowAck{} |
| 4291 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4292 |
require_Equal(t, batchFlowAck.Messages, 4) |
| 4293 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 4294 |
|
| 4295 |
mset, err := s.globalAccount().lookupStream("TEST") |
| 4296 |
require_NoError(t, err) |
| 4297 |
mset.mu.Lock() |
| 4298 |
batches := mset.batches |
| 4299 |
mset.mu.Unlock() |
| 4300 |
require_NotNil(t, batches) |
| 4301 |
|
| 4302 |
batches.mu.Lock() |
| 4303 |
b := batches.fast["uuid"] |
| 4304 |
|
| 4305 |
// Simulate a pending message that will take some time to be processed due to replication. |
| 4306 |
b.lseq++ |
| 4307 |
b.pending++ |
| 4308 |
|
| 4309 |
// Simulate a bunch of messages being marked as duplicate and not being accounted for. |
| 4310 |
// These two would trigger the first ack. |
| 4311 |
b.lseq += 2 |
| 4312 |
// These would trigger the second ack. |
| 4313 |
b.lseq += 4 |
| 4314 |
|
| 4315 |
// Now simulate the second message we published is processed. |
| 4316 |
reply := generateFastBatchReply(inbox, "uuid", 2, 4, FastBatchGapFail, FastBatchOpAppend) |
| 4317 |
batches.fastBatchRegisterSequences(mset, reply, 2, true, &FastBatch{id: "uuid", seq: 2}) |
| 4318 |
batches.mu.Unlock() |
| 4319 |
|
| 4320 |
// Normally we'd receive two flow control messages, but since both were triggered due to |
| 4321 |
// the above process finishing, we only send one out to save bandwidth. |
| 4322 |
rmsg, err = sub.NextMsg(time.Second) |
| 4323 |
require_NoError(t, err) |
| 4324 |
batchFlowAck = BatchFlowAck{} |
| 4325 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4326 |
require_Equal(t, batchFlowAck.Messages, 4) |
| 4327 |
require_Equal(t, batchFlowAck.Sequence, 8) |
| 4328 |
|
| 4329 |
// Now commit the batch (but this message is also a duplicate). |
| 4330 |
m.Reply = generateFastBatchReply(inbox, "uuid", 9, 0, FastBatchGapFail, FastBatchOpCommit) |
| 4331 |
require_NoError(t, nc.PublishMsg(m)) |
| 4332 |
rmsg, err = sub.NextMsg(time.Second) |
| 4333 |
require_NoError(t, err) |
| 4334 |
pubAck = JSPubAckResponse{} |
| 4335 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4336 |
require_True(t, pubAck.Error == nil) |
| 4337 |
require_Equal(t, pubAck.Sequence, 2) |
| 4338 |
require_False(t, pubAck.Duplicate) |
| 4339 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4340 |
require_Equal(t, pubAck.BatchSize, 9) |
| 4341 |
} |
| 4342 |
|
| 4343 |
func TestJetStreamFastBatchPublishDuplicatesEobCommit(t *testing.T) { |
| 4344 |
test := func(t *testing.T, replicas int) { |
| 4345 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4346 |
defer c.shutdown() |
| 4347 |
|
| 4348 |
nc := clientConnectToServer(t, c.randomServer()) |
| 4349 |
defer nc.Close() |
| 4350 |
|
| 4351 |
var batchFlowAck BatchFlowAck |
| 4352 |
var pubAck JSPubAckResponse |
| 4353 |
|
| 4354 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4355 |
Name: "TEST", |
| 4356 |
Subjects: []string{"foo"}, |
| 4357 |
Storage: FileStorage, |
| 4358 |
Replicas: replicas, |
| 4359 |
AllowBatchPublish: true, |
| 4360 |
}) |
| 4361 |
require_NoError(t, err) |
| 4362 |
|
| 4363 |
inbox := nats.NewInbox() |
| 4364 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4365 |
require_NoError(t, err) |
| 4366 |
defer sub.Drain() |
| 4367 |
|
| 4368 |
msgId := "msgId" |
| 4369 |
m := nats.NewMsg("foo") |
| 4370 |
m.Header.Set(JSMsgId, msgId) |
| 4371 |
for seq := uint64(1); seq <= 2; seq++ { |
| 4372 |
if seq == 1 { |
| 4373 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpStart) |
| 4374 |
} else { |
| 4375 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpAppend) |
| 4376 |
} |
| 4377 |
require_NoError(t, nc.PublishMsg(m)) |
| 4378 |
} |
| 4379 |
rmsg, err := sub.NextMsg(time.Second) |
| 4380 |
require_NoError(t, err) |
| 4381 |
batchFlowAck = BatchFlowAck{} |
| 4382 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4383 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 4384 |
|
| 4385 |
m.Reply = generateFastBatchReply(inbox, "uuid", 3, 0, FastBatchGapFail, FastBatchOpCommitEob) |
| 4386 |
require_NoError(t, nc.PublishMsg(m)) |
| 4387 |
rmsg, err = sub.NextMsg(time.Second) |
| 4388 |
require_NoError(t, err) |
| 4389 |
pubAck = JSPubAckResponse{} |
| 4390 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4391 |
require_True(t, pubAck.Error == nil) |
| 4392 |
require_Equal(t, pubAck.Sequence, 1) |
| 4393 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4394 |
require_Equal(t, pubAck.BatchSize, 2) |
| 4395 |
} |
| 4396 |
|
| 4397 |
for _, replicas := range []int{1, 3} { |
| 4398 |
t.Run(fmt.Sprintf("R%d", replicas), func(t *testing.T) { |
| 4399 |
test(t, replicas) |
| 4400 |
}) |
| 4401 |
} |
| 4402 |
} |
| 4403 |
|
| 4404 |
func TestJetStreamFastBatchPublishHeaderCheckError(t *testing.T) { |
| 4405 |
test := func(t *testing.T, replicas int, gapMode string) { |
| 4406 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4407 |
defer c.shutdown() |
| 4408 |
|
| 4409 |
nc := clientConnectToServer(t, c.randomServer()) |
| 4410 |
defer nc.Close() |
| 4411 |
|
| 4412 |
var batchFlowAck BatchFlowAck |
| 4413 |
var pubAck JSPubAckResponse |
| 4414 |
|
| 4415 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4416 |
Name: "TEST", |
| 4417 |
Subjects: []string{"foo"}, |
| 4418 |
Storage: FileStorage, |
| 4419 |
Replicas: replicas, |
| 4420 |
AllowBatchPublish: true, |
| 4421 |
}) |
| 4422 |
require_NoError(t, err) |
| 4423 |
|
| 4424 |
inbox := nats.NewInbox() |
| 4425 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4426 |
require_NoError(t, err) |
| 4427 |
defer sub.Drain() |
| 4428 |
|
| 4429 |
// Send the first message. |
| 4430 |
m := nats.NewMsg("foo") |
| 4431 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, gapMode, FastBatchOpStart) |
| 4432 |
require_NoError(t, nc.PublishMsg(m)) |
| 4433 |
|
| 4434 |
// Add a header that will require returning an error. |
| 4435 |
m.Header.Set(JSExpectedLastSeq, "100") |
| 4436 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 0, gapMode, FastBatchOpAppend) |
| 4437 |
require_NoError(t, nc.PublishMsg(m)) |
| 4438 |
|
| 4439 |
// The first message triggered the initial flow control message. |
| 4440 |
rmsg, err := sub.NextMsg(time.Second) |
| 4441 |
require_NoError(t, err) |
| 4442 |
batchFlowAck = BatchFlowAck{} |
| 4443 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4444 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 4445 |
|
| 4446 |
// The second message should always report the error based on the header. |
| 4447 |
// But it should report about this error on that sequence. |
| 4448 |
rmsg, err = sub.NextMsg(time.Second) |
| 4449 |
require_NoError(t, err) |
| 4450 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"err\",")) |
| 4451 |
var batchFlowErr BatchFlowErr |
| 4452 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowErr)) |
| 4453 |
require_Equal(t, batchFlowErr.Sequence, 2) |
| 4454 |
require_True(t, batchFlowErr.Error != nil) |
| 4455 |
require_Equal(t, batchFlowErr.Error.Error(), NewJSStreamWrongLastSequenceError(1).Error()) |
| 4456 |
|
| 4457 |
switch gapMode { |
| 4458 |
case FastBatchGapFail: |
| 4459 |
// Nothing to do, we simply wait for the PubAck below. |
| 4460 |
break |
| 4461 |
case FastBatchGapOk: |
| 4462 |
// Commit the batch. |
| 4463 |
m.Header.Del(JSExpectedLastSeq) |
| 4464 |
m.Reply = generateFastBatchReply(inbox, "uuid", 3, 0, gapMode, FastBatchOpCommitEob) |
| 4465 |
require_NoError(t, nc.PublishMsg(m)) |
| 4466 |
default: |
| 4467 |
t.Fatalf("Unexpected gap mode: %q", gapMode) |
| 4468 |
} |
| 4469 |
|
| 4470 |
// We always expect a PubAck containing the last persisted message data. |
| 4471 |
rmsg, err = sub.NextMsg(time.Second) |
| 4472 |
require_NoError(t, err) |
| 4473 |
pubAck = JSPubAckResponse{} |
| 4474 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4475 |
require_True(t, pubAck.Error == nil) |
| 4476 |
require_Equal(t, pubAck.Sequence, 1) |
| 4477 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4478 |
switch { |
| 4479 |
case gapMode == FastBatchGapFail: |
| 4480 |
require_Equal(t, pubAck.BatchSize, 1) |
| 4481 |
case gapMode == FastBatchGapOk: |
| 4482 |
require_Equal(t, pubAck.BatchSize, 2) |
| 4483 |
default: |
| 4484 |
t.Fatalf("Unexpected gap mode: %q", gapMode) |
| 4485 |
} |
| 4486 |
} |
| 4487 |
|
| 4488 |
for _, replicas := range []int{1, 3} { |
| 4489 |
for _, gapMode := range []string{FastBatchGapFail, FastBatchGapOk} { |
| 4490 |
t.Run(fmt.Sprintf("R%d/%s", replicas, gapMode), func(t *testing.T) { |
| 4491 |
test(t, replicas, gapMode) |
| 4492 |
}) |
| 4493 |
} |
| 4494 |
} |
| 4495 |
} |
| 4496 |
|
| 4497 |
func TestJetStreamFastBatchPublishHeaderCheckErrorOnCommit(t *testing.T) { |
| 4498 |
test := func(t *testing.T, replicas int, gapMode string, gap bool) { |
| 4499 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4500 |
defer c.shutdown() |
| 4501 |
|
| 4502 |
nc := clientConnectToServer(t, c.randomServer()) |
| 4503 |
defer nc.Close() |
| 4504 |
|
| 4505 |
var batchFlowAck BatchFlowAck |
| 4506 |
var pubAck JSPubAckResponse |
| 4507 |
|
| 4508 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4509 |
Name: "TEST", |
| 4510 |
Subjects: []string{"foo"}, |
| 4511 |
Storage: FileStorage, |
| 4512 |
Replicas: replicas, |
| 4513 |
AllowBatchPublish: true, |
| 4514 |
}) |
| 4515 |
require_NoError(t, err) |
| 4516 |
|
| 4517 |
inbox := nats.NewInbox() |
| 4518 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4519 |
require_NoError(t, err) |
| 4520 |
defer sub.Drain() |
| 4521 |
|
| 4522 |
// Send the first message. |
| 4523 |
m := nats.NewMsg("foo") |
| 4524 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, gapMode, FastBatchOpStart) |
| 4525 |
require_NoError(t, nc.PublishMsg(m)) |
| 4526 |
|
| 4527 |
// The first message triggered the initial flow control message. |
| 4528 |
rmsg, err := sub.NextMsg(time.Second) |
| 4529 |
require_NoError(t, err) |
| 4530 |
batchFlowAck = BatchFlowAck{} |
| 4531 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4532 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 4533 |
|
| 4534 |
// Now commit the batch, but have the commit message itself fail the header checks. |
| 4535 |
commitSeq := uint64(2) |
| 4536 |
if gap { |
| 4537 |
commitSeq = 3 |
| 4538 |
} |
| 4539 |
m.Header.Set(JSExpectedLastSeq, "100") |
| 4540 |
m.Reply = generateFastBatchReply(inbox, "uuid", commitSeq, 0, gapMode, FastBatchOpCommit) |
| 4541 |
require_NoError(t, nc.PublishMsg(m)) |
| 4542 |
|
| 4543 |
// A forward gap is always reported first. |
| 4544 |
if gap { |
| 4545 |
rmsg, err = sub.NextMsg(time.Second) |
| 4546 |
require_NoError(t, err) |
| 4547 |
var batchFlowGap BatchFlowGap |
| 4548 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 4549 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 2) |
| 4550 |
require_Equal(t, batchFlowGap.CurrentSequence, 3) |
| 4551 |
} |
| 4552 |
|
| 4553 |
// The commit message should report the error based on the header. |
| 4554 |
rmsg, err = sub.NextMsg(time.Second) |
| 4555 |
require_NoError(t, err) |
| 4556 |
require_True(t, strings.HasPrefix(string(rmsg.Data), "{\"type\":\"err\",")) |
| 4557 |
var batchFlowErr BatchFlowErr |
| 4558 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowErr)) |
| 4559 |
require_Equal(t, batchFlowErr.Sequence, commitSeq) |
| 4560 |
require_True(t, batchFlowErr.Error != nil) |
| 4561 |
require_Equal(t, batchFlowErr.Error.Error(), NewJSStreamWrongLastSequenceError(1).Error()) |
| 4562 |
|
| 4563 |
// Since the commit message errored, the commit must still complete and a PubAck |
| 4564 |
// must be sent containing the last persisted message data. Otherwise, the batch |
| 4565 |
// would be stranded; no PubAck, the cleanup timer stopped, and inflight accounting leaked. |
| 4566 |
rmsg, err = sub.NextMsg(time.Second) |
| 4567 |
require_NoError(t, err) |
| 4568 |
pubAck = JSPubAckResponse{} |
| 4569 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4570 |
require_True(t, pubAck.Error == nil) |
| 4571 |
require_Equal(t, pubAck.Sequence, 1) |
| 4572 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4573 |
// The batch size reflects the last accepted batch sequence, which includes skipped gaps. |
| 4574 |
require_Equal(t, pubAck.BatchSize, commitSeq-1) |
| 4575 |
|
| 4576 |
// The batch must also be unregistered and not leak inflight accounting. |
| 4577 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 4578 |
require_NotNil(t, sl) |
| 4579 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 4580 |
require_NoError(t, err) |
| 4581 |
mset.mu.RLock() |
| 4582 |
batches := mset.batches |
| 4583 |
mset.mu.RUnlock() |
| 4584 |
require_NotNil(t, batches) |
| 4585 |
checkFor(t, 2*time.Second, 100*time.Millisecond, func() error { |
| 4586 |
batches.mu.Lock() |
| 4587 |
fastBatches := len(batches.fast) |
| 4588 |
batches.mu.Unlock() |
| 4589 |
if fastBatches != 0 { |
| 4590 |
return fmt.Errorf("expected no inflight fast batches, got %d", fastBatches) |
| 4591 |
} |
| 4592 |
return nil |
| 4593 |
}) |
| 4594 |
} |
| 4595 |
|
| 4596 |
for _, replicas := range []int{1, 3} { |
| 4597 |
for _, gapMode := range []string{FastBatchGapFail, FastBatchGapOk} { |
| 4598 |
t.Run(fmt.Sprintf("R%d/%s", replicas, gapMode), func(t *testing.T) { |
| 4599 |
test(t, replicas, gapMode, false) |
| 4600 |
}) |
| 4601 |
} |
| 4602 |
// A forward gap on the commit message is only allowed in gap-ok mode. |
| 4603 |
t.Run(fmt.Sprintf("R%d/gap/%s", replicas, FastBatchGapOk), func(t *testing.T) { |
| 4604 |
test(t, replicas, FastBatchGapOk, true) |
| 4605 |
}) |
| 4606 |
} |
| 4607 |
} |
| 4608 |
|
| 4609 |
func TestJetStreamFastBatchPublishPing(t *testing.T) { |
| 4610 |
s := RunBasicJetStreamServer(t) |
| 4611 |
defer s.Shutdown() |
| 4612 |
|
| 4613 |
nc := clientConnectToServer(t, s) |
| 4614 |
defer nc.Close() |
| 4615 |
|
| 4616 |
var batchFlowAck BatchFlowAck |
| 4617 |
var pubAck JSPubAckResponse |
| 4618 |
|
| 4619 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4620 |
Name: "TEST", |
| 4621 |
Subjects: []string{"foo"}, |
| 4622 |
Storage: FileStorage, |
| 4623 |
AllowBatchPublish: true, |
| 4624 |
}) |
| 4625 |
require_NoError(t, err) |
| 4626 |
|
| 4627 |
inbox := nats.NewInbox() |
| 4628 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4629 |
require_NoError(t, err) |
| 4630 |
defer sub.Drain() |
| 4631 |
|
| 4632 |
// Send the first message. |
| 4633 |
m := nats.NewMsg("foo") |
| 4634 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 2, FastBatchGapOk, FastBatchOpStart) |
| 4635 |
require_NoError(t, nc.PublishMsg(m)) |
| 4636 |
rmsg, err := sub.NextMsg(time.Second) |
| 4637 |
require_NoError(t, err) |
| 4638 |
batchFlowAck = BatchFlowAck{} |
| 4639 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4640 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4641 |
|
| 4642 |
// Send the second message that will trigger the flow control message. |
| 4643 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 2, FastBatchGapOk, FastBatchOpAppend) |
| 4644 |
require_NoError(t, nc.PublishMsg(m)) |
| 4645 |
rmsg, err = sub.NextMsg(time.Second) |
| 4646 |
require_NoError(t, err) |
| 4647 |
|
| 4648 |
// A ping will resend the flow control message. |
| 4649 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 2, FastBatchGapOk, FastBatchOpPing) |
| 4650 |
require_NoError(t, nc.PublishMsg(m)) |
| 4651 |
for i := range 2 { |
| 4652 |
if i > 0 { |
| 4653 |
rmsg, err = sub.NextMsg(time.Second) |
| 4654 |
require_NoError(t, err) |
| 4655 |
} |
| 4656 |
batchFlowAck = BatchFlowAck{} |
| 4657 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4658 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4659 |
require_Equal(t, batchFlowAck.Sequence, 2) |
| 4660 |
} |
| 4661 |
|
| 4662 |
// Simulate losing one message and a ping making us aware of the gap. |
| 4663 |
m.Reply = generateFastBatchReply(inbox, "uuid", 3, 2, FastBatchGapOk, FastBatchOpPing) |
| 4664 |
require_NoError(t, nc.PublishMsg(m)) |
| 4665 |
// First, we get the report of the detected gap. |
| 4666 |
rmsg, err = sub.NextMsg(time.Second) |
| 4667 |
require_NoError(t, err) |
| 4668 |
var batchFlowGap BatchFlowGap |
| 4669 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 4670 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 3) |
| 4671 |
require_Equal(t, batchFlowGap.CurrentSequence, 4) |
| 4672 |
// Second, we get the last flow control message, since we might have missed that before. |
| 4673 |
rmsg, err = sub.NextMsg(time.Second) |
| 4674 |
require_NoError(t, err) |
| 4675 |
batchFlowAck = BatchFlowAck{} |
| 4676 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4677 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4678 |
require_Equal(t, batchFlowAck.Sequence, 2) |
| 4679 |
|
| 4680 |
// Send another message. |
| 4681 |
m.Reply = generateFastBatchReply(inbox, "uuid", 4, 2, FastBatchGapOk, FastBatchOpAppend) |
| 4682 |
require_NoError(t, nc.PublishMsg(m)) |
| 4683 |
rmsg, err = sub.NextMsg(time.Second) |
| 4684 |
require_NoError(t, err) |
| 4685 |
batchFlowAck = BatchFlowAck{} |
| 4686 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4687 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4688 |
require_Equal(t, batchFlowAck.Sequence, 4) |
| 4689 |
|
| 4690 |
// Simulate losing many messages and a ping making us aware of the gap as well as updating flow control. |
| 4691 |
m.Reply = generateFastBatchReply(inbox, "uuid", 100, 2, FastBatchGapOk, FastBatchOpPing) |
| 4692 |
require_NoError(t, nc.PublishMsg(m)) |
| 4693 |
// First, we get the report of the detected gap. |
| 4694 |
rmsg, err = sub.NextMsg(time.Second) |
| 4695 |
require_NoError(t, err) |
| 4696 |
batchFlowGap = BatchFlowGap{} |
| 4697 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 4698 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 5) |
| 4699 |
require_Equal(t, batchFlowGap.CurrentSequence, 101) |
| 4700 |
// Second, we get the updated flow control message. |
| 4701 |
rmsg, err = sub.NextMsg(time.Second) |
| 4702 |
require_NoError(t, err) |
| 4703 |
batchFlowAck = BatchFlowAck{} |
| 4704 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4705 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4706 |
require_Equal(t, batchFlowAck.Sequence, 100) |
| 4707 |
|
| 4708 |
m.Reply = generateFastBatchReply(inbox, "uuid", 101, 2, FastBatchGapOk, FastBatchOpCommitEob) |
| 4709 |
require_NoError(t, nc.PublishMsg(m)) |
| 4710 |
rmsg, err = sub.NextMsg(time.Second) |
| 4711 |
require_NoError(t, err) |
| 4712 |
pubAck = JSPubAckResponse{} |
| 4713 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4714 |
require_True(t, pubAck.Error == nil) |
| 4715 |
require_Equal(t, pubAck.Sequence, 3) |
| 4716 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4717 |
require_Equal(t, pubAck.BatchSize, 100) |
| 4718 |
} |
| 4719 |
|
| 4720 |
func TestJetStreamFastBatchPublishGapOkBackwardSeq(t *testing.T) { |
| 4721 |
s := RunBasicJetStreamServer(t) |
| 4722 |
defer s.Shutdown() |
| 4723 |
|
| 4724 |
nc := clientConnectToServer(t, s) |
| 4725 |
defer nc.Close() |
| 4726 |
|
| 4727 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4728 |
Name: "TEST", |
| 4729 |
Subjects: []string{"foo"}, |
| 4730 |
Storage: FileStorage, |
| 4731 |
AllowBatchPublish: true, |
| 4732 |
}) |
| 4733 |
require_NoError(t, err) |
| 4734 |
|
| 4735 |
inbox := nats.NewInbox() |
| 4736 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4737 |
require_NoError(t, err) |
| 4738 |
defer sub.Drain() |
| 4739 |
|
| 4740 |
// Start the batch in gapOk mode. |
| 4741 |
m := nats.NewMsg("foo") |
| 4742 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapOk, FastBatchOpStart) |
| 4743 |
require_NoError(t, nc.PublishMsg(m)) |
| 4744 |
rmsg, err := sub.NextMsg(time.Second) |
| 4745 |
require_NoError(t, err) |
| 4746 |
var batchFlowAck BatchFlowAck |
| 4747 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4748 |
|
| 4749 |
// Forward-jump to seq=5; the gap is accepted. |
| 4750 |
m.Reply = generateFastBatchReply(inbox, "uuid", 5, 0, FastBatchGapOk, FastBatchOpAppend) |
| 4751 |
require_NoError(t, nc.PublishMsg(m)) |
| 4752 |
rmsg, err = sub.NextMsg(time.Second) |
| 4753 |
require_NoError(t, err) |
| 4754 |
var batchFlowGap BatchFlowGap |
| 4755 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowGap)) |
| 4756 |
require_Equal(t, batchFlowGap.ExpectedLastSequence, 2) |
| 4757 |
require_Equal(t, batchFlowGap.CurrentSequence, 5) |
| 4758 |
|
| 4759 |
// A backward batch.seq must not rewind b.lseq; it aborts the batch. |
| 4760 |
// No BatchFlowGap should be sent, since gap notifications are only for forward gaps. |
| 4761 |
m.Reply = generateFastBatchReply(inbox, "uuid", 3, 0, FastBatchGapOk, FastBatchOpAppend) |
| 4762 |
require_NoError(t, nc.PublishMsg(m)) |
| 4763 |
|
| 4764 |
// The batch is committed directly and a PubAck is delivered (would never arrive if the |
| 4765 |
// backward seq were silently accepted and the batch kept running). |
| 4766 |
rmsg, err = sub.NextMsg(time.Second) |
| 4767 |
require_NoError(t, err) |
| 4768 |
var pubAck JSPubAckResponse |
| 4769 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4770 |
require_True(t, pubAck.Error == nil) |
| 4771 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4772 |
|
| 4773 |
// Ensure no stray BatchFlowGap arrived alongside the PubAck. |
| 4774 |
_, err = sub.NextMsg(200 * time.Millisecond) |
| 4775 |
require_Error(t, err, nats.ErrTimeout) |
| 4776 |
} |
| 4777 |
|
| 4778 |
func TestJetStreamFastBatchSequentialDuplicateAndErrorPubAck(t *testing.T) { |
| 4779 |
s := RunBasicJetStreamServer(t) |
| 4780 |
defer s.Shutdown() |
| 4781 |
|
| 4782 |
nc := clientConnectToServer(t, s) |
| 4783 |
defer nc.Close() |
| 4784 |
|
| 4785 |
_, err := jsStreamCreate(t, nc, &StreamConfig{ |
| 4786 |
Name: "TEST", |
| 4787 |
Subjects: []string{"foo"}, |
| 4788 |
Storage: FileStorage, |
| 4789 |
AllowBatchPublish: true, |
| 4790 |
}) |
| 4791 |
require_NoError(t, err) |
| 4792 |
|
| 4793 |
// Publish the first message. |
| 4794 |
msgId := "msgId" |
| 4795 |
m := nats.NewMsg("foo") |
| 4796 |
m.Header.Set(JSMsgId, msgId) |
| 4797 |
_, err = nc.RequestMsg(m, time.Second) |
| 4798 |
require_NoError(t, err) |
| 4799 |
|
| 4800 |
inbox := nats.NewInbox() |
| 4801 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4802 |
require_NoError(t, err) |
| 4803 |
defer sub.Drain() |
| 4804 |
|
| 4805 |
// Send the first message, which is a duplicate. |
| 4806 |
m.Header.Set(JSMsgId, msgId) |
| 4807 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 2, FastBatchGapFail, FastBatchOpStart) |
| 4808 |
require_NoError(t, nc.PublishMsg(m)) |
| 4809 |
rmsg, err := sub.NextMsg(time.Second) |
| 4810 |
require_NoError(t, err) |
| 4811 |
var batchFlowAck BatchFlowAck |
| 4812 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4813 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4814 |
|
| 4815 |
// Send the second message which triggers an error and terminates the batch. |
| 4816 |
m.Header.Del(JSMsgId) |
| 4817 |
m.Header.Set(JSExpectedLastSeq, "100") |
| 4818 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 2, FastBatchGapFail, FastBatchOpAppend) |
| 4819 |
require_NoError(t, nc.PublishMsg(m)) |
| 4820 |
rmsg, err = sub.NextMsg(time.Second) |
| 4821 |
require_NoError(t, err) |
| 4822 |
var batchFlowErr BatchFlowErr |
| 4823 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowErr)) |
| 4824 |
require_Equal(t, batchFlowErr.Sequence, 2) |
| 4825 |
require_True(t, batchFlowErr.Error != nil) |
| 4826 |
require_Equal(t, batchFlowErr.Error.Error(), NewJSStreamWrongLastSequenceError(1).Error()) |
| 4827 |
|
| 4828 |
// Lastly, we expect the PubAck. |
| 4829 |
rmsg, err = sub.NextMsg(time.Second) |
| 4830 |
require_NoError(t, err) |
| 4831 |
var pubAck JSPubAckResponse |
| 4832 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4833 |
require_True(t, pubAck.Error == nil) |
| 4834 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4835 |
require_Equal(t, pubAck.BatchSize, 1) |
| 4836 |
// The batch only had duplicate messages. |
| 4837 |
// Technically, we shouldn't return a zero-sequence, but it's unavoidable. |
| 4838 |
require_Equal(t, pubAck.Sequence, 0) |
| 4839 |
} |
| 4840 |
|
| 4841 |
func TestJetStreamFastBatchPublishAccImportExport(t *testing.T) { |
| 4842 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4843 |
listen: 127.0.0.1:-1 |
| 4844 |
jetstream: {max_mem_store: 1MB, max_file_store: 1MB, store_dir: %q} |
| 4845 |
accounts: { |
| 4846 |
A: { |
| 4847 |
jetstream: enabled |
| 4848 |
users: [ {user: a, password: a} ] |
| 4849 |
exports [ |
| 4850 |
{ service: "foo" } |
| 4851 |
] |
| 4852 |
}, |
| 4853 |
B: { |
| 4854 |
users: [ {user: b, password: b} ] |
| 4855 |
imports [ |
| 4856 |
{ service: { subject: "foo", account: A } } |
| 4857 |
] |
| 4858 |
}, |
| 4859 |
} |
| 4860 |
`, t.TempDir()))) |
| 4861 |
|
| 4862 |
s, _ := RunServerWithConfig(conf) |
| 4863 |
defer s.Shutdown() |
| 4864 |
|
| 4865 |
nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("a", "a")) |
| 4866 |
require_NoError(t, err) |
| 4867 |
defer nc.Close() |
| 4868 |
|
| 4869 |
cfg := &StreamConfig{ |
| 4870 |
Name: "TEST", |
| 4871 |
Subjects: []string{"foo"}, |
| 4872 |
Storage: FileStorage, |
| 4873 |
AllowBatchPublish: true, |
| 4874 |
} |
| 4875 |
_, err = jsStreamCreate(t, nc, cfg) |
| 4876 |
require_NoError(t, err) |
| 4877 |
|
| 4878 |
checkFastBatchPublish := func(user string) { |
| 4879 |
nc, err := nats.Connect(s.ClientURL(), nats.UserInfo(user, user)) |
| 4880 |
require_NoError(t, err) |
| 4881 |
defer nc.Close() |
| 4882 |
|
| 4883 |
inbox := nats.NewInbox() |
| 4884 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4885 |
require_NoError(t, err) |
| 4886 |
defer sub.Drain() |
| 4887 |
|
| 4888 |
m := nats.NewMsg("foo") |
| 4889 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 4890 |
require_NoError(t, nc.PublishMsg(m)) |
| 4891 |
rmsg, err := sub.NextMsg(time.Second) |
| 4892 |
require_NoError(t, err) |
| 4893 |
var pubAck JSPubAckResponse |
| 4894 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 4895 |
require_True(t, pubAck.Error == nil) |
| 4896 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 4897 |
require_Equal(t, pubAck.BatchSize, 1) |
| 4898 |
} |
| 4899 |
checkFastBatchPublish("a") |
| 4900 |
checkFastBatchPublish("b") |
| 4901 |
} |
| 4902 |
|
| 4903 |
func TestJetStreamFastBatchPublishFlowControlOnLeaderChange(t *testing.T) { |
| 4904 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 4905 |
defer c.shutdown() |
| 4906 |
|
| 4907 |
nc := clientConnectToServer(t, c.randomServer()) |
| 4908 |
defer nc.Close() |
| 4909 |
|
| 4910 |
cfg := &StreamConfig{ |
| 4911 |
Name: "TEST", |
| 4912 |
Subjects: []string{"foo"}, |
| 4913 |
Storage: FileStorage, |
| 4914 |
Replicas: 3, |
| 4915 |
AllowBatchPublish: true, |
| 4916 |
} |
| 4917 |
|
| 4918 |
_, err := jsStreamCreate(t, nc, cfg) |
| 4919 |
require_NoError(t, err) |
| 4920 |
|
| 4921 |
inbox := nats.NewInbox() |
| 4922 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 4923 |
require_NoError(t, err) |
| 4924 |
defer sub.Drain() |
| 4925 |
|
| 4926 |
m := nats.NewMsg("foo") |
| 4927 |
for seq := uint64(1); seq <= 3; seq++ { |
| 4928 |
if seq == 1 { |
| 4929 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpStart) |
| 4930 |
} else { |
| 4931 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpAppend) |
| 4932 |
} |
| 4933 |
require_NoError(t, nc.PublishMsg(m)) |
| 4934 |
} |
| 4935 |
rmsg, err := sub.NextMsg(time.Second) |
| 4936 |
require_NoError(t, err) |
| 4937 |
var batchFlowAck BatchFlowAck |
| 4938 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4939 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4940 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 4941 |
|
| 4942 |
rmsg, err = sub.NextMsg(time.Second) |
| 4943 |
require_NoError(t, err) |
| 4944 |
batchFlowAck = BatchFlowAck{} |
| 4945 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4946 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4947 |
require_Equal(t, batchFlowAck.Sequence, 2) |
| 4948 |
|
| 4949 |
// Should receive a flow ack after a leader change. This sends us a ping, but also informs us which |
| 4950 |
// messages were persisted after the leader change. |
| 4951 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 4952 |
require_NotNil(t, sl) |
| 4953 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 4954 |
require_NoError(t, err) |
| 4955 |
require_NoError(t, mset.raftNode().StepDown()) |
| 4956 |
|
| 4957 |
rmsg, err = sub.NextMsg(time.Second) |
| 4958 |
require_NoError(t, err) |
| 4959 |
batchFlowAck = BatchFlowAck{} |
| 4960 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4961 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4962 |
require_Equal(t, batchFlowAck.Sequence, 3) |
| 4963 |
|
| 4964 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 4965 |
if err = checkState(t, c, globalAccountName, "TEST"); err != nil { |
| 4966 |
return err |
| 4967 |
} |
| 4968 |
for _, s := range c.servers { |
| 4969 |
mset, err = s.globalAccount().lookupStream("TEST") |
| 4970 |
if err != nil { |
| 4971 |
return err |
| 4972 |
} |
| 4973 |
mset.mu.RLock() |
| 4974 |
var batches int |
| 4975 |
if mset.batches != nil { |
| 4976 |
mset.batches.mu.Lock() |
| 4977 |
batches = len(mset.batches.fast) |
| 4978 |
mset.batches.mu.Unlock() |
| 4979 |
} |
| 4980 |
mset.mu.RUnlock() |
| 4981 |
if batches != 1 { |
| 4982 |
return fmt.Errorf("expected 1 batch on %s, got %d", s.Name(), batches) |
| 4983 |
} |
| 4984 |
} |
| 4985 |
return nil |
| 4986 |
}) |
| 4987 |
|
| 4988 |
// We now expect a new flow ack after two messages. |
| 4989 |
for seq := uint64(4); seq <= 5; seq++ { |
| 4990 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 2, FastBatchGapFail, FastBatchOpAppend) |
| 4991 |
require_NoError(t, nc.PublishMsg(m)) |
| 4992 |
} |
| 4993 |
rmsg, err = sub.NextMsg(time.Second) |
| 4994 |
require_NoError(t, err) |
| 4995 |
batchFlowAck = BatchFlowAck{} |
| 4996 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 4997 |
require_Equal(t, batchFlowAck.Messages, 2) |
| 4998 |
require_Equal(t, batchFlowAck.Sequence, 5) |
| 4999 |
|
| 5000 |
// Commit the final message. We expect that the followers also clean up their state. |
| 5001 |
m.Reply = generateFastBatchReply(inbox, "uuid", 6, 2, FastBatchGapFail, FastBatchOpCommit) |
| 5002 |
require_NoError(t, nc.PublishMsg(m)) |
| 5003 |
rmsg, err = sub.NextMsg(time.Second) |
| 5004 |
require_NoError(t, err) |
| 5005 |
var pubAck JSPubAckResponse |
| 5006 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 5007 |
require_True(t, pubAck.Error == nil) |
| 5008 |
require_Equal(t, pubAck.BatchId, "uuid") |
| 5009 |
require_Equal(t, pubAck.BatchSize, 6) |
| 5010 |
require_Equal(t, pubAck.Sequence, 6) |
| 5011 |
|
| 5012 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 5013 |
if err = checkState(t, c, globalAccountName, "TEST"); err != nil { |
| 5014 |
return err |
| 5015 |
} |
| 5016 |
for _, s := range c.servers { |
| 5017 |
mset, err = s.globalAccount().lookupStream("TEST") |
| 5018 |
if err != nil { |
| 5019 |
return err |
| 5020 |
} |
| 5021 |
mset.mu.RLock() |
| 5022 |
var batches int |
| 5023 |
if mset.batches != nil { |
| 5024 |
mset.batches.mu.Lock() |
| 5025 |
batches = len(mset.batches.fast) |
| 5026 |
mset.batches.mu.Unlock() |
| 5027 |
} |
| 5028 |
mset.mu.RUnlock() |
| 5029 |
if batches > 0 { |
| 5030 |
return fmt.Errorf("expected no batches on %s, got %d", s.Name(), batches) |
| 5031 |
} |
| 5032 |
} |
| 5033 |
return nil |
| 5034 |
}) |
| 5035 |
} |
| 5036 |
|
| 5037 |
func TestJetStreamFastBatchPublishFlowControlOnLeaderChangeAfterFailedCommitProposal(t *testing.T) { |
| 5038 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 5039 |
defer c.shutdown() |
| 5040 |
|
| 5041 |
nc := clientConnectToServer(t, c.randomServer()) |
| 5042 |
defer nc.Close() |
| 5043 |
|
| 5044 |
cfg := &StreamConfig{ |
| 5045 |
Name: "TEST", |
| 5046 |
Subjects: []string{"foo"}, |
| 5047 |
Storage: FileStorage, |
| 5048 |
Replicas: 3, |
| 5049 |
AllowBatchPublish: true, |
| 5050 |
} |
| 5051 |
|
| 5052 |
_, err := jsStreamCreate(t, nc, cfg) |
| 5053 |
require_NoError(t, err) |
| 5054 |
|
| 5055 |
inbox := nats.NewInbox() |
| 5056 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 5057 |
require_NoError(t, err) |
| 5058 |
defer sub.Drain() |
| 5059 |
|
| 5060 |
m := nats.NewMsg("foo") |
| 5061 |
for seq := uint64(1); seq <= 3; seq++ { |
| 5062 |
if seq == 1 { |
| 5063 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpStart) |
| 5064 |
} else { |
| 5065 |
m.Reply = generateFastBatchReply(inbox, "uuid", seq, 0, FastBatchGapFail, FastBatchOpAppend) |
| 5066 |
} |
| 5067 |
require_NoError(t, nc.PublishMsg(m)) |
| 5068 |
} |
| 5069 |
rmsg, err := sub.NextMsg(time.Second) |
| 5070 |
require_NoError(t, err) |
| 5071 |
var batchFlowAck BatchFlowAck |
| 5072 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 5073 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 5074 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 5075 |
|
| 5076 |
// Should receive a flow ack after a leader change. This sends us a ping, but also informs us which |
| 5077 |
// messages were persisted after the leader change. |
| 5078 |
sl := c.streamLeader(globalAccountName, "TEST") |
| 5079 |
require_NotNil(t, sl) |
| 5080 |
mset, err := sl.globalAccount().lookupStream("TEST") |
| 5081 |
require_NoError(t, err) |
| 5082 |
|
| 5083 |
mset.mu.Lock() |
| 5084 |
if mset.batches == nil { |
| 5085 |
mset.mu.Unlock() |
| 5086 |
t.Fatal("batches map is nil") |
| 5087 |
} |
| 5088 |
mset.batches.mu.Lock() |
| 5089 |
b := mset.batches.fast["uuid"] |
| 5090 |
if b == nil { |
| 5091 |
mset.batches.mu.Unlock() |
| 5092 |
mset.mu.Unlock() |
| 5093 |
t.Fatal("batch is nil") |
| 5094 |
} |
| 5095 |
// Simulate one more pending message that commits, but the proposal didn't make it due to the leader change. |
| 5096 |
b.commit = true |
| 5097 |
b.pending++ |
| 5098 |
mset.batches.mu.Unlock() |
| 5099 |
mset.mu.Unlock() |
| 5100 |
|
| 5101 |
// Change to any other leader. |
| 5102 |
require_NoError(t, mset.raftNode().StepDown()) |
| 5103 |
|
| 5104 |
// Change back to the previous leader. |
| 5105 |
c.waitOnStreamLeader(globalAccountName, "TEST") |
| 5106 |
nl := c.streamLeader(globalAccountName, "TEST") |
| 5107 |
require_NotNil(t, nl) |
| 5108 |
require_NotEqual(t, nl, sl) |
| 5109 |
nmset, err := nl.globalAccount().lookupStream("TEST") |
| 5110 |
require_NoError(t, err) |
| 5111 |
require_NoError(t, nmset.raftNode().StepDown(mset.raftNode().ID())) |
| 5112 |
|
| 5113 |
c.waitOnStreamLeader(globalAccountName, "TEST") |
| 5114 |
require_Equal(t, c.streamLeader(globalAccountName, "TEST"), sl) |
| 5115 |
|
| 5116 |
// The previous leader should now have reset the committed flag as the proposal failed. |
| 5117 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 5118 |
mset.mu.RLock() |
| 5119 |
defer mset.mu.RUnlock() |
| 5120 |
if mset.batches == nil { |
| 5121 |
return errors.New("batches map is nil") |
| 5122 |
} |
| 5123 |
mset.batches.mu.Lock() |
| 5124 |
defer mset.batches.mu.Unlock() |
| 5125 |
b = mset.batches.fast["uuid"] |
| 5126 |
if b == nil { |
| 5127 |
return errors.New("batch is nil") |
| 5128 |
} |
| 5129 |
if b.pending != 0 { |
| 5130 |
return errors.New("pending isn't reset") |
| 5131 |
} |
| 5132 |
if b.commit { |
| 5133 |
return errors.New("commit isn't reset") |
| 5134 |
} |
| 5135 |
return nil |
| 5136 |
}) |
| 5137 |
} |
| 5138 |
|
| 5139 |
func TestJetStreamFastBatchPublishLimits(t *testing.T) { |
| 5140 |
streamMaxFastBatchInflightPerStream = 1 |
| 5141 |
streamMaxFastBatchInflightTotal = 1 |
| 5142 |
streamMaxBatchTimeout = 500 * time.Millisecond |
| 5143 |
defer func() { |
| 5144 |
streamMaxFastBatchInflightPerStream = streamDefaultMaxFastBatchInflightPerStream |
| 5145 |
streamMaxFastBatchInflightTotal = streamDefaultMaxFastBatchInflightTotal |
| 5146 |
streamMaxBatchTimeout = streamDefaultMaxBatchTimeout |
| 5147 |
}() |
| 5148 |
|
| 5149 |
test := func(t *testing.T, replicas int) { |
| 5150 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 5151 |
defer c.shutdown() |
| 5152 |
|
| 5153 |
nc := clientConnectToServer(t, c.randomServer()) |
| 5154 |
defer nc.Close() |
| 5155 |
|
| 5156 |
var batchFlowAck BatchFlowAck |
| 5157 |
var pubAck JSPubAckResponse |
| 5158 |
|
| 5159 |
cfg := &StreamConfig{ |
| 5160 |
Name: "FOO", |
| 5161 |
Subjects: []string{"foo"}, |
| 5162 |
Storage: FileStorage, |
| 5163 |
Retention: LimitsPolicy, |
| 5164 |
Replicas: replicas, |
| 5165 |
AllowBatchPublish: true, |
| 5166 |
} |
| 5167 |
_, err := jsStreamCreate(t, nc, cfg) |
| 5168 |
require_NoError(t, err) |
| 5169 |
|
| 5170 |
// For testing total server-wide maximum inflight batches. |
| 5171 |
cfg = &StreamConfig{ |
| 5172 |
Name: "BAR", |
| 5173 |
Subjects: []string{"bar"}, |
| 5174 |
Storage: FileStorage, |
| 5175 |
Retention: LimitsPolicy, |
| 5176 |
Replicas: replicas, |
| 5177 |
AllowBatchPublish: true, |
| 5178 |
} |
| 5179 |
_, err = jsStreamCreate(t, nc, cfg) |
| 5180 |
require_NoError(t, err) |
| 5181 |
|
| 5182 |
inbox := nats.NewInbox() |
| 5183 |
sub, err := nc.SubscribeSync(fmt.Sprintf("%s.>", inbox)) |
| 5184 |
require_NoError(t, err) |
| 5185 |
defer sub.Drain() |
| 5186 |
|
| 5187 |
// A batch ID must not exceed the maximum length. |
| 5188 |
for _, length := range []int{64, 65} { |
| 5189 |
longBatchId := strings.Repeat("A", length) |
| 5190 |
m := nats.NewMsg("foo") |
| 5191 |
m.Reply = generateFastBatchReply(inbox, longBatchId, 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 5192 |
require_NoError(t, nc.PublishMsg(m)) |
| 5193 |
|
| 5194 |
rmsg, err := sub.NextMsg(time.Second) |
| 5195 |
require_NoError(t, err) |
| 5196 |
pubAck = JSPubAckResponse{} |
| 5197 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 5198 |
if length <= 64 { |
| 5199 |
require_True(t, pubAck.Error == nil) |
| 5200 |
} else { |
| 5201 |
require_NotNil(t, pubAck.Error) |
| 5202 |
require_Error(t, pubAck.Error, NewJSBatchPublishInvalidBatchIDError()) |
| 5203 |
} |
| 5204 |
} |
| 5205 |
|
| 5206 |
// One batch is inflight. |
| 5207 |
m := nats.NewMsg("foo") |
| 5208 |
m.Reply = generateFastBatchReply(inbox, "uuid", 1, 0, FastBatchGapFail, FastBatchOpStart) |
| 5209 |
require_NoError(t, nc.PublishMsg(m)) |
| 5210 |
|
| 5211 |
rmsg, err := sub.NextMsg(time.Second) |
| 5212 |
require_NoError(t, err) |
| 5213 |
batchFlowAck = BatchFlowAck{} |
| 5214 |
require_NoError(t, json.Unmarshal(rmsg.Data, &batchFlowAck)) |
| 5215 |
require_Equal(t, batchFlowAck.Messages, 10) |
| 5216 |
require_Equal(t, batchFlowAck.Sequence, 0) |
| 5217 |
|
| 5218 |
// Another batch moves over the threshold and batch is denied. |
| 5219 |
m = nats.NewMsg("foo") |
| 5220 |
m.Reply = generateFastBatchReply(inbox, "exceeds_threshold", 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 5221 |
require_NoError(t, nc.PublishMsg(m)) |
| 5222 |
rmsg, err = sub.NextMsg(time.Second) |
| 5223 |
require_NoError(t, err) |
| 5224 |
pubAck = JSPubAckResponse{} |
| 5225 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 5226 |
require_Error(t, pubAck.Error, NewJSBatchPublishTooManyInflightError()) |
| 5227 |
|
| 5228 |
// Another batch on a different stream moves over the server-wide threshold and batch is denied. |
| 5229 |
m = nats.NewMsg("bar") |
| 5230 |
m.Reply = generateFastBatchReply(inbox, "bar", 1, 0, FastBatchGapFail, FastBatchOpCommit) |
| 5231 |
require_NoError(t, nc.PublishMsg(m)) |
| 5232 |
rmsg, err = sub.NextMsg(time.Second) |
| 5233 |
require_NoError(t, err) |
| 5234 |
pubAck = JSPubAckResponse{} |
| 5235 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 5236 |
require_Error(t, pubAck.Error, NewJSBatchPublishTooManyInflightError()) |
| 5237 |
|
| 5238 |
// The first batch should now time out. |
| 5239 |
sl := c.streamLeader(globalAccountName, "FOO") |
| 5240 |
mset, err := sl.globalAccount().lookupStream("FOO") |
| 5241 |
require_NoError(t, err) |
| 5242 |
checkFor(t, 2*time.Second, 200*time.Millisecond, func() error { |
| 5243 |
mset.mu.RLock() |
| 5244 |
batches := mset.batches |
| 5245 |
mset.mu.RUnlock() |
| 5246 |
if batches == nil { |
| 5247 |
return errors.New("batches not found") |
| 5248 |
} |
| 5249 |
batches.mu.Lock() |
| 5250 |
groups := len(batches.fast) |
| 5251 |
batches.mu.Unlock() |
| 5252 |
if groups != 0 { |
| 5253 |
return fmt.Errorf("expected 0 groups, got %d", groups) |
| 5254 |
} |
| 5255 |
return nil |
| 5256 |
}) |
| 5257 |
|
| 5258 |
// Publishing to the batch should also error since it timed out. |
| 5259 |
m = nats.NewMsg("foo") |
| 5260 |
m.Reply = generateFastBatchReply(inbox, "uuid", 2, 0, FastBatchGapFail, FastBatchOpCommit) |
| 5261 |
require_NoError(t, nc.PublishMsg(m)) |
| 5262 |
|
| 5263 |
rmsg, err = sub.NextMsg(time.Second) |
| 5264 |
require_NoError(t, err) |
| 5265 |
pubAck = JSPubAckResponse{} |
| 5266 |
require_NoError(t, json.Unmarshal(rmsg.Data, &pubAck)) |
| 5267 |
require_Error(t, pubAck.Error, NewJSBatchPublishUnknownBatchIDError()) |
| 5268 |
} |
| 5269 |
|
| 5270 |
t.Run("R1", func(t *testing.T) { test(t, 1) }) |
| 5271 |
t.Run("R3", func(t *testing.T) { test(t, 3) }) |
| 5272 |
} |