| 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 |
"encoding/binary" |
| 18 |
"errors" |
| 19 |
"io" |
| 20 |
"math" |
| 21 |
"slices" |
| 22 |
"strings" |
| 23 |
"time" |
| 24 |
|
| 25 |
"github.com/nats-io/nats-server/v2/server/thw" |
| 26 |
) |
| 27 |
|
| 28 |
// Error for when we try to decode a binary-encoded message schedule with an unknown version number. |
| 29 |
var ErrMsgScheduleInvalidVersion = errors.New("msg scheduling: encoded version not known") |
| 30 |
|
| 31 |
const ( |
| 32 |
headerLen = 17 // 1 byte magic + 2x uint64s |
| 33 |
) |
| 34 |
|
| 35 |
type MsgScheduling struct { |
| 36 |
run func() |
| 37 |
ttls *thw.HashWheel |
| 38 |
timer *time.Timer |
| 39 |
running bool |
| 40 |
deadline int64 |
| 41 |
schedules map[string]*MsgSchedule |
| 42 |
seqToSubj map[uint64]string |
| 43 |
inflight map[string]struct{} |
| 44 |
} |
| 45 |
|
| 46 |
type MsgSchedule struct { |
| 47 |
seq uint64 |
| 48 |
ts int64 |
| 49 |
} |
| 50 |
|
| 51 |
func newMsgScheduling(run func()) *MsgScheduling { |
| 52 |
return &MsgScheduling{ |
| 53 |
run: run, |
| 54 |
ttls: thw.NewHashWheel(), |
| 55 |
schedules: make(map[string]*MsgSchedule), |
| 56 |
seqToSubj: make(map[uint64]string), |
| 57 |
inflight: make(map[string]struct{}), |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
func (ms *MsgScheduling) add(seq uint64, subj string, ts int64) { |
| 62 |
ms.init(seq, subj, ts) |
| 63 |
ms.resetTimer() |
| 64 |
} |
| 65 |
|
| 66 |
func (ms *MsgScheduling) init(seq uint64, subj string, ts int64) { |
| 67 |
if sched, ok := ms.schedules[subj]; ok { |
| 68 |
delete(ms.seqToSubj, sched.seq) |
| 69 |
// Remove and add separately, since they'll have different sequences. |
| 70 |
ms.ttls.Remove(sched.seq, sched.ts) |
| 71 |
ms.ttls.Add(seq, ts) |
| 72 |
sched.ts, sched.seq = ts, seq |
| 73 |
} else { |
| 74 |
ms.ttls.Add(seq, ts) |
| 75 |
ms.schedules[subj] = &MsgSchedule{seq: seq, ts: ts} |
| 76 |
} |
| 77 |
ms.seqToSubj[seq] = subj |
| 78 |
delete(ms.inflight, subj) |
| 79 |
} |
| 80 |
|
| 81 |
func (ms *MsgScheduling) update(subj string, ts int64) { |
| 82 |
if sched, ok := ms.schedules[subj]; ok { |
| 83 |
// Remove and add separately, it's for the same sequence, but if replicated |
| 84 |
// this server could not know the previous timestamp yet. |
| 85 |
ms.ttls.Remove(sched.seq, sched.ts) |
| 86 |
ms.ttls.Add(sched.seq, ts) |
| 87 |
sched.ts = ts |
| 88 |
delete(ms.inflight, subj) |
| 89 |
ms.resetTimer() |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
func (ms *MsgScheduling) markInflight(subj string) { |
| 94 |
if _, ok := ms.schedules[subj]; ok { |
| 95 |
ms.inflight[subj] = struct{}{} |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
func (ms *MsgScheduling) isInflight(subj string) bool { |
| 100 |
_, ok := ms.inflight[subj] |
| 101 |
return ok |
| 102 |
} |
| 103 |
|
| 104 |
func (ms *MsgScheduling) remove(seq uint64) { |
| 105 |
if subj, ok := ms.seqToSubj[seq]; ok { |
| 106 |
ms.removeSubject(subj) |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
func (ms *MsgScheduling) removeSubject(subj string) { |
| 111 |
if sched, ok := ms.schedules[subj]; ok { |
| 112 |
ms.ttls.Remove(sched.seq, sched.ts) |
| 113 |
delete(ms.schedules, subj) |
| 114 |
delete(ms.seqToSubj, sched.seq) |
| 115 |
delete(ms.inflight, subj) |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
func (ms *MsgScheduling) clearInflight() { |
| 120 |
ms.inflight = make(map[string]struct{}) |
| 121 |
} |
| 122 |
|
| 123 |
func (ms *MsgScheduling) resetTimer() { |
| 124 |
// If we're already scheduling messages, it will make sure to reset. |
| 125 |
// Don't trigger again, as that could result in many expire goroutines. |
| 126 |
if ms.running { |
| 127 |
return |
| 128 |
} |
| 129 |
|
| 130 |
next := ms.ttls.GetNextExpiration(math.MaxInt64) |
| 131 |
if next == math.MaxInt64 { |
| 132 |
clearTimer(&ms.timer) |
| 133 |
return |
| 134 |
} |
| 135 |
fireIn := time.Until(time.Unix(0, next)) |
| 136 |
|
| 137 |
// Make sure we aren't firing too often either way, otherwise we can |
| 138 |
// negatively impact stream ingest performance. |
| 139 |
if fireIn < 250*time.Millisecond { |
| 140 |
fireIn = 250 * time.Millisecond |
| 141 |
} |
| 142 |
|
| 143 |
// If we want to kick the timer to run later than what was assigned before, don't reset it. |
| 144 |
// Otherwise, we could get in a situation where the timer is continuously reset, and it never runs. |
| 145 |
deadline := time.Now().UnixNano() + fireIn.Nanoseconds() |
| 146 |
if ms.deadline > 0 && deadline > ms.deadline { |
| 147 |
return |
| 148 |
} |
| 149 |
|
| 150 |
ms.deadline = deadline |
| 151 |
if ms.timer != nil { |
| 152 |
ms.timer.Reset(fireIn) |
| 153 |
} else { |
| 154 |
ms.timer = time.AfterFunc(fireIn, ms.run) |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
func (ms *MsgScheduling) getScheduledMessages(loadMsg func(seq uint64, smv *StoreMsg) *StoreMsg, loadLast func(subj string, smv *StoreMsg) *StoreMsg) []*inMsg { |
| 159 |
var ( |
| 160 |
smv StoreMsg |
| 161 |
srcSmv StoreMsg |
| 162 |
sm *StoreMsg |
| 163 |
msgs []*inMsg |
| 164 |
) |
| 165 |
ms.ttls.ExpireTasks(func(seq uint64, ts int64) bool { |
| 166 |
// Need to grab the message for the specified sequence, and check |
| 167 |
// if it hasn't been removed in the meantime. |
| 168 |
sm = loadMsg(seq, &smv) |
| 169 |
if sm != nil { |
| 170 |
// If already inflight, don't duplicate a scheduled message. The stream could |
| 171 |
// be replicated and the scheduled message could take some time to propagate. |
| 172 |
subj := sm.subj |
| 173 |
if ms.isInflight(subj) { |
| 174 |
return false |
| 175 |
} |
| 176 |
// Validate the contents are correct if not, we just remove it from THW. |
| 177 |
pattern := bytesToString(sliceHeader(JSSchedulePattern, sm.hdr)) |
| 178 |
if pattern == _EMPTY_ { |
| 179 |
ms.remove(seq) |
| 180 |
return true |
| 181 |
} |
| 182 |
loc, apiErr := loadMessageScheduleLocation(sm.hdr) |
| 183 |
if apiErr != nil { |
| 184 |
ms.remove(seq) |
| 185 |
return true |
| 186 |
} |
| 187 |
next, repeat, ok := parseMsgSchedule(pattern, loc, ts) |
| 188 |
if !ok { |
| 189 |
ms.remove(seq) |
| 190 |
return true |
| 191 |
} |
| 192 |
ttl, ok := getMessageScheduleTTL(sm.hdr) |
| 193 |
if !ok { |
| 194 |
ms.remove(seq) |
| 195 |
return true |
| 196 |
} |
| 197 |
target := getMessageScheduleTarget(sm.hdr) |
| 198 |
if target == _EMPTY_ { |
| 199 |
ms.remove(seq) |
| 200 |
return true |
| 201 |
} |
| 202 |
rollup := getMessageScheduleRollup(sm.hdr) |
| 203 |
source := getMessageScheduleSource(sm.hdr) |
| 204 |
if source != _EMPTY_ { |
| 205 |
// Fall back to the scheduled message's own content if the source has no last message. |
| 206 |
if srcSm := loadLast(source, &srcSmv); srcSm != nil { |
| 207 |
sm = srcSm |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
// Copy, as this is retrieved directly from storage, and we'll need to keep hold of this for some time. |
| 212 |
// And in the case of headers, we'll copy all of them, but make changes. |
| 213 |
hdr, msg := copyBytes(sm.hdr), copyBytes(sm.msg) |
| 214 |
|
| 215 |
// Strip headers specific to message scheduling. |
| 216 |
// Covers Nats-Schedule, Nats-Schedule-*, and Nats-Scheduler. |
| 217 |
hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Schedule") |
| 218 |
// Strip headers that could prevent persisting this scheduled message. |
| 219 |
hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Expected-") |
| 220 |
hdr = removeHeaderIfPresent(hdr, JSMsgId) |
| 221 |
hdr = removeHeaderIfPresent(hdr, JSMessageTTL) |
| 222 |
hdr = removeHeaderIfPresent(hdr, JSMsgRollup) |
| 223 |
|
| 224 |
// Add headers for the scheduled message. |
| 225 |
hdr = genHeader(hdr, JSScheduler, subj) |
| 226 |
if !repeat { |
| 227 |
hdr = genHeader(hdr, JSScheduleNext, JSScheduleNextPurge) // Purge the schedule message itself. |
| 228 |
} else { |
| 229 |
hdr = genHeader(hdr, JSScheduleNext, next.Format(time.RFC3339Nano)) // Next time the schedule fires. |
| 230 |
} |
| 231 |
if ttl != _EMPTY_ { |
| 232 |
hdr = genHeader(hdr, JSMessageTTL, ttl) |
| 233 |
} |
| 234 |
if rollup != _EMPTY_ { |
| 235 |
hdr = genHeader(hdr, JSMsgRollup, rollup) |
| 236 |
} |
| 237 |
msgs = append(msgs, &inMsg{seq: seq, subj: target, hdr: hdr, msg: msg}) |
| 238 |
ms.markInflight(subj) |
| 239 |
return false |
| 240 |
} |
| 241 |
ms.remove(seq) |
| 242 |
return true |
| 243 |
}) |
| 244 |
// THW is unordered, so must sort by sequence. |
| 245 |
slices.SortFunc(msgs, func(a, b *inMsg) int { |
| 246 |
if a.seq == b.seq { |
| 247 |
return 0 |
| 248 |
} else if a.seq < b.seq { |
| 249 |
return -1 |
| 250 |
} else { |
| 251 |
return 1 |
| 252 |
} |
| 253 |
}) |
| 254 |
return msgs |
| 255 |
} |
| 256 |
|
| 257 |
// encode writes out the contents of the schedule into a binary snapshot |
| 258 |
// and returns it. The high seq number is included in the snapshot and will |
| 259 |
// be returned on decode. |
| 260 |
func (ms *MsgScheduling) encode(highSeq uint64) []byte { |
| 261 |
count := uint64(len(ms.schedules)) |
| 262 |
b := make([]byte, 0, headerLen+(count*(2*binary.MaxVarintLen64))) |
| 263 |
b = append(b, 1) // Magic version |
| 264 |
b = binary.LittleEndian.AppendUint64(b, count) // Entry count |
| 265 |
b = binary.LittleEndian.AppendUint64(b, highSeq) // Stamp |
| 266 |
for subj, sched := range ms.schedules { |
| 267 |
slen := min(uint64(len(subj)), math.MaxUint16) |
| 268 |
b = binary.LittleEndian.AppendUint16(b, uint16(slen)) |
| 269 |
b = append(b, subj[:slen]...) |
| 270 |
b = binary.AppendVarint(b, sched.ts) |
| 271 |
b = binary.AppendUvarint(b, sched.seq) |
| 272 |
} |
| 273 |
return b |
| 274 |
} |
| 275 |
|
| 276 |
// decode snapshots a binary-encoded schedule and replaces the contents of this |
| 277 |
// schedule with them. Returns the high seq number from the snapshot. |
| 278 |
func (ms *MsgScheduling) decode(b []byte) (uint64, error) { |
| 279 |
if len(b) < headerLen { |
| 280 |
return 0, io.ErrShortBuffer |
| 281 |
} |
| 282 |
if b[0] != 1 { |
| 283 |
return 0, ErrMsgScheduleInvalidVersion |
| 284 |
} |
| 285 |
|
| 286 |
count := binary.LittleEndian.Uint64(b[1:]) |
| 287 |
stamp := binary.LittleEndian.Uint64(b[9:]) |
| 288 |
b = b[headerLen:] |
| 289 |
for i := uint64(0); i < count; i++ { |
| 290 |
if len(b) < 2 { |
| 291 |
return 0, io.ErrUnexpectedEOF |
| 292 |
} |
| 293 |
sl := int(binary.LittleEndian.Uint16(b)) |
| 294 |
b = b[2:] |
| 295 |
if len(b) < sl { |
| 296 |
return 0, io.ErrUnexpectedEOF |
| 297 |
} |
| 298 |
subj := string(b[:sl]) |
| 299 |
b = b[sl:] |
| 300 |
ts, tn := binary.Varint(b) |
| 301 |
if tn <= 0 { |
| 302 |
return 0, io.ErrUnexpectedEOF |
| 303 |
} |
| 304 |
seq, vn := binary.Uvarint(b[tn:]) |
| 305 |
if vn <= 0 { |
| 306 |
return 0, io.ErrUnexpectedEOF |
| 307 |
} |
| 308 |
ms.init(seq, subj, ts) |
| 309 |
b = b[tn+vn:] |
| 310 |
} |
| 311 |
return stamp, nil |
| 312 |
} |
| 313 |
|
| 314 |
// parseMsgSchedule parses a message schedule pattern and returns the time |
| 315 |
// to fire, whether it is a repeating schedule, and whether the pattern was valid. |
| 316 |
func parseMsgSchedule(pattern string, loc *time.Location, ts int64) (time.Time, bool, bool) { |
| 317 |
if pattern == _EMPTY_ { |
| 318 |
return time.Time{}, false, true |
| 319 |
} |
| 320 |
// Exact time. |
| 321 |
if strings.HasPrefix(pattern, "@at ") { |
| 322 |
// Time zone is not supported for @at. |
| 323 |
if loc != nil { |
| 324 |
return time.Time{}, false, false |
| 325 |
} |
| 326 |
t, err := time.Parse(time.RFC3339, pattern[4:]) |
| 327 |
return t, false, err == nil |
| 328 |
} |
| 329 |
// Repeating on a simple interval. |
| 330 |
if strings.HasPrefix(pattern, "@every ") { |
| 331 |
// Time zone is not supported for @every. |
| 332 |
if loc != nil { |
| 333 |
return time.Time{}, false, false |
| 334 |
} |
| 335 |
dur, err := time.ParseDuration(pattern[7:]) |
| 336 |
if err != nil { |
| 337 |
return time.Time{}, false, false |
| 338 |
} |
| 339 |
// Only allow intervals of at least a second. |
| 340 |
if dur.Seconds() < 1 { |
| 341 |
return time.Time{}, false, false |
| 342 |
} |
| 343 |
// If this schedule would trigger multiple times, for example after a restart, skip ahead and only fire once. |
| 344 |
next := time.Unix(0, ts).UTC().Round(time.Second).Add(dur) |
| 345 |
if now := time.Now().UTC(); next.Before(now) { |
| 346 |
next = now.Round(time.Second).Add(dur) |
| 347 |
} |
| 348 |
return next, true, true |
| 349 |
} |
| 350 |
|
| 351 |
// Predefined schedules for cron. |
| 352 |
switch pattern { |
| 353 |
case "@yearly", "@annually": |
| 354 |
pattern = "0 0 0 1 1 *" |
| 355 |
case "@monthly": |
| 356 |
pattern = "0 0 0 1 * *" |
| 357 |
case "@weekly": |
| 358 |
pattern = "0 0 0 * * 0" |
| 359 |
case "@daily", "@midnight": |
| 360 |
pattern = "0 0 0 * * *" |
| 361 |
case "@hourly": |
| 362 |
pattern = "0 0 * * * *" |
| 363 |
} |
| 364 |
|
| 365 |
// Parse the cron pattern. |
| 366 |
next, err := parseCron(pattern, loc, ts) |
| 367 |
if err != nil { |
| 368 |
return time.Time{}, false, false |
| 369 |
} |
| 370 |
// If this schedule would trigger multiple times, for example after a restart, skip ahead and only fire once. |
| 371 |
if now := time.Now().UTC(); next.Before(now) { |
| 372 |
ts = now.Round(time.Second).UnixNano() |
| 373 |
next, err = parseCron(pattern, loc, ts) |
| 374 |
if err != nil { |
| 375 |
return time.Time{}, false, false |
| 376 |
} |
| 377 |
} |
| 378 |
return next, true, true |
| 379 |
} |