// Package source owns Mongo connection generations and operation lifetimes. package source import ( "context" merrors "git.sendico.io/tech/sxchnge/shared/errors" "go.mongodb.org/mongo-driver/v2/mongo" ) // Source pins one database/client until release. The returned context must be // passed to nested operations so transactions never cross client generations. type Source interface { Acquire(context.Context) (*mongo.Database, context.Context, func(), error) } type fixed struct{ database *mongo.Database } // Fixed adapts an externally owned database, e.g. a test fixture. It never closes it. func Fixed(database *mongo.Database) Source { return &fixed{database: database} } func (s *fixed) Acquire(ctx context.Context) (*mongo.Database, context.Context, func(), error) { if s.database == nil { return nil, ctx, nil, merrors.FailedPrecondition("database is not configured") } if session := mongo.SessionFromContext(ctx); session != nil && session.Client() != s.database.Client() { return nil, ctx, nil, merrors.FailedPrecondition("transaction belongs to another database client") } return s.database, ctx, func() {}, nil }