Exemplo n.º 1
0
        public override void Build()
        {
            var hasher            = new ProjectionHasher();
            var builder           = this as ISettingsBuilder;
            var processorSettings = this as ISubscrptionMiddlewareSettings;
            Func <SubscriptionMiddleware> messageHandlerProcessorFactory = () =>
            {
                var handlerFactory = new DefaultHandlerFactory(processorSettings.HandlerFactory);

                var    clusterServiceMiddleware = new SystemMiddleware(handlerFactory);
                var    middleware             = processorSettings.HandleMiddleware(clusterServiceMiddleware);
                var    subscriptionMiddleware = new SubscriptionMiddleware();
                var    clusterSettings        = builder.Container.Resolve <IClusterSettings>();
                string nodeId = $"{clusterSettings.CurrentNodeName}@{clusterSettings.ClusterName}";
                foreach (var reg in (this as ISubscrptionMiddlewareSettings).HandlerRegistrations)
                {
                    string subscriberId = reg.FullName + "." + nodeId;
                    if (typeof(ISystemProjection).IsAssignableFrom(reg) && reg.IsClass)
                    {
                        subscriptionMiddleware.Subscribe(new SystemProjectionSubscriber(reg, middleware, subscriberId));

                        var transport     = builder.Container.Resolve <ITransport>(builder.Name);
                        var serializer    = builder.Container.Resolve <ISerializer>(null);
                        var publisher     = transport.GetPublisher <ICommand>(serializer);
                        var projManagerId = new ProjectionVersionManagerId(reg.GetContractId());
                        var command       = new RegisterProjection(projManagerId, hasher.CalculateHash(reg).ToString());
                        publisher.Publish(command);
                    }
                }
                return(subscriptionMiddleware);
            };

            builder.Container.RegisterSingleton <SubscriptionMiddleware>(() => messageHandlerProcessorFactory(), builder.Name);
        }
Exemplo n.º 2
0
        private async Task <bool> IsVersionTrackerMissingAsync()
        {
            var versionId = new ProjectionVersionManagerId(ProjectionVersionsHandler.ContractId, context.Tenant);
            var result    = await projectionReader.GetAsync <ProjectionVersionsHandler>(versionId).ConfigureAwait(false);

            return(result.HasError || result.NotFound);
        }
Exemplo n.º 3
0
        bool IsVersionTrackerMissing()
        {
            var versionId = new ProjectionVersionManagerId(ProjectionVersionsHandler.ContractId, context.Tenant);
            var result    = projectionReader.Get <ProjectionVersionsHandler>(versionId);

            return(result.HasError || result.NotFound);
        }
Exemplo n.º 4
0
        private async Task <ProjectionVersion> GetLiveVersion(Type projectionType)
        {
            var           projectionVersionManagerId = new ProjectionVersionManagerId(projectionType.GetContractId(), context.Tenant);
            ProjectionDto dto = await ExploreAsync(projectionVersionManagerId, typeof(ProjectionVersionsHandler)).ConfigureAwait(false);

            var state = dto?.State as ProjectionVersionsHandlerState;

            ProjectionVersion liveVersion = state is null ? null : state.AllVersions.GetLive();

            return(liveVersion);
        }
Exemplo n.º 5
0
        IProjectionGetResult <PersistentProjectionVersionHandler> GetProjectionVersionsFromStore(string contractId)
        {
            var versionId                   = new ProjectionVersionManagerId(contractId);
            var persistentVersionType       = typeof(PersistentProjectionVersionHandler);
            var persistentVersionContractId = persistentVersionType.GetContractId();
            var persistentVersion           = new ProjectionVersion(persistentVersionContractId, ProjectionStatus.Live, 1, persistentVersionType.GetProjectionHash());
            ProjectionStream stream         = LoadProjectionStream(persistentVersionType, persistentVersion, versionId, new NoSnapshot(versionId, contractId));
            var queryResult                 = stream.RestoreFromHistory <PersistentProjectionVersionHandler>();

            return(queryResult);
        }
