| 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 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"time" |
| 19 |
) |
| 20 |
|
| 21 |
// SDMMeta holds pending/proposed data for subject delete markers or message removals. |
| 22 |
type SDMMeta struct { |
| 23 |
totals map[string]uint64 |
| 24 |
pending map[uint64]SDMBySeq |
| 25 |
} |
| 26 |
|
| 27 |
// SDMBySeq holds data for a message with a specific sequence. |
| 28 |
type SDMBySeq struct { |
| 29 |
last bool // Whether the message for this sequence was the last for this subject. |
| 30 |
ts int64 // Last timestamp we proposed a removal/sdm. |
| 31 |
} |
| 32 |
|
| 33 |
func newSDMMeta() *SDMMeta { |
| 34 |
return &SDMMeta{ |
| 35 |
totals: make(map[string]uint64, 1), |
| 36 |
pending: make(map[uint64]SDMBySeq, 1), |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// isSubjectDeleteMarker returns whether the headers indicate this message is a subject delete marker. |
| 41 |
// Either it's a usual marker with JSMarkerReason, or it's a KV Purge marker as the KVOperation. |
| 42 |
func isSubjectDeleteMarker(hdr []byte) bool { |
| 43 |
return len(sliceHeader(JSMarkerReason, hdr)) != 0 || bytes.Equal(sliceHeader(KVOperation, hdr), KVOperationValuePurge) |
| 44 |
} |
| 45 |
|
| 46 |
// empty clears all data. |
| 47 |
func (sdm *SDMMeta) empty() { |
| 48 |
if sdm == nil { |
| 49 |
return |
| 50 |
} |
| 51 |
clear(sdm.totals) |
| 52 |
clear(sdm.pending) |
| 53 |
} |
| 54 |
|
| 55 |
// trackPending caches the given seq and subj and whether it's the last message for that subject. |
| 56 |
func (sdm *SDMMeta) trackPending(seq uint64, subj string, last bool) bool { |
| 57 |
if p, ok := sdm.pending[seq]; ok { |
| 58 |
return p.last |
| 59 |
} |
| 60 |
sdm.pending[seq] = SDMBySeq{last, time.Now().UnixNano()} |
| 61 |
sdm.totals[subj]++ |
| 62 |
return last |
| 63 |
} |
| 64 |
|
| 65 |
// removeSeqAndSubject clears the seq and subj from the cache. |
| 66 |
func (sdm *SDMMeta) removeSeqAndSubject(seq uint64, subj string) { |
| 67 |
if sdm == nil { |
| 68 |
return |
| 69 |
} |
| 70 |
if _, ok := sdm.pending[seq]; ok { |
| 71 |
delete(sdm.pending, seq) |
| 72 |
if msgs, ok := sdm.totals[subj]; ok { |
| 73 |
if msgs <= 1 { |
| 74 |
delete(sdm.totals, subj) |
| 75 |
} else { |
| 76 |
sdm.totals[subj] = msgs - 1 |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |