diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
new file mode 100644
index 0000000..801a3c4
--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,8 @@
+{
+ "name": "PHP preparations",
+ "onCreateCommand": "composer install --ignore-platform-reqs",
+ "extensions": [
+ "ms-azuretools.vscode-docker",
+ "zobo.php-intellisense"
+ ]
+}
\ No newline at end of file
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000..734db04
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,20 @@
+name: "CodeQL"
+
+on: [pull_request]
+jobs:
+ lint:
+ name: CodeQL
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 2
+
+ - run: git checkout HEAD^2
+
+ - name: Run CodeQL
+ run: |
+ docker run --rm -v $PWD:/app composer sh -c \
+ "composer install --profile --ignore-platform-reqs && composer check"
\ No newline at end of file
diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml
new file mode 100644
index 0000000..c2f8cb6
--- /dev/null
+++ b/.github/workflows/linter.yml
@@ -0,0 +1,20 @@
+name: "Linter"
+
+on: [pull_request]
+jobs:
+ lint:
+ name: Linter
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 2
+
+ - run: git checkout HEAD^2
+
+ - name: Run Linter
+ run: |
+ docker run --rm -v $PWD:/app composer sh -c \
+ "composer install --profile --ignore-platform-reqs && composer lint"
\ No newline at end of file
diff --git a/.github/workflows/tester.yml b/.github/workflows/tester.yml
new file mode 100644
index 0000000..b2d8e0b
--- /dev/null
+++ b/.github/workflows/tester.yml
@@ -0,0 +1,20 @@
+name: "Tester"
+
+on: [pull_request]
+jobs:
+ tests:
+ name: Tester
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 2
+
+ - run: git checkout HEAD^2
+
+ - name: Run Tests
+ run: |
+ docker run --rm -v $PWD:/app composer sh -c \
+ "composer install --profile --ignore-platform-reqs && composer test"
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e50d699
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+composer.lock
+/vendor/
+/.idea/
+.phpunit.result.cache
\ No newline at end of file
diff --git a/.gitpod.yml b/.gitpod.yml
new file mode 100644
index 0000000..1bbf0a4
--- /dev/null
+++ b/.gitpod.yml
@@ -0,0 +1,8 @@
+tasks:
+ - name: PHP preparations
+ init: |
+ composer install --ignore-platform-reqs
+vscode:
+ extensions:
+ - ms-azuretools.vscode-docker
+ - zobo.php-intellisense
\ No newline at end of file
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..e9d3a52
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,76 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to make participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity, expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+- Using welcoming and inclusive language
+- Being respectful of differing viewpoints and experiences
+- Gracefully accepting constructive criticism
+- Focusing on what is best for the community
+- Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+- The use of sexualized language or imagery and unwelcome sexual attention or
+ advances
+- Trolling, insulting/derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or electronic
+ address, without explicit permission
+- Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at team@appwrite.io. All complaints will
+be reviewed and investigated and will result in a response that is deemed
+necessary and appropriate to the circumstances. The project team is obligated
+to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..a63b8be
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,101 @@
+# Contributing
+
+We would ❤️ for you to contribute to Utopia-php and help make it better! We want contributing to Utopia-php to be fun, enjoyable, and educational for anyone and everyone. All contributions are welcome, including issues, new docs as well as updates and tweaks, blog posts, workshops, and more.
+
+## How to Start?
+
+If you are worried or don’t know where to start, check out our next section explaining what kind of help we could use and where can you get involved. You can reach out with questions to [Eldad Fux (@eldadfux)](https://twitter.com/eldadfux) or anyone from the [Appwrite team on Discord](https://appwrite.io/discord). You can also submit an issue, and a maintainer can guide you!
+
+## Code of Conduct
+
+Help us keep Utopia-php open and inclusive. Please read and follow our [Code of Conduct](/CODE_OF_CONDUCT.md).
+
+## Submit a Pull Request 🚀
+
+Branch naming convention is as following
+
+`TYPE-ISSUE_ID-DESCRIPTION`
+
+example:
+
+```
+doc-548-submit-a-pull-request-section-to-contribution-guide
+```
+
+When `TYPE` can be:
+
+- **feat** - is a new feature
+- **doc** - documentation only changes
+- **cicd** - changes related to CI/CD system
+- **fix** - a bug fix
+- **refactor** - code change that neither fixes a bug nor adds a feature
+
+**All PRs must include a commit message with the changes description!**
+
+For the initial start, fork the project and use git clone command to download the repository to your computer. A standard procedure for working on an issue would be to:
+
+1. `git pull`, before creating a new branch, pull the changes from upstream. Your master needs to be up to date.
+
+```
+$ git pull
+```
+
+2. Create new branch from `master` like: `doc-548-submit-a-pull-request-section-to-contribution-guide`
+
+```
+$ git checkout -b [name_of_your_new_branch]
+```
+
+3. Work - commit - repeat ( be sure to be in your branch )
+
+4. Push changes to GitHub
+
+```
+$ git push origin [name_of_your_new_branch]
+```
+
+5. Submit your changes for review
+ If you go to your repository on GitHub, you'll see a `Compare & pull request` button. Click on that button.
+6. Start a Pull Request
+ Now submit the pull request and click on `Create pull request`.
+7. Get a code review approval/reject
+8. After approval, merge your PR
+9. GitHub will automatically delete the branch after the merge is done. (they can still be restored).
+
+## Introducing New Features
+
+We would 💖 you to contribute to Utopia-php, but we would also like to make sure Utopia-php is as great as possible and loyal to its vision and mission statement 🙏.
+
+For us to find the right balance, please open an issue explaining your ideas before introducing a new pull request.
+
+This will allow the Utopia-php community to have sufficient discussion about the new feature value and how it fits in the product roadmap and vision.
+
+This is also important for the Utopia-php lead developers to be able to give technical input and different emphasis regarding the feature design and architecture. Some bigger features might need to go through our [RFC process](https://github.com/appwrite/rfc).
+
+## Other Ways to Help
+
+Pull requests are great, but there are many other areas where you can help Utopia-php.
+
+### Blogging & Speaking
+
+Blogging, speaking about, or creating tutorials about one of Utopia-php’s many features is great way to contribute and help our project grow.
+
+### Presenting at Meetups
+
+Presenting at meetups and conferences about your Utopia-php projects. Your unique challenges and successes in building things with Utopia-php can provide great speaking material. We’d love to review your talk abstract/CFP, so get in touch with us if you’d like some help!
+
+### Sending Feedbacks & Reporting Bugs
+
+Sending feedback is a great way for us to understand your different use cases of Utopia-php better. If you had any issues, bugs, or want to share about your experience, feel free to do so on our GitHub issues page or at our [Discord channel](https://appwrite.io/discord).
+
+### Submitting New Ideas
+
+If you think Utopia-php could use a new feature, please open an issue on our GitHub repository, stating as much information as you can think about your new idea and it's implications. We would also use this issue to gather more information, get more feedback from the community, and have a proper discussion about the new feature.
+
+### Improving Documentation
+
+Submitting documentation updates, enhancements, designs, or bug fixes. Spelling or grammar fixes will be very much appreciated.
+
+### Helping Someone
+
+Searching for Utopia-php, GitHub or StackOverflow and helping someone else who needs help. You can also help by teaching others how to contribute to Utopia-php's repo!
\ No newline at end of file
diff --git a/README.md b/README.md
index dcc6f40..6575649 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,140 @@
-# balancing
\ No newline at end of file
+# Utopia Balancing
+
+Utopia Balancing library is simple and lite library for balancingchoices between multiple options. This library is aiming to be as simple and easy to learn and use. This library is maintained by the [Appwrite team](https://appwrite.io).
+
+Although this library is part of the [Utopia Framework](https://github.com/utopia-php/framework) project it is dependency free and can be used as standalone with any other PHP project or framework.
+
+## Getting Started
+
+Install using composer:
+```bash
+composer require utopia-php/balancing
+```
+
+Balancing supports multiple algorithms. Each picks option differently, and may have different set of methods available for configuration.
+
+### 1. Random
+
+`Random` algorithm pick option randomly. The same option could be picked multiple times in a row. Example:
+
+```php
+addFilter(fn (Option $option) => $option->getState('online', false) === true);
+
+$balancing
+ ->addOption(new Option([ 'hostname' => 'proxy-1', 'online' => true ]))
+ ->addOption(new Option([ 'hostname' => 'proxy-2', 'online' => false ]))
+ ->addOption(new Option([ 'hostname' => 'proxy-3', 'online' => true ]));
+
+var_dump($balancing->run());
+var_dump($balancing->run());
+var_dump($balancing->run());
+```
+
+2. First and Last
+
+`First` algorithm always picks first option. Similiarly, `Last` algorithm always picks last option. Example:
+
+```php
+addOption(new Option([ 'runtime' => 'PHP' ]))
+ ->addOption(new Option([ 'runtime' => 'JavaScript' ]))
+ ->addOption(new Option([ 'runtime' => 'Java' ]));
+
+var_dump($balancing->run());
+
+$balancing = new Balancing(new Last());
+
+$balancing
+ ->addOption(new Option([ 'runtime' => 'PHP' ]))
+ ->addOption(new Option([ 'runtime' => 'JavaScript' ]))
+ ->addOption(new Option([ 'runtime' => 'Java' ]));
+
+var_dump($balancing->run());
+```
+
+3. Round Robin
+
+`RoundRobin` algorithm cycles over all options starting first. Once algorithm cycles over all options, it resets back to the beginning. Example:
+
+```php
+addFilter(fn (Option $option) => $option->getState('online', false) === true);
+
+$balancing
+ ->addOption(new Option([ 'dataCenter' => 'fra-1' ]))
+ ->addOption(new Option([ 'dataCenter' => 'fra-2' ]))
+ ->addOption(new Option([ 'dataCenter' => 'lon-1' ]));
+
+var_dump($balancing->run()); // fra-1
+var_dump($balancing->run()); // fra-2
+var_dump($balancing->run()); // lon-1
+var_dump($balancing->run()); // fra-1
+var_dump($balancing->run()); // fra-2
+```
+
+When using `RoundRobin` in concurrency model, make sure to store index in atomic way. Example:
+
+```php
+
+require_once '../vendor/autoload.php';
+
+use Utopia\Balancing\Algorithm\RoundRobin;
+use Utopia\Balancing\Balancing;
+use Utopia\Balancing\Option;
+
+$atomic = new Atomic(-1); // Some atomic implementation, for example: https://openswoole.com/docs/modules/swoole-atomic
+
+function onRequest() {
+ $lastIndex = $atomic->get();
+ $algo = new RoundRobin($lastIndex);
+ $balancing = new Balancing();
+
+ $balancing->addFilter(fn (Option $option) => $option->getState('online', false) === true);
+
+ $balancing
+ ->addOption(new Option([ 'dataCenter' => 'fra-1' ]))
+ ->addOption(new Option([ 'dataCenter' => 'fra-2' ]))
+ ->addOption(new Option([ 'dataCenter' => 'lon-1' ]));
+
+ var_dump($balancing->run());
+
+ $atomic->cmpset($lastIndex, $algo->getIndex());
+}
+```
+## System Requirements
+
+Utopia Framework requires PHP 8.0 or later. We recommend using the latest PHP version whenever possible.
+
+## Copyright and license
+
+The MIT License (MIT) [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)
\ No newline at end of file
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..136f5d1
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,25 @@
+{
+ "name": "utopia-php/balancing",
+ "description": "A simple library to balance choices between multiple options.",
+ "type": "library",
+ "keywords": ["php","framework", "upf", "utopia", "balancing", "balancer"],
+ "license": "MIT",
+ "autoload": {
+ "psr-4": {"Utopia\\Balancing\\": "src/Balancing"}
+ },
+ "scripts": {
+ "lint": "./vendor/bin/pint --preset psr12 --test",
+ "format": "./vendor/bin/pint --preset psr12",
+ "check": "./vendor/bin/phpstan analyse --level max src tests",
+ "test": "./vendor/bin/phpunit --configuration phpunit.xml"
+ },
+ "require": {
+ "php": ">=8.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^9.3",
+ "laravel/pint": "1.2.*",
+ "phpstan/phpstan": "1.8.*"
+ },
+ "minimum-stability": "dev"
+}
\ No newline at end of file
diff --git a/phpunit.xml b/phpunit.xml
new file mode 100644
index 0000000..ec39a7e
--- /dev/null
+++ b/phpunit.xml
@@ -0,0 +1,16 @@
+
+
+
+ ./tests/
+
+
+
\ No newline at end of file
diff --git a/src/Balancing/Algorithm.php b/src/Balancing/Algorithm.php
new file mode 100644
index 0000000..f615fbc
--- /dev/null
+++ b/src/Balancing/Algorithm.php
@@ -0,0 +1,13 @@
+index = $lastIndex;
+ }
+
+ public function getIndex(): int
+ {
+ return $this->index;
+ }
+
+ public function setIndex(int $lastIndex): self
+ {
+ $this->index = $lastIndex;
+ return $this;
+ }
+
+ /**
+ * @param Option[] $options
+ */
+ public function run(array $options): ?Option
+ {
+ $this->index++;
+
+ $keys = \array_keys($options);
+ $option = null;
+
+ if (\count($options) === $this->index) {
+ $option = $options[$keys[0]];
+ $this->index = 0;
+ } else {
+ $option = $options[$keys[$this->index]];
+ }
+
+ return $option;
+ }
+}
diff --git a/src/Balancing/Balancing.php b/src/Balancing/Balancing.php
new file mode 100644
index 0000000..7292824
--- /dev/null
+++ b/src/Balancing/Balancing.php
@@ -0,0 +1,51 @@
+algo = $algo;
+ }
+
+ public function addOption(Option $option): self
+ {
+ $this->options[] = $option;
+ return $this;
+ }
+
+ public function addFilter(callable $filter): self
+ {
+ $this->filters[] = $filter;
+ return $this;
+ }
+
+ public function run(): ?Option
+ {
+ $options = $this->options;
+
+ foreach ($this->filters as $filter) {
+ $options = \array_filter($options, $filter);
+ }
+
+ // TODO: In future allow throwing exception instead of fallback
+ if (\count($options) === 0) {
+ $options = $this->options;
+ }
+
+ return $this->algo->run($options);
+ }
+}
diff --git a/src/Balancing/Option.php b/src/Balancing/Option.php
new file mode 100644
index 0000000..579319c
--- /dev/null
+++ b/src/Balancing/Option.php
@@ -0,0 +1,44 @@
+
+ */
+ private array $state;
+
+ /**
+ * @param array $state
+ */
+ public function __construct(array $state)
+ {
+ $this->state = $state;
+ }
+
+ public function setState(string $key, mixed $value): self
+ {
+ $this->state[$key] = $value;
+ return $this;
+ }
+
+ public function getState(string $key, mixed $default = null): mixed
+ {
+ return $this->state[$key] ?? $default;
+ }
+
+ public function deleteState(string $key): self
+ {
+ unset($this->state[$key]);
+ return $this;
+ }
+
+ /**
+ * @return string[]
+ */
+ public function getStateKeys(): array
+ {
+ return \array_keys($this->state);
+ }
+}
diff --git a/tests/Balancing/BalancingTest.php b/tests/Balancing/BalancingTest.php
new file mode 100644
index 0000000..cfeeda9
--- /dev/null
+++ b/tests/Balancing/BalancingTest.php
@@ -0,0 +1,142 @@
+addOption(new Option(['hostname' => 'worker-1', 'isOnline' => true, 'cpu' => 80]))
+ ->addOption(new Option(['hostname' => 'worker-2', 'isOnline' => false, 'cpu' => 20]))
+ ->addOption(new Option(['hostname' => 'worker-3', 'isOnline' => true, 'cpu' => 35]));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-1', $option->getState('hostname'));
+
+ $balancing->addFilter(fn ($option) => $option->getState('isOnline') === true);
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-3', $option->getState('hostname'));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-1', $option->getState('hostname'));
+
+ $balancing->addFilter(fn ($option) => $option->getState('cpu') < 50);
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-3', $option->getState('hostname'));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-3', $option->getState('hostname'));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-3', $option->getState('hostname'));
+
+ $balancing->addOption(new Option(['hostname' => 'worker-4', 'isOnline' => true, 'cpu' => 5]));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-4', $option->getState('hostname'));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-3', $option->getState('hostname'));
+
+ $option = $balancing->run() ?? new Option([]);
+ $this->assertEquals('worker-4', $option->getState('hostname'));
+ }
+
+ public function testAlgorithms(): void
+ {
+ $options = [
+ new Option([ 'dataCenter' => 'fra-1' ]),
+ new Option([ 'dataCenter' => 'fra-2' ]),
+ new Option([ 'dataCenter' => 'lon-1' ]),
+ ];
+
+ $algo = new First();
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-1", $option->getState('dataCenter'));
+
+ $algo = new Last();
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("lon-1", $option->getState('dataCenter'));
+
+ $algo = new Random();
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertTrue(\in_array($option->getState('dataCenter'), ['fra-1', 'fra-2', 'lon-1']));
+ $this->assertTrue(\in_array($option->getState('dataCenter'), ['fra-1', 'fra-2', 'lon-1']));
+ $this->assertTrue(\in_array($option->getState('dataCenter'), ['fra-1', 'fra-2', 'lon-1']));
+
+ $algo = new RoundRobin(-1);
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-1", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-2", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("lon-1", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-1", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-2", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("lon-1", $option->getState('dataCenter'));
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-1", $option->getState('dataCenter'));
+
+ $algo = new RoundRobin(1);
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("lon-1", $option->getState('dataCenter'));
+ $algo->setIndex(0);
+ $option = $algo->run($options) ?? new Option([]);
+ $this->assertEquals("fra-2", $option->getState('dataCenter'));
+ }
+
+ public function testOption(): void
+ {
+ $option = new Option([]);
+
+ $this->assertIsArray($option->getStateKeys());
+ $this->assertCount(0, $option->getStateKeys());
+
+ $this->assertFalse($option->getState("isOnline", false));
+ $this->assertNull($option->getState("isOnline"));
+
+ $option->setState("isOnline", true);
+
+ $this->assertTrue($option->getState("isOnline", false));
+ $this->assertTrue($option->getState("isOnline"));
+
+ $this->assertNull($option->getState("ISONLINE"));
+
+ $this->assertCount(1, $option->getStateKeys());
+
+ $option
+ ->setState('cpu', 50)
+ ->setState('memory', 1800);
+
+ $this->assertCount(3, $option->getStateKeys());
+ $this->assertTrue($option->getState("isOnline"));
+ $this->assertEquals(50, $option->getState("cpu"));
+ $this->assertEquals(1800, $option->getState("memory"));
+
+ $option
+ ->deleteState('isOnline')
+ ->deleteState('cpu');
+
+ $this->assertCount(1, $option->getStateKeys());
+ $this->assertNull($option->getState("isOnline"));
+ $this->assertNull($option->getState("cpu"));
+ $this->assertEquals(0, $option->getState("cpu", 0));
+ $this->assertEquals(1800, $option->getState("memory"));
+ }
+}