-
Notifications
You must be signed in to change notification settings - Fork 10
/
EventEngine.php
1511 lines (1228 loc) · 54.6 KB
/
EventEngine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file is part of event-engine/php-engine.
* (c) 2018-2021 prooph software GmbH <contact@prooph.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace EventEngine;
use EventEngine\Aggregate\AggregateEventEnvelope;
use EventEngine\Aggregate\Exception\AggregateNotFound;
use EventEngine\Aggregate\FlavouredAggregateRoot;
use EventEngine\Aggregate\GenericAggregateRepository;
use EventEngine\Commanding\CommandDispatch;
use EventEngine\Commanding\CommandPreProcessor;
use EventEngine\Commanding\CommandProcessorDescription;
use EventEngine\Commanding\ControllerDispatch;
use EventEngine\Data\ImmutableRecord;
use EventEngine\DocumentStore\DocumentStore;
use EventEngine\DocumentStore\FieldIndex;
use EventEngine\DocumentStore\MultiFieldIndex;
use EventEngine\EventStore\EventStore;
use EventEngine\Exception\BadMethodCallException;
use EventEngine\Exception\InvalidArgumentException;
use EventEngine\Exception\MissingAggregateCollection;
use EventEngine\Exception\NoDocumentStore;
use EventEngine\Exception\RuntimeException;
use EventEngine\JsonSchema\JsonSchemaAwareRecord;
use EventEngine\Logger\LogEngine;
use EventEngine\Messaging\CommandDispatchResult;
use EventEngine\Messaging\CommandDispatchResultCollection;
use EventEngine\Messaging\GenericEvent;
use EventEngine\Messaging\GenericSchemaMessageFactory;
use EventEngine\Messaging\Message;
use EventEngine\Messaging\MessageBag;
use EventEngine\Messaging\MessageDispatcher;
use EventEngine\Messaging\MessageFactory;
use EventEngine\Messaging\MessageFactoryAware;
use EventEngine\Messaging\MessageProducer;
use EventEngine\Persistence\AggregateStateStore;
use EventEngine\Persistence\DeletableState;
use EventEngine\Persistence\MultiModelStore;
use EventEngine\Persistence\Stream;
use EventEngine\Projecting\AggregateProjector;
use EventEngine\Projecting\CustomEventProjector;
use EventEngine\Projecting\DocumentStoreIndexAware;
use EventEngine\Projecting\Exception\ProjectorFailed;
use EventEngine\Projecting\FlavourAware;
use EventEngine\Projecting\OptionsAware;
use EventEngine\Projecting\ProjectionDescription;
use EventEngine\Projecting\ProjectionInfoList;
use EventEngine\Projecting\Projector;
use EventEngine\Projecting\Projection;
use EventEngine\Querying\QueryDescription;
use EventEngine\Runtime\Flavour;
use EventEngine\Schema\InputTypeSchema;
use EventEngine\Schema\MessageBox\CommandMap;
use EventEngine\Schema\MessageBox\EventMap;
use EventEngine\Schema\MessageBox\QueryMap;
use EventEngine\Schema\MessageSchema;
use EventEngine\Schema\PayloadSchema;
use EventEngine\Schema\ResponseTypeSchema;
use EventEngine\Schema\Schema;
use EventEngine\Schema\TypeSchema;
use EventEngine\Schema\TypeSchemaMap;
use EventEngine\Util\MapIterator;
use EventEngine\Util\MessageTuple;
use EventEngine\Util\VariableType;
use Psr\Container\ContainerInterface;
final class EventEngine implements MessageDispatcher, MessageProducer, AggregateStateStore
{
public const ENV_PROD = 'prod';
public const ENV_DEV = 'dev';
public const ENV_TEST = 'test';
/**
* Map of command message schemas indexed by message name
*
* @var MessageSchema[]
*/
private $commandMap = [];
/**
* Map of command names and corresponding list of preprocessors given as container service id
*
* @var string[]
*/
private $commandPreProcessors = [];
/**
* Map of command names and corresponding list of controllers given as container service ids or callable
*
* @var string[]|callable[]
*/
private $commandControllers = [];
/**
* @var array
*/
private $commandRouting = [];
/**
* @var array
*/
private $compiledCommandRouting;
/**
* @var array
*/
private $aggregateDescriptions;
/**
* Map of event message schemas indexed by event message name
*
* @var MessageSchema[]
*/
private $eventMap = [];
/**
* Map of event names and corresponding list of listeners given as container service id
*
* @var string[]
*/
private $eventRouting = [];
/**
* Map of projection names and corresponding projection descriptions
*
* @var ProjectionDescription[] indexed by projection name
*/
private $projectionMap = [];
/**
* @var QueryDescription[string] list of QueryDescription indexed by query name
*/
private $queryDescriptions = [];
/**
* @var array list of compiled query descriptions indexed by query name
*/
private $compiledQueryDescriptions = [];
/**
* Map of query message schemas indexed by message name
*
* @var MessageSchema[]
*/
private $queryMap = [];
/**
* Map of response type schemas indexed by type name
*
* @var ResponseTypeSchema[]
*/
private $responseTypes = [];
/**
* Map of input type schemas indexed by type name
*
* @var InputTypeSchema[]
*/
private $inputTypes = [];
private $typeSchemaMap;
/**
* @var array
*/
private $compiledProjectionDescriptions = [];
private $initialized = false;
private $bootstrapped = false;
private $debugMode = false;
private $env = self::ENV_PROD;
private $testMode = false;
/**
* @var ContainerInterface
*/
private $container;
/**
* @var LogEngine
*/
private $log;
/**
* @var Flavour
*/
private $flavour;
/**
* @var MessageFactory
*/
private $messageFactory;
/**
* @var Schema
*/
private $schema;
private $writeModelStreamName = 'event_stream';
/**
* @var EventStore
*/
private $eventStore;
/**
* @var DocumentStore|null
*/
private $documentStore;
/**
* @var MessageProducer|null
*/
private $eventQueue;
/**
* @var mixed[]
*/
private $aggregateCache = [];
/**
* Use EventEngine::disableAutoPublish() to take control of event publishing yourself
*
* @var bool
*/
private $autoPublishEnabled = true;
/**
* Use EventEngine::disableAutoPojecting() to take control of projection runs
*
* @var bool
*/
private $autoProjectingEnabled = true;
/**
* Use EventEngine::enableMetadataForwarding() to pass on metadata from message to message
*
* If enabled:
* Command metadata is merged into each event metadata that gets recorded
* Event metadata is merged into each command returned from a process manager/event listener
*
* @var bool
*/
private $forwardMetadata = false;
public function __construct(Schema $schema)
{
$this->schema = $schema;
$this->typeSchemaMap = new TypeSchemaMap();
}
public static function fromCachedConfig(
array $config,
Schema $schema,
Flavour $flavour,
EventStore $eventStore,
LogEngine $logEngine,
ContainerInterface $container,
DocumentStore $documentStore = null,
MessageProducer $eventQueue = null
): self {
$self = new self($schema);
if (! \array_key_exists('commandMap', $config)) {
throw new InvalidArgumentException('Missing key commandMap in cached event engine config');
}
if (! \array_key_exists('eventMap', $config)) {
throw new InvalidArgumentException('Missing key eventMap in cached event engine config');
}
if (! \array_key_exists('compiledCommandRouting', $config)) {
throw new InvalidArgumentException('Missing key compiledCommandRouting in cached event engine config');
}
if (! \array_key_exists('aggregateDescriptions', $config)) {
throw new InvalidArgumentException('Missing key aggregateDescriptions in cached event engine config');
}
if (! \array_key_exists('writeModelStreamName', $config)) {
throw new InvalidArgumentException('Missing key writeModelStreamName in cached event engine config');
}
if (! \array_key_exists('autoPublish', $config)) {
throw new InvalidArgumentException('Missing key autoPublish in cached event engine config');
}
if (! \array_key_exists('autoProjecting', $config)) {
throw new InvalidArgumentException('Missing key autoProjecting in cached event engine config');
}
$mapPayloadSchema = function (array $payloadSchema) use ($schema): PayloadSchema {
return $schema->buildPayloadSchemaFromArray($payloadSchema);
};
$self->commandMap = array_map($mapPayloadSchema, $config['commandMap']);
$self->eventMap = array_map($mapPayloadSchema, $config['eventMap']);
$self->compiledCommandRouting = $config['compiledCommandRouting'];
$self->commandPreProcessors = $config['commandPreProcessors'] ?? [];
$self->commandControllers = $config['commandControllers'] ?? [];
$self->aggregateDescriptions = $config['aggregateDescriptions'];
$self->eventRouting = $config['eventRouting'] ?? [];
$self->compiledProjectionDescriptions = $config['compiledProjectionDescriptions'] ?? [];
$self->compiledQueryDescriptions = $config['compiledQueryDescriptions'];
$self->queryMap = array_map($mapPayloadSchema, $config['queryMap'] ?? []);
foreach ($config['responseTypes'] ?? [] as $typeName => $typeSchema) {
$self->responseTypes[$typeName] = $schema->buildResponseTypeSchemaFromArray($typeName, $typeSchema);
}
foreach ($config['inputTypes'] ?? [] as $typeName => $typeSchema) {
$self->inputTypes[$typeName] = $schema->buildInputTypeSchemaFromArray($typeName, $typeSchema);
}
$self->writeModelStreamName = $config['writeModelStreamName'];
$self->flavour = $flavour;
$self->eventStore = $eventStore;
$self->log = $logEngine;
$self->container = $container;
$self->documentStore = $documentStore;
$self->eventQueue = $eventQueue;
$self->autoPublishEnabled = $config['autoPublish'];
$self->autoProjectingEnabled = $config['autoProjecting'];
$self->forwardMetadata = $config['forwardMetadata'] ?? false;
foreach ($self->responseTypes as $typeName => $responseType) {
$self->typeSchemaMap->add($typeName, $responseType);
}
foreach ($self->inputTypes as $typeName => $inputType) {
$self->typeSchemaMap->add($typeName, $inputType);
}
$self->initialized = true;
$self->log->initializedFromCachedConfig($config);
return $self;
}
public function compileCacheableConfig(): array
{
$assertClosure = function ($val) {
if ($val instanceof \Closure) {
throw new RuntimeException('At least one EventEngineDescription contains a Closure and is therefor not cacheable!');
}
};
if ($this->initialized === false) {
$this->compile();
}
\array_walk_recursive($this->compiledCommandRouting, $assertClosure);
\array_walk_recursive($this->aggregateDescriptions, $assertClosure);
\array_walk_recursive($this->eventRouting, $assertClosure);
\array_walk_recursive($this->projectionMap, $assertClosure);
\array_walk_recursive($this->compiledQueryDescriptions, $assertClosure);
\array_walk_recursive($this->commandControllers, $assertClosure);
$schemaToArray = function (TypeSchema $typeSchema): array {
return $typeSchema->toArray();
};
return [
'commandMap' => array_map($schemaToArray, $this->commandMap),
'eventMap' => array_map($schemaToArray, $this->eventMap),
'compiledCommandRouting' => $this->compiledCommandRouting,
'commandPreProcessors' => $this->commandPreProcessors,
'commandControllers' => $this->commandControllers,
'aggregateDescriptions' => $this->aggregateDescriptions,
'eventRouting' => $this->eventRouting,
'compiledProjectionDescriptions' => $this->compiledProjectionDescriptions,
'compiledQueryDescriptions' => $this->compiledQueryDescriptions,
'queryMap' => array_map($schemaToArray, $this->queryMap),
'responseTypes' => array_map($schemaToArray, $this->responseTypes),
'inputTypes' => array_map($schemaToArray, $this->inputTypes),
'writeModelStreamName' => $this->writeModelStreamName,
'autoPublish' => $this->autoPublishEnabled,
'autoProjecting' => $this->autoProjectingEnabled,
'forwardMetadata' => $this->forwardMetadata,
];
}
public function load(string $description): void
{
$this->assertNotInitialized(__METHOD__);
\call_user_func([$description, 'describe'], $this);
}
public function setWriteModelStreamName(string $streamName): self
{
$this->assertNotInitialized(__METHOD__);
$this->writeModelStreamName = $streamName;
return $this;
}
public function disableAutoPublish(): self
{
$this->assertNotInitialized(__METHOD__);
$this->autoPublishEnabled = false;
return $this;
}
public function disableAutoProjecting(): self
{
$this->assertNotInitialized(__METHOD__);
$this->autoProjectingEnabled = false;
return $this;
}
public function enableMetadataForwarding(): self
{
$this->assertNotInitialized(__METHOD__);
$this->forwardMetadata = true;
return $this;
}
public function registerCommand(string $commandName, PayloadSchema $schema): self
{
$this->assertNotInitialized(__METHOD__);
if ($this->isKnownQuery($commandName)) {
throw new RuntimeException("Query with name $commandName was already registered.");
}
if ($this->isKnownEvent($commandName)) {
throw new RuntimeException("Event with name $commandName was already registered.");
}
if ($this->isKnownCommand($commandName)) {
throw new RuntimeException("Command $commandName was already registered.");
}
$this->commandMap[$commandName] = $schema;
return $this;
}
public function registerEvent(string $eventName, PayloadSchema $schema): self
{
$this->assertNotInitialized(__METHOD__);
if ($this->isKnownCommand($eventName)) {
throw new RuntimeException("Command with name $eventName was already registered.");
}
if ($this->isKnownQuery($eventName)) {
throw new RuntimeException("Query with name $eventName was already registered.");
}
if ($this->isKnownEvent($eventName)) {
throw new RuntimeException("Event $eventName was already registered.");
}
$this->schema->assertPayloadSchema($eventName, $schema);
$this->eventMap[$eventName] = $schema;
return $this;
}
public function registerQuery(string $queryName, PayloadSchema $payloadSchema = null): QueryDescription
{
$this->assertNotInitialized(__METHOD__);
if ($payloadSchema) {
$this->schema()->assertPayloadSchema($queryName, $payloadSchema);
} else {
$payloadSchema = $this->schema()->emptyPayloadSchema();
}
if ($this->isKnownCommand($queryName)) {
throw new RuntimeException("Command with name $queryName was already registered.");
}
if ($this->isKnownEvent($queryName)) {
throw new RuntimeException("Event with name $queryName was already registered.");
}
if ($this->isKnownQuery($queryName)) {
throw new RuntimeException("Query $queryName was already registered");
}
$this->queryMap[$queryName] = $payloadSchema;
$queryDesc = new QueryDescription($queryName, $this);
$this->queryDescriptions[$queryName] = $queryDesc;
return $queryDesc;
}
public function registerProjection(string $projectionName, ProjectionDescription $projectionDescription): void
{
$this->assertNotInitialized(__METHOD__);
if ($this->isKnownProjection($projectionName)) {
throw new RuntimeException("Projection with name $projectionName is already registered.");
}
$this->projectionMap[$projectionName] = $projectionDescription;
}
public function registerType(string $nameOrImmutableRecordClass, ResponseTypeSchema $schema = null): void
{
$this->registerResponseType($nameOrImmutableRecordClass, $schema);
}
public function registerResponseType(string $nameOrImmutableRecordClass, ResponseTypeSchema $schema = null): void
{
$this->assertNotInitialized(__METHOD__);
if (null === $schema) {
$refObj = new \ReflectionClass($nameOrImmutableRecordClass);
if (! $refObj->implementsInterface(JsonSchemaAwareRecord::class)) {
throw new InvalidArgumentException("Invalid type given. $nameOrImmutableRecordClass does not implement " . JsonSchemaAwareRecord::class);
}
$name = \call_user_func([$nameOrImmutableRecordClass, '__type']);
$schema = \call_user_func([$nameOrImmutableRecordClass, '__schema']);
} else {
$name = $nameOrImmutableRecordClass;
}
if ($this->isKnownType($name)) {
throw new RuntimeException("Type $name is already registered");
}
$this->schema()->assertResponseTypeSchema($name, $schema);
$this->responseTypes[$name] = $schema;
$this->typeSchemaMap->add($name, $schema);
}
public function registerInputType(string $nameOrImmutableRecordClass, InputTypeSchema $schema = null): void
{
$this->assertNotInitialized(__METHOD__);
if (null === $schema) {
$refObj = new \ReflectionClass($nameOrImmutableRecordClass);
if (! $refObj->implementsInterface(JsonSchemaAwareRecord::class)) {
throw new InvalidArgumentException("Invalid type given. $nameOrImmutableRecordClass does not implement " . JsonSchemaAwareRecord::class);
}
$name = \call_user_func([$nameOrImmutableRecordClass, '__type']);
$schema = \call_user_func([$nameOrImmutableRecordClass, '__schema']);
} else {
$name = $nameOrImmutableRecordClass;
}
if ($this->isKnownType($name)) {
throw new RuntimeException("Type $name is already registered");
}
$this->schema()->assertInputTypeSchema($name, $schema);
$this->inputTypes[$name] = $schema;
$this->typeSchemaMap->add($name, $schema);
}
public function preProcess(string $commandName, $preProcessor): self
{
$this->assertNotInitialized(__METHOD__);
if (! $this->isKnownCommand($commandName)) {
throw new InvalidArgumentException("Preprocessor attached to unknown command $commandName. You should register the command first");
}
if (! \is_string($preProcessor) && ! $preProcessor instanceof CommandPreProcessor) {
throw new InvalidArgumentException('PreProcessor should either be a service id given as string or an instance of '.CommandPreProcessor::class.'. Got '
. VariableType::determine($preProcessor));
}
$this->commandPreProcessors[$commandName][] = $preProcessor;
return $this;
}
public function passToController(string $commandName, $controller): self
{
$this->assertNotInitialized(__METHOD__);
$this->assertNotInitialized(__METHOD__);
if (! $this->isKnownCommand($commandName)) {
throw new InvalidArgumentException("Controller attached to unknown command $commandName. You should register the command first");
}
if (! \is_string($controller) && ! \is_callable($controller)) {
throw new InvalidArgumentException('Controller should either be a service id given as string or callable. Got '
. VariableType::determine($controller));
}
if (\array_key_exists($commandName, $this->commandRouting)) {
throw new \BadMethodCallException('Method process was already called for the same command: ' . $commandName);
}
if (\array_key_exists($commandName, $this->commandControllers)) {
throw new \BadMethodCallException('Method passToController was already called for the same command: ' . $commandName);
}
$this->commandControllers[$commandName] = $controller;
return $this;
}
public function process(string $commandName): CommandProcessorDescription
{
$this->assertNotInitialized(__METHOD__);
if (\array_key_exists($commandName, $this->commandRouting)) {
throw new \BadMethodCallException('Method process was called twice for the same command: ' . $commandName);
}
if (\array_key_exists($commandName, $this->commandControllers)) {
throw new \BadMethodCallException('Method passToController was already called for the same command: ' . $commandName);
}
if (! \array_key_exists($commandName, $this->commandMap)) {
throw new \BadMethodCallException("Command $commandName is unknown. You should register it first.");
}
$this->commandRouting[$commandName] = new CommandProcessorDescription($commandName, $this);
return $this->commandRouting[$commandName];
}
public function on(string $eventName, $listener): self
{
$this->assertNotInitialized(__METHOD__);
if (! $this->isKnownEvent($eventName)) {
throw new InvalidArgumentException("Listener attached to unknown event $eventName. You should register the event first");
}
if (! \is_string($listener) && ! \is_callable($listener)) {
throw new InvalidArgumentException('Listener should be either a service id given as string or a callable. Got '
. (\is_object($listener) ? \get_class($listener) : \gettype($listener)));
}
$this->eventRouting[$eventName][] = $listener;
return $this;
}
public function watch(Stream ...$streams): ProjectionDescription
{
foreach ($streams as $i => $stream) {
if ($stream->streamName() === Stream::WRITE_MODEL_STREAM) {
$streams[$i] = $stream->withStreamName($this->writeModelStreamName);
}
}
//ProjectionDescriptions register itself using EventMachine::registerProjection within ProjectionDescription::with call
return new ProjectionDescription($this, ...$streams);
}
public function isKnownCommand(string $commandName): bool
{
return \array_key_exists($commandName, $this->commandMap);
}
public function isKnownEvent(string $eventName): bool
{
return \array_key_exists($eventName, $this->eventMap);
}
public function isKnownQuery(string $queryName): bool
{
return \array_key_exists($queryName, $this->queryMap);
}
public function isKnownProjection(string $projectionName): bool
{
return \array_key_exists($projectionName, $this->projectionMap);
}
public function isKnownType(string $typeName): bool
{
return $this->typeSchemaMap->contains($typeName);
}
public function isTestMode(): bool
{
return $this->testMode;
}
public function schema(): Schema
{
return $this->schema;
}
public function writeModelStreamName(): string
{
return $this->writeModelStreamName;
}
public function messageFactory(): MessageFactory
{
$this->assertBootstrapped(__METHOD__);
return $this->messageFactory;
}
public function flavour(): Flavour
{
return $this->flavour;
}
public function messageBoxSchema(): array
{
$this->assertInitialized(__METHOD__);
$queryDescriptions = [];
foreach ($this->compiledQueryDescriptions as $name => $desc) {
$desc['returnType'] = $this->schema->buildResponseTypeSchemaFromArray($name, $desc['returnType']);
$queryDescriptions[$name] = $desc;
}
return $this->schema->buildMessageBoxSchema(
CommandMap::fromEventEngineMap($this->commandMap),
EventMap::fromEventEngineMap($this->eventMap),
QueryMap::fromEventEngineMapAndQueryDescriptions($this->queryMap, $queryDescriptions),
$this->typeSchemaMap
);
}
public function initialize(
Flavour $flavour,
EventStore $eventStore,
LogEngine $logEngine,
ContainerInterface $container,
DocumentStore $documentStore = null,
MessageProducer $eventQueue = null
): self {
$this->assertNotInitialized(__METHOD__);
$this->compile();
$this->flavour = $flavour;
$this->eventStore = $eventStore;
$this->log = $logEngine;
$this->container = $container;
$this->documentStore = $documentStore;
$this->eventQueue = $eventQueue;
$this->initialized = true;
$this->log->initializedAfterLoadingDescriptions($this->commandMap, $this->eventMap, $this->queryMap);
return $this;
}
public function bootstrap(string $env = self::ENV_PROD, $debugMode = false): self
{
$envModes = [self::ENV_PROD, self::ENV_DEV, self::ENV_TEST];
if (! \in_array($env, $envModes)) {
throw new InvalidArgumentException("Invalid env. Got $env but expected is one of " . \implode(', ', $envModes));
}
$this->assertInitialized(__METHOD__);
$this->assertNotBootstrapped(__METHOD__);
$this->messageFactory = new GenericSchemaMessageFactory(
$this->schema,
$this->commandMap,
$this->eventMap,
$this->queryMap,
$this->typeSchemaMap,
$this->flavour
);
if($this->flavour instanceof MessageFactoryAware) {
$this->flavour->setMessageFactory($this->messageFactory);
}
$this->bootstrapped = true;
$this->debugMode = $debugMode;
$this->env = $env;
$this->log->bootstrapped($this->env, $this->debugMode);
return $this;
}
/**
* {@inheritdoc}
* @throws \Throwable
*/
public function dispatch($messageOrName, array $payload = [], array $metadata = [])
{
$this->assertBootstrapped(__METHOD__);
if (\is_string($messageOrName)) {
$messageOrName = $this->messageFactory()->createMessageFromArray($messageOrName, ['payload' => $payload, 'metadata' => $metadata]);
} else {
$messageOrName = $this->flavour->convertMessageReceivedFromNetwork($messageOrName);
if(!empty($metadata)) {
$msgMetadata = $messageOrName->metadata();
$messageOrName = $messageOrName->withMetadata(array_merge($msgMetadata, $metadata));
}
}
if (! $messageOrName instanceof Message) {
throw new InvalidArgumentException(
'Invalid message received. Must be either a known message name or an instance of EventEngine\Messaging\Message. Got '
. VariableType::determine($messageOrName)
);
}
$this->log->dispatchStarted($messageOrName);
switch ($messageOrName->messageType()) {
case Message::TYPE_COMMAND:
$command = $messageOrName;
foreach ($this->commandPreProcessors[$messageOrName->messageName()] ?? [] as $preProcessor) {
if (\is_string($preProcessor)) {
$preProcessor = $this->container->get($preProcessor);
}
$command = $this->flavour->callCommandPreProcessor($preProcessor, $command);
if($command instanceof CommandDispatchResult) {
$this->log->preProcessorReturnedDispatchResult($preProcessor, $messageOrName, $command);
return $command;
} else {
$this->log->preProcessorCalled($preProcessor, $messageOrName, $command);
}
}
//Preprocessor has rerouted command
if($command->messageName() !== $messageOrName->messageName()) {
$forwardedMetadata = $this->forwardMetadata ? $messageOrName->metadata() : [];
return $this->dispatch($command, [], $forwardedMetadata);
}
if($controller = $this->commandControllers[$command->messageName()] ?? null) {
if(is_string($controller)) {
$controller = $this->container->get($controller);
}
return ControllerDispatch::exec(
$command,
$this->flavour,
$this->log,
$this,
$controller,
$this->forwardMetadata
);
}
$this->clearAggregateCache();
$processorDesc = $this->compiledCommandRouting[$command->messageName()] ?? [];
$contextProviders = $processorDesc['contextProviders'] ?? [];
foreach ($contextProviders as $cIndex => $cServiceId) {
$contextProviders[$cIndex] = $this->container->get($cServiceId);
}
$services = $processorDesc['services'] ?? [];
foreach ($services as $sIndex => $serviceId) {
$services[$sIndex] = $this->container->get($serviceId);
}
return CommandDispatch::exec(
$command,
$this->flavour,
$this->eventStore,
$this->log,
$processorDesc,
$this->aggregateDescriptions,
$this->autoPublishEnabled,
$this->autoProjectingEnabled,
$this->eventQueue ?? $this,
$this,
$this->documentStore,
$contextProviders,
$services,
$this->forwardMetadata
);
break;
case Message::TYPE_EVENT:
$listeners = $this->eventRouting[$messageOrName->messageName()] ?? [];
$dispatchResults = new CommandDispatchResultCollection();
foreach ($listeners as $listener) {
if(\is_string($listener)) {
$listener = $this->container->get($listener);
}
$result = $this->flavour->callEventListener($listener, $messageOrName);
$this->log->eventListenerCalled($listener, $messageOrName);
if(!$result) {
continue;
}
if(\is_object($result) && $result instanceof Message) {
$forwardedMetadata = $this->forwardMetadata ? array_merge($messageOrName->metadata(), $result->metadata()) : [];
$dispatchResults = $dispatchResults->push($this->dispatch($result, [], $forwardedMetadata));
continue;
}
if (\is_array($result)) {
[$commandName, $payload, $metadata] = MessageTuple::normalize($result);
if($this->forwardMetadata) {
$metadata = array_merge($messageOrName->metadata(), $metadata);
}
$dispatchResults = $dispatchResults->push($this->dispatch($commandName, $payload, $metadata));
continue;
}
throw new RuntimeException(
"Event listener " . Util\VariableType::determine($listener) . " returned a command, but Event Engine is unable to handle it. The command is either unknown or has the wrong format. Got "
. Util\VariableType::determine($result)
);
}
return $dispatchResults;
break;
case Message::TYPE_QUERY:
$queryDesc = $this->compiledQueryDescriptions[$messageOrName->messageName()] ?? null;
if(!$queryDesc) {
throw new RuntimeException("No routing information found for query {$messageOrName->messageName()}");
}
$resolver = $this->container->get($queryDesc['resolver'] ?? null);
$result = $this->flavour->callQueryResolver($resolver, $messageOrName);
$this->log->queryResolverCalled($resolver, $messageOrName);
return $result;
break;
default:
throw new RuntimeException('Unsupported message type: ' . $messageOrName->messageType());
}
}
public function produce(Message $message)
{
return $this->dispatch($message);
}
/**
* Loads all events from aggregate and saves the aggregate state. No cache is used.
*
* @param string $aggregateType
* @param string $aggregateId
*/
public function rebuildAggregateState(string $aggregateType, string $aggregateId): void
{
if (null === $this->documentStore && !$this->eventStore instanceof MultiModelStore) {
throw NoDocumentStore::forAggregate($aggregateType, $aggregateId);
}
$aggregateCollection = $this->aggregateDescriptions[$aggregateType]['aggregateCollection'] ?? null;
if (null === $aggregateCollection) {
throw MissingAggregateCollection::forAggregate($aggregateType);
}
$aggregateRoot = $this->loadAggregateRoot($aggregateType, $aggregateId, null, true);
$aggregateState = $aggregateRoot->currentState();
if (is_object($aggregateState) && $aggregateState instanceof DeletableState && $aggregateState->deleted()) {
if ($this->eventStore instanceof MultiModelStore) {
$this->eventStore->deleteDoc(
(string)$aggregateCollection,
(string)$aggregateRoot->aggregateId()
);
} else {
$this->documentStore->deleteDoc(
(string)$aggregateCollection,
(string)$aggregateRoot->aggregateId()
);
}
return;
}
$doc = [
'state' => $this->flavour->convertAggregateStateToArray($aggregateRoot->aggregateType(), $aggregateState),