github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/operations_manager/service.go (about)

     1  package operationsmanager
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/kyma-incubator/compass/components/director/pkg/persistence"
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  const (
    11  	completedOpStatus = "COMPLETED"
    12  	failedOpStatus    = "FAILED"
    13  	scheduledOpStatus = "SCHEDULED"
    14  )
    15  
    16  // Service consists of various resource services responsible for service-layer Operations.
    17  type Service struct {
    18  	transact persistence.Transactioner
    19  
    20  	opSvc        OperationService
    21  	ordOpCreator OperationCreator
    22  }
    23  
    24  // NewOperationService returns a new object responsible for service-layer Operation operations.
    25  func NewOperationService(transact persistence.Transactioner, opSvc OperationService, ordOpCreator OperationCreator) *Service {
    26  	return &Service{
    27  		transact:     transact,
    28  		opSvc:        opSvc,
    29  		ordOpCreator: ordOpCreator,
    30  	}
    31  }
    32  
    33  // CreateORDOperations creates ord operations
    34  func (s *Service) CreateORDOperations(ctx context.Context) error {
    35  	return s.ordOpCreator.Create(ctx)
    36  }
    37  
    38  // DeleteOldOperations deletes all operations of type `opType` which are:
    39  // - in status COMPLETED and older than `completedOpDays`
    40  // - in status FAILED and older than `failedOpDays`
    41  func (s *Service) DeleteOldOperations(ctx context.Context, opType string, completedOpDays, failedOpDays int) error {
    42  	tx, err := s.transact.Begin()
    43  	if err != nil {
    44  		return err
    45  	}
    46  	defer s.transact.RollbackUnlessCommitted(ctx, tx)
    47  	ctx = persistence.SaveToContext(ctx, tx)
    48  
    49  	if err := s.opSvc.DeleteOlderThan(ctx, opType, completedOpStatus, completedOpDays); err != nil {
    50  		return errors.Wrap(err, "while deleting completed operations")
    51  	}
    52  
    53  	if err := s.opSvc.DeleteOlderThan(ctx, opType, failedOpStatus, failedOpDays); err != nil {
    54  		return errors.Wrap(err, "while deleting failed operations")
    55  	}
    56  
    57  	return tx.Commit()
    58  }