-
Notifications
You must be signed in to change notification settings - Fork 0
/
versions_manifest.go
99 lines (76 loc) · 2.14 KB
/
versions_manifest.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package launcher
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"github.com/brawaru/marct/network"
"github.com/brawaru/marct/utils"
"github.com/brawaru/marct/utils/osfile"
"github.com/brawaru/marct/validfile"
)
func (w *Instance) ReadVersions() (manifest *VersionsManifest, err error) {
name := filepath.Join(w.Path, filepath.FromSlash(versionsManifestPath))
var bytes []byte
bytes, err = os.ReadFile(name)
if err == nil {
err = json.Unmarshal(bytes, &manifest)
}
return
}
type manifestCacheKeyType int
var manifestCacheKey manifestCacheKeyType = manifestCacheKeyType(1)
type ManifestCache struct {
CachedManifest VersionsManifest
CachedAt time.Time
}
func (w *Instance) FetchVersions(force bool) (manifest *VersionsManifest, err error) {
name := filepath.Join(w.Path, filepath.FromSlash(versionsManifestPath))
if !force {
if v, ok := w.GetTempValue(manifestCacheKey).(ManifestCache); ok && time.Since(v.CachedAt) < versionsManifestTTL {
manifest = &v.CachedManifest
return
}
}
expired := force || (validfile.NotExpired(name, versionsManifestTTL) != nil)
if !expired {
return w.ReadVersions()
}
req, rawErr := http.NewRequest(http.MethodGet, versionsManifestURL, nil)
if rawErr != nil {
err = fmt.Errorf("create request: %w", rawErr)
return
}
resp, rawErr := network.PerformRequest(req, network.WithRetries())
if rawErr != nil {
err = fmt.Errorf("send request: %w", rawErr)
return
}
defer utils.DClose(resp.Body)
manifestFile, rawErr := osfile.New(name)
if rawErr != nil {
err = fmt.Errorf("create file: %w", rawErr)
return
}
defer utils.DClose(manifestFile)
bodyReadWriter := io.TeeReader(resp.Body, manifestFile)
if rawErr := json.NewDecoder(bodyReadWriter).Decode(&manifest); rawErr != nil {
err = fmt.Errorf("decode response: %w", rawErr)
_ = manifestFile.Close()
_ = os.Remove(versionsManifestPath)
return
}
_, rawErr = io.Copy(manifestFile, resp.Body)
if rawErr != nil {
err = fmt.Errorf("write response: %w", rawErr)
return
}
w.SetTempValue(manifestCacheKey, ManifestCache{
CachedManifest: *manifest,
CachedAt: time.Now(),
})
return
}