Ejemplo n.º 1
0
        static Global()
        {
            CommitId = ConfigurationManager.AppSettings.Get("appharbor.commit_id");

            var settings = LoadSettings();

            var integrationPath = settings["DataPath"];
            var contracts       = Contracts.CreateStreamer();
            var strategy        = new DocumentStrategy();

            if (integrationPath.StartsWith("file:"))
            {
                var path   = integrationPath.Remove(0, 5);
                var config = FileStorage.CreateConfig(path);

                Docs   = config.CreateNuclear(strategy).Container;
                Client = new WebEndpoint(new NuclearStorage(Docs), contracts, config.CreateQueueWriter(Topology.RouterQueue));
            }
            else if (integrationPath.StartsWith("azure:"))
            {
                var path   = integrationPath.Remove(0, 6);
                var config = AzureStorage.CreateConfig(path);
                Docs   = config.CreateNuclear(strategy).Container;
                Client = new WebEndpoint(new NuclearStorage(Docs), contracts, config.CreateQueueWriter(Topology.RouterQueue));
            }
            else
            {
                throw new InvalidOperationException("Unsupported environment");
            }



            Forms = new FormsAuth(Docs.GetReader <UserId, LoginView>());
            Auth  = new WebAuth(Client);
        }
Ejemplo n.º 2
0
        static void AttachToLocalLog(string filePath)
        {
            SimpleMessageSender sender;
            var cache = new FileTapeStream(filePath);
            var store = new LocalEventStore(null, cache);

            var directoryName = Path.GetDirectoryName(filePath) ?? "";
            var dir           = new DirectoryInfo(directoryName);
            FileStorageConfig config;

            if (dir.Name == Topology.TapesContainer)
            {
                // we are in proper tapes container
                config = FileStorage.CreateConfig(dir.Parent);
            }
            else
            {
                var temp = Path.Combine(dir.FullName, string.Format("temp-{0:yyyy-MM-dd-HHmm}", DateTime.Now));
                config = FileStorage.CreateConfig(temp);
            }

            var send     = config.CreateQueueWriter(Topology.RouterQueue);
            var endpoint = new SimpleMessageSender(EnvelopeStreamer, send);

            Application.Run(new DomainLogView(store, endpoint, EnvelopeStreamer));
        }
Ejemplo n.º 3
0
        public void Test()
        {
            var streamer = EnvelopeStreamer.CreateDefault(typeof(SecondPassed));
            var builder  = new CqrsEngineBuilder(streamer);
            var store    = FileStorage.CreateConfig(GetType().Name, reset: true);


            builder.Handle(store.CreateInbox("inbox"), BuildRouter(store, streamer));
            builder.Handle(store.CreateInbox("process"), ie => Console.WriteLine("Message from past!"));

            var inboxWriter     = store.CreateQueueWriter("inbox");
            var futureContainer = store.CreateStreaming().GetContainer("future");
            var timer           = new StreamingTimerService(inboxWriter, futureContainer, streamer);

            builder.AddProcess(timer);
            builder.Handle(store.CreateInbox("timer"), timer.PutMessage);

            using (var engine = builder.Build())
            {
                var bytes = streamer.SaveEnvelopeData(new SecondPassed(), c => c.DelayBy(TimeSpan.FromSeconds(4)));
                inboxWriter.PutMessage(bytes);
                Console.WriteLine("Sent message to future...");
                engine.RunForever();
            }
        }
Ejemplo n.º 4
0
        public void create_AppendOnlyStore()
        {
            var path            = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config          = FileStorage.CreateConfig(new DirectoryInfo(path));
            var appendOnlyStore = config.CreateAppendOnlyStore("append_only");

            Assert.IsNotNull(appendOnlyStore);
        }
Ejemplo n.º 5
0
        public void create_inbox()
        {
            var path   = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config = FileStorage.CreateConfig(new DirectoryInfo(path));
            var inbox  = config.CreateInbox("inbox name", x => new TimeSpan(x));

            Assert.IsNotNull(inbox);
        }
