droboticflow/internal/store/query_replica_binding.go

56 lines
1.7 KiB
Go

package store
import (
"context"
"os"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Namespace is an explicit deployment identity, not a credential or a process
// ID. Local fixtures without environment configuration use their isolated DB.
func queryReplicaNamespace(sourceDatabase string) string {
if ns := os.Getenv("QUERY_SERVING_NAMESPACE"); ns != "" {
return ns
}
return "local:" + sourceDatabase
}
type queryReplicaBinding struct {
SourceDatabase string `bson:"sourceDatabase"`
Namespace string `bson:"namespace"`
}
func (q *QueryReplica) binding() queryReplicaBinding {
return queryReplicaBinding{q.Source.db.Name(), queryReplicaNamespace(q.Source.db.Name())}
}
func (q *QueryReplica) bind(ctx context.Context) error {
want := q.binding()
var got queryReplicaBinding
e := q.control().FindOneAndUpdate(ctx, bson.M{"_id": "source-binding"}, bson.M{"$setOnInsert": want}, options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)).Decode(&got)
if e != nil {
return e
}
if got != want {
return ErrQueryReplicaNotReady
}
return nil
}
func (s *MongoStore) verifyReplicaBinding(target *MongoStore) error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return s.verifyReplicaBindingContext(ctx, target)
}
func (s *MongoStore) verifyReplicaBindingContext(ctx context.Context, target *MongoStore) error {
var got queryReplicaBinding
if e := target.db.Collection(queryReplicaControl).FindOne(ctx, bson.M{"_id": "source-binding"}).Decode(&got); e != nil {
return ErrQueryReplicaNotReady
}
if got.SourceDatabase != s.db.Name() || got.Namespace != queryReplicaNamespace(s.db.Name()) {
return ErrQueryReplicaNotReady
}
return nil
}