refactor: invoker implementations and clean up code (#10962)

This pull request refactors the command execution and transaction
handling logic within the `domain` package. The primary goal is to
simplify the invoker chain, clarify transaction management, and improve
the overall structure for better maintainability and readability.

### Key Changes:

- **Simplified Invoker Chain**: The previous chain of invokers has been
refactored. A new `transactionInvoker` is introduced to explicitly
manage database transactions for commands that require them. This
responsibility is no longer spread across different parts of the
invocation flow.
- **`Transactional` Interface**: A new `Transactional` interface has
been introduced. Commands that need to run within a database transaction
now implement this interface. This provides a clear and explicit
contract for transactional operations.
- **Consolidated Transaction Logic**: The logic for starting,
committing, and rolling back transactions is now centralized within the
`transactionInvoker` and the `eventStoreInvoker`. The `EnsureTx` method
on `InvokeOpts` has been removed, and transaction handling is now
managed automatically by the invocation framework.
- **Improved Event Handling**: The `eventStoreInvoker` and its
`eventCollector` have been rewritten to be more robust and to correctly
handle nested and batched commands, ensuring that all events are
collected and published within the same transaction.
- **Code Cleanup**: A significant amount of now-unused code, including
the old `invoker_test.go`, has been removed. Various comments and
variable declarations have also been cleaned up.
- **Updated Command Implementations**: All commands in the `domain`
package (e.g., `ActivateOrgCommand`, `DeactivateOrgCommand`,
`DeleteOrgCommand`, `UpdateOrgCommand`) have been updated to use the new
`Transactional` interface where appropriate, removing manual transaction
management.
- **Enhanced Testing**: Tests have been added and updated to cover the
new transaction and event handling logic, ensuring the refactoring is
sound.
- **Use `PrimaryKeyCondition`**: Use the
`repository.PrimaryKeyCondition(...)` method instead of using
`database.And(...)` where possible.

These changes lead to a cleaner, more decoupled architecture for command
handling in ZITADEL.

---------

Co-authored-by: Marco A. <[email protected]>
This commit is contained in:
Silvan
2025-10-27 14:04:06 +00:00
committed by GitHub
co-authored by Marco A.
parent 9dc127ddb5
commit c4221a9c0f
34 changed files with 1361 additions and 932 deletions
+36 -47
View File
@@ -23,20 +23,17 @@ func NewDeleteOrgCommand(organizationID string) *DeleteOrgCommand {
return &DeleteOrgCommand{ID: organizationID}
}
// RequiresTransaction implements [Transactional].
func (cmd *DeleteOrgCommand) RequiresTransaction() {}
// Events implements [Commander].
//
// TODO(IAM-Marco): Finish implementation when policies, org settings, idp links and entities repositories
// are implemented
func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]eventstore.Command, error) {
closeFunc, err := opts.EnsureTx(ctx)
if err != nil {
return nil, err
}
defer func() { err = closeFunc(ctx, err) }()
func (cmd *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]eventstore.Command, error) {
usernames := []string{}
// userRepo := opts.usersRepo(pool)
// users, err := userRepo.List(ctx, database.WithCondition(opts.organizationRepo(pool).IDCondition(d.ID)))
// userRepo := opts.usersRepo(opts.DB())
// users, err := userRepo.List(ctx, database.WithCondition(opts.organizationRepo(opts.DB()).IDCondition(d.ID)))
// if err != nil {
// return nil, err
// }
@@ -44,13 +41,13 @@ func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]even
// usernames = append(usernames, u.UserID)
// }
// domainPolicyRepo := opts.domainPolicyRepo(pool)
// domainPolicyRepo := opts.domainPolicyRepo(opts.DB())
// policy, err := domainPolicyRepo.Get(ctx, instanceID, d.ID)
// if err != nil {
// return nil, err
// }
// orgSettingsRepo := opts.organizationSettingsRepo(pool)
// orgSettingsRepo := opts.organizationSettingsRepo(opts.DB())
// orgSettings, err := orgSettingsRepo.Get(ctx, d.ID)
// if err != nil {
// return nil, err
@@ -58,13 +55,13 @@ func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]even
// areUsernamesOrganizationScoped := policy.UserLoginMustBeDomain || orgSettings.UsernamesUnique
areUsernamesOrganizationScoped := false
domainNames := make([]string, len(d.Domains))
for i, domain := range d.Domains {
domainNames := make([]string, len(cmd.Domains))
for i, domain := range cmd.Domains {
domainNames[i] = domain.Domain
}
externalIDPLinks := []*internal_domain.UserIDPLink{}
// idpLinksRepo := opts.idpLinksRepo(pool)
// idpLinksRepo := opts.idpLinksRepo(opts.DB())
// idpLinks, err := idpLinksRepo.List(ctx, d.ID)
// if err != nil {
// return nil, err
@@ -75,7 +72,7 @@ func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]even
// }
samlEntityIDs := []string{}
// entityIDsRepo := opts.entityIDsRepo(pool)
// entityIDsRepo := opts.entityIDsRepo(opts.DB())
// entityIDs, err := entityIDsRepo.List(ctx, d.ID)
// if err != nil {
// return nil, err
@@ -87,8 +84,8 @@ func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]even
return []eventstore.Command{
org.NewOrgRemovedEvent(
ctx,
&org.NewAggregate(d.ID).Aggregate,
d.OrganizationName,
&org.NewAggregate(cmd.ID).Aggregate,
cmd.OrganizationName,
usernames,
areUsernamesOrganizationScoped,
domainNames,
@@ -99,32 +96,22 @@ func (d *DeleteOrgCommand) Events(ctx context.Context, opts *InvokeOpts) ([]even
}
// Execute implements [Commander].
func (d *DeleteOrgCommand) Execute(ctx context.Context, opts *InvokeOpts) (err error) {
closeFunc, err := opts.EnsureTx(ctx)
if err != nil {
return err
}
defer func() { err = closeFunc(ctx, err) }()
func (cmd *DeleteOrgCommand) Execute(ctx context.Context, opts *InvokeOpts) (err error) {
instance := authz.GetInstance(ctx)
orgRepo := opts.organizationRepo.LoadDomains()
orgToDelete, err := orgRepo.Get(ctx, pool, database.WithCondition(database.And(
orgRepo.IDCondition(d.ID),
orgRepo.InstanceIDCondition(instance.InstanceID()),
)))
orgToDelete, err := orgRepo.Get(ctx, opts.DB(), database.WithCondition(
orgRepo.PrimaryKeyCondition(instance.InstanceID(), cmd.ID),
))
if err != nil {
return err
}
d.OrganizationName = orgToDelete.Name
d.Domains = orgToDelete.Domains
cmd.OrganizationName = orgToDelete.Name
cmd.Domains = orgToDelete.Domains
deletedRows, err := orgRepo.Delete(ctx, pool,
database.And(
orgRepo.IDCondition(d.ID),
orgRepo.InstanceIDCondition(authz.GetInstance(ctx).InstanceID()),
),
deletedRows, err := orgRepo.Delete(ctx, opts.DB(),
orgRepo.PrimaryKeyCondition(authz.GetInstance(ctx).InstanceID(), cmd.ID),
)
if err != nil {
return err
@@ -142,25 +129,25 @@ func (d *DeleteOrgCommand) Execute(ctx context.Context, opts *InvokeOpts) (err e
}
// String implements [Commander].
func (d *DeleteOrgCommand) String() string {
func (DeleteOrgCommand) String() string {
return "DeleteOrgCommand"
}
// Validate implements [Commander].
func (d *DeleteOrgCommand) Validate(ctx context.Context, opts *InvokeOpts) (err error) {
func (cmd *DeleteOrgCommand) Validate(ctx context.Context, opts *InvokeOpts) (err error) {
instance := authz.GetInstance(ctx)
d.ID = strings.TrimSpace(d.ID)
if d.ID == instance.DefaultOrganisationID() {
cmd.ID = strings.TrimSpace(cmd.ID)
if cmd.ID == instance.DefaultOrganisationID() {
return zerrors.ThrowPreconditionFailed(nil, "DOM-LCkE69", "Errors.Org.DefaultOrgNotDeletable")
}
// Check if the ZITADEL project exists on the input organization
projectRepo := opts.projectRepo
_, getErr := projectRepo.Get(ctx, pool,
_, getErr := projectRepo.Get(ctx, opts.DB(),
database.WithCondition(database.And(
projectRepo.IDCondition(instance.ProjectID()),
projectRepo.OrganizationIDCondition(d.ID),
projectRepo.OrganizationIDCondition(cmd.ID),
projectRepo.InstanceIDCondition(instance.InstanceID()),
)),
)
@@ -174,11 +161,10 @@ func (d *DeleteOrgCommand) Validate(ctx context.Context, opts *InvokeOpts) (err
}
orgRepo := opts.organizationRepo
_, errGetOrg := orgRepo.Get(ctx, pool,
database.WithCondition(database.And(
orgRepo.IDCondition(d.ID),
orgRepo.InstanceIDCondition(instance.InstanceID()),
)))
_, errGetOrg := orgRepo.Get(ctx, opts.DB(),
database.WithCondition(
orgRepo.PrimaryKeyCondition(instance.InstanceID(), cmd.ID),
))
if errGetOrg != nil {
if errors.Is(errGetOrg, &database.NoRowFoundError{}) {
err = zerrors.ThrowNotFound(errGetOrg, "DOM-8KYOH3", "Errors.Org.NotFound")
@@ -189,4 +175,7 @@ func (d *DeleteOrgCommand) Validate(ctx context.Context, opts *InvokeOpts) (err
return err
}
var _ Commander = (*DeleteOrgCommand)(nil)
var (
_ Commander = (*DeleteOrgCommand)(nil)
_ Transactional = (*DeleteOrgCommand)(nil)
)