Ejemplo n.º 6
0
        public void create_config_with_directory_info()
        {
            var path   = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config = FileStorage.CreateConfig(new DirectoryInfo(path));

            Assert.AreEqual(path, config.FullPath);
            Assert.IsFalse(Directory.Exists(path));
            Assert.AreEqual(new DirectoryInfo(path).Name, config.AccountName);
        }
Ejemplo n.º 7
0
        public void create_config_and_not_reset()
        {
            var path   = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config = FileStorage.CreateConfig(path, "testaccount", false);

            Assert.AreEqual(path, config.FullPath);
            Assert.IsFalse(Directory.Exists(path));
            Assert.AreEqual("testaccount", config.AccountName);
        }
Ejemplo n.º 8
0
        public void create_streaming()
        {
            var path      = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config    = FileStorage.CreateConfig(path);
            var container = config.CreateStreaming();

            Assert.IsTrue(Directory.Exists(path));
            CollectionAssert.IsEmpty(container.ListContainers());
        }
Ejemplo n.º 9
0
        public void when_create_child_streaming()
        {
            var path      = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config    = FileStorage.CreateConfig(path);
            var container = config.CreateStreaming("child");

            Assert.IsTrue(Directory.Exists(path));
            Assert.IsTrue(Directory.Exists(Path.Combine(path, "child")));
            Assert.IsTrue(container.Exists());
        }
Ejemplo n.º 10
0
        public void create_MessageSender()
        {
            var path       = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config     = FileStorage.CreateConfig(new DirectoryInfo(path));
            var serializer = new TestMessageSerializer(new[] { typeof(SerializerTest1), typeof(SerializerTest2), });
            var streamer   = new EnvelopeStreamer(serializer);
            var sender     = config.CreateMessageSender(streamer, "QueueName");

            Assert.IsNotNull(sender);
        }
Ejemplo n.º 11
0
        public void create_QueueWriter()
        {
            var path        = Path.Combine(Path.GetTempPath(), "lokad-cqrs-test", Guid.NewGuid().ToString());
            var config      = FileStorage.CreateConfig(new DirectoryInfo(path));
            var queueWriter = config.CreateQueueWriter("QueueName");

            Assert.IsNotNull(queueWriter);
            Assert.AreEqual("QueueName", queueWriter.Name);
            Assert.IsTrue(Directory.Exists(path));
        }
Ejemplo n.º 12
0
        static FileStorageConfig GetDataFolder()
        {
            var current = Directory.GetCurrentDirectory();
            var cache   = Path.Combine(current, "data");

            if (!Directory.Exists(cache))
            {
                Directory.CreateDirectory(cache);
            }

            return(FileStorage.CreateConfig(cache, "files"));
        }
Ejemplo n.º 13
0
        static void AttachToLocalLog(string filePath)
        {
            var config = FileStorage.CreateConfig(Path.GetDirectoryName(filePath) ?? "");

            var cache = new FileTapeStream(filePath);

            var store    = new LocalEventStore(null, cache);
            var send     = config.CreateQueueWriter(Topology.RouterQueue);
            var endpoint = new SimpleMessageSender(EnvelopeStreamer, send);

            Application.Run(new DomainLogView(store, endpoint, EnvelopeStreamer));
        }
Ejemplo n.º 14
0
        public void Test()
        {
            var nuclearStorage = FileStorage.CreateConfig(GetType().Name).CreateNuclear(new TestStrategy());

            var writer = nuclearStorage.Container.GetWriter <unit, Dunno>();

            writer.UpdateEnforcingNew(unit.it, dunno => dunno.Count += 1);
            writer.UpdateEnforcingNew(unit.it, dunno => dunno.Count += 1);

            var count = nuclearStorage.Container.GetReader <unit, Dunno>().GetOrNew().Count;

            Console.WriteLine(count);
        }
