feat(gemini-web): Namespace conversation index by account label

This commit is contained in:
hkfires
2025-09-29 21:05:20 +08:00
parent 82187bffba
commit 6080527e9e
3 changed files with 182 additions and 91 deletions

View File

@@ -1,15 +1,16 @@
package conversation package conversation
import ( import (
"encoding/json" "bytes"
"errors" "encoding/json"
"os" "errors"
"path/filepath" "os"
"strings" "path/filepath"
"sync" "strings"
"time" "sync"
"time"
bolt "go.etcd.io/bbolt" bolt "go.etcd.io/bbolt"
) )
const ( const (
@@ -65,67 +66,148 @@ func indexPath() string {
// StoreMatch persists or updates a conversation hash mapping. // StoreMatch persists or updates a conversation hash mapping.
func StoreMatch(hash string, record MatchRecord) error { func StoreMatch(hash string, record MatchRecord) error {
if strings.TrimSpace(hash) == "" { if strings.TrimSpace(hash) == "" {
return errors.New("gemini-web conversation: empty hash") return errors.New("gemini-web conversation: empty hash")
} }
db, err := openIndex() db, err := openIndex()
if err != nil { if err != nil {
return err return err
} }
record.UpdatedAt = time.Now().UTC().Unix() record.UpdatedAt = time.Now().UTC().Unix()
payload, err := json.Marshal(record) payload, err := json.Marshal(record)
if err != nil { if err != nil {
return err return err
} }
return db.Update(func(tx *bolt.Tx) error { return db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(bucketMatches)) bucket, err := tx.CreateBucketIfNotExists([]byte(bucketMatches))
if err != nil { if err != nil {
return err return err
} }
return bucket.Put([]byte(hash), payload) // Namespace by account label to avoid cross-account collisions.
}) label := strings.ToLower(strings.TrimSpace(record.AccountLabel))
if label == "" {
return errors.New("gemini-web conversation: empty account label")
}
key := []byte(hash + ":" + label)
if err := bucket.Put(key, payload); err != nil {
return err
}
// Best-effort cleanup of legacy single-key format (hash -> MatchRecord).
// We do not know its label; leave it for lookup fallback/cleanup elsewhere.
return nil
})
} }
// LookupMatch retrieves a stored mapping. // LookupMatch retrieves a stored mapping.
// It prefers namespaced entries (hash:label). If multiple labels exist for the same
// hash, it returns not found to avoid redirecting to the wrong credential.
// Falls back to legacy single-key entries if present.
func LookupMatch(hash string) (MatchRecord, bool, error) { func LookupMatch(hash string) (MatchRecord, bool, error) {
db, err := openIndex() db, err := openIndex()
if err != nil { if err != nil {
return MatchRecord{}, false, err return MatchRecord{}, false, err
} }
var record MatchRecord var foundOne bool
err = db.View(func(tx *bolt.Tx) error { var single MatchRecord
bucket := tx.Bucket([]byte(bucketMatches)) err = db.View(func(tx *bolt.Tx) error {
if bucket == nil { bucket := tx.Bucket([]byte(bucketMatches))
return nil if bucket == nil {
} return nil
raw := bucket.Get([]byte(hash)) }
if len(raw) == 0 { // Scan namespaced keys with prefix "hash:"
return nil prefix := []byte(hash + ":")
} c := bucket.Cursor()
return json.Unmarshal(raw, &record) for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
}) if len(v) == 0 {
if err != nil { continue
return MatchRecord{}, false, err }
} var rec MatchRecord
if record.AccountLabel == "" || record.PrefixLen <= 0 { if err := json.Unmarshal(v, &rec); err != nil {
return MatchRecord{}, false, nil // Ignore malformed; removal is handled elsewhere.
} continue
return record, true, nil }
if strings.TrimSpace(rec.AccountLabel) == "" || rec.PrefixLen <= 0 {
continue
}
if foundOne {
// More than one distinct label exists for this hash; ambiguous.
return nil
}
single = rec
foundOne = true
}
if foundOne {
return nil
}
// Fallback to legacy single-key format
raw := bucket.Get([]byte(hash))
if len(raw) == 0 {
return nil
}
return json.Unmarshal(raw, &single)
})
if err != nil {
return MatchRecord{}, false, err
}
if strings.TrimSpace(single.AccountLabel) == "" || single.PrefixLen <= 0 {
return MatchRecord{}, false, nil
}
return single, true, nil
} }
// RemoveMatch deletes a mapping for the given hash. // RemoveMatch deletes all mappings for the given hash (all labels and legacy key).
func RemoveMatch(hash string) error { func RemoveMatch(hash string) error {
db, err := openIndex() db, err := openIndex()
if err != nil { if err != nil {
return err return err
} }
return db.Update(func(tx *bolt.Tx) error { return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketMatches)) bucket := tx.Bucket([]byte(bucketMatches))
if bucket == nil { if bucket == nil {
return nil return nil
} }
return bucket.Delete([]byte(hash)) // Delete namespaced entries
}) prefix := []byte(hash + ":")
c := bucket.Cursor()
for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() {
if err := bucket.Delete(k); err != nil {
return err
}
}
// Delete legacy entry
_ = bucket.Delete([]byte(hash))
return nil
})
}
// RemoveMatchForLabel deletes the mapping for the given hash and label only.
func RemoveMatchForLabel(hash, label string) error {
label = strings.ToLower(strings.TrimSpace(label))
if strings.TrimSpace(hash) == "" || label == "" {
return nil
}
db, err := openIndex()
if err != nil {
return err
}
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketMatches))
if bucket == nil {
return nil
}
// Remove namespaced key
_ = bucket.Delete([]byte(hash + ":" + label))
// If legacy single-key exists and matches label, remove it as well.
if raw := bucket.Get([]byte(hash)); len(raw) > 0 {
var rec MatchRecord
if err := json.Unmarshal(raw, &rec); err == nil {
if strings.EqualFold(strings.TrimSpace(rec.AccountLabel), label) {
_ = bucket.Delete([]byte(hash))
}
}
}
return nil
})
} }
// RemoveMatchesByLabel removes all entries associated with the specified label. // RemoveMatchesByLabel removes all entries associated with the specified label.

