blob: 49607711ddfb307633a87acb9943ac1c8cb18a87 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Serge Bazanskic00318e2021-03-03 12:39:24 +01002// SPDX-License-Identifier: Apache-2.0
Serge Bazanskic00318e2021-03-03 12:39:24 +01003
Serge Bazanski68ca5ee2021-04-27 16:09:16 +02004package memory
Serge Bazanskic00318e2021-03-03 12:39:24 +01005
6import (
7 "context"
Serge Bazanski37110c32023-03-01 13:57:27 +00008 "errors"
Serge Bazanskic00318e2021-03-03 12:39:24 +01009 "fmt"
10 "sync"
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020011
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020012 "source.monogon.dev/osbase/event"
Serge Bazanskic00318e2021-03-03 12:39:24 +010013)
14
15var (
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020016 // Type assert that *Value implements Value. We do this artificially, as
Serge Bazanskic00318e2021-03-03 12:39:24 +010017 // there currently is no code path that needs this to be strictly true. However,
18 // users of this library might want to rely on the Value type instead of
19 // particular Value implementations.
Serge Bazanski37110c32023-03-01 13:57:27 +000020 _ event.Value[int] = &Value[int]{}
Serge Bazanskic00318e2021-03-03 12:39:24 +010021)
22
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020023// Value is a 'memory value', which implements a event.Value stored in memory.
24// It is safe to construct an empty object of this type. However, this must not
25// be copied.
Serge Bazanski37110c32023-03-01 13:57:27 +000026type Value[T any] struct {
Serge Bazanskic00318e2021-03-03 12:39:24 +010027 // mu guards the inner, innerSet and watchers fields.
28 mu sync.RWMutex
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020029 // inner is the latest data Set on the Value. It is used to provide the
30 // newest version of the Set data to new watchers.
Serge Bazanski37110c32023-03-01 13:57:27 +000031 inner T
Serge Bazanskic00318e2021-03-03 12:39:24 +010032 // innerSet is true when inner has been Set at least once. It is used to
33 // differentiate between a nil and unset value.
34 innerSet bool
35 // watchers is the list of watchers that should be updated when new data is
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020036 // Set. It will grow on every .Watch() and shrink any time a watcher is
Serge Bazanskic00318e2021-03-03 12:39:24 +010037 // determined to have been closed.
Serge Bazanski37110c32023-03-01 13:57:27 +000038 watchers []*watcher[T]
Serge Bazanskic00318e2021-03-03 12:39:24 +010039}
40
41// Set updates the Value to the given data. It is safe to call this from
42// multiple goroutines, including concurrently.
43//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020044// For more information about guarantees, see event.Value.Set.
Serge Bazanski37110c32023-03-01 13:57:27 +000045func (m *Value[T]) Set(val T) {
Serge Bazanskic00318e2021-03-03 12:39:24 +010046 m.mu.Lock()
47 defer m.mu.Unlock()
48
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020049 // Update the data that is provided on first Get() to watchers.
Serge Bazanskic00318e2021-03-03 12:39:24 +010050 m.inner = val
51 m.innerSet = true
52
53 // Go through all watchers, updating them on the new value and filtering out
54 // all closed watchers.
Jan Schär36bde9c2024-03-19 15:05:33 +010055 newWatchers := m.watchers[:0]
Serge Bazanskic00318e2021-03-03 12:39:24 +010056 for _, w := range m.watchers {
Serge Bazanskic00318e2021-03-03 12:39:24 +010057 if w.closed() {
58 continue
59 }
Jan Schär5b997a12024-12-19 15:10:07 +010060 w.update(val)
Serge Bazanskic00318e2021-03-03 12:39:24 +010061 newWatchers = append(newWatchers, w)
62 }
Jan Schär36bde9c2024-03-19 15:05:33 +010063 if cap(newWatchers) > len(newWatchers)*3 {
64 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
65 newWatchers = append(reallocated, newWatchers...)
66 }
Serge Bazanskic00318e2021-03-03 12:39:24 +010067 m.watchers = newWatchers
68}
69
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020070// watcher implements the event.Watcher interface for watchers returned by
71// Value.
Serge Bazanski37110c32023-03-01 13:57:27 +000072type watcher[T any] struct {
Jan Schär5b997a12024-12-19 15:10:07 +010073 // valueC is a buffered channel of size 1 for submitting values to the
Jan Schär36bde9c2024-03-19 15:05:33 +010074 // watcher.
Jan Schär5b997a12024-12-19 15:10:07 +010075 valueC chan T
Serge Bazanskic00318e2021-03-03 12:39:24 +010076
77 // getSem is a channel-based semaphore (which is of size 1, and thus in
78 // fact a mutex) that is used to ensure that only a single .Get() call is
79 // active. It is implemented as a channel to permit concurrent .Get() calls
80 // to error out instead of blocking.
81 getSem chan struct{}
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020082 // close is a channel that is closed when this watcher is itself Closed.
Serge Bazanskic00318e2021-03-03 12:39:24 +010083 close chan struct{}
84}
85
86// Watch retrieves a Watcher that keeps track on the version of the data
87// contained within the Value that was last seen by a consumer.
88//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020089// For more information about guarantees, see event.Value.Watch.
Serge Bazanski37110c32023-03-01 13:57:27 +000090func (m *Value[T]) Watch() event.Watcher[T] {
91 waiter := &watcher[T]{
Jan Schär5b997a12024-12-19 15:10:07 +010092 valueC: make(chan T, 1),
93 close: make(chan struct{}),
94 getSem: make(chan struct{}, 1),
Serge Bazanskic00318e2021-03-03 12:39:24 +010095 }
Serge Bazanskic00318e2021-03-03 12:39:24 +010096
Serge Bazanskic00318e2021-03-03 12:39:24 +010097 m.mu.Lock()
Jan Schär36bde9c2024-03-19 15:05:33 +010098 // If the watchers slice is at capacity, drop closed watchers, and
99 // reallocate the slice at 2x length if it is not between 1.5x and 3x.
100 if len(m.watchers) == cap(m.watchers) {
101 newWatchers := m.watchers[:0]
102 for _, w := range m.watchers {
103 if !w.closed() {
104 newWatchers = append(newWatchers, w)
105 }
106 }
107 if cap(newWatchers)*2 < len(newWatchers)*3 || cap(newWatchers) > len(newWatchers)*3 {
108 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
109 newWatchers = append(reallocated, newWatchers...)
110 }
111 m.watchers = newWatchers
112 }
113 // Append this watcher to the Value.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100114 m.watchers = append(m.watchers, waiter)
Jan Schär5b997a12024-12-19 15:10:07 +0100115 // If the Value already has some value set, put it in the channel.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100116 if m.innerSet {
Jan Schär5b997a12024-12-19 15:10:07 +0100117 waiter.valueC <- m.inner
Serge Bazanskic00318e2021-03-03 12:39:24 +0100118 }
119 m.mu.Unlock()
120
121 return waiter
122}
123
Serge Bazanskic00318e2021-03-03 12:39:24 +0100124// closed returns whether this watcher has been closed.
Serge Bazanski37110c32023-03-01 13:57:27 +0000125func (m *watcher[T]) closed() bool {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100126 select {
127 case _, ok := <-m.close:
128 if !ok {
129 return true
130 }
131 default:
132 }
133 return false
134}
135
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200136// update is the high level update-this-watcher function called by Value.
Jan Schär5b997a12024-12-19 15:10:07 +0100137func (m *watcher[T]) update(val T) {
138 // If there is already a value in the channel that was not retrieved, drop it.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100139 select {
Jan Schär5b997a12024-12-19 15:10:07 +0100140 case <-m.valueC:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100141 default:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100142 }
Jan Schär36bde9c2024-03-19 15:05:33 +0100143 // The channel is now empty, so sending to it cannot block.
Jan Schär5b997a12024-12-19 15:10:07 +0100144 m.valueC <- val
Serge Bazanskic00318e2021-03-03 12:39:24 +0100145}
146
Serge Bazanski37110c32023-03-01 13:57:27 +0000147func (m *watcher[T]) Close() error {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100148 close(m.close)
149 return nil
150}
151
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200152// Get blocks until a Value's data is available. See event.Watcher.Get for
153// guarantees and more information.
Serge Bazanski37110c32023-03-01 13:57:27 +0000154func (m *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100155 // Make sure we're the only active .Get call.
Serge Bazanski37110c32023-03-01 13:57:27 +0000156 var empty T
Serge Bazanskic00318e2021-03-03 12:39:24 +0100157 select {
158 case m.getSem <- struct{}{}:
159 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000160 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic00318e2021-03-03 12:39:24 +0100161 }
162 defer func() {
163 <-m.getSem
164 }()
165
Serge Bazanski37110c32023-03-01 13:57:27 +0000166 var predicate func(t T) bool
167 for _, opt := range opts {
168 if opt.Predicate != nil {
169 predicate = opt.Predicate
170 }
Tim Windelschmidt885668a2024-04-19 00:01:06 +0200171 if opt.BacklogOnly {
Serge Bazanski37110c32023-03-01 13:57:27 +0000172 return empty, errors.New("BacklogOnly is not implemented for memory watchers")
Serge Bazanski8d45a052021-10-18 17:24:24 +0200173 }
174 }
175
Serge Bazanskic00318e2021-03-03 12:39:24 +0100176 for {
177 select {
Jan Schär5b997a12024-12-19 15:10:07 +0100178 case <-ctx.Done():
179 return empty, ctx.Err()
180 case val := <-m.valueC:
181 if predicate != nil && !predicate(val) {
182 continue
Serge Bazanski37110c32023-03-01 13:57:27 +0000183 }
Jan Schär5b997a12024-12-19 15:10:07 +0100184 return val, nil
Serge Bazanskic00318e2021-03-03 12:39:24 +0100185 }
186 }
187}