Files
zitadel/backend/v3/domain/org_list.go
T
c4221a9c0f 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]>
2025-10-27 14:04:06 +00:00

121 lines
3.8 KiB
Go

package domain
import (
"context"
"github.com/zitadel/zitadel/backend/v3/api/object"
"github.com/zitadel/zitadel/backend/v3/storage/database"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/zerrors"
v2_org "github.com/zitadel/zitadel/pkg/grpc/org/v2"
)
type ListOrgsQuery struct {
Request *v2_org.ListOrganizationsRequest
result []*Organization
}
// Result implements [Querier].
func (l *ListOrgsQuery) Result() []*Organization {
return l.result
}
func NewListOrgsQuery(inputRequest *v2_org.ListOrganizationsRequest) *ListOrgsQuery {
return &ListOrgsQuery{
Request: inputRequest,
}
}
// Execute implements [Querier].
func (l *ListOrgsQuery) Execute(ctx context.Context, opts *InvokeOpts) (err error) {
organizationRepo := opts.organizationRepo.LoadDomains()
domainRepo := opts.organizationDomainRepo
sorting := l.Sorting(organizationRepo)
limit, pagination := l.Pagination()
conditions, condErr := l.conditions(ctx, organizationRepo, domainRepo)
if condErr != nil {
err = condErr
return err
}
l.result, err = organizationRepo.List(ctx, opts.DB(), conditions, sorting, limit, pagination)
return err
}
func (l *ListOrgsQuery) Sorting(orgRepo OrganizationRepository) database.QueryOption {
var sortingCol database.Column
switch l.Request.GetSortingColumn() {
case v2_org.OrganizationFieldName_ORGANIZATION_FIELD_NAME_NAME:
sortingCol = orgRepo.NameColumn()
case v2_org.OrganizationFieldName_ORGANIZATION_FIELD_NAME_UNSPECIFIED:
fallthrough
default:
return func(opts *database.QueryOpts) {}
}
orderDirection := database.OrderDirectionDesc
if l.Request.GetQuery().GetAsc() {
orderDirection = database.OrderDirectionAsc
}
return database.WithOrderBy(orderDirection, sortingCol)
}
func (l *ListOrgsQuery) Pagination() (database.QueryOption, database.QueryOption) {
return database.WithLimit(l.Request.GetQuery().GetLimit()),
database.WithOffset(uint32(l.Request.GetQuery().GetOffset()))
}
func (l *ListOrgsQuery) conditions(ctx context.Context, orgRepo OrganizationRepository, domainRepo OrganizationDomainRepository) (database.QueryOption, error) {
conditions := make([]database.Condition, len(l.Request.GetQueries()))
instance := authz.GetInstance(ctx)
for i, query := range l.Request.GetQueries() {
switch assertedType := query.GetQuery().(type) {
case *v2_org.SearchQuery_DefaultQuery:
conditions[i] = orgRepo.IDCondition(instance.DefaultOrganisationID())
case *v2_org.SearchQuery_DomainQuery:
method, err := object.TextQueryMethodToTextOperation(assertedType.DomainQuery.GetMethod())
if err != nil {
return nil, err
}
conditions[i] = database.And(
orgRepo.InstanceIDCondition(instance.InstanceID()),
orgRepo.ExistsDomain(domainRepo.DomainCondition(method, assertedType.DomainQuery.GetDomain())),
)
case *v2_org.SearchQuery_IdQuery:
conditions[i] = orgRepo.IDCondition(assertedType.IdQuery.GetId())
case *v2_org.SearchQuery_NameQuery:
method, err := object.TextQueryMethodToTextOperation(assertedType.NameQuery.GetMethod())
if err != nil {
return nil, err
}
conditions[i] = orgRepo.NameCondition(method, assertedType.NameQuery.GetName())
case *v2_org.SearchQuery_StateQuery:
conditions[i] = orgRepo.StateCondition(OrgState(assertedType.StateQuery.GetState()))
default:
return nil, zerrors.ThrowInvalidArgument(NewUnexpectedQueryTypeError(assertedType), "DOM-TCEzcr", "List.Query.Invalid")
}
}
return database.WithCondition(database.And(
append(conditions, orgRepo.InstanceIDCondition(instance.InstanceID()))...,
)), nil
}
// String implements [Querier].
func (l *ListOrgsQuery) String() string {
return "ListOrgsQuery"
}
// Validate implements [Querier].
func (l *ListOrgsQuery) Validate(_ context.Context, _ *InvokeOpts) (err error) {
return nil
}
var _ Querier[[]*Organization] = (*ListOrgsQuery)(nil)