View File

@@ -64,20 +64,20 @@ func (s *geminiWebStickySelector) Pick(ctx context.Context, provider, model stri
if label == "" { if label == "" {
continue continue
} }
auth := findAuthByLabel(auths, label) auth := findAuthByLabel(auths, label)
if auth != nil { if auth != nil {
if opts.Metadata != nil { if opts.Metadata != nil {
opts.Metadata[conversation.MetadataMatchKey] = &conversation.MatchResult{ opts.Metadata[conversation.MetadataMatchKey] = &conversation.MatchResult{
Hash: candidate.Hash, Hash: candidate.Hash,
Record: record, Record: record,
Model: normalizedModel, Model: normalizedModel,
} }
} }
return auth, nil return auth, nil
} }
_ = conversation.RemoveMatch(candidate.Hash) _ = conversation.RemoveMatchForLabel(candidate.Hash, label)
} }
} }
return s.base.Pick(ctx, provider, model, opts, auths) return s.base.Pick(ctx, provider, model, opts, auths)
} }

View File

@@ -206,21 +206,30 @@ func (s *Service) applyCoreAuthRemoval(ctx context.Context, id string) {
return return
} }
GlobalModelRegistry().UnregisterClient(id) GlobalModelRegistry().UnregisterClient(id)
if existing, ok := s.coreManager.GetByID(id); ok && existing != nil { if existing, ok := s.coreManager.GetByID(id); ok && existing != nil {
if strings.EqualFold(existing.Provider, "gemini-web") { if strings.EqualFold(existing.Provider, "gemini-web") {
label := strings.TrimSpace(existing.Label) // Prefer the stable cookie label stored in metadata when available.
if label != "" { var label string
if err := conversation.RemoveMatchesByLabel(label); err != nil { if existing.Metadata != nil {
log.Debugf("failed to remove gemini web sticky entries for %s: %v", label, err) if v, ok := existing.Metadata["label"].(string); ok {
} label = strings.TrimSpace(v)
} }
} }
existing.Disabled = true if label == "" {
existing.Status = coreauth.StatusDisabled label = strings.TrimSpace(existing.Label)
if _, err := s.coreManager.Update(ctx, existing); err != nil { }
log.Errorf("failed to disable auth %s: %v", id, err) if label != "" {
} if err := conversation.RemoveMatchesByLabel(label); err != nil {
} log.Debugf("failed to remove gemini web sticky entries for %s: %v", label, err)
}
}
}
existing.Disabled = true
existing.Status = coreauth.StatusDisabled
if _, err := s.coreManager.Update(ctx, existing); err != nil {
log.Errorf("failed to disable auth %s: %v", id, err)
}
}
} }
func (s *Service) ensureExecutorsForAuth(a *coreauth.Auth) { func (s *Service) ensureExecutorsForAuth(a *coreauth.Auth) {