Debian Codegraph @

safe.go

raw
1 package sturdyc
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 )
8
9 // safeGo is a helper that prevents panics in any of the goroutines
10 // that are running in the background from crashing the process.
11 func (c *Client[T]) safeGo(fn func()) {
12 go func() {
13 defer func() {
14 if err := recover(); err != nil {
15 c.log.Error(fmt.Sprintf("sturdyc: panic recovered: %v", err))
16 }
17 }()
18 fn()
19 }()
20 }
21
22 func wrap[T, V any](fetchFn FetchFn[V]) FetchFn[T] {
23 return func(ctx context.Context) (T, error) {
24 res, err := fetchFn(ctx)
25 if val, ok := any(res).(T); ok {
26 return val, err
27 }
28 var zero T
29 return zero, ErrInvalidType
30 }
31 }
32
33 func unwrap[V, T any](val T, err error) (V, error) {
34 if errors.Is(err, ErrMissingRecord) {
35 return *new(V), err
36 }
37
38 v, ok := any(val).(V)
39 if !ok {
40 return v, ErrInvalidType
41 }
42 return v, err
43 }
44
45 func wrapBatch[T, V any](fetchFn BatchFetchFn[V]) BatchFetchFn[T] {
46 return func(ctx context.Context, ids []string) (map[string]T, error) {
47 resV, err := fetchFn(ctx, ids)
48 resT := make(map[string]T, len(resV))
49 for id, v := range resV {
50 val, ok := any(v).(T)
51 if !ok {
52 return resT, ErrInvalidType
53 }
54 resT[id] = val
55 }
56 return resT, err
57 }
58 }
59
60 func unwrapBatch[V, T any](values map[string]T, err error) (map[string]V, error) {
61 vals := make(map[string]V, len(values))
62 for id, v := range values {
63 val, ok := any(v).(V)
64 if !ok {
65 return vals, ErrInvalidType
66 }
67 vals[id] = val
68 }
69 return vals, err
70 }