github.com/nats-io/nats-server/v2@v2.11.0-preview.2/server/memstore_test.go (about)

     1  // Copyright 2019-2024 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_store_tests
    15  // +build !skip_store_tests
    16  
    17  package server
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  	"math/rand"
    24  	"reflect"
    25  	"testing"
    26  	"time"
    27  )
    28  
    29  func TestMemStoreBasics(t *testing.T) {
    30  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
    31  	require_NoError(t, err)
    32  	defer ms.Stop()
    33  
    34  	subj, msg := "foo", []byte("Hello World")
    35  	now := time.Now().UnixNano()
    36  	if seq, ts, err := ms.StoreMsg(subj, nil, msg); err != nil {
    37  		t.Fatalf("Error storing msg: %v", err)
    38  	} else if seq != 1 {
    39  		t.Fatalf("Expected sequence to be 1, got %d", seq)
    40  	} else if ts < now || ts > now+int64(time.Millisecond) {
    41  		t.Fatalf("Expected timestamp to be current, got %v", ts-now)
    42  	}
    43  
    44  	state := ms.State()
    45  	if state.Msgs != 1 {
    46  		t.Fatalf("Expected 1 msg, got %d", state.Msgs)
    47  	}
    48  	expectedSize := memStoreMsgSize(subj, nil, msg)
    49  	if state.Bytes != expectedSize {
    50  		t.Fatalf("Expected %d bytes, got %d", expectedSize, state.Bytes)
    51  	}
    52  	sm, err := ms.LoadMsg(1, nil)
    53  	if err != nil {
    54  		t.Fatalf("Unexpected error looking up msg: %v", err)
    55  	}
    56  	if sm.subj != subj {
    57  		t.Fatalf("Subjects don't match, original %q vs %q", subj, sm.subj)
    58  	}
    59  	if !bytes.Equal(sm.msg, msg) {
    60  		t.Fatalf("Msgs don't match, original %q vs %q", msg, sm.msg)
    61  	}
    62  }
    63  
    64  func TestMemStoreMsgLimit(t *testing.T) {
    65  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage, MaxMsgs: 10})
    66  	require_NoError(t, err)
    67  	defer ms.Stop()
    68  
    69  	subj, msg := "foo", []byte("Hello World")
    70  	for i := 0; i < 10; i++ {
    71  		ms.StoreMsg(subj, nil, msg)
    72  	}
    73  	state := ms.State()
    74  	if state.Msgs != 10 {
    75  		t.Fatalf("Expected %d msgs, got %d", 10, state.Msgs)
    76  	}
    77  	if _, _, err := ms.StoreMsg(subj, nil, msg); err != nil {
    78  		t.Fatalf("Error storing msg: %v", err)
    79  	}
    80  	state = ms.State()
    81  	if state.Msgs != 10 {
    82  		t.Fatalf("Expected %d msgs, got %d", 10, state.Msgs)
    83  	}
    84  	if state.LastSeq != 11 {
    85  		t.Fatalf("Expected the last sequence to be 11 now, but got %d", state.LastSeq)
    86  	}
    87  	if state.FirstSeq != 2 {
    88  		t.Fatalf("Expected the first sequence to be 2 now, but got %d", state.FirstSeq)
    89  	}
    90  	// Make sure we can not lookup seq 1.
    91  	if _, err := ms.LoadMsg(1, nil); err == nil {
    92  		t.Fatalf("Expected error looking up seq 1 but got none")
    93  	}
    94  }
    95  
    96  func TestMemStoreBytesLimit(t *testing.T) {
    97  	subj, msg := "foo", make([]byte, 512)
    98  	storedMsgSize := memStoreMsgSize(subj, nil, msg)
    99  
   100  	toStore := uint64(1024)
   101  	maxBytes := storedMsgSize * toStore
   102  
   103  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage, MaxBytes: int64(maxBytes)})
   104  	require_NoError(t, err)
   105  	defer ms.Stop()
   106  
   107  	for i := uint64(0); i < toStore; i++ {
   108  		ms.StoreMsg(subj, nil, msg)
   109  	}
   110  	state := ms.State()
   111  	if state.Msgs != toStore {
   112  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   113  	}
   114  	if state.Bytes != storedMsgSize*toStore {
   115  		t.Fatalf("Expected bytes to be %d, got %d", storedMsgSize*toStore, state.Bytes)
   116  	}
   117  
   118  	// Now send 10 more and check that bytes limit enforced.
   119  	for i := 0; i < 10; i++ {
   120  		if _, _, err := ms.StoreMsg(subj, nil, msg); err != nil {
   121  			t.Fatalf("Error storing msg: %v", err)
   122  		}
   123  	}
   124  	state = ms.State()
   125  	if state.Msgs != toStore {
   126  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   127  	}
   128  	if state.Bytes != storedMsgSize*toStore {
   129  		t.Fatalf("Expected bytes to be %d, got %d", storedMsgSize*toStore, state.Bytes)
   130  	}
   131  	if state.FirstSeq != 11 {
   132  		t.Fatalf("Expected first sequence to be 11, got %d", state.FirstSeq)
   133  	}
   134  	if state.LastSeq != toStore+10 {
   135  		t.Fatalf("Expected last sequence to be %d, got %d", toStore+10, state.LastSeq)
   136  	}
   137  }
   138  
   139  // https://github.com/nats-io/nats-server/issues/4771
   140  func TestMemStoreBytesLimitWithDiscardNew(t *testing.T) {
   141  	subj, msg := "tiny", make([]byte, 7)
   142  	storedMsgSize := memStoreMsgSize(subj, nil, msg)
   143  
   144  	toStore := uint64(3)
   145  	maxBytes := 100
   146  
   147  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage, MaxBytes: int64(maxBytes), Discard: DiscardNew})
   148  	require_NoError(t, err)
   149  	defer ms.Stop()
   150  
   151  	// Now send 10 messages and check that bytes limit enforced.
   152  	for i := 0; i < 10; i++ {
   153  		_, _, err := ms.StoreMsg(subj, nil, msg)
   154  		if i < int(toStore) {
   155  			if err != nil {
   156  				t.Fatalf("Error storing msg: %v", err)
   157  			}
   158  		} else if !errors.Is(err, ErrMaxBytes) {
   159  			t.Fatalf("Storing msg should result in: %v", ErrMaxBytes)
   160  		}
   161  	}
   162  	state := ms.State()
   163  	if state.Msgs != toStore {
   164  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   165  	}
   166  	if state.Bytes != storedMsgSize*toStore {
   167  		t.Fatalf("Expected bytes to be %d, got %d", storedMsgSize*toStore, state.Bytes)
   168  	}
   169  }
   170  
   171  func TestMemStoreAgeLimit(t *testing.T) {
   172  	maxAge := 10 * time.Millisecond
   173  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage, MaxAge: maxAge})
   174  	require_NoError(t, err)
   175  	defer ms.Stop()
   176  
   177  	// Store some messages. Does not really matter how many.
   178  	subj, msg := "foo", []byte("Hello World")
   179  	toStore := 100
   180  	for i := 0; i < toStore; i++ {
   181  		ms.StoreMsg(subj, nil, msg)
   182  	}
   183  	state := ms.State()
   184  	if state.Msgs != uint64(toStore) {
   185  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   186  	}
   187  	checkExpired := func(t *testing.T) {
   188  		t.Helper()
   189  		checkFor(t, time.Second, maxAge, func() error {
   190  			state = ms.State()
   191  			if state.Msgs != 0 {
   192  				return fmt.Errorf("Expected no msgs, got %d", state.Msgs)
   193  			}
   194  			if state.Bytes != 0 {
   195  				return fmt.Errorf("Expected no bytes, got %d", state.Bytes)
   196  			}
   197  			return nil
   198  		})
   199  	}
   200  	// Let them expire
   201  	checkExpired(t)
   202  	// Now add some more and make sure that timer will fire again.
   203  	for i := 0; i < toStore; i++ {
   204  		ms.StoreMsg(subj, nil, msg)
   205  	}
   206  	state = ms.State()
   207  	if state.Msgs != uint64(toStore) {
   208  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   209  	}
   210  	checkExpired(t)
   211  }
   212  
   213  func TestMemStoreTimeStamps(t *testing.T) {
   214  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   215  	require_NoError(t, err)
   216  	defer ms.Stop()
   217  
   218  	last := time.Now().UnixNano()
   219  	subj, msg := "foo", []byte("Hello World")
   220  	for i := 0; i < 10; i++ {
   221  		time.Sleep(5 * time.Microsecond)
   222  		ms.StoreMsg(subj, nil, msg)
   223  	}
   224  	var smv StoreMsg
   225  	for seq := uint64(1); seq <= 10; seq++ {
   226  		sm, err := ms.LoadMsg(seq, &smv)
   227  		if err != nil {
   228  			t.Fatalf("Unexpected error looking up msg: %v", err)
   229  		}
   230  		// These should be different
   231  		if sm.ts <= last {
   232  			t.Fatalf("Expected different timestamps, got %v", sm.ts)
   233  		}
   234  		last = sm.ts
   235  	}
   236  }
   237  
   238  func TestMemStorePurge(t *testing.T) {
   239  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   240  	require_NoError(t, err)
   241  	defer ms.Stop()
   242  
   243  	subj, msg := "foo", []byte("Hello World")
   244  	for i := 0; i < 10; i++ {
   245  		ms.StoreMsg(subj, nil, msg)
   246  	}
   247  	if state := ms.State(); state.Msgs != 10 {
   248  		t.Fatalf("Expected 10 msgs, got %d", state.Msgs)
   249  	}
   250  	ms.Purge()
   251  	if state := ms.State(); state.Msgs != 0 {
   252  		t.Fatalf("Expected no msgs, got %d", state.Msgs)
   253  	}
   254  }
   255  
   256  func TestMemStoreCompact(t *testing.T) {
   257  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   258  	require_NoError(t, err)
   259  	defer ms.Stop()
   260  
   261  	subj, msg := "foo", []byte("Hello World")
   262  	for i := 0; i < 10; i++ {
   263  		ms.StoreMsg(subj, nil, msg)
   264  	}
   265  	if state := ms.State(); state.Msgs != 10 {
   266  		t.Fatalf("Expected 10 msgs, got %d", state.Msgs)
   267  	}
   268  	n, err := ms.Compact(6)
   269  	if err != nil {
   270  		t.Fatalf("Unexpected error: %v", err)
   271  	}
   272  	if n != 5 {
   273  		t.Fatalf("Expected to have purged 5 msgs, got %d", n)
   274  	}
   275  	state := ms.State()
   276  	if state.Msgs != 5 {
   277  		t.Fatalf("Expected 5 msgs, got %d", state.Msgs)
   278  	}
   279  	if state.FirstSeq != 6 {
   280  		t.Fatalf("Expected first seq of 6, got %d", state.FirstSeq)
   281  	}
   282  	// Now test that compact will also reset first if seq > last
   283  	n, err = ms.Compact(100)
   284  	if err != nil {
   285  		t.Fatalf("Unexpected error: %v", err)
   286  	}
   287  	if n != 5 {
   288  		t.Fatalf("Expected to have purged 5 msgs, got %d", n)
   289  	}
   290  	if state = ms.State(); state.FirstSeq != 100 {
   291  		t.Fatalf("Expected first seq of 100, got %d", state.FirstSeq)
   292  	}
   293  }
   294  
   295  func TestMemStoreEraseMsg(t *testing.T) {
   296  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   297  	require_NoError(t, err)
   298  	defer ms.Stop()
   299  
   300  	subj, msg := "foo", []byte("Hello World")
   301  	ms.StoreMsg(subj, nil, msg)
   302  	sm, err := ms.LoadMsg(1, nil)
   303  	if err != nil {
   304  		t.Fatalf("Unexpected error looking up msg: %v", err)
   305  	}
   306  	if !bytes.Equal(msg, sm.msg) {
   307  		t.Fatalf("Expected same msg, got %q vs %q", sm.msg, msg)
   308  	}
   309  	if removed, _ := ms.EraseMsg(1); !removed {
   310  		t.Fatalf("Expected erase msg to return success")
   311  	}
   312  }
   313  
   314  func TestMemStoreMsgHeaders(t *testing.T) {
   315  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   316  	require_NoError(t, err)
   317  	defer ms.Stop()
   318  
   319  	subj, hdr, msg := "foo", []byte("name:derek"), []byte("Hello World")
   320  	if sz := int(memStoreMsgSize(subj, hdr, msg)); sz != (len(subj) + len(hdr) + len(msg) + 16) {
   321  		t.Fatalf("Wrong size for stored msg with header")
   322  	}
   323  	ms.StoreMsg(subj, hdr, msg)
   324  	sm, err := ms.LoadMsg(1, nil)
   325  	if err != nil {
   326  		t.Fatalf("Unexpected error looking up msg: %v", err)
   327  	}
   328  	if !bytes.Equal(msg, sm.msg) {
   329  		t.Fatalf("Expected same msg, got %q vs %q", sm.msg, msg)
   330  	}
   331  	if !bytes.Equal(hdr, sm.hdr) {
   332  		t.Fatalf("Expected same hdr, got %q vs %q", sm.hdr, hdr)
   333  	}
   334  	if removed, _ := ms.EraseMsg(1); !removed {
   335  		t.Fatalf("Expected erase msg to return success")
   336  	}
   337  }
   338  
   339  func TestMemStoreStreamStateDeleted(t *testing.T) {
   340  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   341  	require_NoError(t, err)
   342  	defer ms.Stop()
   343  
   344  	subj, toStore := "foo", uint64(10)
   345  	for i := uint64(1); i <= toStore; i++ {
   346  		msg := []byte(fmt.Sprintf("[%08d] Hello World!", i))
   347  		if _, _, err := ms.StoreMsg(subj, nil, msg); err != nil {
   348  			t.Fatalf("Error storing msg: %v", err)
   349  		}
   350  	}
   351  	state := ms.State()
   352  	if len(state.Deleted) != 0 {
   353  		t.Fatalf("Expected deleted to be empty")
   354  	}
   355  	// Now remove some interior messages.
   356  	var expected []uint64
   357  	for seq := uint64(2); seq < toStore; seq += 2 {
   358  		ms.RemoveMsg(seq)
   359  		expected = append(expected, seq)
   360  	}
   361  	state = ms.State()
   362  	if !reflect.DeepEqual(state.Deleted, expected) {
   363  		t.Fatalf("Expected deleted to be %+v, got %+v\n", expected, state.Deleted)
   364  	}
   365  	// Now fill the gap by deleting 1 and 3
   366  	ms.RemoveMsg(1)
   367  	ms.RemoveMsg(3)
   368  	expected = expected[2:]
   369  	state = ms.State()
   370  	if !reflect.DeepEqual(state.Deleted, expected) {
   371  		t.Fatalf("Expected deleted to be %+v, got %+v\n", expected, state.Deleted)
   372  	}
   373  	if state.FirstSeq != 5 {
   374  		t.Fatalf("Expected first seq to be 5, got %d", state.FirstSeq)
   375  	}
   376  	ms.Purge()
   377  	if state = ms.State(); len(state.Deleted) != 0 {
   378  		t.Fatalf("Expected no deleted after purge, got %+v\n", state.Deleted)
   379  	}
   380  }
   381  
   382  func TestMemStoreStreamTruncate(t *testing.T) {
   383  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   384  	require_NoError(t, err)
   385  	defer ms.Stop()
   386  
   387  	tseq := uint64(50)
   388  
   389  	subj, toStore := "foo", uint64(100)
   390  	for i := uint64(1); i < tseq; i++ {
   391  		_, _, err := ms.StoreMsg(subj, nil, []byte("ok"))
   392  		require_NoError(t, err)
   393  	}
   394  	subj = "bar"
   395  	for i := tseq; i <= toStore; i++ {
   396  		_, _, err := ms.StoreMsg(subj, nil, []byte("ok"))
   397  		require_NoError(t, err)
   398  	}
   399  
   400  	if state := ms.State(); state.Msgs != toStore {
   401  		t.Fatalf("Expected %d msgs, got %d", toStore, state.Msgs)
   402  	}
   403  
   404  	// Check that sequence has to be interior.
   405  	if err := ms.Truncate(toStore + 1); err != ErrInvalidSequence {
   406  		t.Fatalf("Expected err of '%v', got '%v'", ErrInvalidSequence, err)
   407  	}
   408  
   409  	if err := ms.Truncate(tseq); err != nil {
   410  		t.Fatalf("Unexpected error: %v", err)
   411  	}
   412  	if state := ms.State(); state.Msgs != tseq {
   413  		t.Fatalf("Expected %d msgs, got %d", tseq, state.Msgs)
   414  	}
   415  
   416  	// Now make sure we report properly if we have some deleted interior messages.
   417  	ms.RemoveMsg(10)
   418  	ms.RemoveMsg(20)
   419  	ms.RemoveMsg(30)
   420  	ms.RemoveMsg(40)
   421  
   422  	tseq = uint64(25)
   423  	if err := ms.Truncate(tseq); err != nil {
   424  		t.Fatalf("Unexpected error: %v", err)
   425  	}
   426  	state := ms.State()
   427  	if state.Msgs != tseq-2 {
   428  		t.Fatalf("Expected %d msgs, got %d", tseq-2, state.Msgs)
   429  	}
   430  	if state.NumSubjects != 1 {
   431  		t.Fatalf("Expected only 1 subject, got %d", state.NumSubjects)
   432  	}
   433  	expected := []uint64{10, 20}
   434  	if !reflect.DeepEqual(state.Deleted, expected) {
   435  		t.Fatalf("Expected deleted to be %+v, got %+v\n", expected, state.Deleted)
   436  	}
   437  }
   438  
   439  func TestMemStorePurgeExWithSubject(t *testing.T) {
   440  	ms, err := newMemStore(&StreamConfig{Storage: MemoryStorage})
   441  	require_NoError(t, err)
   442  	defer ms.Stop()
   443  
   444  	for i := 0; i < 100; i++ {
   445  		_, _, err = ms.StoreMsg("foo", nil, nil)
   446  		require_NoError(t, err)
   447  	}
   448  
   449  	// This should purge all.
   450  	ms.PurgeEx("foo", 1, 0)
   451  	require_True(t, ms.State().Msgs == 0)
   452  }
   453  
   454  func TestMemStoreUpdateMaxMsgsPerSubject(t *testing.T) {
   455  	cfg := &StreamConfig{
   456  		Name:       "TEST",
   457  		Storage:    MemoryStorage,
   458  		Subjects:   []string{"foo"},
   459  		MaxMsgsPer: 10,
   460  	}
   461  	ms, err := newMemStore(cfg)
   462  	require_NoError(t, err)
   463  	defer ms.Stop()
   464  
   465  	// Make sure this is honored on an update.
   466  	cfg.MaxMsgsPer = 50
   467  	err = ms.UpdateConfig(cfg)
   468  	require_NoError(t, err)
   469  
   470  	numStored := 22
   471  	for i := 0; i < numStored; i++ {
   472  		_, _, err = ms.StoreMsg("foo", nil, nil)
   473  		require_NoError(t, err)
   474  	}
   475  
   476  	ss := ms.SubjectsState("foo")["foo"]
   477  	if ss.Msgs != uint64(numStored) {
   478  		t.Fatalf("Expected to have %d stored, got %d", numStored, ss.Msgs)
   479  	}
   480  
   481  	// Now make sure we trunk if setting to lower value.
   482  	cfg.MaxMsgsPer = 10
   483  	err = ms.UpdateConfig(cfg)
   484  	require_NoError(t, err)
   485  
   486  	ss = ms.SubjectsState("foo")["foo"]
   487  	if ss.Msgs != 10 {
   488  		t.Fatalf("Expected to have %d stored, got %d", 10, ss.Msgs)
   489  	}
   490  }
   491  
   492  func TestMemStoreStreamTruncateReset(t *testing.T) {
   493  	cfg := &StreamConfig{
   494  		Name:     "TEST",
   495  		Storage:  MemoryStorage,
   496  		Subjects: []string{"foo"},
   497  	}
   498  	ms, err := newMemStore(cfg)
   499  	require_NoError(t, err)
   500  	defer ms.Stop()
   501  
   502  	subj, msg := "foo", []byte("Hello World")
   503  	for i := 0; i < 1000; i++ {
   504  		_, _, err := ms.StoreMsg(subj, nil, msg)
   505  		require_NoError(t, err)
   506  	}
   507  
   508  	// Reset everything
   509  	require_NoError(t, ms.Truncate(0))
   510  
   511  	state := ms.State()
   512  	require_True(t, state.Msgs == 0)
   513  	require_True(t, state.Bytes == 0)
   514  	require_True(t, state.FirstSeq == 0)
   515  	require_True(t, state.LastSeq == 0)
   516  	require_True(t, state.NumSubjects == 0)
   517  	require_True(t, state.NumDeleted == 0)
   518  
   519  	for i := 0; i < 1000; i++ {
   520  		_, _, err := ms.StoreMsg(subj, nil, msg)
   521  		require_NoError(t, err)
   522  	}
   523  
   524  	state = ms.State()
   525  	require_True(t, state.Msgs == 1000)
   526  	require_True(t, state.Bytes == 30000)
   527  	require_True(t, state.FirstSeq == 1)
   528  	require_True(t, state.LastSeq == 1000)
   529  	require_True(t, state.NumSubjects == 1)
   530  	require_True(t, state.NumDeleted == 0)
   531  }
   532  
   533  func TestMemStoreStreamCompactMultiBlockSubjectInfo(t *testing.T) {
   534  	cfg := &StreamConfig{
   535  		Name:     "TEST",
   536  		Storage:  MemoryStorage,
   537  		Subjects: []string{"foo.*"},
   538  	}
   539  	ms, err := newMemStore(cfg)
   540  	require_NoError(t, err)
   541  	defer ms.Stop()
   542  
   543  	for i := 0; i < 1000; i++ {
   544  		subj := fmt.Sprintf("foo.%d", i)
   545  		_, _, err := ms.StoreMsg(subj, nil, []byte("Hello World"))
   546  		require_NoError(t, err)
   547  	}
   548  
   549  	// Compact such that we know we throw blocks away from the beginning.
   550  	deleted, err := ms.Compact(501)
   551  	require_NoError(t, err)
   552  	require_True(t, deleted == 500)
   553  
   554  	// Make sure we adjusted for subjects etc.
   555  	state := ms.State()
   556  	require_True(t, state.NumSubjects == 500)
   557  }
   558  
   559  func TestMemStoreSubjectsTotals(t *testing.T) {
   560  	cfg := &StreamConfig{
   561  		Name:     "TEST",
   562  		Storage:  MemoryStorage,
   563  		Subjects: []string{"*.*"},
   564  	}
   565  	ms, err := newMemStore(cfg)
   566  	require_NoError(t, err)
   567  	defer ms.Stop()
   568  
   569  	fmap := make(map[int]int)
   570  	bmap := make(map[int]int)
   571  
   572  	var m map[int]int
   573  	var ft string
   574  
   575  	for i := 0; i < 10_000; i++ {
   576  		// Flip coin for prefix
   577  		if rand.Intn(2) == 0 {
   578  			ft, m = "foo", fmap
   579  		} else {
   580  			ft, m = "bar", bmap
   581  		}
   582  		dt := rand.Intn(100)
   583  		subj := fmt.Sprintf("%s.%d", ft, dt)
   584  		m[dt]++
   585  
   586  		_, _, err := ms.StoreMsg(subj, nil, []byte("Hello World"))
   587  		require_NoError(t, err)
   588  	}
   589  
   590  	// Now test SubjectsTotal
   591  	for dt, total := range fmap {
   592  		subj := fmt.Sprintf("foo.%d", dt)
   593  		m := ms.SubjectsTotals(subj)
   594  		if m[subj] != uint64(total) {
   595  			t.Fatalf("Expected %q to have %d total, got %d", subj, total, m[subj])
   596  		}
   597  	}
   598  
   599  	// Check fmap.
   600  	if st := ms.SubjectsTotals("foo.*"); len(st) != len(fmap) {
   601  		t.Fatalf("Expected %d subjects for %q, got %d", len(fmap), "foo.*", len(st))
   602  	} else {
   603  		expected := 0
   604  		for _, n := range fmap {
   605  			expected += n
   606  		}
   607  		received := uint64(0)
   608  		for _, n := range st {
   609  			received += n
   610  		}
   611  		if received != uint64(expected) {
   612  			t.Fatalf("Expected %d total but got %d", expected, received)
   613  		}
   614  	}
   615  
   616  	// Check bmap.
   617  	if st := ms.SubjectsTotals("bar.*"); len(st) != len(bmap) {
   618  		t.Fatalf("Expected %d subjects for %q, got %d", len(bmap), "bar.*", len(st))
   619  	} else {
   620  		expected := 0
   621  		for _, n := range bmap {
   622  			expected += n
   623  		}
   624  		received := uint64(0)
   625  		for _, n := range st {
   626  			received += n
   627  		}
   628  		if received != uint64(expected) {
   629  			t.Fatalf("Expected %d total but got %d", expected, received)
   630  		}
   631  	}
   632  
   633  	// All with pwc match.
   634  	if st, expected := ms.SubjectsTotals("*.*"), len(bmap)+len(fmap); len(st) != expected {
   635  		t.Fatalf("Expected %d subjects for %q, got %d", expected, "*.*", len(st))
   636  	}
   637  }
   638  
   639  func TestMemStoreNumPending(t *testing.T) {
   640  	cfg := &StreamConfig{
   641  		Name:     "TEST",
   642  		Storage:  MemoryStorage,
   643  		Subjects: []string{"*.*.*.*"},
   644  	}
   645  	ms, err := newMemStore(cfg)
   646  	require_NoError(t, err)
   647  	defer ms.Stop()
   648  
   649  	tokens := []string{"foo", "bar", "baz"}
   650  	genSubj := func() string {
   651  		return fmt.Sprintf("%s.%s.%s.%s",
   652  			tokens[rand.Intn(len(tokens))],
   653  			tokens[rand.Intn(len(tokens))],
   654  			tokens[rand.Intn(len(tokens))],
   655  			tokens[rand.Intn(len(tokens))],
   656  		)
   657  	}
   658  
   659  	for i := 0; i < 50_000; i++ {
   660  		subj := genSubj()
   661  		_, _, err := ms.StoreMsg(subj, nil, []byte("Hello World"))
   662  		require_NoError(t, err)
   663  	}
   664  
   665  	state := ms.State()
   666  
   667  	// Scan one by one for sanity check against other calculations.
   668  	sanityCheck := func(sseq uint64, filter string) SimpleState {
   669  		t.Helper()
   670  		var ss SimpleState
   671  		var smv StoreMsg
   672  		// For here we know 0 is invalid, set to 1.
   673  		if sseq == 0 {
   674  			sseq = 1
   675  		}
   676  		for seq := sseq; seq <= state.LastSeq; seq++ {
   677  			sm, err := ms.LoadMsg(seq, &smv)
   678  			if err != nil {
   679  				t.Logf("Encountered error %v loading sequence: %d", err, seq)
   680  				continue
   681  			}
   682  			if subjectIsSubsetMatch(sm.subj, filter) {
   683  				ss.Msgs++
   684  				ss.Last = seq
   685  				if ss.First == 0 || seq < ss.First {
   686  					ss.First = seq
   687  				}
   688  			}
   689  		}
   690  		return ss
   691  	}
   692  
   693  	check := func(sseq uint64, filter string) {
   694  		t.Helper()
   695  		np, lvs := ms.NumPending(sseq, filter, false)
   696  		ss := ms.FilteredState(sseq, filter)
   697  		sss := sanityCheck(sseq, filter)
   698  		if lvs != state.LastSeq {
   699  			t.Fatalf("Expected NumPending to return valid through last of %d but got %d", state.LastSeq, lvs)
   700  		}
   701  		if ss.Msgs != np {
   702  			t.Fatalf("NumPending of %d did not match ss.Msgs of %d", np, ss.Msgs)
   703  		}
   704  		if ss != sss {
   705  			t.Fatalf("Failed sanity check, expected %+v got %+v", sss, ss)
   706  		}
   707  	}
   708  
   709  	sanityCheckLastOnly := func(sseq uint64, filter string) SimpleState {
   710  		t.Helper()
   711  		var ss SimpleState
   712  		var smv StoreMsg
   713  		// For here we know 0 is invalid, set to 1.
   714  		if sseq == 0 {
   715  			sseq = 1
   716  		}
   717  		seen := make(map[string]bool)
   718  		for seq := state.LastSeq; seq >= sseq; seq-- {
   719  			sm, err := ms.LoadMsg(seq, &smv)
   720  			if err != nil {
   721  				t.Logf("Encountered error %v loading sequence: %d", err, seq)
   722  				continue
   723  			}
   724  			if !seen[sm.subj] && subjectIsSubsetMatch(sm.subj, filter) {
   725  				ss.Msgs++
   726  				if ss.Last == 0 {
   727  					ss.Last = seq
   728  				}
   729  				if ss.First == 0 || seq < ss.First {
   730  					ss.First = seq
   731  				}
   732  				seen[sm.subj] = true
   733  			}
   734  		}
   735  		return ss
   736  	}
   737  
   738  	checkLastOnly := func(sseq uint64, filter string) {
   739  		t.Helper()
   740  		np, lvs := ms.NumPending(sseq, filter, true)
   741  		ss := sanityCheckLastOnly(sseq, filter)
   742  		if lvs != state.LastSeq {
   743  			t.Fatalf("Expected NumPending to return valid through last of %d but got %d", state.LastSeq, lvs)
   744  		}
   745  		if ss.Msgs != np {
   746  			t.Fatalf("NumPending of %d did not match ss.Msgs of %d", np, ss.Msgs)
   747  		}
   748  	}
   749  
   750  	startSeqs := []uint64{0, 1, 2, 200, 444, 555, 2222, 8888, 12_345, 28_222, 33_456, 44_400, 49_999}
   751  	checkSubs := []string{"foo.>", "*.bar.>", "foo.bar.*.baz", "*.bar.>", "*.foo.bar.*", "foo.foo.bar.baz"}
   752  
   753  	for _, filter := range checkSubs {
   754  		for _, start := range startSeqs {
   755  			check(start, filter)
   756  			checkLastOnly(start, filter)
   757  		}
   758  	}
   759  }
   760  
   761  func TestMemStoreInitialFirstSeq(t *testing.T) {
   762  	cfg := &StreamConfig{
   763  		Name:     "zzz",
   764  		Storage:  MemoryStorage,
   765  		FirstSeq: 1000,
   766  	}
   767  	ms, err := newMemStore(cfg)
   768  	require_NoError(t, err)
   769  	defer ms.Stop()
   770  
   771  	seq, _, err := ms.StoreMsg("A", nil, []byte("OK"))
   772  	require_NoError(t, err)
   773  	if seq != 1000 {
   774  		t.Fatalf("Message should have been sequence 1000 but was %d", seq)
   775  	}
   776  
   777  	seq, _, err = ms.StoreMsg("B", nil, []byte("OK"))
   778  	require_NoError(t, err)
   779  	if seq != 1001 {
   780  		t.Fatalf("Message should have been sequence 1001 but was %d", seq)
   781  	}
   782  
   783  	var state StreamState
   784  	ms.FastState(&state)
   785  	switch {
   786  	case state.Msgs != 2:
   787  		t.Fatalf("Expected 2 messages, got %d", state.Msgs)
   788  	case state.FirstSeq != 1000:
   789  		t.Fatalf("Expected first seq 1000, got %d", state.FirstSeq)
   790  	case state.LastSeq != 1001:
   791  		t.Fatalf("Expected last seq 1001, got %d", state.LastSeq)
   792  	}
   793  }
   794  
   795  func TestMemStoreDeleteBlocks(t *testing.T) {
   796  	cfg := &StreamConfig{
   797  		Name:     "zzz",
   798  		Subjects: []string{"*"},
   799  		Storage:  MemoryStorage,
   800  	}
   801  	ms, err := newMemStore(cfg)
   802  	require_NoError(t, err)
   803  	defer ms.Stop()
   804  
   805  	// Put in 10_000 msgs.
   806  	total := 10_000
   807  	for i := 0; i < total; i++ {
   808  		_, _, err := ms.StoreMsg("A", nil, []byte("OK"))
   809  		require_NoError(t, err)
   810  	}
   811  
   812  	// Now pick 5k random sequences.
   813  	delete := 5000
   814  	deleteMap := make(map[int]struct{}, delete)
   815  	for len(deleteMap) < delete {
   816  		deleteMap[rand.Intn(total)+1] = struct{}{}
   817  	}
   818  	// Now remove?
   819  	for seq := range deleteMap {
   820  		ms.RemoveMsg(uint64(seq))
   821  	}
   822  
   823  	var state StreamState
   824  	ms.FastState(&state)
   825  
   826  	// For now we just track via one dmap.
   827  	ms.mu.RLock()
   828  	dmap := ms.dmap.Clone()
   829  	ms.mu.RUnlock()
   830  
   831  	require_True(t, dmap.Size() == state.NumDeleted)
   832  }
   833  
   834  // https://github.com/nats-io/nats-server/issues/4850
   835  func TestMemStoreGetSeqFromTimeWithLastDeleted(t *testing.T) {
   836  	cfg := &StreamConfig{
   837  		Name:     "zzz",
   838  		Subjects: []string{"*"},
   839  		Storage:  MemoryStorage,
   840  	}
   841  	ms, err := newMemStore(cfg)
   842  	require_NoError(t, err)
   843  	defer ms.Stop()
   844  
   845  	// Put in 1000 msgs.
   846  	total := 1000
   847  	var st time.Time
   848  	for i := 1; i <= total; i++ {
   849  		_, _, err := ms.StoreMsg("A", nil, []byte("OK"))
   850  		require_NoError(t, err)
   851  		if i == total/2 {
   852  			time.Sleep(100 * time.Millisecond)
   853  			st = time.Now()
   854  		}
   855  	}
   856  	// Delete last 100
   857  	for seq := total - 100; seq <= total; seq++ {
   858  		ms.RemoveMsg(uint64(seq))
   859  	}
   860  
   861  	// Make sure this does not panic with last sequence no longer accessible.
   862  	seq := ms.GetSeqFromTime(st)
   863  	// Make sure we get the right value.
   864  	require_Equal(t, seq, 501)
   865  }
   866  
   867  func TestMemStoreSkipMsgs(t *testing.T) {
   868  	cfg := &StreamConfig{
   869  		Name:     "zzz",
   870  		Subjects: []string{"*"},
   871  		Storage:  MemoryStorage,
   872  	}
   873  	ms, err := newMemStore(cfg)
   874  	require_NoError(t, err)
   875  	defer ms.Stop()
   876  
   877  	// Test on empty FS first.
   878  	// Make sure wrong starting sequence fails.
   879  	err = ms.SkipMsgs(10, 100)
   880  	require_Error(t, err, ErrSequenceMismatch)
   881  
   882  	err = ms.SkipMsgs(1, 100)
   883  	require_NoError(t, err)
   884  
   885  	state := ms.State()
   886  	require_Equal(t, state.FirstSeq, 101)
   887  	require_Equal(t, state.LastSeq, 100)
   888  
   889  	// Now add alot.
   890  	err = ms.SkipMsgs(101, 100_000)
   891  	require_NoError(t, err)
   892  	state = ms.State()
   893  	require_Equal(t, state.FirstSeq, 100_101)
   894  	require_Equal(t, state.LastSeq, 100_100)
   895  
   896  	// Now add in a message, and then skip to check dmap.
   897  	ms, err = newMemStore(cfg)
   898  	require_NoError(t, err)
   899  	ms.StoreMsg("foo", nil, nil)
   900  
   901  	err = ms.SkipMsgs(2, 10)
   902  	require_NoError(t, err)
   903  	state = ms.State()
   904  	require_Equal(t, state.FirstSeq, 1)
   905  	require_Equal(t, state.LastSeq, 11)
   906  	require_Equal(t, state.Msgs, 1)
   907  	require_Equal(t, state.NumDeleted, 10)
   908  	require_Equal(t, len(state.Deleted), 10)
   909  
   910  	// Check Fast State too.
   911  	state.Deleted = nil
   912  	ms.FastState(&state)
   913  	require_Equal(t, state.FirstSeq, 1)
   914  	require_Equal(t, state.LastSeq, 11)
   915  	require_Equal(t, state.Msgs, 1)
   916  	require_Equal(t, state.NumDeleted, 10)
   917  }
   918  
   919  func TestMemStoreMultiLastSeqs(t *testing.T) {
   920  	cfg := &StreamConfig{
   921  		Name:     "zzz",
   922  		Subjects: []string{"foo.*"},
   923  		Storage:  MemoryStorage,
   924  	}
   925  	ms, err := newMemStore(cfg)
   926  	require_NoError(t, err)
   927  	defer ms.Stop()
   928  
   929  	msg := []byte("abc")
   930  	for i := 0; i < 33; i++ {
   931  		ms.StoreMsg("foo.foo", nil, msg)
   932  		ms.StoreMsg("foo.bar", nil, msg)
   933  		ms.StoreMsg("foo.baz", nil, msg)
   934  	}
   935  	for i := 0; i < 33; i++ {
   936  		ms.StoreMsg("bar.foo", nil, msg)
   937  		ms.StoreMsg("bar.bar", nil, msg)
   938  		ms.StoreMsg("bar.baz", nil, msg)
   939  	}
   940  
   941  	checkResults := func(seqs, expected []uint64) {
   942  		t.Helper()
   943  		if len(seqs) != len(expected) {
   944  			t.Fatalf("Expected %+v got %+v", expected, seqs)
   945  		}
   946  		for i := range seqs {
   947  			if seqs[i] != expected[i] {
   948  				t.Fatalf("Expected %+v got %+v", expected, seqs)
   949  			}
   950  		}
   951  	}
   952  
   953  	// UpTo sequence 3. Tests block split.
   954  	seqs, err := ms.MultiLastSeqs([]string{"foo.*"}, 3, -1)
   955  	require_NoError(t, err)
   956  	checkResults(seqs, []uint64{1, 2, 3})
   957  	// Up to last sequence of the stream.
   958  	seqs, err = ms.MultiLastSeqs([]string{"foo.*"}, 0, -1)
   959  	require_NoError(t, err)
   960  	checkResults(seqs, []uint64{97, 98, 99})
   961  	// Check for bar.* at the end.
   962  	seqs, err = ms.MultiLastSeqs([]string{"bar.*"}, 0, -1)
   963  	require_NoError(t, err)
   964  	checkResults(seqs, []uint64{196, 197, 198})
   965  	// This should find nothing.
   966  	seqs, err = ms.MultiLastSeqs([]string{"bar.*"}, 99, -1)
   967  	require_NoError(t, err)
   968  	checkResults(seqs, nil)
   969  
   970  	// Do multiple subjects explicitly.
   971  	seqs, err = ms.MultiLastSeqs([]string{"foo.foo", "foo.bar", "foo.baz"}, 3, -1)
   972  	require_NoError(t, err)
   973  	checkResults(seqs, []uint64{1, 2, 3})
   974  	seqs, err = ms.MultiLastSeqs([]string{"foo.foo", "foo.bar", "foo.baz"}, 0, -1)
   975  	require_NoError(t, err)
   976  	checkResults(seqs, []uint64{97, 98, 99})
   977  	seqs, err = ms.MultiLastSeqs([]string{"bar.foo", "bar.bar", "bar.baz"}, 0, -1)
   978  	require_NoError(t, err)
   979  	checkResults(seqs, []uint64{196, 197, 198})
   980  	seqs, err = ms.MultiLastSeqs([]string{"bar.foo", "bar.bar", "bar.baz"}, 99, -1)
   981  	require_NoError(t, err)
   982  	checkResults(seqs, nil)
   983  
   984  	// Check single works
   985  	seqs, err = ms.MultiLastSeqs([]string{"foo.foo"}, 3, -1)
   986  	require_NoError(t, err)
   987  	checkResults(seqs, []uint64{1})
   988  
   989  	// Now test that we properly de-duplicate between filters.
   990  	seqs, err = ms.MultiLastSeqs([]string{"foo.*", "foo.bar"}, 3, -1)
   991  	require_NoError(t, err)
   992  	checkResults(seqs, []uint64{1, 2, 3})
   993  	seqs, err = ms.MultiLastSeqs([]string{"bar.>", "bar.bar", "bar.baz"}, 0, -1)
   994  	require_NoError(t, err)
   995  	checkResults(seqs, []uint64{196, 197, 198})
   996  
   997  	// All
   998  	seqs, err = ms.MultiLastSeqs([]string{">"}, 0, -1)
   999  	require_NoError(t, err)
  1000  	checkResults(seqs, []uint64{97, 98, 99, 196, 197, 198})
  1001  	seqs, err = ms.MultiLastSeqs([]string{">"}, 99, -1)
  1002  	require_NoError(t, err)
  1003  	checkResults(seqs, []uint64{97, 98, 99})
  1004  }
  1005  
  1006  func TestMemStoreMultiLastSeqsMaxAllowed(t *testing.T) {
  1007  	cfg := &StreamConfig{
  1008  		Name:     "zzz",
  1009  		Subjects: []string{"foo.*"},
  1010  		Storage:  MemoryStorage,
  1011  	}
  1012  	ms, err := newMemStore(cfg)
  1013  	require_NoError(t, err)
  1014  	defer ms.Stop()
  1015  
  1016  	msg := []byte("abc")
  1017  	for i := 1; i <= 100; i++ {
  1018  		ms.StoreMsg(fmt.Sprintf("foo.%d", i), nil, msg)
  1019  	}
  1020  	// Test that if we specify maxAllowed that we get the correct error.
  1021  	seqs, err := ms.MultiLastSeqs([]string{"foo.*"}, 0, 10)
  1022  	require_True(t, seqs == nil)
  1023  	require_Error(t, err, ErrTooManyResults)
  1024  }
  1025  
  1026  // Bug would cause PurgeEx to fail if it encountered a deleted msg at sequence to delete up to.
  1027  func TestMemStorePurgeExWithDeletedMsgs(t *testing.T) {
  1028  	cfg := &StreamConfig{
  1029  		Name:     "zzz",
  1030  		Subjects: []string{"foo"},
  1031  		Storage:  MemoryStorage,
  1032  	}
  1033  	ms, err := newMemStore(cfg)
  1034  	require_NoError(t, err)
  1035  	defer ms.Stop()
  1036  
  1037  	msg := []byte("abc")
  1038  	for i := 1; i <= 10; i++ {
  1039  		ms.StoreMsg("foo", nil, msg)
  1040  	}
  1041  	ms.RemoveMsg(2)
  1042  	ms.RemoveMsg(9) // This was the bug
  1043  
  1044  	n, err := ms.PurgeEx(_EMPTY_, 9, 0)
  1045  	require_NoError(t, err)
  1046  	require_Equal(t, n, 7)
  1047  
  1048  	var state StreamState
  1049  	ms.FastState(&state)
  1050  	require_Equal(t, state.FirstSeq, 10)
  1051  	require_Equal(t, state.LastSeq, 10)
  1052  	require_Equal(t, state.Msgs, 1)
  1053  }