Skip to content
Snippets Groups Projects
Select Git revision
  • 014260e181db5c6920b627fb90e5d72b007700f0
  • master default protected
  • feature/PRXS-3383-CollectionsSort
  • feature/2781-SpacesLoggingMiddleware
  • feature/PRXS-3421-ImplementNewRefAPI
  • feature/PRXS-3143-3235-ReferenceOptions
  • feature/PRXS-3143-LimitReferenceFields
  • feature/PRXS-3234-FeaturePruneIdents
  • PRXS-3421-RecursiveReferences
  • feature/3109-SerializeFeature
  • release/0.33
  • feature/3109-RecoverySchema
  • feature/3109-feature
  • fix/PRXS-3369-ValidateFields
  • refactor/PRXS-3306-MovePkgGroup1
  • refactor/6-pkg-refactor-expr
  • fix/PRXS-3360-TemplateBuilderPatch
  • feature/3293-MongoV2
  • feature/3272-GoVersionUp
  • feature/PRXS-3218-HideTemplateActions
  • feature/PRXS-3234-PruneIdents
  • v0.33.1
  • v0.32.0
  • v0.31.1
  • v0.31.0
  • v0.30.0
  • v0.29.0
  • v0.28.0
  • v0.27.0-alpha.1+16
  • v0.27.0-alpha.1+15
  • v0.27.0-alpha.1+14
  • v0.27.0-alpha.1+13
  • v0.27.0-alpha.1+12
  • v0.27.0-alpha.1+11
  • v0.27.0-alpha.1+10
  • v0.27.0-alpha.1+9
  • v0.27.0-alpha.1+8
  • v0.27.0-alpha.1+7
  • v0.27.0-alpha.1+6
  • v0.27.0-alpha.1+5
  • v0.27.0-alpha.1+4
41 results

collection.go

