blob: 09b120f76636ef780a7e6f3506df1d43b124eca5 [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
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020025 "source.monogon.dev/osbase/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}
53
54// Set updates the Value to the given data. It is safe to call this from
55// multiple goroutines, including concurrently.
56//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020057// For more information about guarantees, see event.Value.Set.
Serge Bazanski37110c32023-03-01 13:57:27 +000058func (m *Value[T]) Set(val T) {
Serge Bazanskic00318e2021-03-03 12:39:24 +010059 m.mu.Lock()
60 defer m.mu.Unlock()
61
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020062 // Update the data that is provided on first Get() to watchers.
Serge Bazanskic00318e2021-03-03 12:39:24 +010063 m.inner = val
64 m.innerSet = true
65
66 // Go through all watchers, updating them on the new value and filtering out
67 // all closed watchers.
Jan Schär36bde9c2024-03-19 15:05:33 +010068 newWatchers := m.watchers[:0]
Serge Bazanskic00318e2021-03-03 12:39:24 +010069 for _, w := range m.watchers {
Serge Bazanskic00318e2021-03-03 12:39:24 +010070 if w.closed() {
71 continue
72 }
Jan Schär5b997a12024-12-19 15:10:07 +010073 w.update(val)
Serge Bazanskic00318e2021-03-03 12:39:24 +010074 newWatchers = append(newWatchers, w)
75 }
Jan Schär36bde9c2024-03-19 15:05:33 +010076 if cap(newWatchers) > len(newWatchers)*3 {
77 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
78 newWatchers = append(reallocated, newWatchers...)
79 }
Serge Bazanskic00318e2021-03-03 12:39:24 +010080 m.watchers = newWatchers
81}
82
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020083// watcher implements the event.Watcher interface for watchers returned by
84// Value.
Serge Bazanski37110c32023-03-01 13:57:27 +000085type watcher[T any] struct {
Jan Schär5b997a12024-12-19 15:10:07 +010086 // valueC is a buffered channel of size 1 for submitting values to the
Jan Schär36bde9c2024-03-19 15:05:33 +010087 // watcher.
Jan Schär5b997a12024-12-19 15:10:07 +010088 valueC chan T
Serge Bazanskic00318e2021-03-03 12:39:24 +010089
90 // getSem is a channel-based semaphore (which is of size 1, and thus in
91 // fact a mutex) that is used to ensure that only a single .Get() call is
92 // active. It is implemented as a channel to permit concurrent .Get() calls
93 // to error out instead of blocking.
94 getSem chan struct{}
Serge Bazanski68ca5ee2021-04-27 16:09:16 +020095 // close is a channel that is closed when this watcher is itself Closed.
Serge Bazanskic00318e2021-03-03 12:39:24 +010096 close chan struct{}
97}
98
99// Watch retrieves a Watcher that keeps track on the version of the data
100// contained within the Value that was last seen by a consumer.
101//
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200102// For more information about guarantees, see event.Value.Watch.
Serge Bazanski37110c32023-03-01 13:57:27 +0000103func (m *Value[T]) Watch() event.Watcher[T] {
104 waiter := &watcher[T]{
Jan Schär5b997a12024-12-19 15:10:07 +0100105 valueC: make(chan T, 1),
106 close: make(chan struct{}),
107 getSem: make(chan struct{}, 1),
Serge Bazanskic00318e2021-03-03 12:39:24 +0100108 }
Serge Bazanskic00318e2021-03-03 12:39:24 +0100109
Serge Bazanskic00318e2021-03-03 12:39:24 +0100110 m.mu.Lock()
Jan Schär36bde9c2024-03-19 15:05:33 +0100111 // If the watchers slice is at capacity, drop closed watchers, and
112 // reallocate the slice at 2x length if it is not between 1.5x and 3x.
113 if len(m.watchers) == cap(m.watchers) {
114 newWatchers := m.watchers[:0]
115 for _, w := range m.watchers {
116 if !w.closed() {
117 newWatchers = append(newWatchers, w)
118 }
119 }
120 if cap(newWatchers)*2 < len(newWatchers)*3 || cap(newWatchers) > len(newWatchers)*3 {
121 reallocated := make([]*watcher[T], 0, len(newWatchers)*2)
122 newWatchers = append(reallocated, newWatchers...)
123 }
124 m.watchers = newWatchers
125 }
126 // Append this watcher to the Value.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100127 m.watchers = append(m.watchers, waiter)
Jan Schär5b997a12024-12-19 15:10:07 +0100128 // If the Value already has some value set, put it in the channel.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100129 if m.innerSet {
Jan Schär5b997a12024-12-19 15:10:07 +0100130 waiter.valueC <- m.inner
Serge Bazanskic00318e2021-03-03 12:39:24 +0100131 }
132 m.mu.Unlock()
133
134 return waiter
135}
136
Serge Bazanskic00318e2021-03-03 12:39:24 +0100137// closed returns whether this watcher has been closed.
Serge Bazanski37110c32023-03-01 13:57:27 +0000138func (m *watcher[T]) closed() bool {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100139 select {
140 case _, ok := <-m.close:
141 if !ok {
142 return true
143 }
144 default:
145 }
146 return false
147}
148
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200149// update is the high level update-this-watcher function called by Value.
Jan Schär5b997a12024-12-19 15:10:07 +0100150func (m *watcher[T]) update(val T) {
151 // If there is already a value in the channel that was not retrieved, drop it.
Serge Bazanskic00318e2021-03-03 12:39:24 +0100152 select {
Jan Schär5b997a12024-12-19 15:10:07 +0100153 case <-m.valueC:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100154 default:
Serge Bazanskic00318e2021-03-03 12:39:24 +0100155 }
Jan Schär36bde9c2024-03-19 15:05:33 +0100156 // The channel is now empty, so sending to it cannot block.
Jan Schär5b997a12024-12-19 15:10:07 +0100157 m.valueC <- val
Serge Bazanskic00318e2021-03-03 12:39:24 +0100158}
159
Serge Bazanski37110c32023-03-01 13:57:27 +0000160func (m *watcher[T]) Close() error {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100161 close(m.close)
162 return nil
163}
164
Serge Bazanski68ca5ee2021-04-27 16:09:16 +0200165// Get blocks until a Value's data is available. See event.Watcher.Get for
166// guarantees and more information.
Serge Bazanski37110c32023-03-01 13:57:27 +0000167func (m *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
Serge Bazanskic00318e2021-03-03 12:39:24 +0100168 // Make sure we're the only active .Get call.
Serge Bazanski37110c32023-03-01 13:57:27 +0000169 var empty T
Serge Bazanskic00318e2021-03-03 12:39:24 +0100170 select {
171 case m.getSem <- struct{}{}:
172 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000173 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic00318e2021-03-03 12:39:24 +0100174 }
175 defer func() {
176 <-m.getSem
177 }()
178
Serge Bazanski37110c32023-03-01 13:57:27 +0000179 var predicate func(t T) bool
180 for _, opt := range opts {
181 if opt.Predicate != nil {
182 predicate = opt.Predicate
183 }
Tim Windelschmidt885668a2024-04-19 00:01:06 +0200184 if opt.BacklogOnly {
Serge Bazanski37110c32023-03-01 13:57:27 +0000185 return empty, errors.New("BacklogOnly is not implemented for memory watchers")
Serge Bazanski8d45a052021-10-18 17:24:24 +0200186 }
187 }
188
Serge Bazanskic00318e2021-03-03 12:39:24 +0100189 for {
190 select {
Jan Schär5b997a12024-12-19 15:10:07 +0100191 case <-ctx.Done():
192 return empty, ctx.Err()
193 case val := <-m.valueC:
194 if predicate != nil && !predicate(val) {
195 continue
Serge Bazanski37110c32023-03-01 13:57:27 +0000196 }
Jan Schär5b997a12024-12-19 15:10:07 +0100197 return val, nil
Serge Bazanskic00318e2021-03-03 12:39:24 +0100198 }
199 }
200}