Ejemplo n.º 15
0
        DirectoryInfo[] ObserveViews(ViewMapInfo[] handlers, DomainQueryManager queryManager)
        {
            WriteLine("Configuring {0} view handlers", handlers.Length);

            var name     = string.Format("view-{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now);
            var combined = Path.Combine(Path.GetTempPath(), name);

            WriteLine("Redirecting atomic views to {0}", combined);
            var directoryInfo = new DirectoryInfo(combined);

            var file    = FileStorage.CreateConfig(combined, reset: true);
            var nuclear = file.CreateNuclear(new ProjectionStrategy());

            var watch           = Stopwatch.StartNew();
            var projectionTypes = new HashSet <Type>(handlers.Select(v => v.Projection));

            WriteLine("Building consumers...");

            var projections =
                BootstrapProjections.BuildProjectionsWithWhenConvention(nuclear.Factory).Where(
                    x => projectionTypes.Contains(x.GetType()));

            var wire = new RedirectToDynamicEvent();

            foreach (var projection in projections)
            {
                wire.WireToWhen(projection);
            }
            var handlersWatch = Stopwatch.StartNew();


            queryManager.QueryConsumer(envelope => CallHandlers(wire, envelope));
            WriteLine("Saved to {0}.", directoryInfo.FullName);


            var timeTotal      = watch.Elapsed.TotalSeconds;
            var handlerTicks   = handlersWatch.ElapsedTicks;
            var timeInHandlers = Math.Round(TimeSpan.FromTicks(handlerTicks).TotalSeconds, 1);

            WriteLine("Total Elapsed: {0}sec ({1}sec in handlers)", Math.Round(timeTotal, 0), timeInHandlers);

            WriteLine("Saved to {0}.", directoryInfo.FullName);

            var directoryInfos = handlers
                                 .Select(h => _strategy.GetFolderForEntity(h.ViewType, h.KeyType))
                                 .Distinct()
                                 .Select(f => new DirectoryInfo(Path.Combine(directoryInfo.FullName, f.ToString())))
                                 .ToArray();

            return(directoryInfos);
        }
Ejemplo n.º 16
0
        public static Container BuildEnvironment()
        {
            //JsConfig.DateHandler = JsonDateHandler.ISO8601;
            ConfigureObserver();
            var integrationPath = AzureSettingsProvider.GetStringOrThrow(Conventions.StorageConfigName);
            //var email = AzureSettingsProvider.GetStringOrThrow(Conventions.SmtpConfigName);


            //var core = new SmtpHandlerCore(email);
            var setup = new Setup
            {
                //Smtp = core,
                //FreeApiKey = freeApiKey,
                //WebClientUrl = clientUri,
                //HttpEndpoint = endPoint,
                //EncryptorTool = new EncryptorTool(systemKey)
            };

            if (integrationPath.StartsWith("file:"))
            {
                var path = integrationPath.Remove(0, 5);

                SystemObserver.Notify("Using store : {0}", path);

                var config = FileStorage.CreateConfig(path);
                setup.Streaming              = config.CreateStreaming();
                setup.DocumentStoreFactory   = config.CreateDocumentStore;
                setup.QueueReaderFactory     = s => config.CreateInbox(s, DecayEvil.BuildExponentialDecay(500));
                setup.QueueWriterFactory     = config.CreateQueueWriter;
                setup.AppendOnlyStoreFactory = config.CreateAppendOnlyStore;

                setup.ConfigureQueues(1, 1);

                return(setup.Build());
            }
            if (integrationPath.StartsWith("Default") || integrationPath.Equals("UseDevelopmentStorage=true", StringComparison.InvariantCultureIgnoreCase))
            {
                var config = AzureStorage.CreateConfig(integrationPath);
                setup.Streaming              = config.CreateStreaming();
                setup.DocumentStoreFactory   = config.CreateDocumentStore;
                setup.QueueReaderFactory     = s => config.CreateQueueReader(s);
                setup.QueueWriterFactory     = config.CreateQueueWriter;
                setup.AppendOnlyStoreFactory = config.CreateAppendOnlyStore;
                setup.ConfigureQueues(4, 4);
                return(setup.Build());
            }
            throw new InvalidOperationException("Unsupported environment");
        }
        protected override void CurrentConfig(CqrsEngineBuilder config)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var bus = Path.Combine(currentDirectory, "test");
            var dir = new DirectoryInfo(bus);

            if (dir.Exists)
            {
                dir.Delete(true);
            }
            var store = FileStorage.CreateConfig(bus, "file");

            config.File(m =>
            {
                m.AddFileProcess(store, "do", x => x.DispatchAsCommandBatch());
                m.AddFileSender(store, "do", cb => cb.IdGeneratorForTests());
            });
        }
