feat(backend): state persisted objects (#9870)

This PR initiates the rework of Zitadel's backend to state-persisted
objects. This change is a step towards a more scalable and maintainable
architecture.

## Changes

* **New `/backend/v3` package**: A new package structure has been
introduced to house the reworked backend logic. This includes:
* `domain`: Contains the core business logic, commands, and repository
interfaces.
* `storage`: Implements the repository interfaces for database
interactions with new transactional tables.
  * `telemetry`: Provides logging and tracing capabilities.
* **Transactional Tables**: New database tables have been defined for
`instances`, `instance_domains`, `organizations`, and `org_domains`.
* **Projections**: New projections have been created to populate the new
relational tables from the existing event store, ensuring data
consistency during the migration.
* **Repositories**: New repositories provide an abstraction layer for
accessing and manipulating the data in the new tables.
* **Setup**: A new setup step for `TransactionalTables` has been added
to manage the database migrations for the new tables.

This PR lays the foundation for future work to fully transition to
state-persisted objects for these components, which will improve
performance and simplify data access patterns.

This PR initiates the rework of ZITADEL's backend to state-persisted
objects. This is a foundational step towards a new architecture that
will improve performance and maintainability.

The following objects are migrated from event-sourced aggregates to
state-persisted objects:

* Instances
  * incl. Domains
* Orgs
  * incl. Domains

The structure of the new backend implementation follows the software
architecture defined in this [wiki
page](https://github.com/zitadel/zitadel/wiki/Software-Architecturel).

This PR includes:

* The initial implementation of the new transactional repositories for
the objects listed above.
* Projections to populate the new relational tables from the existing
event store.
* Adjustments to the build and test process to accommodate the new
backend structure.

This is a work in progress and further changes will be made to complete
the migration.

---------

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Iraq Jaber <[email protected]>
Co-authored-by: Iraq <[email protected]>
Co-authored-by: Tim Möhlmann <[email protected]>
This commit is contained in:
Silvan
2025-09-05 09:54:34 +01:00
committed by GitHub
co-authored by Copilot Iraq Jaber Iraq Tim Möhlmann
parent 8cc79c1376
commit 61cab8878e
119 changed files with 13940 additions and 11 deletions
+131
View File
@@ -0,0 +1,131 @@
package domain
// import (
// "context"
// "fmt"
// "github.com/zitadel/zitadel/backend/v3/storage/database"
// )
// // Commander is the all it needs to implement the command pattern.
// // It is the interface all manipulations need to implement.
// // If possible it should also be used for queries. We will find out if this is possible in the future.
// type Commander interface {
// Execute(ctx context.Context, opts *CommandOpts) (err error)
// fmt.Stringer
// }
// // Invoker is part of the command pattern.
// // It is the interface that is used to execute commands.
// type Invoker interface {
// Invoke(ctx context.Context, command Commander, opts *CommandOpts) error
// }
// // CommandOpts are passed to each command
// // the provide common fields used by commands like the database client.
// type CommandOpts struct {
// DB database.QueryExecutor
// Invoker Invoker
// }
// type ensureTxOpts struct {
// *database.TransactionOptions
// }
// type EnsureTransactionOpt func(*ensureTxOpts)
// // EnsureTx ensures that the DB is a transaction. If it is not, it will start a new transaction.
// // The returned close function will end the transaction. If the DB is already a transaction, the close function
// // will do nothing because another [Commander] is already responsible for ending the transaction.
// func (o *CommandOpts) EnsureTx(ctx context.Context, opts ...EnsureTransactionOpt) (close func(context.Context, error) error, err error) {
// beginner, ok := o.DB.(database.Beginner)
// if !ok {
// // db is already a transaction
// return func(_ context.Context, err error) error {
// return err
// }, nil
// }
// txOpts := &ensureTxOpts{
// TransactionOptions: new(database.TransactionOptions),
// }
// for _, opt := range opts {
// opt(txOpts)
// }
// tx, err := beginner.Begin(ctx, txOpts.TransactionOptions)
// if err != nil {
// return nil, err
// }
// o.DB = tx
// return func(ctx context.Context, err error) error {
// return tx.End(ctx, err)
// }, nil
// }
// // EnsureClient ensures that the o.DB is a client. If it is not, it will get a new client from the [database.Pool].
// // The returned close function will release the client. If the o.DB is already a client or transaction, the close function
// // will do nothing because another [Commander] is already responsible for releasing the client.
// func (o *CommandOpts) EnsureClient(ctx context.Context) (close func(_ context.Context) error, err error) {
// pool, ok := o.DB.(database.Pool)
// if !ok {
// // o.DB is already a client
// return func(_ context.Context) error {
// return nil
// }, nil
// }
// client, err := pool.Acquire(ctx)
// if err != nil {
// return nil, err
// }
// o.DB = client
// return func(ctx context.Context) error {
// return client.Release(ctx)
// }, nil
// }
// func (o *CommandOpts) Invoke(ctx context.Context, command Commander) error {
// if o.Invoker == nil {
// return command.Execute(ctx, o)
// }
// return o.Invoker.Invoke(ctx, command, o)
// }
// func DefaultOpts(invoker Invoker) *CommandOpts {
// if invoker == nil {
// invoker = &noopInvoker{}
// }
// return &CommandOpts{
// DB: pool,
// Invoker: invoker,
// }
// }
// // commandBatch is a batch of commands.
// // It uses the [Invoker] provided by the opts to execute each command.
// type commandBatch struct {
// Commands []Commander
// }
// func BatchCommands(cmds ...Commander) *commandBatch {
// return &commandBatch{
// Commands: cmds,
// }
// }
// // String implements [Commander].
// func (cmd *commandBatch) String() string {
// return "commandBatch"
// }
// func (b *commandBatch) Execute(ctx context.Context, opts *CommandOpts) (err error) {
// for _, cmd := range b.Commands {
// if err = opts.Invoke(ctx, cmd); err != nil {
// return err
// }
// }
// return nil
// }
// var _ Commander = (*commandBatch)(nil)
+90
View File
@@ -0,0 +1,90 @@
package domain
// import (
// "context"
// "github.com/zitadel/zitadel/backend/v3/storage/eventstore"
// )
// // CreateUserCommand adds a new user including the email verification for humans.
// // In the future it might make sense to separate the command into two commands:
// // - CreateHumanCommand: creates a new human user
// // - CreateMachineCommand: creates a new machine user
// type CreateUserCommand struct {
// user *User
// email *SetEmailCommand
// }
// var (
// _ Commander = (*CreateUserCommand)(nil)
// _ eventer = (*CreateUserCommand)(nil)
// )
// // opts heavily reduces the complexity for email verification because each type of verification is a simple option which implements the [Commander] interface.
// func NewCreateHumanCommand(username string, opts ...CreateHumanOpt) *CreateUserCommand {
// cmd := &CreateUserCommand{
// user: &User{
// Username: username,
// Traits: &Human{},
// },
// }
// for _, opt := range opts {
// opt.applyOnCreateHuman(cmd)
// }
// return cmd
// }
// // String implements [Commander].
// func (cmd *CreateUserCommand) String() string {
// return "CreateUserCommand"
// }
// // Events implements [eventer].
// func (c *CreateUserCommand) Events() []*eventstore.Event {
// return []*eventstore.Event{
// {
// AggregateType: "user",
// AggregateID: c.user.ID,
// Type: "user.added",
// Payload: c.user,
// },
// }
// }
// // Execute implements [Commander].
// func (c *CreateUserCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// if err := c.ensureUserID(); err != nil {
// return err
// }
// c.email.UserID = c.user.ID
// if err := opts.Invoke(ctx, c.email); err != nil {
// return err
// }
// return nil
// }
// type CreateHumanOpt interface {
// applyOnCreateHuman(*CreateUserCommand)
// }
// type createHumanIDOpt string
// // applyOnCreateHuman implements [CreateHumanOpt].
// func (c createHumanIDOpt) applyOnCreateHuman(cmd *CreateUserCommand) {
// cmd.user.ID = string(c)
// }
// var _ CreateHumanOpt = (*createHumanIDOpt)(nil)
// func CreateHumanWithID(id string) CreateHumanOpt {
// return createHumanIDOpt(id)
// }
// func (c *CreateUserCommand) ensureUserID() (err error) {
// if c.user.ID != "" {
// return nil
// }
// c.user.ID, err = generateID()
// return err
// }
+37
View File
@@ -0,0 +1,37 @@
package domain
// import (
// "context"
// "github.com/zitadel/zitadel/internal/crypto"
// )
// type generateCodeCommand struct {
// code string
// value *crypto.CryptoValue
// }
// // I didn't update this repository to the solution proposed please view one of the following interfaces for correct usage:
// // - [UserRepository]
// // - [InstanceRepository]
// // - [OrgRepository]
// type CryptoRepository interface {
// GetEncryptionConfig(ctx context.Context) (*crypto.GeneratorConfig, error)
// }
// // String implements [Commander].
// func (cmd *generateCodeCommand) String() string {
// return "generateCodeCommand"
// }
// func (cmd *generateCodeCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// config, err := cryptoRepo(opts.DB).GetEncryptionConfig(ctx)
// if err != nil {
// return err
// }
// generator := crypto.NewEncryptionGenerator(*config, userCodeAlgorithm)
// cmd.value, cmd.code, err = crypto.NewCode(generator)
// return err
// }
// var _ Commander = (*generateCodeCommand)(nil)
+127
View File
@@ -0,0 +1,127 @@
package domain
import (
"time"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
//go:generate enumer -type DomainValidationType -transform lower -trimprefix DomainValidationType -sql
type DomainValidationType uint8
const (
DomainValidationTypeDNS DomainValidationType = iota
DomainValidationTypeHTTP
)
//go:generate enumer -type DomainType -transform lower -trimprefix DomainType -sql
type DomainType uint8
const (
DomainTypeCustom DomainType = iota
DomainTypeTrusted
)
type domainColumns interface {
// InstanceIDColumn returns the column for the instance id field.
InstanceIDColumn() database.Column
// DomainColumn returns the column for the domain field.
DomainColumn() database.Column
// IsPrimaryColumn returns the column for the is primary field.
IsPrimaryColumn() database.Column
// CreatedAtColumn returns the column for the created at field.
CreatedAtColumn() database.Column
// UpdatedAtColumn returns the column for the updated at field.
UpdatedAtColumn() database.Column
}
type domainConditions interface {
// InstanceIDCondition returns a filter on the instance id field.
InstanceIDCondition(instanceID string) database.Condition
// DomainCondition returns a filter on the domain field.
DomainCondition(op database.TextOperation, domain string) database.Condition
// IsPrimaryCondition returns a filter on the is primary field.
IsPrimaryCondition(isPrimary bool) database.Condition
}
type domainChanges interface {
// SetPrimary sets a domain as primary based on the condition.
// All other domains will be set to non-primary.
//
// An error is returned if:
// - The condition identifies multiple domains.
// - The condition does not identify any domain.
//
// This is a no-op if:
// - The domain is already primary.
// - No domain matches the condition.
SetPrimary() database.Change
// SetUpdatedAt sets the updated at column.
// This is used for reducing events.
SetUpdatedAt(t time.Time) database.Change
}
// import (
// "math/rand/v2"
// "strconv"
// "github.com/zitadel/zitadel/backend/v3/storage/cache"
// "github.com/zitadel/zitadel/backend/v3/storage/database"
// // "github.com/zitadel/zitadel/backend/v3/telemetry/logging"
// "github.com/zitadel/zitadel/backend/v3/telemetry/tracing"
// "github.com/zitadel/zitadel/internal/crypto"
// )
// // The variables could also be moved to a struct.
// // I just started with the singleton pattern and kept it like this.
// var (
// pool database.Pool
// userCodeAlgorithm crypto.EncryptionAlgorithm
// tracer tracing.Tracer
// // logger logging.Logger
// userRepo func(database.QueryExecutor) UserRepository
// // instanceRepo func(database.QueryExecutor) InstanceRepository
// cryptoRepo func(database.QueryExecutor) CryptoRepository
// orgRepo func(database.QueryExecutor) OrgRepository
// // instanceCache cache.Cache[instanceCacheIndex, string, *Instance]
// orgCache cache.Cache[orgCacheIndex, string, *Org]
// generateID func() (string, error) = func() (string, error) {
// return strconv.FormatUint(rand.Uint64(), 10), nil
// }
// )
// func SetPool(p database.Pool) {
// pool = p
// }
// func SetUserCodeAlgorithm(algorithm crypto.EncryptionAlgorithm) {
// userCodeAlgorithm = algorithm
// }
// func SetTracer(t tracing.Tracer) {
// tracer = t
// }
// // func SetLogger(l logging.Logger) {
// // logger = l
// // }
// func SetUserRepository(repo func(database.QueryExecutor) UserRepository) {
// userRepo = repo
// }
// func SetOrgRepository(repo func(database.QueryExecutor) OrgRepository) {
// orgRepo = repo
// }
// // func SetInstanceRepository(repo func(database.QueryExecutor) InstanceRepository) {
// // instanceRepo = repo
// // }
// func SetCryptoRepository(repo func(database.QueryExecutor) CryptoRepository) {
// cryptoRepo = repo
// }
+67
View File
@@ -0,0 +1,67 @@
package domain_test
// import (
// "context"
// "log/slog"
// "testing"
// "github.com/stretchr/testify/assert"
// "github.com/stretchr/testify/require"
// "go.opentelemetry.io/otel"
// "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
// sdktrace "go.opentelemetry.io/otel/sdk/trace"
// "go.uber.org/mock/gomock"
// . "github.com/zitadel/zitadel/backend/v3/domain"
// "github.com/zitadel/zitadel/backend/v3/storage/database/dbmock"
// "github.com/zitadel/zitadel/backend/v3/storage/database/repository"
// "github.com/zitadel/zitadel/backend/v3/telemetry/logging"
// "github.com/zitadel/zitadel/backend/v3/telemetry/tracing"
// )
// These tests give an overview of how to use the domain package.
// func TestExample(t *testing.T) {
// t.Skip("skip example test because it is not a real test")
// ctx := context.Background()
// ctrl := gomock.NewController(t)
// pool := dbmock.NewMockPool(ctrl)
// tx := dbmock.NewMockTransaction(ctrl)
// pool.EXPECT().Begin(gomock.Any(), gomock.Any()).Return(tx, nil)
// tx.EXPECT().End(gomock.Any(), gomock.Any()).Return(nil)
// SetPool(pool)
// exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
// require.NoError(t, err)
// tracerProvider := sdktrace.NewTracerProvider(
// sdktrace.WithSyncer(exporter),
// )
// otel.SetTracerProvider(tracerProvider)
// SetTracer(tracing.Tracer{Tracer: tracerProvider.Tracer("test")})
// defer func() { assert.NoError(t, tracerProvider.Shutdown(ctx)) }()
// SetLogger(logging.Logger{Logger: slog.Default()})
// SetUserRepository(repository.UserRepository)
// SetOrgRepository(repository.OrgRepository)
// // SetInstanceRepository(repository.Instance)
// // SetCryptoRepository(repository.Crypto)
// t.Run("create org", func(t *testing.T) {
// org := NewAddOrgCommand("testorg", NewAddMemberCommand("testuser", "ORG_OWNER"))
// user := NewCreateHumanCommand("testuser")
// err := Invoke(ctx, BatchCommands(org, user))
// assert.NoError(t, err)
// })
// t.Run("verified email", func(t *testing.T) {
// err := Invoke(ctx, NewSetEmailCommand("u1", "[email protected]", NewEmailVerifiedCommand("u1", true)))
// assert.NoError(t, err)
// })
// t.Run("unverified email", func(t *testing.T) {
// err := Invoke(ctx, NewSetEmailCommand("u2", "[email protected]", NewEmailVerifiedCommand("u2", false)))
// assert.NoError(t, err)
// })
// }
+109
View File
@@ -0,0 +1,109 @@
// Code generated by "enumer -type DomainType -transform lower -trimprefix DomainType -sql"; DO NOT EDIT.
package domain
import (
"database/sql/driver"
"fmt"
"strings"
)
const _DomainTypeName = "customtrusted"
var _DomainTypeIndex = [...]uint8{0, 6, 13}
const _DomainTypeLowerName = "customtrusted"
func (i DomainType) String() string {
if i >= DomainType(len(_DomainTypeIndex)-1) {
return fmt.Sprintf("DomainType(%d)", i)
}
return _DomainTypeName[_DomainTypeIndex[i]:_DomainTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _DomainTypeNoOp() {
var x [1]struct{}
_ = x[DomainTypeCustom-(0)]
_ = x[DomainTypeTrusted-(1)]
}
var _DomainTypeValues = []DomainType{DomainTypeCustom, DomainTypeTrusted}
var _DomainTypeNameToValueMap = map[string]DomainType{
_DomainTypeName[0:6]: DomainTypeCustom,
_DomainTypeLowerName[0:6]: DomainTypeCustom,
_DomainTypeName[6:13]: DomainTypeTrusted,
_DomainTypeLowerName[6:13]: DomainTypeTrusted,
}
var _DomainTypeNames = []string{
_DomainTypeName[0:6],
_DomainTypeName[6:13],
}
// DomainTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func DomainTypeString(s string) (DomainType, error) {
if val, ok := _DomainTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _DomainTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to DomainType values", s)
}
// DomainTypeValues returns all values of the enum
func DomainTypeValues() []DomainType {
return _DomainTypeValues
}
// DomainTypeStrings returns a slice of all String values of the enum
func DomainTypeStrings() []string {
strs := make([]string, len(_DomainTypeNames))
copy(strs, _DomainTypeNames)
return strs
}
// IsADomainType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i DomainType) IsADomainType() bool {
for _, v := range _DomainTypeValues {
if i == v {
return true
}
}
return false
}
func (i DomainType) Value() (driver.Value, error) {
return i.String(), nil
}
func (i *DomainType) Scan(value interface{}) error {
if value == nil {
return nil
}
var str string
switch v := value.(type) {
case []byte:
str = string(v)
case string:
str = v
case fmt.Stringer:
str = v.String()
default:
return fmt.Errorf("invalid value of DomainType: %[1]T(%[1]v)", value)
}
val, err := DomainTypeString(str)
if err != nil {
return err
}
*i = val
return nil
}
@@ -0,0 +1,109 @@
// Code generated by "enumer -type DomainValidationType -transform lower -trimprefix DomainValidationType -sql"; DO NOT EDIT.
package domain
import (
"database/sql/driver"
"fmt"
"strings"
)
const _DomainValidationTypeName = "dnshttp"
var _DomainValidationTypeIndex = [...]uint8{0, 3, 7}
const _DomainValidationTypeLowerName = "dnshttp"
func (i DomainValidationType) String() string {
if i >= DomainValidationType(len(_DomainValidationTypeIndex)-1) {
return fmt.Sprintf("DomainValidationType(%d)", i)
}
return _DomainValidationTypeName[_DomainValidationTypeIndex[i]:_DomainValidationTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _DomainValidationTypeNoOp() {
var x [1]struct{}
_ = x[DomainValidationTypeDNS-(0)]
_ = x[DomainValidationTypeHTTP-(1)]
}
var _DomainValidationTypeValues = []DomainValidationType{DomainValidationTypeDNS, DomainValidationTypeHTTP}
var _DomainValidationTypeNameToValueMap = map[string]DomainValidationType{
_DomainValidationTypeName[0:3]: DomainValidationTypeDNS,
_DomainValidationTypeLowerName[0:3]: DomainValidationTypeDNS,
_DomainValidationTypeName[3:7]: DomainValidationTypeHTTP,
_DomainValidationTypeLowerName[3:7]: DomainValidationTypeHTTP,
}
var _DomainValidationTypeNames = []string{
_DomainValidationTypeName[0:3],
_DomainValidationTypeName[3:7],
}
// DomainValidationTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func DomainValidationTypeString(s string) (DomainValidationType, error) {
if val, ok := _DomainValidationTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _DomainValidationTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to DomainValidationType values", s)
}
// DomainValidationTypeValues returns all values of the enum
func DomainValidationTypeValues() []DomainValidationType {
return _DomainValidationTypeValues
}
// DomainValidationTypeStrings returns a slice of all String values of the enum
func DomainValidationTypeStrings() []string {
strs := make([]string, len(_DomainValidationTypeNames))
copy(strs, _DomainValidationTypeNames)
return strs
}
// IsADomainValidationType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i DomainValidationType) IsADomainValidationType() bool {
for _, v := range _DomainValidationTypeValues {
if i == v {
return true
}
}
return false
}
func (i DomainValidationType) Value() (driver.Value, error) {
return i.String(), nil
}
func (i *DomainValidationType) Scan(value interface{}) error {
if value == nil {
return nil
}
var str string
switch v := value.(type) {
case []byte:
str = string(v)
case string:
str = v
case fmt.Stringer:
str = v.String()
default:
return fmt.Errorf("invalid value of DomainValidationType: %[1]T(%[1]v)", value)
}
val, err := DomainValidationTypeString(str)
if err != nil {
return err
}
*i = val
return nil
}
+175
View File
@@ -0,0 +1,175 @@
package domain
// import (
// "context"
// "time"
// )
// // EmailVerifiedCommand verifies an email address for a user.
// type EmailVerifiedCommand struct {
// UserID string `json:"userId"`
// Email *Email `json:"email"`
// }
// func NewEmailVerifiedCommand(userID string, isVerified bool) *EmailVerifiedCommand {
// return &EmailVerifiedCommand{
// UserID: userID,
// Email: &Email{
// VerifiedAt: time.Time{},
// },
// }
// }
// // String implements [Commander].
// func (cmd *EmailVerifiedCommand) String() string {
// return "EmailVerifiedCommand"
// }
// var (
// _ Commander = (*EmailVerifiedCommand)(nil)
// _ SetEmailOpt = (*EmailVerifiedCommand)(nil)
// )
// // Execute implements [Commander]
// func (cmd *EmailVerifiedCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// repo := userRepo(opts.DB).Human()
// return repo.Update(ctx, repo.IDCondition(cmd.UserID), repo.SetEmailVerifiedAt(time.Time{}))
// }
// // applyOnSetEmail implements [SetEmailOpt]
// func (cmd *EmailVerifiedCommand) applyOnSetEmail(setEmailCmd *SetEmailCommand) {
// cmd.UserID = setEmailCmd.UserID
// cmd.Email.Address = setEmailCmd.Email
// setEmailCmd.verification = cmd
// }
// // SendCodeCommand sends a verification code to the user's email address.
// // If the URLTemplate is not set it will use the default of the organization / instance.
// type SendCodeCommand struct {
// UserID string `json:"userId"`
// Email string `json:"email"`
// URLTemplate *string `json:"urlTemplate"`
// generator *generateCodeCommand
// }
// var (
// _ Commander = (*SendCodeCommand)(nil)
// _ SetEmailOpt = (*SendCodeCommand)(nil)
// )
// func NewSendCodeCommand(userID string, urlTemplate *string) *SendCodeCommand {
// return &SendCodeCommand{
// UserID: userID,
// generator: &generateCodeCommand{},
// URLTemplate: urlTemplate,
// }
// }
// // String implements [Commander].
// func (cmd *SendCodeCommand) String() string {
// return "SendCodeCommand"
// }
// // Execute implements [Commander]
// func (cmd *SendCodeCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// if err := cmd.ensureEmail(ctx, opts); err != nil {
// return err
// }
// if err := cmd.ensureURL(ctx, opts); err != nil {
// return err
// }
// if err := opts.Invoker.Invoke(ctx, cmd.generator, opts); err != nil {
// return err
// }
// // TODO: queue notification
// return nil
// }
// func (cmd *SendCodeCommand) ensureEmail(ctx context.Context, opts *CommandOpts) error {
// if cmd.Email != "" {
// return nil
// }
// repo := userRepo(opts.DB).Human()
// email, err := repo.GetEmail(ctx, repo.IDCondition(cmd.UserID))
// if err != nil || !email.VerifiedAt.IsZero() {
// return err
// }
// cmd.Email = email.Address
// return nil
// }
// func (cmd *SendCodeCommand) ensureURL(ctx context.Context, opts *CommandOpts) error {
// if cmd.URLTemplate != nil && *cmd.URLTemplate != "" {
// return nil
// }
// _, _ = ctx, opts
// // TODO: load default template
// return nil
// }
// // applyOnSetEmail implements [SetEmailOpt]
// func (cmd *SendCodeCommand) applyOnSetEmail(setEmailCmd *SetEmailCommand) {
// cmd.UserID = setEmailCmd.UserID
// cmd.Email = setEmailCmd.Email
// setEmailCmd.verification = cmd
// }
// // ReturnCodeCommand creates the code and returns it to the caller.
// // The caller gets the code by calling the Code field after the command got executed.
// type ReturnCodeCommand struct {
// UserID string `json:"userId"`
// Email string `json:"email"`
// Code string `json:"code"`
// generator *generateCodeCommand
// }
// var (
// _ Commander = (*ReturnCodeCommand)(nil)
// _ SetEmailOpt = (*ReturnCodeCommand)(nil)
// )
// func NewReturnCodeCommand(userID string) *ReturnCodeCommand {
// return &ReturnCodeCommand{
// UserID: userID,
// generator: &generateCodeCommand{},
// }
// }
// // String implements [Commander].
// func (cmd *ReturnCodeCommand) String() string {
// return "ReturnCodeCommand"
// }
// // Execute implements [Commander]
// func (cmd *ReturnCodeCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// if err := cmd.ensureEmail(ctx, opts); err != nil {
// return err
// }
// if err := opts.Invoker.Invoke(ctx, cmd.generator, opts); err != nil {
// return err
// }
// cmd.Code = cmd.generator.code
// return nil
// }
// func (cmd *ReturnCodeCommand) ensureEmail(ctx context.Context, opts *CommandOpts) error {
// if cmd.Email != "" {
// return nil
// }
// repo := userRepo(opts.DB).Human()
// email, err := repo.GetEmail(ctx, repo.IDCondition(cmd.UserID))
// if err != nil || !email.VerifiedAt.IsZero() {
// return err
// }
// cmd.Email = email.Address
// return nil
// }
// // applyOnSetEmail implements [SetEmailOpt]
// func (cmd *ReturnCodeCommand) applyOnSetEmail(setEmailCmd *SetEmailCommand) {
// cmd.UserID = setEmailCmd.UserID
// cmd.Email = setEmailCmd.Email
// setEmailCmd.verification = cmd
// }
+7
View File
@@ -0,0 +1,7 @@
package domain
import "errors"
var (
ErrNoAdminSpecified = errors.New("at least one admin must be specified")
)
+117
View File
@@ -0,0 +1,117 @@
package domain
import (
"context"
"time"
"golang.org/x/text/language"
"github.com/zitadel/zitadel/backend/v3/storage/cache"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type Instance struct {
ID string `json:"id,omitempty" db:"id"`
Name string `json:"name,omitempty" db:"name"`
DefaultOrgID string `json:"defaultOrgId,omitempty" db:"default_org_id"`
IAMProjectID string `json:"iamProjectId,omitempty" db:"iam_project_id"`
ConsoleClientID string `json:"consoleClientId,omitempty" db:"console_client_id"`
ConsoleAppID string `json:"consoleAppId,omitempty" db:"console_app_id"`
DefaultLanguage string `json:"defaultLanguage,omitempty" db:"default_language"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
Domains []*InstanceDomain `json:"domains,omitempty" db:"-"`
}
type instanceCacheIndex uint8
const (
instanceCacheIndexUndefined instanceCacheIndex = iota
instanceCacheIndexID
)
// Keys implements the [cache.Entry].
func (i *Instance) Keys(index instanceCacheIndex) (key []string) {
if index == instanceCacheIndexID {
return []string{i.ID}
}
return nil
}
var _ cache.Entry[instanceCacheIndex, string] = (*Instance)(nil)
// instanceColumns define all the columns of the instance table.
type instanceColumns interface {
// IDColumn returns the column for the id field.
IDColumn() database.Column
// NameColumn returns the column for the name field.
NameColumn() database.Column
// DefaultOrgIDColumn returns the column for the default org id field
DefaultOrgIDColumn() database.Column
// IAMProjectIDColumn returns the column for the default IAM org id field
IAMProjectIDColumn() database.Column
// ConsoleClientIDColumn returns the column for the default IAM org id field
ConsoleClientIDColumn() database.Column
// ConsoleAppIDColumn returns the column for the console client id field
ConsoleAppIDColumn() database.Column
// DefaultLanguageColumn returns the column for the default language field
DefaultLanguageColumn() database.Column
// CreatedAtColumn returns the column for the created at field.
CreatedAtColumn() database.Column
// UpdatedAtColumn returns the column for the updated at field.
UpdatedAtColumn() database.Column
}
// instanceConditions define all the conditions for the instance table.
type instanceConditions interface {
// IDCondition returns an equal filter on the id field.
IDCondition(instanceID string) database.Condition
// NameCondition returns a filter on the name field.
NameCondition(op database.TextOperation, name string) database.Condition
}
// instanceChanges define all the changes for the instance table.
type instanceChanges interface {
// SetName sets the name column.
SetName(name string) database.Change
// SetUpdatedAt sets the updated at column.
SetUpdatedAt(time time.Time) database.Change
// SetIAMProject sets the iam project column.
SetIAMProject(id string) database.Change
// SetDefaultOrg sets the default org column.
SetDefaultOrg(id string) database.Change
// SetDefaultLanguage sets the default language column.
SetDefaultLanguage(language language.Tag) database.Change
// SetConsoleClientID sets the console client id column.
SetConsoleClientID(id string) database.Change
// SetConsoleAppID sets the console app id column.
SetConsoleAppID(id string) database.Change
}
// InstanceRepository is the interface for the instance repository.
type InstanceRepository interface {
instanceColumns
instanceConditions
instanceChanges
// TODO
// Member returns the member repository which is a sub repository of the instance repository.
// Member() MemberRepository
Get(ctx context.Context, opts ...database.QueryOption) (*Instance, error)
List(ctx context.Context, opts ...database.QueryOption) ([]*Instance, error)
Create(ctx context.Context, instance *Instance) error
Update(ctx context.Context, id string, changes ...database.Change) (int64, error)
Delete(ctx context.Context, id string) (int64, error)
// Domains returns the domain sub repository for the instance.
// If shouldLoad is true, the domains will be loaded from the database and written to the [Instance].Domains field.
// If shouldLoad is set to true once, the Domains field will be set even if shouldLoad is false in the future.
Domains(shouldLoad bool) InstanceDomainRepository
}
type CreateInstance struct {
Name string `json:"name"`
}
+79
View File
@@ -0,0 +1,79 @@
package domain
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type InstanceDomain struct {
InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
Domain string `json:"domain,omitempty" db:"domain"`
// IsPrimary indicates if the domain is the primary domain of the instance.
// It is only set for custom domains.
IsPrimary *bool `json:"isPrimary,omitempty" db:"is_primary"`
// IsGenerated indicates if the domain is a generated domain.
// It is only set for custom domains.
IsGenerated *bool `json:"isGenerated,omitempty" db:"is_generated"`
Type DomainType `json:"type,omitempty" db:"type"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
}
type AddInstanceDomain struct {
InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
Domain string `json:"domain,omitempty" db:"domain"`
IsPrimary *bool `json:"isPrimary,omitempty" db:"is_primary"`
IsGenerated *bool `json:"isGenerated,omitempty" db:"is_generated"`
Type DomainType `json:"type,omitempty" db:"type"`
// CreatedAt is the time when the domain was added.
// It is set by the repository and should not be set by the caller.
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
// UpdatedAt is the time when the domain was last updated.
// It is set by the repository and should not be set by the caller.
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
}
type instanceDomainColumns interface {
domainColumns
// IsGeneratedColumn returns the column for the is generated field.
IsGeneratedColumn() database.Column
// TypeColumn returns the column for the type field.
TypeColumn() database.Column
}
type instanceDomainConditions interface {
domainConditions
// TypeCondition returns a filter for the type field.
TypeCondition(typ DomainType) database.Condition
}
type instanceDomainChanges interface {
domainChanges
// SetType sets the type column.
SetType(typ DomainType) database.Change
}
type InstanceDomainRepository interface {
instanceDomainColumns
instanceDomainConditions
instanceDomainChanges
// Get returns a single domain based on the criteria.
// If no domain is found, it returns an error of type [database.ErrNotFound].
// If multiple domains are found, it returns an error of type [database.ErrMultipleRows].
Get(ctx context.Context, opts ...database.QueryOption) (*InstanceDomain, error)
// List returns a list of domains based on the criteria.
// If no domains are found, it returns an empty slice.
List(ctx context.Context, opts ...database.QueryOption) ([]*InstanceDomain, error)
// Add adds a new domain to the instance.
Add(ctx context.Context, domain *AddInstanceDomain) error
// Update updates an existing domain in the instance.
Update(ctx context.Context, condition database.Condition, changes ...database.Change) (int64, error)
// Remove removes a domain from the instance.
Remove(ctx context.Context, condition database.Condition) (int64, error)
}
+158
View File
@@ -0,0 +1,158 @@
package domain
// import (
// "context"
// "fmt"
// "github.com/zitadel/zitadel/backend/v3/storage/eventstore"
// )
// // Invoke provides a way to execute commands within the domain package.
// // It uses a chain of responsibility pattern to handle the command execution.
// // The default chain includes logging, tracing, and event publishing.
// // If you want to invoke multiple commands in a single transaction, you can use the [commandBatch].
// func Invoke(ctx context.Context, cmd Commander) error {
// invoker := newEventStoreInvoker(newLoggingInvoker(newTraceInvoker(nil)))
// opts := &CommandOpts{
// Invoker: invoker.collector,
// DB: pool,
// }
// return invoker.Invoke(ctx, cmd, opts)
// }
// // eventStoreInvoker checks if the command implements the [eventer] interface.
// // If it does, it collects the events and publishes them to the event store.
// type eventStoreInvoker struct {
// collector *eventCollector
// }
// func newEventStoreInvoker(next Invoker) *eventStoreInvoker {
// return &eventStoreInvoker{collector: &eventCollector{next: next}}
// }
// func (i *eventStoreInvoker) Invoke(ctx context.Context, command Commander, opts *CommandOpts) (err error) {
// err = i.collector.Invoke(ctx, command, opts)
// if err != nil {
// return err
// }
// if len(i.collector.events) > 0 {
// err = eventstore.Publish(ctx, i.collector.events, opts.DB)
// if err != nil {
// return err
// }
// }
// return nil
// }
// // eventCollector collects events from all commands. The [eventStoreInvoker] pushes the collected events after all commands are executed.
// type eventCollector struct {
// next Invoker
// events []*eventstore.Event
// }
// type eventer interface {
// Events() []*eventstore.Event
// }
// func (i *eventCollector) Invoke(ctx context.Context, command Commander, opts *CommandOpts) (err error) {
// if e, ok := command.(eventer); ok && len(e.Events()) > 0 {
// // we need to ensure all commands are executed in the same transaction
// close, err := opts.EnsureTx(ctx)
// if err != nil {
// return err
// }
// defer func() { err = close(ctx, err) }()
// i.events = append(i.events, e.Events()...)
// }
// if i.next != nil {
// return i.next.Invoke(ctx, command, opts)
// }
// return command.Execute(ctx, opts)
// }
// // traceInvoker decorates each command with tracing.
// type traceInvoker struct {
// next Invoker
// }
// func newTraceInvoker(next Invoker) *traceInvoker {
// return &traceInvoker{next: next}
// }
// func (i *traceInvoker) Invoke(ctx context.Context, command Commander, opts *CommandOpts) (err error) {
// ctx, span := tracer.Start(ctx, fmt.Sprintf("%T", command))
// defer func() {
// if err != nil {
// span.RecordError(err)
// }
// span.End()
// }()
// if i.next != nil {
// return i.next.Invoke(ctx, command, opts)
// }
// return command.Execute(ctx, opts)
// }
// // loggingInvoker decorates each command with logging.
// // It is an example implementation and logs the command name at the beginning and success or failure after the command got executed.
// type loggingInvoker struct {
// next Invoker
// }
// func newLoggingInvoker(next Invoker) *loggingInvoker {
// return &loggingInvoker{next: next}
// }
// func (i *loggingInvoker) Invoke(ctx context.Context, command Commander, opts *CommandOpts) (err error) {
// logger.InfoContext(ctx, "Invoking command", "command", command.String())
// if i.next != nil {
// err = i.next.Invoke(ctx, command, opts)
// } else {
// err = command.Execute(ctx, opts)
// }
// if err != nil {
// logger.ErrorContext(ctx, "Command invocation failed", "command", command.String(), "error", err)
// return err
// }
// logger.InfoContext(ctx, "Command invocation succeeded", "command", command.String())
// return nil
// }
// type noopInvoker struct {
// next Invoker
// }
// func (i *noopInvoker) Invoke(ctx context.Context, command Commander, opts *CommandOpts) error {
// if i.next != nil {
// return i.next.Invoke(ctx, command, opts)
// }
// return command.Execute(ctx, opts)
// }
// // cacheInvoker could be used in the future to do the caching.
// // My goal would be to have two interfaces:
// // - cacheSetter: which caches an object
// // - cacheGetter: which gets an object from the cache, this should also skip the command execution
// type cacheInvoker struct {
// next Invoker
// }
// type cacher interface {
// Cache(opts *CommandOpts)
// }
// func (i *cacheInvoker) Invoke(ctx context.Context, command Commander, opts *CommandOpts) (err error) {
// if c, ok := command.(cacher); ok {
// c.Cache(opts)
// }
// if i.next != nil {
// err = i.next.Invoke(ctx, command, opts)
// } else {
// err = command.Execute(ctx, opts)
// }
// return err
// }
+137
View File
@@ -0,0 +1,137 @@
package domain
// import (
// "context"
// "github.com/zitadel/zitadel/backend/v3/storage/eventstore"
// )
// // AddOrgCommand adds a new organization.
// // I'm unsure if we should add the Admins here or if this should be a separate command.
// type AddOrgCommand struct {
// ID string `json:"id"`
// Name string `json:"name"`
// Admins []*AddMemberCommand `json:"admins"`
// }
// func NewAddOrgCommand(name string, admins ...*AddMemberCommand) *AddOrgCommand {
// return &AddOrgCommand{
// Name: name,
// Admins: admins,
// }
// }
// // String implements [Commander].
// func (cmd *AddOrgCommand) String() string {
// return "AddOrgCommand"
// }
// // Execute implements Commander.
// func (cmd *AddOrgCommand) Execute(ctx context.Context, opts *CommandOpts) (err error) {
// if len(cmd.Admins) == 0 {
// return ErrNoAdminSpecified
// }
// if err = cmd.ensureID(); err != nil {
// return err
// }
// close, err := opts.EnsureTx(ctx)
// if err != nil {
// return err
// }
// defer func() { err = close(ctx, err) }()
// err = orgRepo(opts.DB).Create(ctx, &Org{
// ID: cmd.ID,
// Name: cmd.Name,
// })
// if err != nil {
// return err
// }
// for _, admin := range cmd.Admins {
// admin.orgID = cmd.ID
// if err = opts.Invoke(ctx, admin); err != nil {
// return err
// }
// }
// orgCache.Set(ctx, &Org{
// ID: cmd.ID,
// Name: cmd.Name,
// })
// return nil
// }
// // Events implements [eventer].
// func (cmd *AddOrgCommand) Events() []*eventstore.Event {
// return []*eventstore.Event{
// {
// AggregateType: "org",
// AggregateID: cmd.ID,
// Type: "org.added",
// Payload: cmd,
// },
// }
// }
// var (
// _ Commander = (*AddOrgCommand)(nil)
// _ eventer = (*AddOrgCommand)(nil)
// )
// func (cmd *AddOrgCommand) ensureID() (err error) {
// if cmd.ID != "" {
// return nil
// }
// cmd.ID, err = generateID()
// return err
// }
// // AddMemberCommand adds a new member to an organization.
// // I'm not sure if we should make it more generic to also use it for instances.
// type AddMemberCommand struct {
// orgID string
// UserID string `json:"userId"`
// Roles []string `json:"roles"`
// }
// func NewAddMemberCommand(userID string, roles ...string) *AddMemberCommand {
// return &AddMemberCommand{
// UserID: userID,
// Roles: roles,
// }
// }
// // String implements [Commander].
// func (cmd *AddMemberCommand) String() string {
// return "AddMemberCommand"
// }
// // Execute implements Commander.
// func (a *AddMemberCommand) Execute(ctx context.Context, opts *CommandOpts) (err error) {
// close, err := opts.EnsureTx(ctx)
// if err != nil {
// return err
// }
// defer func() { err = close(ctx, err) }()
// return orgRepo(opts.DB).Member().AddMember(ctx, a.orgID, a.UserID, a.Roles)
// }
// // Events implements [eventer].
// func (a *AddMemberCommand) Events() []*eventstore.Event {
// return []*eventstore.Event{
// {
// AggregateType: "org",
// AggregateID: a.UserID,
// Type: "member.added",
// Payload: a,
// },
// }
// }
// var (
// _ Commander = (*AddMemberCommand)(nil)
// _ eventer = (*AddMemberCommand)(nil)
// )
+100
View File
@@ -0,0 +1,100 @@
package domain
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
//go:generate enumer -type OrgState -transform lower -trimprefix OrgState -sql
type OrgState uint8
const (
OrgStateActive OrgState = iota
OrgStateInactive
)
type Organization struct {
ID string `json:"id,omitempty" db:"id"`
Name string `json:"name,omitempty" db:"name"`
InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
State OrgState `json:"state,omitempty" db:"state"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
Domains []*OrganizationDomain `json:"domains,omitempty" db:"-"` // domains need to be handled separately
}
// OrgIdentifierCondition is used to help specify a single Organization,
// it will either be used as the organization ID or organization name,
// as organizations can be identified either using (instanceID + ID) OR (instanceID + name)
type OrgIdentifierCondition interface {
database.Condition
}
// organizationColumns define all the columns of the instance table.
type organizationColumns interface {
// IDColumn returns the column for the id field.
IDColumn() database.Column
// NameColumn returns the column for the name field.
NameColumn() database.Column
// InstanceIDColumn returns the column for the default org id field
InstanceIDColumn() database.Column
// StateColumn returns the column for the name field.
StateColumn() database.Column
// CreatedAtColumn returns the column for the created at field.
CreatedAtColumn() database.Column
// UpdatedAtColumn returns the column for the updated at field.
UpdatedAtColumn() database.Column
}
// organizationConditions define all the conditions for the instance table.
type organizationConditions interface {
// IDCondition returns an equal filter on the id field.
IDCondition(instanceID string) OrgIdentifierCondition
// NameCondition returns a filter on the name field.
NameCondition(name string) OrgIdentifierCondition
// InstanceIDCondition returns a filter on the instance id field.
InstanceIDCondition(instanceID string) database.Condition
// StateCondition returns a filter on the name field.
StateCondition(state OrgState) database.Condition
}
// organizationChanges define all the changes for the instance table.
type organizationChanges interface {
// SetName sets the name column.
SetName(name string) database.Change
// SetState sets the name column.
SetState(state OrgState) database.Change
}
// OrganizationRepository is the interface for the instance repository.
type OrganizationRepository interface {
organizationColumns
organizationConditions
organizationChanges
Get(ctx context.Context, opts ...database.QueryOption) (*Organization, error)
List(ctx context.Context, opts ...database.QueryOption) ([]*Organization, error)
Create(ctx context.Context, instance *Organization) error
Update(ctx context.Context, id OrgIdentifierCondition, instance_id string, changes ...database.Change) (int64, error)
Delete(ctx context.Context, id OrgIdentifierCondition, instance_id string) (int64, error)
// Domains returns the domain sub repository for the organization.
// If shouldLoad is true, the domains will be loaded from the database and written to the [Instance].Domains field.
// If shouldLoad is set to true once, the Domains field will be set event if shouldLoad is false in the future.
Domains(shouldLoad bool) OrganizationDomainRepository
}
type CreateOrganization struct {
Name string `json:"name"`
}
// MemberRepository is a sub repository of the org repository and maybe the instance repository.
type MemberRepository interface {
AddMember(ctx context.Context, orgID, userID string, roles []string) error
SetMemberRoles(ctx context.Context, orgID, userID string, roles []string) error
RemoveMember(ctx context.Context, orgID, userID string) error
}
+84
View File
@@ -0,0 +1,84 @@
package domain
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type OrganizationDomain struct {
InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
OrgID string `json:"orgId,omitempty" db:"org_id"`
Domain string `json:"domain,omitempty" db:"domain"`
IsVerified bool `json:"isVerified,omitempty" db:"is_verified"`
IsPrimary bool `json:"isPrimary,omitempty" db:"is_primary"`
ValidationType *DomainValidationType `json:"validationType,omitempty" db:"validation_type"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
}
type AddOrganizationDomain struct {
InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
OrgID string `json:"orgId,omitempty" db:"org_id"`
Domain string `json:"domain,omitempty" db:"domain"`
IsVerified bool `json:"isVerified,omitempty" db:"is_verified"`
IsPrimary bool `json:"isPrimary,omitempty" db:"is_primary"`
ValidationType *DomainValidationType `json:"validationType,omitempty" db:"validation_type"`
// CreatedAt is the time when the domain was added.
// It is set by the repository and should not be set by the caller.
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
// UpdatedAt is the time when the domain was added.
// It is set by the repository and should not be set by the caller.
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
}
type organizationDomainColumns interface {
domainColumns
// OrgIDColumn returns the column for the org id field.
OrgIDColumn() database.Column
// IsVerifiedColumn returns the column for the is verified field.
IsVerifiedColumn() database.Column
// ValidationTypeColumn returns the column for the verification type field.
ValidationTypeColumn() database.Column
}
type organizationDomainConditions interface {
domainConditions
// OrgIDCondition returns a filter on the org id field.
OrgIDCondition(orgID string) database.Condition
// IsVerifiedCondition returns a filter on the is verified field.
IsVerifiedCondition(isVerified bool) database.Condition
}
type organizationDomainChanges interface {
domainChanges
// SetVerified sets the is verified column to true.
SetVerified() database.Change
// SetValidationType sets the verification type column.
// If the domain is already verified, this is a no-op.
SetValidationType(verificationType DomainValidationType) database.Change
}
type OrganizationDomainRepository interface {
organizationDomainColumns
organizationDomainConditions
organizationDomainChanges
// Get returns a single domain based on the criteria.
// If no domain is found, it returns an error of type [database.ErrNotFound].
// If multiple domains are found, it returns an error of type [database.ErrMultipleRows].
Get(ctx context.Context, opts ...database.QueryOption) (*OrganizationDomain, error)
// List returns a list of domains based on the criteria.
// If no domains are found, it returns an empty slice.
List(ctx context.Context, opts ...database.QueryOption) ([]*OrganizationDomain, error)
// Add adds a new domain to the organization.
Add(ctx context.Context, domain *AddOrganizationDomain) error
// Update updates an existing domain in the organization.
Update(ctx context.Context, condition database.Condition, changes ...database.Change) (int64, error)
// Remove removes a domain from the organization.
Remove(ctx context.Context, condition database.Condition) (int64, error)
}
+109
View File
@@ -0,0 +1,109 @@
// Code generated by "enumer -type OrgState -transform lower -trimprefix OrgState -sql"; DO NOT EDIT.
package domain
import (
"database/sql/driver"
"fmt"
"strings"
)
const _OrgStateName = "activeinactive"
var _OrgStateIndex = [...]uint8{0, 6, 14}
const _OrgStateLowerName = "activeinactive"
func (i OrgState) String() string {
if i >= OrgState(len(_OrgStateIndex)-1) {
return fmt.Sprintf("OrgState(%d)", i)
}
return _OrgStateName[_OrgStateIndex[i]:_OrgStateIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _OrgStateNoOp() {
var x [1]struct{}
_ = x[OrgStateActive-(0)]
_ = x[OrgStateInactive-(1)]
}
var _OrgStateValues = []OrgState{OrgStateActive, OrgStateInactive}
var _OrgStateNameToValueMap = map[string]OrgState{
_OrgStateName[0:6]: OrgStateActive,
_OrgStateLowerName[0:6]: OrgStateActive,
_OrgStateName[6:14]: OrgStateInactive,
_OrgStateLowerName[6:14]: OrgStateInactive,
}
var _OrgStateNames = []string{
_OrgStateName[0:6],
_OrgStateName[6:14],
}
// OrgStateString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func OrgStateString(s string) (OrgState, error) {
if val, ok := _OrgStateNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _OrgStateNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to OrgState values", s)
}
// OrgStateValues returns all values of the enum
func OrgStateValues() []OrgState {
return _OrgStateValues
}
// OrgStateStrings returns a slice of all String values of the enum
func OrgStateStrings() []string {
strs := make([]string, len(_OrgStateNames))
copy(strs, _OrgStateNames)
return strs
}
// IsAOrgState returns "true" if the value is listed in the enum definition. "false" otherwise
func (i OrgState) IsAOrgState() bool {
for _, v := range _OrgStateValues {
if i == v {
return true
}
}
return false
}
func (i OrgState) Value() (driver.Value, error) {
return i.String(), nil
}
func (i *OrgState) Scan(value interface{}) error {
if value == nil {
return nil
}
var str string
switch v := value.(type) {
case []byte:
str = string(v)
case string:
str = v
case fmt.Stringer:
str = v.String()
default:
return fmt.Errorf("invalid value of OrgState: %[1]T(%[1]v)", value)
}
val, err := OrgStateString(str)
if err != nil {
return err
}
*i = val
return nil
}
+74
View File
@@ -0,0 +1,74 @@
package domain
// import (
// "context"
// "github.com/zitadel/zitadel/backend/v3/storage/eventstore"
// )
// // SetEmailCommand sets the email address of a user.
// // If allows verification as a sub command.
// // The verification command is executed after the email address is set.
// // The verification command is executed in the same transaction as the email address update.
// type SetEmailCommand struct {
// UserID string `json:"userId"`
// Email string `json:"email"`
// verification Commander
// }
// var (
// _ Commander = (*SetEmailCommand)(nil)
// _ eventer = (*SetEmailCommand)(nil)
// _ CreateHumanOpt = (*SetEmailCommand)(nil)
// )
// type SetEmailOpt interface {
// applyOnSetEmail(*SetEmailCommand)
// }
// func NewSetEmailCommand(userID, email string, verificationType SetEmailOpt) *SetEmailCommand {
// cmd := &SetEmailCommand{
// UserID: userID,
// Email: email,
// }
// verificationType.applyOnSetEmail(cmd)
// return cmd
// }
// // String implements [Commander].
// func (cmd *SetEmailCommand) String() string {
// return "SetEmailCommand"
// }
// func (cmd *SetEmailCommand) Execute(ctx context.Context, opts *CommandOpts) error {
// close, err := opts.EnsureTx(ctx)
// if err != nil {
// return err
// }
// defer func() { err = close(ctx, err) }()
// // userStatement(opts.DB).Human().ByID(cmd.UserID).SetEmail(ctx, cmd.Email)
// repo := userRepo(opts.DB).Human()
// err = repo.Update(ctx, repo.IDCondition(cmd.UserID), repo.SetEmailAddress(cmd.Email))
// if err != nil {
// return err
// }
// return opts.Invoke(ctx, cmd.verification)
// }
// // Events implements [eventer].
// func (cmd *SetEmailCommand) Events() []*eventstore.Event {
// return []*eventstore.Event{
// {
// AggregateType: "user",
// AggregateID: cmd.UserID,
// Type: "user.email.set",
// Payload: cmd,
// },
// }
// }
// // applyOnCreateHuman implements [CreateHumanOpt].
// func (cmd *SetEmailCommand) applyOnCreateHuman(createUserCmd *CreateUserCommand) {
// createUserCmd.email = cmd
// }
+241
View File
@@ -0,0 +1,241 @@
package domain
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
// userColumns define all the columns of the user table.
type userColumns interface {
// InstanceIDColumn returns the column for the instance id field.
InstanceIDColumn() database.Column
// OrgIDColumn returns the column for the org id field.
OrgIDColumn() database.Column
// IDColumn returns the column for the id field.
IDColumn() database.Column
// UsernameColumn returns the column for the username field.
UsernameColumn() database.Column
// CreatedAtColumn returns the column for the created at field.
CreatedAtColumn() database.Column
// UpdatedAtColumn returns the column for the updated at field.
UpdatedAtColumn() database.Column
// DeletedAtColumn returns the column for the deleted at field.
DeletedAtColumn() database.Column
}
// userConditions define all the conditions for the user table.
type userConditions interface {
// InstanceIDCondition returns an equal filter on the instance id field.
InstanceIDCondition(instanceID string) database.Condition
// OrgIDCondition returns an equal filter on the org id field.
OrgIDCondition(orgID string) database.Condition
// IDCondition returns an equal filter on the id field.
IDCondition(userID string) database.Condition
// UsernameCondition returns a filter on the username field.
UsernameCondition(op database.TextOperation, username string) database.Condition
// CreatedAtCondition returns a filter on the created at field.
CreatedAtCondition(op database.NumberOperation, createdAt time.Time) database.Condition
// UpdatedAtCondition returns a filter on the updated at field.
UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition
// DeletedAtCondition filters for deleted users is isDeleted is set to true otherwise only not deleted users must be filtered.
DeletedCondition(isDeleted bool) database.Condition
// DeletedAtCondition filters for deleted users based on the given parameters.
DeletedAtCondition(op database.NumberOperation, deletedAt time.Time) database.Condition
}
// userChanges define all the changes for the user table.
type userChanges interface {
// SetUsername sets the username column.
SetUsername(username string) database.Change
}
// UserRepository is the interface for the user repository.
type UserRepository interface {
userColumns
userConditions
userChanges
// Get returns a user based on the given condition.
Get(ctx context.Context, opts ...database.QueryOption) (*User, error)
// List returns a list of users based on the given condition.
List(ctx context.Context, opts ...database.QueryOption) ([]*User, error)
// Create creates a new user.
Create(ctx context.Context, user *User) error
// Delete removes users based on the given condition.
Delete(ctx context.Context, condition database.Condition) error
// Human returns the [HumanRepository].
Human() HumanRepository
// Machine returns the [MachineRepository].
Machine() MachineRepository
}
// humanColumns define all the columns of the human table which inherits the user table.
type humanColumns interface {
userColumns
// FirstNameColumn returns the column for the first name field.
FirstNameColumn() database.Column
// LastNameColumn returns the column for the last name field.
LastNameColumn() database.Column
// EmailAddressColumn returns the column for the email address field.
EmailAddressColumn() database.Column
// EmailVerifiedAtColumn returns the column for the email verified at field.
EmailVerifiedAtColumn() database.Column
// PhoneNumberColumn returns the column for the phone number field.
PhoneNumberColumn() database.Column
// PhoneVerifiedAtColumn returns the column for the phone verified at field.
PhoneVerifiedAtColumn() database.Column
}
// humanConditions define all the conditions for the human table which inherits the user table.
type humanConditions interface {
userConditions
// FirstNameCondition returns a filter on the first name field.
FirstNameCondition(op database.TextOperation, firstName string) database.Condition
// LastNameCondition returns a filter on the last name field.
LastNameCondition(op database.TextOperation, lastName string) database.Condition
// EmailAddressCondition returns a filter on the email address field.
EmailAddressCondition(op database.TextOperation, email string) database.Condition
// EmailVerifiedCondition returns a filter that checks if the email is verified or not.
EmailVerifiedCondition(isVerified bool) database.Condition
// EmailVerifiedAtCondition returns a filter on the email verified at field.
EmailVerifiedAtCondition(op database.NumberOperation, emailVerifiedAt time.Time) database.Condition
// PhoneNumberCondition returns a filter on the phone number field.
PhoneNumberCondition(op database.TextOperation, phoneNumber string) database.Condition
// PhoneVerifiedCondition returns a filter that checks if the phone is verified or not.
PhoneVerifiedCondition(isVerified bool) database.Condition
// PhoneVerifiedAtCondition returns a filter on the phone verified at field.
PhoneVerifiedAtCondition(op database.NumberOperation, phoneVerifiedAt time.Time) database.Condition
}
// humanChanges define all the changes for the human table which inherits the user table.
type humanChanges interface {
userChanges
// SetFirstName sets the first name field of the human.
SetFirstName(firstName string) database.Change
// SetLastName sets the last name field of the human.
SetLastName(lastName string) database.Change
// SetEmail sets the email address and verified field of the email
// if verifiedAt is nil the email is not verified
SetEmail(address string, verifiedAt *time.Time) database.Change
// SetEmailAddress sets the email address field of the email
SetEmailAddress(email string) database.Change
// SetEmailVerifiedAt sets the verified column of the email
// if at is zero the statement uses the database timestamp
SetEmailVerifiedAt(at time.Time) database.Change
// SetPhone sets the phone number and verified field
// if verifiedAt is nil the phone is not verified
SetPhone(number string, verifiedAt *time.Time) database.Change
// SetPhoneNumber sets the phone number field
SetPhoneNumber(phoneNumber string) database.Change
// SetPhoneVerifiedAt sets the verified field of the phone
// if at is zero the statement uses the database timestamp
SetPhoneVerifiedAt(at time.Time) database.Change
}
// HumanRepository is the interface for the human repository it inherits the user repository.
type HumanRepository interface {
humanColumns
humanConditions
humanChanges
// Get returns an email based on the given condition.
GetEmail(ctx context.Context, condition database.Condition) (*Email, error)
// Update updates human users based on the given condition and changes.
Update(ctx context.Context, condition database.Condition, changes ...database.Change) error
}
// machineColumns define all the columns of the machine table which inherits the user table.
type machineColumns interface {
userColumns
// DescriptionColumn returns the column for the description field.
DescriptionColumn() database.Column
}
// machineConditions define all the conditions for the machine table which inherits the user table.
type machineConditions interface {
userConditions
// DescriptionCondition returns a filter on the description field.
DescriptionCondition(op database.TextOperation, description string) database.Condition
}
// machineChanges define all the changes for the machine table which inherits the user table.
type machineChanges interface {
userChanges
// SetDescription sets the description field of the machine.
SetDescription(description string) database.Change
}
// MachineRepository is the interface for the machine repository it inherits the user repository.
type MachineRepository interface {
// Update updates machine users based on the given condition and changes.
Update(ctx context.Context, condition database.Condition, changes ...database.Change) error
machineColumns
machineConditions
machineChanges
}
// UserTraits is implemented by [Human] and [Machine].
type UserTraits interface {
Type() UserType
}
type UserType string
const (
UserTypeHuman UserType = "human"
UserTypeMachine UserType = "machine"
)
type User struct {
InstanceID string
OrgID string
ID string
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
Username string
Traits UserTraits
}
type Human struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email *Email `json:"email,omitempty"`
Phone *Phone `json:"phone,omitempty"`
}
// Type implements [UserTraits].
func (h *Human) Type() UserType {
return UserTypeHuman
}
var _ UserTraits = (*Human)(nil)
type Email struct {
Address string `json:"address"`
VerifiedAt time.Time `json:"verifiedAt"`
}
type Phone struct {
Number string `json:"number"`
VerifiedAt time.Time `json:"verifiedAt"`
}
type Machine struct {
Description string `json:"description"`
}
// Type implements [UserTraits].
func (m *Machine) Type() UserType {
return UserTypeMachine
}
var _ UserTraits = (*Machine)(nil)