package organization import ( "context" "errors" "git.sendico.io/tech/sxchnge/bff/pkg/auth" "git.sendico.io/tech/sxchnge/bff/pkg/db/policy" "git.sendico.io/tech/sxchnge/bff/pkg/db/repository" "git.sendico.io/tech/sxchnge/bff/pkg/db/repository/builder" ri "git.sendico.io/tech/sxchnge/bff/pkg/db/repository/index" "git.sendico.io/tech/sxchnge/bff/pkg/db/storable" "git.sendico.io/tech/sxchnge/bff/pkg/merrors" "git.sendico.io/tech/sxchnge/bff/pkg/mlogger" "git.sendico.io/tech/sxchnge/bff/pkg/model" "git.sendico.io/tech/sxchnge/bff/pkg/mservice" "go.mongodb.org/mongo-driver/v2/mongo" "go.uber.org/zap" ) type OrganizationDB struct { auth.ProtectedDBImp[*model.Organization] } func Create(ctx context.Context, logger mlogger.Logger, enforcer auth.Enforcer, pdb policy.DB, db *mongo.Database, ) (*OrganizationDB, error) { p, err := auth.CreateDBImp[*model.Organization](ctx, logger, pdb, enforcer, mservice.Organizations, db) if err != nil { return nil, err } res := &OrganizationDB{ ProtectedDBImp: *p, } p.DBImp.SetDeleter(res.DeleteCascade) if err := ensureProvisioningIndexes(ctx, res); err != nil { return nil, err } return res, nil } // ensureProvisioningIndexes guards concurrent operator-driven provisioning: // two attempts creating an organization for the same owner and name race the // find-then-create in the provisioner, and the unique index makes the loser // fail over to the winner's organization instead of duplicating it. The index // spans every provisioned state, not only pending: activation keeps the // provisioning provenance, so a retry racing a concurrent finalization is // stopped here rather than by the pre-create lookups alone. It is keyed by the // immutable provisioning name snapshot, not the mutable display name, so a // rename can neither free the key for a duplicate nor collide with a neighbour. func ensureProvisioningIndexes(ctx context.Context, db *OrganizationDB) error { definition := &ri.Definition{ Name: "uq_organization_provisioning_owner_name", Keys: []ri.Key{ {Field: model.OrganizationProvisioningOwnerRefField, Sort: ri.Asc}, {Field: model.OrganizationProvisioningNameField, Sort: ri.Asc}, }, Unique: true, // Archived organizations leave the index: archiving is how an operator // retires a name, and a retired name must be reusable. Documents from // builds that predate the name snapshot stay out as well; sharing the // missing-name key would otherwise make them collide with each other. PartialFilter: repository.Query(). Comparison(repository.Field(model.OrganizationProvisioningOwnerRefField), builder.Exists, true). Comparison(repository.Field(model.OrganizationProvisioningNameField), builder.Exists, true). Filter(repository.Field(storable.IsArchivedField), false), } if err := db.DBImp.Repository.CreateIndex(definition); err != nil { db.DBImp.Logger.Error("Failed to create provisioned organization index", zap.String("index", definition.Name), zap.Error(err)) return merrors.InternalWrap(err, "failed to create provisioned organization index") } // Predecessors of this index on environments that ran earlier builds of // this feature: the pending-only variant ignored isArchived, the display // name variant let a rename detach the organization from its dedup key. if err := dropSupersededProvisioningIndexes(ctx, db.DBImp.Repository); err != nil { db.DBImp.Logger.Error("Failed to remove superseded organization provisioning indexes", zap.Error(err)) return err } return nil } var supersededProvisioningIndexes = [...]string{ "uq_organization_pending_provisioning_owner_name", "uq_organization_provisioned_owner_name", } func dropSupersededProvisioningIndexes(ctx context.Context, repo repository.Repository) error { for _, name := range supersededProvisioningIndexes { if err := repo.DropIndex(ctx, name); err != nil { if provisioningIndexNotFound(err) { continue } return merrors.InternalWrap(err, "failed to drop superseded organization provisioning index "+name) } } return nil } const ( mongoNamespaceNotFoundCode = 26 mongoIndexNotFoundCode = 27 ) func provisioningIndexNotFound(err error) bool { var serverErr mongo.ServerError return errors.As(err, &serverErr) && (serverErr.HasErrorCode(mongoNamespaceNotFoundCode) || serverErr.HasErrorCode(mongoIndexNotFoundCode)) }