|
7 | 7 | "net/url" |
8 | 8 | "sync" |
9 | 9 |
|
| 10 | + "golang.org/x/sync/singleflight" |
10 | 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
11 | 12 | "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
12 | 13 | "k8s.io/apimachinery/pkg/runtime" |
@@ -35,12 +36,12 @@ type entry struct { |
35 | 36 |
|
36 | 37 | // StateWatcher watches App CRDs in Kubernetes and provides a local cache of app states. |
37 | 38 | type StateWatcher struct { |
38 | | - client dynamic.Interface |
39 | | - namespace string |
40 | | - logger log.Logger |
41 | | - hasSynced cache.InformerSynced |
42 | | - // apps: AppID → entry |
43 | | - apps sync.Map |
| 39 | + client dynamic.Interface |
| 40 | + namespace string |
| 41 | + logger log.Logger |
| 42 | + hasSynced cache.InformerSynced |
| 43 | + apps sync.Map // AppID → entry |
| 44 | + tokenLoadGroup singleflight.Group // coalesces concurrent lazy-load K8s API calls per secret |
44 | 45 | } |
45 | 46 |
|
46 | 47 | type dependencies interface { |
@@ -127,10 +128,15 @@ func (w *StateWatcher) GetState(appID api.AppID) (AppInfo, bool) { |
127 | 128 | e := v.(entry) |
128 | 129 |
|
129 | 130 | // Lazy-load E2B token: the Secret may not have existed when the App CRD event was processed. |
| 131 | + // a singleflight coalesces concurrent requests for the same secret into a single K8s API call. |
130 | 132 | if e.e2bAccessToken == "" && e.e2bSecretName != "" { |
131 | | - token, err := w.loadSecretToken(context.Background(), e.e2bSecretName) |
132 | | - if err == nil && token != "" { |
133 | | - e.e2bAccessToken = token |
| 133 | + token, err, _ := w.tokenLoadGroup.Do(e.e2bSecretName, func() (any, error) { |
| 134 | + return w.loadSecretToken(context.Background(), e.e2bSecretName) |
| 135 | + }) |
| 136 | + if err != nil { |
| 137 | + w.logger.Warnf(context.Background(), "App %s: failed to lazy-load E2B access token from secret %q: %s", appID, e.e2bSecretName, err) |
| 138 | + } else if t, ok := token.(string); t != "" && ok { |
| 139 | + e.e2bAccessToken = t |
134 | 140 | w.apps.Store(appID, e) |
135 | 141 | w.logger.Infof(context.Background(), "App %s: lazy-loaded E2B access token from secret %q", appID, e.e2bSecretName) |
136 | 142 | } |
|
0 commit comments