Skip to content

Commit 367ce2c

Browse files
committed
feat: implement singleflight for lazy-loading E2B access token from Kubernetes Secret
1 parent b5e0093 commit 367ce2c

1 file changed

Lines changed: 15 additions & 9 deletions

File tree

  • internal/pkg/service/appsproxy/dataapps/k8sapp

internal/pkg/service/appsproxy/dataapps/k8sapp/watcher.go

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net/url"
88
"sync"
99

10+
"golang.org/x/sync/singleflight"
1011
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1112
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
1213
"k8s.io/apimachinery/pkg/runtime"
@@ -35,12 +36,12 @@ type entry struct {
3536

3637
// StateWatcher watches App CRDs in Kubernetes and provides a local cache of app states.
3738
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
4445
}
4546

4647
type dependencies interface {
@@ -127,10 +128,15 @@ func (w *StateWatcher) GetState(appID api.AppID) (AppInfo, bool) {
127128
e := v.(entry)
128129

129130
// 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.
130132
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
134140
w.apps.Store(appID, e)
135141
w.logger.Infof(context.Background(), "App %s: lazy-loaded E2B access token from secret %q", appID, e.e2bSecretName)
136142
}

0 commit comments

Comments
 (0)