Blame
  • collection.go 8.81 KiB
    package setup
    
    import (
    	"context"
    	"strings"
    
    	"git.perx.ru/perxis/perxis-go/pkg/data"
    
    	"git.perx.ru/perxis/perxis-go/pkg/collections"
    	"git.perx.ru/perxis/perxis-go/pkg/errors"
    	"go.uber.org/zap"
    )
    
    var (
    	ErrCheckCollections     = errors.New("collections check error")
    	ErrInstallCollections   = errors.New("failed to install collections")
    	ErrUninstallCollections = errors.New("failed to uninstall collections")
    )
    
    //
    // Collection Configuration
    //
    
    type (
    	Collection       = Entity[CollectionConf, *collections.Collection]
    	Collections      = EntityList[CollectionConf, *collections.Collection]
    	CollectionOption = EntityOption[CollectionConf, *collections.Collection]
    	CollectionFilter = FilterFunc[*collections.Collection]
    
    	CollectionConf struct {
    		SkipMigration bool
    	}
    )
    
    var (
    	OverwriteCollection          = Overwrite[CollectionConf, *collections.Collection]
    	KeepCollection               = Keep[CollectionConf, *collections.Collection]
    	DeleteCollection             = Delete[CollectionConf, *collections.Collection]
    	DeleteCollectionIfRemoveFlag = DeleteIfRemoveFlag[CollectionConf, *collections.Collection]
    )
    
    // Init инициализирует конфигурацию коллекции
    func (CollectionConf) Init(e *Entity[CollectionConf, *collections.Collection]) {
    	// Сформированная вручную схема может иметь разные типы данных для одних и тех же полей
    	// (`[]interface{}/[]string`, `int/int64`, etc.), что может привести к ошибкам
    	// при сравнении схем. Поэтому приводим все типы данных к одному типу.
    	if e.value.Schema != nil {
    		if err := e.value.Schema.ConvertTypes(); err != nil {
    			panic(err)
    		}
    	}
    
    	// Устанавливаем стратегии обновления и удаления коллекции по умолчанию
    	UpdateExistingCollection()(e)
    	DeleteCollectionIfRemoveFlag()(e)
    }
    
    func IsSchemaUpdateRequired(old, new *collections.Collection) bool {
    	return !new.IsView() && (old == nil || !old.Schema.Equal(new.Schema))
    }
    
    // AddMetadata добавляет метаданные к коллекции
    func AddMetadata(key, value string) CollectionOption {
    	return func(e *Collection) {
    		e.ValueFunc = append(e.ValueFunc, func(s *Setup, c *collections.Collection) {
    			if c.Schema != nil {
    				c.Schema.WithMetadata(key, value)
    			}
    		})
    	}
    }
    
    // SkipMigration пропускает миграцию коллекции
    func SkipMigration() CollectionOption {
    	return func(e *Collection) {
    		e.Conf.SkipMigration = true
    	}
    }
    
    // UpdateExistingCollection обновляет существующую коллекцию
    func UpdateExistingCollection() CollectionOption {
    	return func(e *Collection) {
    		e.UpdateFunc = func(s *Setup, old, new *collections.Collection) (*collections.Collection, bool) {
    			// Копируем теги из старой коллекции в новую
    			if len(old.Tags) > 0 {
    				new.Tags = data.SetFromSlice(append(old.Tags, new.Tags...))
    			}
    
    			var update bool
    			update = new.Name != old.Name || new.IsSingle() != old.IsSingle() || new.IsSystem() != old.IsSystem() ||
    				new.IsNoData() != old.IsNoData() || new.Hidden != old.Hidden || new.IsView() != old.IsView() && data.ElementsMatch(old.Tags, new.Tags)
    
    			if old.View != nil && new.View != nil {
    				update = update || *old.View != *new.View
    			}
    
    			return new, update || IsSchemaUpdateRequired(old, new)
    		}
    	}
    }
    
    //
    // Collection Setup
    //
    
    // AddCollection добавляет требование к настройке коллекции в пространстве (runtime)
    func (s *Setup) AddCollection(collection *collections.Collection, opt ...CollectionOption) *Setup {
    	s.Config.Collections.Add(collection, opt...)
    	return s
    }
    
    // AddCollections добавляет несколько требований к настройке коллекций в пространстве (runtime)
    func (s *Setup) AddCollections(collections []*collections.Collection, opt ...CollectionOption) *Setup {
    	for _, c := range collections {
    		s.AddCollection(c, opt...)
    	}
    	return s
    }
    
    func (s *Setup) InstallCollection(ctx context.Context, c *Collection) (updateSchema bool, err error) {
    	collection := c.Value(s)
    	collection.SpaceID, collection.EnvID = s.SpaceID, s.EnvironmentID
    
    	var exist *collections.Collection
    	// isForce - не удалять коллекцию, если она уже существует
    	exist, err = s.content.Collections.Get(ctx, collection.SpaceID, collection.EnvID, collection.ID)
    	if err != nil && !strings.Contains(err.Error(), collections.ErrNotFound.Error()) {
    		return false, err
    	}
    
    	if exist == nil {
    		if _, err = s.content.Collections.Create(ctx, collection); err != nil {
    			return false, err
    		}
    	} else {
    		var updateCollection bool
    		collection, updateCollection = c.UpdateFunc(s, exist, collection)
    		if !updateCollection {
    			return false, nil
    		}
    
    		// TODO: Проверить, что коллекция изменилась
    		// TODO: Тест на сравнение схем
    		// Замена возможного алиаса окружения на реального ID окружения перед сравнением
    		collection.EnvID = exist.EnvID
    		if !exist.Equal(collection) {
    			if err = s.content.Collections.Update(ctx, collection); err != nil {
    				return false, err
    			}
    		}
    	}
    
    	// Проверяем, нужно ли обновить схему коллекции
    	if IsSchemaUpdateRequired(exist, collection) {
    		return true, s.content.Collections.SetSchema(ctx, collection.SpaceID, collection.EnvID, collection.ID, collection.Schema)
    	}
    
    	return false, nil
    }
    
    func (s *Setup) InstallCollections(ctx context.Context) (err error) {
    	if len(s.Collections) == 0 {
    		return nil
    	}
    
    	s.logger.Debug("Install collections", zap.Int("Collections", len(s.Collections)))
    
    	var migrate, setSchema bool
    
    	for _, c := range s.Collections {
    		setSchema, err = s.InstallCollection(ctx, c)
    		if err != nil {
    			collection := c.Value(s)
    			s.logger.Error("Failed to install collection",
    				zap.String("Collection ID", collection.ID),
    				zap.String("Collection Name", collection.Name),
    				zap.Error(err),
    			)
    			return errors.WithDetailf(errors.Wrap(err, "failed to install collection"), "Возникла ошибка при настройке коллекции %s(%s)", collection.Name, collection.ID)
    		}
    
    		if !c.Conf.SkipMigration && setSchema {
    			migrate = true
    		}
    	}
    
    	if migrate {
    		if err = s.content.Environments.Migrate(ctx, s.SpaceID, s.EnvironmentID); err != nil {
    			s.logger.Error(
    				"Failed to migrate environment",
    				zap.String("Space ID", s.SpaceID),
    				zap.String("Environment ID", s.EnvironmentID),
    				zap.Error(err),
    			)
    
    			return errors.WithDetail(errors.Wrap(err, "migrate"), "Возникла ошибка при миграции данных")
    		}
    	}
    
    	return nil
    }
    
    func (s *Setup) CheckCollections(ctx context.Context) error {
    	if len(s.Collections) == 0 {
    		return nil
    	}
    
    	s.logger.Debug("Check collections", zap.Int("Collections", len(s.Collections)))
    
    	var errs []error
    	for _, c := range s.Collections {
    		collection := c.Value(s)
    		if err := s.CheckCollection(ctx, collection); err != nil {
    			errs = append(errs, errors.WithDetailf(err, "Не найдена коллекция %s(%s)", collection.ID, collection.Name))
    		}
    	}
    
    	if len(errs) > 0 {
    		return errors.WithErrors(ErrCheckCollections, errs...)
    	}
    
    	return nil
    }
    
    func (s *Setup) CheckCollection(ctx context.Context, c *collections.Collection) (err error) {
    	_, err = s.content.Collections.Get(ctx, s.SpaceID, s.EnvironmentID, c.ID)
    	return err
    }
    
    func (s *Setup) UninstallCollections(ctx context.Context) error {
    	if len(s.Collections) == 0 {
    		return nil
    	}
    
    	s.logger.Debug("Uninstall collections", zap.Int("Collections", len(s.Collections)))
    
    	for _, c := range s.Collections {
    		if err := s.UninstallCollection(ctx, c); err != nil {
    			collection := c.Value(s)
    			s.logger.Error("Failed to uninstall collection",
    				zap.String("Collection ID", collection.ID),
    				zap.String("Collection Name", collection.Name),
    				zap.Error(err),
    			)
    			return errors.WithDetailf(errors.Wrap(err, "failed to uninstall collection"),
    				"Возникла ошибка при удалении коллекции %s(%s)", collection.Name, collection.ID)
    		}
    	}
    
    	return nil
    }
    
    func (s *Setup) UninstallCollection(ctx context.Context, c *Collection) error {
    	collection := c.Value(s)
    	deleteCollection := c.DeleteFunc(s, collection)
    	if deleteCollection {
    		if err := s.content.Collections.Delete(ctx, s.SpaceID, s.EnvironmentID, collection.ID); err != nil && !strings.Contains(err.Error(), collections.ErrNotFound.Error()) {
    			return err
    		}
    
    		// TODO: Проверить, в чем смысл происходящего
    		//s.removeItems(c.collection.ID) // после удаления коллекции нет смысла удалять ее элементы
    	}
    	return nil
    }