Exemplo n.º 6
0
 public void Bootstrap()
 {
     foreach (var handler in handlerTypeContainer.Items)
     {
         foreach (var tenant in tenants.GetTenants())
         {
             var id      = new ProjectionVersionManagerId(handler.GetContractId(), tenant);
             var command = new RegisterProjection(id, hasher.CalculateHash(handler));
             publisher.Publish(command);
         }
     }
 }
Exemplo n.º 7
0
        private async Task <ProjectionVersions> GetAllVersionsAsync(ProjectionVersion version)
        {
            var versionId = new ProjectionVersionManagerId(version.ProjectionName, context.Tenant);
            var result    = await projectionReader.GetAsync <ProjectionVersionsHandler>(versionId).ConfigureAwait(false);

            if (result.IsSuccess)
            {
                return(result.Data.State.AllVersions);
            }

            return(new ProjectionVersions());
        }
Exemplo n.º 8
0
        ProjectionVersions GetAllVersions(ProjectionVersion version)
        {
            var versionId = new ProjectionVersionManagerId(version.ProjectionName, context.Tenant);
            var result    = projectionReader.Get <ProjectionVersionsHandler>(versionId);

            if (result.IsSuccess)
            {
                return(result.Data.State.AllVersions);
            }

            return(new ProjectionVersions());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Meta([FromQuery] RequestModel model)
        {
            IEnumerable <Assembly> loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.IsDynamic == false);
            Type metadata = loadedAssemblies
                            .SelectMany(assembly => assembly.GetLoadableTypes()
                                        .Where(x => typeof(IProjection).IsAssignableFrom(x))
                                        .Where(x => x.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0))
                            .Where(x => x.GetContractId() == model.ProjectionContractId)
                            .FirstOrDefault();

            if (metadata is null)
            {
                return(new BadRequestObjectResult(new ResponseResult <string>($"Projection with contract '{model.ProjectionContractId}' not found")));
            }

            var           id  = new ProjectionVersionManagerId(model.ProjectionContractId, context.Tenant);
            ProjectionDto dto = await _projectionExplorer.ExploreAsync(id, typeof(ProjectionVersionsHandler));

            var state = dto?.State as ProjectionVersionsHandlerState;

            var metaProjection = new ProjectionMeta()
            {
                ProjectionContractId = metadata.GetContractId(),
                ProjectionName       = metadata.Name,
                IsReplayable         = typeof(IAmEventSourcedProjection).IsAssignableFrom(metadata)
            };

            if (state is null)
            {
                metaProjection.Versions.Add(new ProjectionVersionDto()
                {
                    Status   = ProjectionStatus.NotPresent,
                    Hash     = projectionHasher.CalculateHash(typeof(ProjectionVersionsHandler)),
                    Revision = 0
                });
            }
            else
            {
                foreach (var ver in state.AllVersions)
                {
                    metaProjection.Versions.Add(new ProjectionVersionDto()
                    {
                        Hash     = ver.Hash,
                        Revision = ver.Revision,
                        Status   = ver.Status
                    });
                }
            }

            return(Ok(new ResponseResult <ProjectionMeta>(metaProjection)));
        }
