blob: 7402d645c0851e29dc58b2efb66ea3ef7c4c2a43 [file] [log] [blame]
Serge Bazanskic00318e2021-03-03 12:39:24 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020017package memory
Serge Bazanskic00318e2021-03-03 12:39:24 +010018
19import (
20 "context"
Serge Bazanski37110c32023-03-01 13:57:27 +000021 "errors"
Serge Bazanskic00318e2021-03-03 12:39:24 +010022 "fmt"
23 "sync"
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020024
25 "source.monogon.dev/metropolis/pkg/event"
Serge Bazanskic00318e2021-03-03 12:39:24 +010026)
27
28var (
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020029 // Type assert that *Value implements Value. We do this artificially, as
Serge Bazanskic00318e2021-03-03 12:39:24 +010030 // there currently is no code path that needs this to be strictly true. However,
31 // users of this library might want to rely on the Value type instead of
32 // particular Value implementations.
Serge Bazanski37110c32023-03-01 13:57:27 +000033 _ event.Value[int] = &Value[int]{}
Serge Bazanskic00318e2021-03-03 12:39:24 +010034)
35
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020036// Value is a 'memory value', which implements a event.Value stored in memory.
37// It is safe to construct an empty object of this type. However, this must not
38// be copied.
Serge Bazanski37110c32023-03-01 13:57:27 +000039type Value[T any] struct {
Serge Bazanskic00318e2021-03-03 12:39:24 +010040 // mu guards the inner, innerSet and watchers fields.
41 mu sync.RWMutex
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020042 // inner is the latest data Set on the Value. It is used to provide the
43 // newest version of the Set data to new watchers.
Serge Bazanski37110c32023-03-01 13:57:27 +000044 inner T
Serge Bazanskic00318e2021-03-03 12:39:24 +010045 // innerSet is true when inner has been Set at least once. It is used to
46 // differentiate between a nil and unset value.
47 innerSet bool
48 // watchers is the list of watchers that should be updated when new data is
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020049 // Set. It will grow on every .Watch() and shrink any time a watcher is
Serge Bazanskic00318e2021-03-03 12:39:24 +010050 // determined to have been closed.
Serge Bazanski37110c32023-03-01 13:57:27 +000051 watchers []*watcher[T]
Serge Bazanskic00318e2021-03-03 12:39:24 +010052
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020053 // Sync, if set to true, blocks all .Set() calls on the Value until all
54 // Watchers derived from it actively .Get() the new value. This can be used
55 // to ensure Watchers always receive a full log of all Set() calls.
Serge Bazanskic00318e2021-03-03 12:39:24 +010056 //
57 // This must not be changed after the first .Set/.Watch call.
58 //
59 // This is an experimental API and subject to change. It might be migrated
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020060 // to per-Watcher settings defined within the main event.Value/Watcher
Serge Bazanskic00318e2021-03-03 12:39:24 +010061 // interfaces.
62 Sync bool
63}
64
65// Set updates the Value to the given data. It is safe to call this from
66// multiple goroutines, including concurrently.
67//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020068// For more information about guarantees, see event.Value.Set.
Serge Bazanski37110c32023-03-01 13:57:27 +000069func (m *Value[T]) Set(val T) {
Serge Bazanskic00318e2021-03-03 12:39:24 +010070 m.mu.Lock()
71 defer m.mu.Unlock()
72
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020073 // Update the data that is provided on first Get() to watchers.
Serge Bazanskic00318e2021-03-03 12:39:24 +010074 m.inner = val
75 m.innerSet = true
76
77 // Go through all watchers, updating them on the new value and filtering out
78 // all closed watchers.
Jan Schär36bde9c2024-03-19 15:05:33 +010079 newWatchers := m.watchers[:0]
Serge Bazanskic00318e2021-03-03 12:39:24 +010080 for _, w := range m.watchers {
Serge Bazanskic00318e2021-03-03 12:39:24 +010081 if w.closed() {
82 continue
83 }
84 w.update(m.Sync, val)
85 newWatchers = append(newWatchers, w)
86 }
Jan Schär36bde9c2024-03-19 15:05:33 +010087 if cap(newWatchers) > len(newWatchers)*3 {
88 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
89 newWatchers = append(reallocated, newWatchers...)
90 }
Serge Bazanskic00318e2021-03-03 12:39:24 +010091 m.watchers = newWatchers
92}
93
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020094// watcher implements the event.Watcher interface for watchers returned by
95// Value.
Serge Bazanski37110c32023-03-01 13:57:27 +000096type watcher[T any] struct {
Jan Schär36bde9c2024-03-19 15:05:33 +010097 // bufferedC is a buffered channel of size 1 for submitting values to the
98 // watcher.
99 bufferedC chan T
100 // unbufferedC is an unbuffered channel, which is used when Sync is enabled.
101 unbufferedC chan T
Serge Bazanskic00318e2021-03-03 12:39:24 +0100102
103 // getSem is a channel-based semaphore (which is of size 1, and thus in
104 // fact a mutex) that is used to ensure that only a single .Get() call is
105 // active. It is implemented as a channel to permit concurrent .Get() calls
106 // to error out instead of blocking.
107 getSem chan struct{}
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200108 // close is a channel that is closed when this watcher is itself Closed.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100109 close chan struct{}
110}
111
112// Watch retrieves a Watcher that keeps track on the version of the data
113// contained within the Value that was last seen by a consumer.
114//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200115// For more information about guarantees, see event.Value.Watch.
Serge Bazanski37110c32023-03-01 13:57:27 +0000116func (m *Value[T]) Watch() event.Watcher[T] {
117 waiter := &watcher[T]{
Jan Schär36bde9c2024-03-19 15:05:33 +0100118 bufferedC: make(chan T, 1),
119 unbufferedC: make(chan T),
120 close: make(chan struct{}),
121 getSem: make(chan struct{}, 1),
Serge Bazanskic00318e2021-03-03 12:39:24 +0100122 }
Serge Bazanskic00318e2021-03-03 12:39:24 +0100123
Serge Bazanskic00318e2021-03-03 12:39:24 +0100124 m.mu.Lock()
Jan Schär36bde9c2024-03-19 15:05:33 +0100125 // If the watchers slice is at capacity, drop closed watchers, and
126 // reallocate the slice at 2x length if it is not between 1.5x and 3x.
127 if len(m.watchers) == cap(m.watchers) {
128 newWatchers := m.watchers[:0]
129 for _, w := range m.watchers {
130 if !w.closed() {
131 newWatchers = append(newWatchers, w)
132 }
133 }
134 if cap(newWatchers)*2 < len(newWatchers)*3 || cap(newWatchers) > len(newWatchers)*3 {
135 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
136 newWatchers = append(reallocated, newWatchers...)
137 }
138 m.watchers = newWatchers
139 }
140 // Append this watcher to the Value.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100141 m.watchers = append(m.watchers, waiter)
Jan Schär36bde9c2024-03-19 15:05:33 +0100142 // If the Value already has some value set, put it in the buffered channel.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100143 if m.innerSet {
Jan Schär36bde9c2024-03-19 15:05:33 +0100144 waiter.bufferedC <- m.inner
Serge Bazanskic00318e2021-03-03 12:39:24 +0100145 }
146 m.mu.Unlock()
147
148 return waiter
149}
150
Serge Bazanskic00318e2021-03-03 12:39:24 +0100151// closed returns whether this watcher has been closed.
Serge Bazanski37110c32023-03-01 13:57:27 +0000152func (m *watcher[T]) closed() bool {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100153 select {
154 case _, ok := <-m.close:
155 if !ok {
156 return true
157 }
158 default:
159 }
160 return false
161}
162
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200163// update is the high level update-this-watcher function called by Value.
Serge Bazanski37110c32023-03-01 13:57:27 +0000164func (m *watcher[T]) update(sync bool, val T) {
Jan Schär36bde9c2024-03-19 15:05:33 +0100165 // If synchronous delivery was requested, block until a watcher .Gets it,
166 // or is closed.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100167 if sync {
Jan Schär36bde9c2024-03-19 15:05:33 +0100168 select {
169 case m.unbufferedC <- val:
170 case <-m.close:
171 }
Serge Bazanskic00318e2021-03-03 12:39:24 +0100172 return
173 }
174
Jan Schär36bde9c2024-03-19 15:05:33 +0100175 // Otherwise, deliver asynchronously. If there is already a value in the
176 // buffered channel that was not retrieved, drop it.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100177 select {
Jan Schär36bde9c2024-03-19 15:05:33 +0100178 case <-m.bufferedC:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100179 default:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100180 }
Jan Schär36bde9c2024-03-19 15:05:33 +0100181 // The channel is now empty, so sending to it cannot block.
182 m.bufferedC <- val
Serge Bazanskic00318e2021-03-03 12:39:24 +0100183}
184
Serge Bazanski37110c32023-03-01 13:57:27 +0000185func (m *watcher[T]) Close() error {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100186 close(m.close)
187 return nil
188}
189
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200190// Get blocks until a Value's data is available. See event.Watcher.Get for
191// guarantees and more information.
Serge Bazanski37110c32023-03-01 13:57:27 +0000192func (m *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100193 // Make sure we're the only active .Get call.
Serge Bazanski37110c32023-03-01 13:57:27 +0000194 var empty T
Serge Bazanskic00318e2021-03-03 12:39:24 +0100195 select {
196 case m.getSem <- struct{}{}:
197 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000198 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic00318e2021-03-03 12:39:24 +0100199 }
200 defer func() {
201 <-m.getSem
202 }()
203
Serge Bazanski37110c32023-03-01 13:57:27 +0000204 var predicate func(t T) bool
205 for _, opt := range opts {
206 if opt.Predicate != nil {
207 predicate = opt.Predicate
208 }
Tim Windelschmidt885668a2024-04-19 00:01:06 +0200209 if opt.BacklogOnly {
Serge Bazanski37110c32023-03-01 13:57:27 +0000210 return empty, errors.New("BacklogOnly is not implemented for memory watchers")
Serge Bazanski8d45a052021-10-18 17:24:24 +0200211 }
212 }
213
Serge Bazanskic00318e2021-03-03 12:39:24 +0100214 for {
Jan Schär36bde9c2024-03-19 15:05:33 +0100215 var val T
216 // For Sync values, ensure the initial value in the buffered
217 // channel is delivered first.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100218 select {
Jan Schär36bde9c2024-03-19 15:05:33 +0100219 case val = <-m.bufferedC:
220 default:
221 select {
222 case <-ctx.Done():
223 return empty, ctx.Err()
224 case val = <-m.bufferedC:
225 case val = <-m.unbufferedC:
Serge Bazanski37110c32023-03-01 13:57:27 +0000226 }
Serge Bazanskic00318e2021-03-03 12:39:24 +0100227 }
Jan Schär36bde9c2024-03-19 15:05:33 +0100228 if predicate != nil && !predicate(val) {
229 continue
230 }
231 return val, nil
Serge Bazanskic00318e2021-03-03 12:39:24 +0100232 }
233}