package store import ( "context" "crypto/rand" "encoding/hex" "time" ) // ClusterSecret returns the named secret, creating a random one the first time // it is asked for. // // Insert-if-absent and then read, so two control planes asking at once end up // with the same value: the loser's insert changes nothing and it reads the // winner's. func (s *DB) ClusterSecret(ctx context.Context, name string) (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } if _, err := s.db.ExecContext(ctx, `INSERT INTO cluster_secrets (name, value, created_at) VALUES (?, ?, ?) ON CONFLICT (name) DO NOTHING`, name, hex.EncodeToString(b), time.Now().UnixMilli()); err != nil { return "", err } var v string err := s.db.QueryRowContext(ctx, `SELECT value FROM cluster_secrets WHERE name = ?`, name).Scan(&v) return v, err }