Debian Codegraph @

runtimevar/runtimevar.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package runtimevar provides an easy and portable way to watch runtime
16 // configuration variables. Subpackages contain driver implementations of
17 // runtimevar for supported services.
18 //
19 // See https://gocloud.dev/howto/runtimevar/ for a detailed how-to guide.
20 //
21 // # OpenTelemetry Integration
22 //
23 // OpenTelemetry supports tracing and metric collection for multiple languages and
24 // backend providers. See https://opentelemetry.io.
25 //
26 // This API collects an OpenTelemetry metric "gocloud.dev/runtimevar/value_changes",
27 // a count of the number of times all variables have changed values, by driver.
28 //
29 // To enable metric collection in your application, see the OpenTelemetry documentation at
30 // https://opentelemetry.io/docs/instrumentation/go/getting-started/
31 package runtimevar // import "gocloud.dev/runtimevar"
32
33 import (
34 "bytes"
35 "context"
36 "encoding/gob"
37 "encoding/json"
38 "errors"
39 "fmt"
40 "net/url"
41 "os"
42 "reflect"
43 "strings"
44 "sync"
45 "time"
46
47 "go.opentelemetry.io/otel/metric"
48 "gocloud.dev/internal/gcerr"
49 "gocloud.dev/internal/openurl"
50 "gocloud.dev/runtimevar/driver"
51 "gocloud.dev/secrets"
52
53 gcdkotel "gocloud.dev/internal/otel"
54 )
55
56 // Snapshot contains a snapshot of a variable's value and metadata about it.
57 // It is intended to be read-only for users.
58 type Snapshot struct {
59 // Value contains the value of the variable.
60 // The type for Value depends on the decoder used when creating the Variable.
61 Value any
62
63 // UpdateTime is the time when the last change was detected.
64 UpdateTime time.Time
65
66 asFunc func(any) bool
67 }
68
69 // As converts i to driver-specific types.
70 // See https://gocloud.dev/concepts/as/ for background information, the "As"
71 // examples in this package for examples, and the driver package
72 // documentation for the specific types supported for that driver.
73 func (s *Snapshot) As(i any) bool {
74 if s.asFunc == nil {
75 return false
76 }
77 return s.asFunc(i)
78 }
79
80 const pkgName = "gocloud.dev/runtimevar"
81
82 var (
83 OpenTelemetryViews = gcdkotel.CounterView(pkgName, "/value_changes",
84 "Count of variable value changes by driver.")
85 )
86
87 // Variable provides an easy and portable way to watch runtime configuration
88 // variables. To create a Variable, use constructors found in driver subpackages.
89 type Variable struct {
90 dw driver.Watcher
91 changeMeasure metric.Int64Counter
92
93 // For cancelling the background goroutine, and noticing when it has exited.
94 backgroundCancel context.CancelFunc
95 backgroundDone chan struct{}
96
97 // haveGoodCh is closed when we get the first good value for the variable.
98 haveGoodCh chan struct{}
99 // A reference to changed at the last time Watch was called.
100 // Not protected by mu because it's only referenced in Watch, which is not
101 // supposed to be called from multiple goroutines.
102 lastWatch <-chan struct{}
103
104 mu sync.RWMutex
105 changed chan struct{} // closed when changing any of the other variables and replaced with a new channel
106 last Snapshot
107 lastErr error
108 lastGood Snapshot
109 }
110
111 // New is intended for use by drivers only. Do not use in application code.
112 var New = newVar
113
114 // newVar creates a new *Variable based on a specific driver implementation.
115 func newVar(w driver.Watcher) *Variable {
116 ctx, cancel := context.WithCancel(context.Background())
117 changed := make(chan struct{})
118
119 providerName := gcdkotel.ProviderName(w)
120
121 v := &Variable{
122 dw: w,
123 changeMeasure: gcdkotel.DimensionlessMeasure(pkgName, providerName, "/value_changes",
124 "Count of variable value changes by driver"),
125 backgroundCancel: cancel,
126 backgroundDone: make(chan struct{}),
127 haveGoodCh: make(chan struct{}),
128 changed: changed,
129 lastWatch: changed,
130 lastErr: gcerr.Newf(gcerr.FailedPrecondition, nil, "no value yet"),
131 }
132 go v.background(ctx)
133 return v
134 }
135
136 // ErrClosed is returned from Watch when the Variable has been Closed.
137 var ErrClosed = gcerr.Newf(gcerr.FailedPrecondition, nil, "Variable has been Closed")
138
139 // Watch returns when there is a new Snapshot of the current value of the
140 // variable.
141 //
142 // The first call to Watch will block while reading the variable from the
143 // driver, and will return the resulting Snapshot or error. If an error is
144 // returned, the returned Snapshot is a zero value and should be ignored.
145 // Subsequent calls will block until the variable's value changes or a different
146 // error occurs.
147 //
148 // Watch returns an ErrClosed error if the Variable has been closed.
149 //
150 // Watch should not be called on the same variable from multiple goroutines
151 // concurrently. The typical use case is to call it in a single goroutine in a
152 // loop.
153 //
154 // If the variable does not exist, Watch returns an error for which
155 // gcerrors.Code will return gcerrors.NotFound.
156 //
157 // Alternatively, use Latest to retrieve the latest good value.
158 func (c *Variable) Watch(ctx context.Context) (Snapshot, error) {
159 // Block until there's a change since the last Watch call, signaled
160 // by lastWatch being closed by the background goroutine.
161 var ctxErr error
162 select {
163 case <-c.lastWatch:
164 case <-ctx.Done():
165 ctxErr = ctx.Err()
166 }
167 c.mu.Lock()
168 defer c.mu.Unlock()
169 if errors.Is(c.lastErr, ErrClosed) {
170 return Snapshot{}, ErrClosed
171 } else if ctxErr != nil {
172 return Snapshot{}, ctxErr
173 }
174 c.lastWatch = c.changed
175 return c.last, c.lastErr
176 }
177
178 func (c *Variable) background(ctx context.Context) {
179 var curState, prevState driver.State
180 var wait time.Duration
181 for {
182 select {
183 case <-ctx.Done():
184 // We're shutting down; exit the goroutine.
185 close(c.backgroundDone)
186 return
187 case <-time.After(wait):
188 // Continue.
189 }
190
191 curState, wait = c.dw.WatchVariable(ctx, prevState)
192 if curState == nil {
193 // No change.
194 continue
195 }
196
197 // There's something new to return!
198 prevState = curState
199 c.changeMeasure.Add(ctx, 1)
200 // Error from RecordWithTags is not possible.
201
202 // Updates under the lock.
203 c.mu.Lock()
204 if errors.Is(c.lastErr, ErrClosed) {
205 close(c.backgroundDone)
206 c.mu.Unlock()
207 return
208 }
209 if val, err := curState.Value(); err == nil {
210 // We got a good value!
211 c.last = Snapshot{
212 Value: val,
213 UpdateTime: curState.UpdateTime(),
214 asFunc: curState.As,
215 }
216 c.lastErr = nil
217 c.lastGood = c.last
218 // Close c.haveGoodCh if it's not already closed.
219 select {
220 case <-c.haveGoodCh:
221 default:
222 close(c.haveGoodCh)
223 }
224 } else {
225 // We got an error value.
226 c.last = Snapshot{}
227 c.lastErr = wrapError(c.dw, err)
228 }
229 close(c.changed)
230 c.changed = make(chan struct{})
231 c.mu.Unlock()
232 }
233 }
234
235 func (c *Variable) haveGood() bool {
236 select {
237 case <-c.haveGoodCh:
238 return true
239 default:
240 return false
241 }
242 }
243
244 // Latest is intended to be called per request, with the request context.
245 // It returns the latest good Snapshot of the variable value, blocking if no
246 // good value has ever been received. If ctx is Done, it returns the latest
247 // error indicating why no good value is available (not the ctx.Err()).
248 // You can pass an already-Done ctx to make Latest not block.
249 //
250 // Latest returns ErrClosed if the Variable has been closed.
251 func (c *Variable) Latest(ctx context.Context) (Snapshot, error) {
252 haveGood := c.haveGood()
253 if !haveGood {
254 select {
255 case <-c.haveGoodCh:
256 haveGood = true
257 case <-ctx.Done():
258 // We don't return ctx.Err().
259 }
260 }
261 c.mu.RLock()
262 defer c.mu.RUnlock()
263 if haveGood && !errors.Is(c.lastErr, ErrClosed) {
264 return c.lastGood, nil
265 }
266 return Snapshot{}, c.lastErr
267 }
268
269 // CheckHealth returns an error unless Latest will return a good value
270 // without blocking.
271 func (c *Variable) CheckHealth() error {
272 haveGood := c.haveGood()
273 c.mu.RLock()
274 defer c.mu.RUnlock()
275 if haveGood && !errors.Is(c.lastErr, ErrClosed) {
276 return nil
277 }
278 return c.lastErr
279 }
280
281 // Close closes the Variable. The Variable is unusable after Close returns.
282 func (c *Variable) Close() error {
283 // Record that we're closing. Subsequent calls to Watch/Latest will return ErrClosed.
284 c.mu.Lock()
285 if errors.Is(c.lastErr, ErrClosed) {
286 c.mu.Unlock()
287 return ErrClosed
288 }
289 c.last = Snapshot{}
290 c.lastErr = ErrClosed
291
292 // Close any remaining channels to wake up any callers that are waiting on them.
293 close(c.changed)
294 // If it's the first good value, close haveGoodCh so that Latest doesn't block.
295 select {
296 case <-c.haveGoodCh:
297 default:
298 close(c.haveGoodCh)
299 }
300 c.mu.Unlock()
301
302 // Shut down the background goroutine.
303 c.backgroundCancel()
304 <-c.backgroundDone
305
306 // Close the driver.
307 err := c.dw.Close()
308 return wrapError(c.dw, err)
309 }
310
311 func wrapError(w driver.Watcher, err error) error {
312 if err == nil {
313 return nil
314 }
315 if gcerr.DoNotWrap(err) {
316 return err
317 }
318 return gcerr.New(w.ErrorCode(err), err, 2, "runtimevar")
319 }
320
321 // ErrorAs converts err to driver-specific types.
322 // ErrorAs panics if i is nil or not a pointer.
323 // ErrorAs returns false if err == nil.
324 // See https://gocloud.dev/concepts/as/ for background information.
325 func (c *Variable) ErrorAs(err error, i any) bool {
326 return gcerr.ErrorAs(err, i, c.dw.ErrorAs)
327 }
328
329 // VariableURLOpener represents types than can open Variables based on a URL.
330 // The opener must not modify the URL argument. OpenVariableURL must be safe to
331 // call from multiple goroutines.
332 //
333 // This interface is generally implemented by types in driver packages.
334 type VariableURLOpener interface {
335 OpenVariableURL(ctx context.Context, u *url.URL) (*Variable, error)
336 }
337
338 // URLMux is a URL opener multiplexer. It matches the scheme of the URLs
339 // against a set of registered schemes and calls the opener that matches the
340 // URL's scheme.
341 // See https://gocloud.dev/concepts/urls/ for more information.
342 //
343 // The zero value is a multiplexer with no registered schemes.
344 type URLMux struct {
345 schemes openurl.SchemeMap
346 }
347
348 // VariableSchemes returns a sorted slice of the registered Variable schemes.
349 func (mux *URLMux) VariableSchemes() []string { return mux.schemes.Schemes() }
350
351 // ValidVariableScheme returns true iff scheme has been registered for Variables.
352 func (mux *URLMux) ValidVariableScheme(scheme string) bool { return mux.schemes.ValidScheme(scheme) }
353
354 // RegisterVariable registers the opener with the given scheme. If an opener
355 // already exists for the scheme, RegisterVariable panics.
356 func (mux *URLMux) RegisterVariable(scheme string, opener VariableURLOpener) {
357 mux.schemes.Register("runtimevar", "Variable", scheme, opener)
358 }
359
360 // OpenVariable calls OpenVariableURL with the URL parsed from urlstr.
361 // OpenVariable is safe to call from multiple goroutines.
362 func (mux *URLMux) OpenVariable(ctx context.Context, urlstr string) (*Variable, error) {
363 opener, u, err := mux.schemes.FromString("Variable", urlstr)
364 if err != nil {
365 return nil, err
366 }
367 return opener.(VariableURLOpener).OpenVariableURL(ctx, u)
368 }
369
370 // OpenVariableURL dispatches the URL to the opener that is registered with the
371 // URL's scheme. OpenVariableURL is safe to call from multiple goroutines.
372 func (mux *URLMux) OpenVariableURL(ctx context.Context, u *url.URL) (*Variable, error) {
373 opener, err := mux.schemes.FromURL("Variable", u)
374 if err != nil {
375 return nil, err
376 }
377 return opener.(VariableURLOpener).OpenVariableURL(ctx, u)
378 }
379
380 var defaultURLMux = new(URLMux)
381
382 // DefaultURLMux returns the URLMux used by OpenVariable.
383 //
384 // Driver packages can use this to register their VariableURLOpener on the mux.
385 func DefaultURLMux() *URLMux {
386 return defaultURLMux
387 }
388
389 // OpenVariable opens the variable identified by the URL given.
390 // See the URLOpener documentation in driver subpackages for
391 // details on supported URL formats, and https://gocloud.dev/concepts/urls
392 // for more information.
393 func OpenVariable(ctx context.Context, urlstr string) (*Variable, error) {
394 return defaultURLMux.OpenVariable(ctx, urlstr)
395 }
396
397 // Decode is a function type for unmarshaling/decoding a slice of bytes into
398 // an arbitrary type. Decode functions are used when creating a Decoder via
399 // NewDecoder. This package provides common Decode functions including
400 // GobDecode and JSONDecode.
401 type Decode func(context.Context, []byte, any) error
402
403 // Decoder decodes a slice of bytes into a particular Go object.
404 //
405 // This package provides some common Decoders that you can use directly,
406 // including StringDecoder and BytesDecoder. You can also NewDecoder to
407 // construct other Decoders.
408 type Decoder struct {
409 typ reflect.Type
410 fn Decode
411 }
412
413 // NewDecoder returns a Decoder that uses fn to decode a slice of bytes into
414 // an object of type obj.
415 //
416 // This package provides some common Decode functions, including JSONDecode
417 // and GobDecode, which can be passed to this function to create Decoders for
418 // JSON and gob values.
419 func NewDecoder(obj any, fn Decode) *Decoder {
420 return &Decoder{
421 typ: reflect.TypeOf(obj),
422 fn: fn,
423 }
424 }
425
426 // Decode decodes b into a new instance of the target type.
427 func (d *Decoder) Decode(ctx context.Context, b []byte) (any, error) {
428 nv := reflect.New(d.typ).Interface()
429 if err := d.fn(ctx, b, nv); err != nil {
430 return nil, err
431 }
432 ptr := reflect.ValueOf(nv)
433 return ptr.Elem().Interface(), nil
434 }
435
436 var (
437 // StringDecoder decodes into strings.
438 StringDecoder = NewDecoder("", StringDecode)
439
440 // BytesDecoder copies the slice of bytes.
441 BytesDecoder = NewDecoder([]byte{}, BytesDecode)
442 )
443
444 // JSONDecode can be passed to NewDecoder when decoding JSON (https://golang.org/pkg/encoding/json/).
445 func JSONDecode(ctx context.Context, data []byte, obj any) error {
446 return json.Unmarshal(data, obj)
447 }
448
449 // GobDecode can be passed to NewDecoder when decoding gobs (https://golang.org/pkg/encoding/gob/).
450 func GobDecode(ctx context.Context, data []byte, obj any) error {
451 return gob.NewDecoder(bytes.NewBuffer(data)).Decode(obj)
452 }
453
454 // StringDecode decodes raw bytes b into a string.
455 func StringDecode(ctx context.Context, b []byte, obj any) error {
456 v := obj.(*string)
457 *v = string(b)
458 return nil
459 }
460
461 // BytesDecode copies the slice of bytes b into obj.
462 func BytesDecode(ctx context.Context, b []byte, obj any) error {
463 v := obj.(*[]byte)
464 *v = b[:]
465 return nil
466 }
467
468 // DecryptDecode returns a decode function that can be passed to NewDecoder when
469 // decoding an encrypted message (https://godoc.org/gocloud.dev/secrets).
470 //
471 // post defaults to BytesDecode. An optional decoder can be passed in to do
472 // further decode operation based on the decrypted message.
473 func DecryptDecode(k *secrets.Keeper, post Decode) Decode {
474 return func(ctx context.Context, b []byte, obj any) error {
475 decrypted, err := k.Decrypt(ctx, b)
476 if err != nil {
477 return err
478 }
479 if post == nil {
480 return BytesDecode(ctx, decrypted, obj)
481 }
482 return post(ctx, decrypted, obj)
483 }
484 }
485
486 // DecoderByName returns a *Decoder based on decoderName.
487 //
488 // It is intended to be used by URL openers in driver packages.
489 //
490 // Supported values include:
491 // - empty string: Returns the default from the URLOpener.Decoder, or
492 // BytesDecoder if URLOpener.Decoder is nil (which is true if you're
493 // using the default URLOpener).
494 // - "bytes": Returns a BytesDecoder; Snapshot.Value will be of type []byte.
495 // - "jsonmap": Returns a JSON decoder for a map[string]any;
496 // Snapshot.Value will be of type *map[string]any.
497 // - "string": Returns StringDecoder; Snapshot.Value will be of type string.
498 //
499 // It also supports using "decrypt+<decoderName>" (or "decrypt" for default
500 // decoder) to decrypt the data before decoding. It uses the secrets package to
501 // open a keeper by the URL string stored in a environment variable
502 // "RUNTIMEVAR_KEEPER_URL". See https://godoc.org/gocloud.dev/secrets#OpenKeeper
503 // for more details.
504 func DecoderByName(ctx context.Context, decoderName string, dflt *Decoder) (*Decoder, error) {
505 // Open a *secrets.Keeper if the decoderName contains "decrypt".
506 k, decoderName, err := decryptByName(ctx, decoderName)
507 if err != nil {
508 return nil, err
509 }
510
511 if dflt == nil {
512 dflt = BytesDecoder
513 }
514 switch decoderName {
515 case "":
516 return maybeDecrypt(ctx, k, dflt), nil
517 case "bytes":
518 return maybeDecrypt(ctx, k, BytesDecoder), nil
519 case "jsonmap":
520 var m map[string]any
521 return maybeDecrypt(ctx, k, NewDecoder(&m, JSONDecode)), nil
522 case "string":
523 return maybeDecrypt(ctx, k, StringDecoder), nil
524 default:
525 return nil, fmt.Errorf("unsupported decoder %q", decoderName)
526 }
527 }
528
529 // decryptByName returns a *secrets.Keeper for decryption when decoderName
530 // contains "decrypt".
531 func decryptByName(ctx context.Context, decoderName string) (*secrets.Keeper, string, error) {
532 if !strings.HasPrefix(decoderName, "decrypt") {
533 return nil, decoderName, nil
534 }
535 keeperURL := os.Getenv("RUNTIMEVAR_KEEPER_URL")
536 if keeperURL == "" {
537 return nil, "", errors.New("environment variable RUNTIMEVAR_KEEPER_URL needed to open a *secrets.Keeper for decryption")
538 }
539 k, err := secrets.OpenKeeper(ctx, keeperURL)
540 if err != nil {
541 return nil, "", err
542 }
543 decoderName = strings.TrimPrefix(decoderName, "decrypt")
544 if decoderName != "" {
545 decoderName = strings.TrimLeftFunc(decoderName, func(r rune) bool {
546 return r == ' ' || r == '+'
547 })
548 }
549 // The parsed value is "decrypt <decoderName>".
550 return k, decoderName, nil
551 }
552
553 func maybeDecrypt(ctx context.Context, k *secrets.Keeper, dec *Decoder) *Decoder {
554 if k == nil {
555 return dec
556 }
557 return NewDecoder(reflect.New(dec.typ).Elem().Interface(), DecryptDecode(k, dec.fn))
558 }