Skip to content

Commit

Permalink
initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
othillo committed May 1, 2020
1 parent 4fc1ae9 commit d7c43b9
Show file tree
Hide file tree
Showing 12 changed files with 330 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .docheader
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* This file is part of the broadway/saga-state-elasticsearch package.
*
* (c) 2020 Broadway project
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/vendor/
composer.lock
.php_cs.cache
.phpunit.result.cache
13 changes: 13 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

$config = require 'vendor/broadway/coding-standard/.php_cs.dist';

$config->setFinder(
\PhpCsFixer\Finder::create()
->in([
__DIR__ . '/src',
__DIR__ . '/test',
])
);

return $config;
23 changes: 23 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
language: php

php:
- 7.2
- 7.3
- 7.4

services:
- elasticsearch

before_install:
# Disable XDebug speed up test execution.
- phpenv config-rm xdebug.ini || return 0
- curl -O https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.6.deb && sudo dpkg -i --force-confnew elasticsearch-1.7.6.deb && sudo service elasticsearch restart

install:
- make dependencies

script:
- make test
- make qa
- make license
- make changelog
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2014 Qandidate.com - http://qandidate.com/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
36 changes: 36 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
.DEFAULT_GOAL:=help

.PHONY: dependencies
dependencies:
composer install --no-interaction --no-suggest --no-scripts --ansi

.PHONY: test
test:
vendor/bin/phpunit --testdox --exclude-group=none --colors=always

.PHONY: qa
qa: php-cs-fixer-ci phpstan

.PHONY: php-cs-fixer
php-cs-fixer:
vendor/bin/php-cs-fixer fix --no-interaction --allow-risky=yes --diff --verbose

.PHONY: php-cs-fixer-ci
php-cs-fixer-ci:
vendor/bin/php-cs-fixer fix --dry-run --no-interaction --allow-risky=yes --diff --verbose

PHONY: phpstan
phpstan:
vendor/bin/phpstan analyse --level=max src/

.PHONY: changelog
changelog:
git log $$(git describe --abbrev=0 --tags)...HEAD --no-merges --pretty=format:"* [%h](http://github.com/${TRAVIS_REPO_SLUG}/commit/%H) %s (%cN)"

.PHONY: license
license:
vendor/bin/docheader check --no-interaction --ansi -vvv {src,test,examples}

# Based on https://suva.sh/posts/well-documented-makefiles/
help: ## Display this help
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-20s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "broadway/saga-state-elasticsearch",
"description": "Saga state persistence for broadway/broadway-saga using elastic/elasticsearch-php.",
"license": "MIT",
"require": {
"php": ">=7.2",
"broadway/broadway-saga": "~0.10",
"elasticsearch/elasticsearch": "^2.0"
},
"authors": [
{
"name": "othillo",
"email": "[email protected]"
}
],
"require-dev": {
"phpunit/phpunit": "^8.0",
"broadway/coding-standard": "~0.1",
"phpstan/phpstan": "@stable"
},
"autoload": {
"psr-4": {
"Broadway\\Saga\\State\\Elasticsearch\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Broadway\\Saga\\State\\Elasticsearch\\": "test/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: '3.2'
services:
elasticsearch:
image: elasticsearch:1-alpine
ports:
- "9200:9200"
2 changes: 2 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
parameters:
checkMissingIterableValueType: false
23 changes: 23 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
bootstrap="vendor/autoload.php"
>
<testsuites>
<testsuite name="Broadway Saga Test Suite">
<directory>./test/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
</phpunit>
112 changes: 112 additions & 0 deletions src/ElasticsearchRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

/*
* This file is part of the broadway/saga-state-elasticsearch package.
*
* (c) 2020 Broadway project
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Broadway\Saga\State\Elasticsearch;

use Broadway\Saga\State;
use Broadway\Saga\State\Criteria;
use Broadway\Saga\State\RepositoryException;
use Broadway\Saga\State\RepositoryInterface;
use Elasticsearch\Client;
use Elasticsearch\Common\Exceptions\Missing404Exception;

class ElasticsearchRepository implements RepositoryInterface
{
/**
* @var Client
*/
private $client;

/**
* @var string
*/
private $index;

public function __construct(Client $client, string $index)
{
$this->client = $client;
$this->index = $index;
}

public function findOneBy(Criteria $criteria, string $sagaId): ?State
{
$fields = array_merge($criteria->getComparisons(), ['done' => false]);

$query = [
'index' => $this->index,
'type' => $sagaId,
'body' => [
'query' => [
'bool' => [
'must' => $this->buildFilter($fields),
],
],
],
'size' => 500,
];

$results = $this->searchAndDeserializeHits($query);
$count = count($results);

if (1 === $count) {
return current($results);
}

if ($count > 1) {
throw new RepositoryException('Multiple saga state instances found.');
}

return null;
}

public function save(State $state, string $sagaId): void
{
$params = [
'index' => $this->index,
'type' => $sagaId,
'id' => $state->getId(),
'body' => $state->serialize(),
'refresh' => true,
];

$this->client->index($params);
}

private function buildFilter(array $filter): array
{
$retval = [];

foreach ($filter as $field => $value) {
$retval[] = ['match' => [$field => $value]];
}

return $retval;
}

private function searchAndDeserializeHits(array $query): array
{
try {
$result = $this->client->search($query);
} catch (Missing404Exception $e) {
return [];
}

if (!array_key_exists('hits', $result)) {
return [];
}

return array_map(function ($serializedSagaState) {
return State::deserialize($serializedSagaState['_source']);
}, $result['hits']['hits']);
}
}
48 changes: 48 additions & 0 deletions test/ElasticsearchRepositoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the broadway/saga-state-elasticsearch package.
*
* (c) 2020 Broadway project
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Broadway\Saga\State\Elasticsearch;

use Broadway\Saga\State\RepositoryInterface;
use Broadway\Saga\State\Testing\AbstractRepositoryTest;
use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;

class ElasticsearchRepositoryTest extends AbstractRepositoryTest
{
public const INDEX = 'saga_state';

/**
* @var Client
*/
private $client;

public function setUp(): void
{
$this->client = ClientBuilder::fromConfig(['hosts' => ['localhost:9200']]);
$this->client->indices()->create(['index' => self::INDEX]);
$this->client->cluster()->health(['index' => self::INDEX, 'wait_for_status' => 'yellow', 'timeout' => '10s']);

parent::setUp();
}

protected function createRepository(): RepositoryInterface
{
return new ElasticsearchRepository($this->client, self::INDEX);
}

public function tearDown(): void
{
$this->client->indices()->delete(['index' => self::INDEX]);
}
}

0 comments on commit d7c43b9

Please sign in to comment.