zitadel/internal/command/limits_model.go
Elio Bischof 385a55bd21
feat: limit audit trail (#6744)
* feat: enable limiting audit trail

* support AddExclusiveQuery

* fix invalid condition

* register event mappers

* fix NullDuration validity

* test query side for limits

* lint

* acceptance test audit trail limit

* fix acceptance test

* translate limits not found

* update tests

* fix linting

* add audit log retention to default instance

* fix tests

* update docs

* remove todo

* improve test name
2023-10-25 11:42:00 +00:00

74 lines
2.0 KiB
Go

package command
import (
"time"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/repository/limits"
)
type limitsWriteModel struct {
eventstore.WriteModel
rollingAggregateID string
auditLogRetention *time.Duration
}
// newLimitsWriteModel aggregateId is filled by reducing unit matching events
func newLimitsWriteModel(instanceId, resourceOwner string) *limitsWriteModel {
return &limitsWriteModel{
WriteModel: eventstore.WriteModel{
InstanceID: instanceId,
ResourceOwner: resourceOwner,
},
}
}
func (wm *limitsWriteModel) Query() *eventstore.SearchQueryBuilder {
query := eventstore.NewSearchQueryBuilder(eventstore.ColumnsEvent).
ResourceOwner(wm.ResourceOwner).
InstanceID(wm.InstanceID).
AddQuery().
AggregateTypes(limits.AggregateType).
EventTypes(
limits.SetEventType,
limits.ResetEventType,
)
return query.Builder()
}
func (wm *limitsWriteModel) Reduce() error {
for _, event := range wm.Events {
wm.ChangeDate = event.CreatedAt()
switch e := event.(type) {
case *limits.SetEvent:
wm.rollingAggregateID = e.Aggregate().ID
if e.AuditLogRetention != nil {
wm.auditLogRetention = e.AuditLogRetention
}
case *limits.ResetEvent:
wm.rollingAggregateID = ""
wm.auditLogRetention = nil
}
}
if err := wm.WriteModel.Reduce(); err != nil {
return err
}
// wm.WriteModel.Reduce() sets the aggregateID to the first event's aggregateID, but we need the last one
wm.AggregateID = wm.rollingAggregateID
return nil
}
// NewChanges returns all changes that need to be applied to the aggregate.
// nil properties in setLimits are ignored
func (wm *limitsWriteModel) NewChanges(setLimits *SetLimits) (changes []limits.LimitsChange) {
if setLimits == nil {
return nil
}
changes = make([]limits.LimitsChange, 0, 1)
if setLimits.AuditLogRetention != nil && (wm.auditLogRetention == nil || *wm.auditLogRetention != *setLimits.AuditLogRetention) {
changes = append(changes, limits.ChangeAuditLogRetention(setLimits.AuditLogRetention))
}
return changes
}