forked from ko-build/ko
/
shared.go
78 lines (66 loc) · 2.09 KB
/
shared.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2018 Google LLC All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build
import (
"context"
"sync"
)
// Caching wraps a builder implementation in a layer that shares build results
// for the same inputs using a simple "future" implementation. Cached results
// may be invalidated by calling Invalidate with the same input passed to Build.
type Caching struct {
inner Interface
m sync.Mutex
results map[string]*future
}
// Caching implements Interface
var _ Interface = (*Caching)(nil)
// NewCaching wraps the provided build.Interface in an implementation that
// shares build results for a given path until the result has been invalidated.
func NewCaching(inner Interface) (*Caching, error) {
return &Caching{
inner: inner,
results: make(map[string]*future),
}, nil
}
// Build implements Interface
func (c *Caching) Build(ctx context.Context, ip string) (Result, error) {
f := func() *future {
// Lock the map of futures.
c.m.Lock()
defer c.m.Unlock()
// If a future for "ip" exists, then return it.
f, ok := c.results[ip]
if ok {
return f
}
// Otherwise create and record a future for a Build of "ip".
f = newFuture(func() (Result, error) {
return c.inner.Build(ctx, ip)
})
c.results[ip] = f
return f
}()
return f.Get()
}
// IsSupportedReference implements Interface
func (c *Caching) IsSupportedReference(ip string) error {
return c.inner.IsSupportedReference(ip)
}
// Invalidate removes an import path's cached results.
func (c *Caching) Invalidate(ip string) {
c.m.Lock()
defer c.m.Unlock()
delete(c.results, ip)
}