Ejemplo n.º 18
0
        public void Start()
        {
            var config = FileStorage.CreateConfig(IntegrationPath, "files");

            var setup = new SetupClassThatReplacesIoCContainerFramework
            {
                CreateNuclear     = strategy => config.CreateNuclear(strategy),
                Streaming         = config.CreateStreaming(),
                Tapes             = config.CreateTape(Topology.TapesContainer),
                CreateInbox       = s => config.CreateInbox(s),
                CreateQueueWriter = s => config.CreateQueueWriter(s),
            };

            var components = setup.AssembleComponents();

            cts    = new CancellationTokenSource();
            engine = components.Builder.Build();
            task   = engine.Start(cts.Token);

            Bus.SetBus(new SimpleBus(components.Sender, components.Dispatcher));
            ProviderFactory.SetFactory(components.ProjectionFactory);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            ConfigureObserver();

            var settings = LoadSettings();

            foreach (var setting in settings)
            {
                SystemObserver.Notify("[{0}] = {1}", setting.Key, setting.Value);
            }

            var setup = new SetupClassThatReplacesIoCContainerFramework();

            var integrationPath = settings["DataPath"];

            if (integrationPath.StartsWith("file:"))
            {
                var path   = integrationPath.Remove(0, 5);
                var config = FileStorage.CreateConfig(path);
                setup.Streaming         = config.CreateStreaming();
                setup.Tapes             = config.CreateTape;
                setup.Docs              = config.CreateNuclear(setup.Strategy).Container;
                setup.CreateInbox       = s => config.CreateInbox(s);
                setup.CreateQueueWriter = config.CreateQueueWriter;
            }
            else if (integrationPath.StartsWith("azure:"))
            {
                var path   = integrationPath.Remove(0, 6);
                var config = AzureStorage.CreateConfig(path);
                setup.Streaming         = config.CreateStreaming();
                setup.Tapes             = config.CreateTape;
                setup.Docs              = config.CreateNuclear(setup.Strategy).Container;
                setup.CreateInbox       = s => config.CreateInbox(s);
                setup.CreateQueueWriter = config.CreateQueueWriter;
            }
            else
            {
                throw new InvalidOperationException("Unsupperted environment");
            }
            var components = setup.AssembleComponents();


            var stream = setup.Tapes(Topology.TapesContainer).GetOrCreateStream(Topology.DomainLogName);

            StartupProjectionRebuilder.Rebuild(components.Setup.Docs, stream);
            using (var cts = new CancellationTokenSource())
                using (var engine = components.Builder.Build())
                {
                    var task = engine.Start(cts.Token);

                    var version         = ConfigurationManager.AppSettings.Get("appharbor.commit_id");
                    var instanceStarted = new InstanceStarted(version, "engine", Process.GetCurrentProcess().ProcessName);
                    components.Simple.SendOne(instanceStarted);

                    //startupMessages.ForEach(c => components.Sender.SendCommandsAsBatch(new ISampleCommand[] { c }));

                    Console.WriteLine(@"Press enter to stop");
                    Console.ReadLine();
                    cts.Cancel();
                    if (!task.Wait(5000))
                    {
                        Console.WriteLine(@"Terminating");
                    }
                }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            const string integrationPath = @"temp";

            ConfigureObserver();

            var config = FileStorage.CreateConfig(integrationPath, "files");

            var demoMessages   = new List <ISampleMessage>();
            var currentProcess = Process.GetCurrentProcess();

            demoMessages.Add(new InstanceStarted("Inject git rev", currentProcess.ProcessName,
                                                 currentProcess.Id.ToString()));


            {
                // wipe all folders
                config.Reset();
                Console.WriteLine("Starting in funny mode");
                var security = new SecurityId(0);
                demoMessages.Add(new CreateSecurityAggregate(security));
                demoMessages.Add(new AddSecurityPassword(security, "Rinat Abdullin", "*****@*****.**", "password"));
                demoMessages.Add(new AddSecurityIdentity(security, "Rinat's Open ID", "http://abdullin.myopenid.org"));
                demoMessages.Add(new AddSecurityKey(security, "some key"));
            }



            var atomic   = config.CreateNuclear(new DocumentStrategy());
            var identity = new IdentityGenerator(atomic);
            var streamer = Contracts.CreateStreamer();

            var tapes       = config.CreateTape(Topology.TapesContainer);
            var streaming   = config.CreateStreaming();
            var routerQueue = config.CreateQueueWriter(Topology.RouterQueue);
            var aggregates  = new AggregateFactory(tapes, streamer, routerQueue, atomic, identity);

            var sender = new SimpleMessageSender(streamer, routerQueue);
            var flow   = new MessageSender(sender);

            var builder = new CqrsEngineBuilder(streamer);


            builder.Handle(config.CreateInbox(Topology.RouterQueue),
                           Topology.Route(config.CreateQueueWriter, streamer, tapes), "router");
            builder.Handle(config.CreateInbox(Topology.EntityQueue), aggregates.Dispatch);

            var functions = new RedirectToDynamicEvent();
            // documents
            //functions.WireToWhen(new RegistrationUniquenessProjection(atomic.Factory.GetEntityWriter<unit, RegistrationUniquenessDocument>()));

            // UI projections
            var projectionStore = config.CreateNuclear(new ProjectionStrategy());

            foreach (var projection in BootstrapProjections.BuildProjectionsWithWhenConvention(projectionStore.Factory))
            {
                functions.WireToWhen(projection);
            }

            // processes
            //functions.WireToWhen(new BillingProcess(flow));
            //functions.WireToWhen(new RegistrationProcess(flow));
            functions.WireToWhen(new ReplicationProcess(flow));

            builder.Handle(config.CreateInbox(Topology.EventsQueue), aem => CallHandlers(functions, aem));


            var timer = new StreamingTimerService(config.CreateQueueWriter(Topology.RouterQueue),
                                                  streaming.GetContainer(Topology.FutureMessagesContainer), streamer);

            builder.Handle(config.CreateInbox(Topology.TimerQueue), timer.PutMessage);
            builder.AddProcess(timer);


            using (var cts = new CancellationTokenSource())
                using (var engine = builder.Build())
                {
                    var task = engine.Start(cts.Token);

                    foreach (var sampleMessage in demoMessages)
                    {
                        sender.SendOne(sampleMessage);
                    }

                    Console.WriteLine(@"Press enter to stop");
                    Console.ReadLine();
                    cts.Cancel();



                    if (task.Wait(5000))
                    {
                        Console.WriteLine(@"Terminating");
                    }
                }
        }
 public Given_Basic_Scenarios_When_Files()
 {
     _config = FileStorage.CreateConfig(typeof(Given_Basic_Scenarios_When_Files).Name);
 }
 public Given_Tx_Scenarios_When_Files()
 {
     _config = FileStorage.CreateConfig(GetType().Name);
 }