Skip to content

Commit 713f3ec

Browse files
committed
Wait at most 1s for the banner fetch, finish it in the background
1 parent 5b2dd16 commit 713f3ec

1 file changed

Lines changed: 24 additions & 11 deletions

File tree

cmd/lk/banner.go

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,12 @@ import (
3535
// file is the whole release process: no build or tag involved.
3636
const bannerURL = "https://raw.githubusercontent.com/livekit/livekit-cli/main/banner.json"
3737

38-
// The banner prints before the command, so the fetch is awaited. To keep that off
39-
// most runs, the fetched file is cached and reused for bannerTTL.
38+
// The banner prints before the command, so the fetch is awaited, but only for
39+
// bannerWait: a slower fetch keeps running in the background to refresh the cache
40+
// for the next run. The fetched file is cached and reused for bannerTTL.
4041
const (
41-
bannerTimeout = time.Second
42+
bannerWait = time.Second
43+
bannerTimeout = 10 * time.Second
4244
bannerTTL = time.Hour
4345
)
4446

@@ -58,7 +60,7 @@ type banner struct {
5860
}
5961

6062
// loadBanner returns banner.json from the cache when it is fresh, otherwise from
61-
// the network, falling back to a stale cache when the fetch fails.
63+
// the network when it answers within bannerWait, falling back to the stale cache.
6264
func loadBanner(ctx context.Context) []byte {
6365
path, err := bannerCachePath()
6466
if err != nil {
@@ -68,14 +70,25 @@ func loadBanner(ctx context.Context) []byte {
6870
raw, _ := os.ReadFile(path)
6971
return raw
7072
}
71-
raw := fetchBanner(ctx)
72-
if raw == nil {
73-
raw, _ = os.ReadFile(path)
74-
return raw
75-
}
76-
if os.MkdirAll(filepath.Dir(path), 0700) == nil {
77-
_ = os.WriteFile(path, raw, 0600)
73+
// The fetch is detached from ctx so it outlives the wait and can still write the
74+
// cache after the command has moved on.
75+
fetched := make(chan []byte, 1)
76+
go func() {
77+
raw := fetchBanner(context.Background())
78+
if raw != nil && os.MkdirAll(filepath.Dir(path), 0700) == nil {
79+
_ = os.WriteFile(path, raw, 0600)
80+
}
81+
fetched <- raw
82+
}()
83+
select {
84+
case raw := <-fetched:
85+
if raw != nil {
86+
return raw
87+
}
88+
case <-time.After(bannerWait):
89+
case <-ctx.Done():
7890
}
91+
raw, _ := os.ReadFile(path)
7992
return raw
8093
}
8194

0 commit comments

Comments
 (0)