Debian Codegraph @

server/ats/ats.go

raw
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 // ats controls the go routines for the access time service.
15 // This allows more efficient unixnano operations for cache access times.
16 // We will have one per binary (usually per server).
17 package ats
18
19 import (
20 "sync/atomic"
21 "time"
22 )
23
24 // Update every 100ms for gathering access time in unix nano.
25 const TickInterval = 100 * time.Millisecond
26
27 var (
28 // Our unix nano time.
29 utime atomic.Int64
30 // How may registered users do we have, controls lifetime of Go routine.
31 refs atomic.Int64
32 // To signal the shutdown of the Go routine.
33 done chan struct{}
34 )
35
36 func init() {
37 // Initialize our done chan.
38 done = make(chan struct{}, 1)
39 }
40
41 // Register usage. This will happen on filestore creation.
42 func Register() {
43 if v := refs.Add(1); v == 1 {
44 // This is the first to register (could also go up and down),
45 // so spin up Go routine and grab initial time.
46 utime.Store(time.Now().UnixNano())
47
48 go func() {
49 ticker := time.NewTicker(TickInterval)
50 defer ticker.Stop()
51 for {
52 select {
53 case <-ticker.C:
54 utime.Store(time.Now().UnixNano())
55 case <-done:
56 return
57 }
58 }
59 }()
60 }
61 }
62
63 // Unregister usage. We will shutdown the go routine if no more registered users.
64 func Unregister() {
65 if v := refs.Add(-1); v == 0 {
66 done <- struct{}{}
67 } else if v < 0 {
68 refs.Store(0)
69 panic("unbalanced unregister for access time state")
70 }
71 }
72
73 // Will load the access time from an atomic.
74 // If no one has registered this will return 0 or stale data.
75 // It is the responsibility of the user to properly register and unregister.
76 func AccessTime() int64 {
77 // Return last updated time.
78 v := utime.Load()
79 if v == 0 {
80 // Always register a time, the worst case is a stale time.
81 // On startup, we can register in parallel and could previously panic.
82 v = time.Now().UnixNano()
83 utime.Store(v)
84 }
85 return v
86 }