Exemplo n.º 10
0
        public void Bootstrap()
        {
            var systemProjection = typeof(ISystemProjection);

            foreach (var handler in handlerTypeContainer.Items.OrderByDescending(x => systemProjection.IsAssignableFrom(x)))
            {
                foreach (var tenant in tenants.GetTenants())
                {
                    var id      = new ProjectionVersionManagerId(handler.GetContractId(), tenant);
                    var command = new RegisterProjection(id, hasher.CalculateHash(handler));
                    publisher.Publish(command);
                }
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> List()
        {
            var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.IsDynamic == false);

            var projectionMetaData = loadedAssemblies
                                     .SelectMany(ass => ass.GetLoadableTypes()
                                                 .Where(x => typeof(IProjection).IsAssignableFrom(x) && x.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0));

            ProjectionListDto result = new ProjectionListDto();

            foreach (var meta in projectionMetaData)
            {
                var id  = new ProjectionVersionManagerId(meta.GetContractId(), context.Tenant);
                var dto = await _projectionExplorer.ExploreAsync(id, typeof(ProjectionVersionsHandler));

                ProjectionVersionsHandlerState state = dto?.State as ProjectionVersionsHandlerState;
                var metaProjection = new ProjectionMeta()
                {
                    ProjectionContractId = meta.GetContractId(),
                    ProjectionName       = meta.Name,
                    IsReplayable         = typeof(IAmEventSourcedProjection).IsAssignableFrom(meta)
                };
                if (ReferenceEquals(null, state))
                {
                    metaProjection.Versions.Add(new ProjectionVersionDto()
                    {
                        Status   = ProjectionStatus.NotPresent,
                        Hash     = projectionHasher.CalculateHash(meta),
                        Revision = 0
                    });
                }
                else
                {
                    foreach (var ver in state.AllVersions)
                    {
                        metaProjection.Versions.Add(new ProjectionVersionDto()
                        {
                            Hash     = ver.Hash,
                            Revision = ver.Revision,
                            Status   = ver.Status
                        });
                    }
                }
                result.Projections.Add(metaProjection);
            }

            return(new OkObjectResult(new ResponseResult <ProjectionListDto>(result)));
        }
Exemplo n.º 12
0
        ProjectionVersions GetProjectionVersions(string contractId)
        {
            ProjectionVersions versions = inMemoryVersionStore.Get(contractId);

            if (versions == null || versions.Count == 0)
            {
                var versionId                   = new ProjectionVersionManagerId(contractId);
                var persistentVersionType       = typeof(PersistentProjectionVersionHandler);
                var persistentVersionContractId = persistentVersionType.GetContractId();
                var persistentVersion           = new ProjectionVersion(persistentVersionContractId, ProjectionStatus.Live, 1, persistentVersionType.GetProjectionHash());
                ProjectionStream stream         = LoadProjectionStream(typeof(PersistentProjectionVersionHandler), persistentVersion, versionId, new NoSnapshot(versionId, contractId));
                var queryResult                 = stream.RestoreFromHistory <PersistentProjectionVersionHandler>();
                if (queryResult.Success)
                {
                    if (queryResult.Projection.State.Live != null)
                    {
                        inMemoryVersionStore.Cache(queryResult.Projection.State.Live);
                    }
                    if (queryResult.Projection.State.Building != null)
                    {
                        inMemoryVersionStore.Cache(queryResult.Projection.State.Building);
                    }
                    versions = inMemoryVersionStore.Get(contractId);
                }

                // inception
                if (versions == null || versions.Count == 0)
                {
                    if (string.Equals(persistentVersionContractId, contractId, StringComparison.OrdinalIgnoreCase))
                    {
                        inMemoryVersionStore.Cache(persistentVersion);
                        versions = inMemoryVersionStore.Get(contractId);
                    }
                    else
                    {
                        var initialVersion = new ProjectionVersion(contractId, ProjectionStatus.Building, 1, contractId.GetTypeByContract().GetProjectionHash());
                        inMemoryVersionStore.Cache(initialVersion);
                        versions = inMemoryVersionStore.Get(contractId);
                    }
                }
            }

            return(versions ?? new ProjectionVersions());
        }
Exemplo n.º 13
0
        ReadResult <ProjectionVersionsHandler> GetProjectionVersionsFromStore(string projectionName)
        {
            try
            {
                var persistentVersionType             = typeof(ProjectionVersionsHandler);
                var projectionVersions_ProjectionName = persistentVersionType.GetContractId();

                var versionId           = new ProjectionVersionManagerId(projectionName, context.Tenant);
                var persistentVersion   = new ProjectionVersion(projectionVersions_ProjectionName, ProjectionStatus.Live, 1, projectionHasher.CalculateHash(persistentVersionType));
                ProjectionStream stream = LoadProjectionStream(persistentVersionType, persistentVersion, versionId, new NoSnapshot(versionId, projectionVersions_ProjectionName).GetMeta());
                var queryResult         = stream.RestoreFromHistory <ProjectionVersionsHandler>();

                return(new ReadResult <ProjectionVersionsHandler>(queryResult));
            }
            catch (Exception ex)
            {
                return(ReadResult <ProjectionVersionsHandler> .WithNotFoundHint(ex.Message));
            }
        }
Exemplo n.º 14
0
        private async Task <ReadResult <ProjectionVersionsHandler> > GetProjectionVersionsFromStoreAsync(string projectionName)
        {
            try
            {
                var persistentVersionType             = typeof(ProjectionVersionsHandler);
                var projectionVersions_ProjectionName = persistentVersionType.GetContractId();

                var versionId           = new ProjectionVersionManagerId(projectionName, context.Tenant);
                var persistentVersion   = new ProjectionVersion(projectionVersions_ProjectionName, ProjectionStatus.Live, 1, projectionHasher.CalculateHash(persistentVersionType));
                ProjectionStream stream = await LoadProjectionStreamAsync(persistentVersionType, persistentVersion, versionId, new NoSnapshot(versionId, projectionVersions_ProjectionName).GetMeta()).ConfigureAwait(false);

                var queryResult = await stream.RestoreFromHistoryAsync <ProjectionVersionsHandler>().ConfigureAwait(false);

                return(new ReadResult <ProjectionVersionsHandler>(queryResult));
            }
            catch (Exception ex)
            {
                log.WarnException(ex, () => $"Failed to load projection versions. ProjectionName: {projectionName}");
                return(ReadResult <ProjectionVersionsHandler> .WithError(ex.Message));
            }
        }
Exemplo n.º 15
0
        public override void Build()
        {
            var hasher            = new ProjectionHasher();
            var builder           = this as ISettingsBuilder;
            var processorSettings = this as ISubscrptionMiddlewareSettings;
            Func <SubscriptionMiddleware> messageHandlerProcessorFactory = () =>
            {
                var handlerFactory = new DefaultHandlerFactory(processorSettings.HandlerFactory);

                //  May be we want to have separate serializer + transport per type?!?!?
                var transport  = builder.Container.Resolve <ITransport>(builder.Name);
                var serializer = builder.Container.Resolve <ISerializer>(null);
                var publisher  = transport.GetPublisher <ICommand>(serializer);

                var projectionsMiddleware  = new ProjectionsMiddleware(handlerFactory);
                var middleware             = processorSettings.HandleMiddleware(projectionsMiddleware);
                var subscriptionMiddleware = new SubscriptionMiddleware();
                var iProjection            = typeof(IProjection);

                foreach (var handler in processorSettings.HandlerRegistrations)
                {
                    if (iProjection.IsAssignableFrom(handler))
                    {
                        subscriptionMiddleware.Subscribe(new HandlerSubscriber <IProjection, IEventHandler <IEvent> >(handler, middleware));
                        var projManagerId = new ProjectionVersionManagerId(handler.GetContractId());
                        var command       = new RegisterProjection(projManagerId, hasher.CalculateHash(handler).ToString());
                        publisher.Publish(command);
                    }
                }
                var indexSubscriber = builder.Container.Resolve <EventTypeIndexForProjections>();
                subscriptionMiddleware.Subscribe(indexSubscriber);
                return(subscriptionMiddleware);
            };

            builder.Container.RegisterSingleton <SubscriptionMiddleware>(() => messageHandlerProcessorFactory(), builder.Name);
        }