| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "sync" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | |
| 11 | |
| 12 | type desktopStatusCache struct { |
| 13 | mu sync.Mutex |
| 14 | generation uint64 |
| 15 | data []byte |
| 16 | expires time.Time |
| 17 | pending *desktopStatusProbe |
| 18 | } |
| 19 | |
| 20 | type desktopStatusProbe struct { |
| 21 | done chan struct{} |
| 22 | data []byte |
| 23 | err error |
| 24 | } |
| 25 | |
| 26 | func (c *desktopStatusCache) invalidate() { |
| 27 | c.mu.Lock() |
| 28 | defer c.mu.Unlock() |
| 29 | c.generation++ |
| 30 | c.data, c.pending = nil, nil |
| 31 | } |
| 32 | |
| 33 | func (c *desktopStatusCache) read(ctx, lifetime context.Context, load func(context.Context) ([]byte, error)) ([]byte, error) { |
| 34 | if err := ctx.Err(); err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | if err := lifetime.Err(); err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | c.mu.Lock() |
| 41 | if c.data != nil && time.Now().Before(c.expires) { |
| 42 | data := c.data |
| 43 | c.mu.Unlock() |
| 44 | return data, nil |
| 45 | } |
| 46 | pending := c.pending |
| 47 | if pending == nil { |
| 48 | pending = &desktopStatusProbe{done: make(chan struct{})} |
| 49 | c.pending = pending |
| 50 | generation := c.generation |
| 51 | go func() { |
| 52 | probeCtx, cancel := context.WithTimeout(lifetime, 12*time.Second) |
| 53 | defer cancel() |
| 54 | data, err := load(probeCtx) |
| 55 | var result struct { |
| 56 | Error string `json:"error"` |
| 57 | } |
| 58 | cacheable := err == nil && probeCtx.Err() == nil && json.Unmarshal(data, &result) == nil && result.Error == "" |
| 59 | c.mu.Lock() |
| 60 | defer c.mu.Unlock() |
| 61 | pending.data, pending.err = data, err |
| 62 | if generation == c.generation { |
| 63 | if cacheable { |
| 64 | c.data, c.expires = data, time.Now().Add(2*time.Second) |
| 65 | } |
| 66 | if c.pending == pending { |
| 67 | c.pending = nil |
| 68 | } |
| 69 | } |
| 70 | close(pending.done) |
| 71 | }() |
| 72 | } |
| 73 | c.mu.Unlock() |
| 74 | select { |
| 75 | case <-ctx.Done(): |
| 76 | return nil, ctx.Err() |
| 77 | case <-pending.done: |
| 78 | return pending.data, pending.err |
| 79 | } |
| 80 | } |