Debian Codegraph @

vendor/clue/connection-manager-extra/README.md

raw
1 # clue/reactphp-connection-manager-extra
2
3 [![CI status](https://github.com/clue/reactphp-connection-manager-extra/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-connection-manager-extra/actions)
4 [![code coverage](https://img.shields.io/badge/code%20coverage-100%25-success)](#tests)
5 [![installs on Packagist](https://img.shields.io/packagist/dt/clue/connection-manager-extra?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/connection-manager-extra)
6
7 This project provides _extra_ (in terms of "additional", "extraordinary", "special" and "unusual") decorators,
8 built on top of [ReactPHP's Socket](https://github.com/reactphp/socket).
9
10 **Table of contents**
11
12 * [Support us](#support-us)
13 * [Introduction](#introduction)
14 * [Usage](#usage)
15 * [Repeat](#repeat)
16 * [Timeout](#timeout)
17 * [Delay](#delay)
18 * [Reject](#reject)
19 * [Swappable](#swappable)
20 * [Consecutive](#consecutive)
21 * [Random](#random)
22 * [Concurrent](#concurrent)
23 * [Selective](#selective)
24 * [Install](#install)
25 * [Tests](#tests)
26 * [License](#license)
27
28 ## Support us
29
30 I maintain an ecosystem of open-source projects that have been downloaded
31 hundreds of millions of times and are actively maintained and continuously
32 improved. If you find any of these projects useful, please consider
33 [becoming a sponsor on GitHub](https://github.com/sponsors/clue). Your support
34 helps ensure long-term maintenance and continued development. Thank you! 🚀
35
36 ## Introduction
37
38 If you're not already familar with [react/socket](https://github.com/reactphp/socket),
39 think of it as an async (non-blocking) version of [`fsockopen()`](https://www.php.net/manual/en/function.fsockopen.php)
40 or [`stream_socket_client()`](https://www.php.net/manual/en/function.stream-socket-client.php).
41 I.e. before you can send and receive data to/from a remote server, you first have to establish a connection - which
42 takes its time because it involves several steps.
43 In order to be able to establish several connections at the same time, [react/socket](https://github.com/reactphp/socket) provides a simple
44 API to establish simple connections in an async (non-blocking) way.
45
46 This project includes several classes that extend this base functionality by implementing the same simple `ConnectorInterface`.
47 This interface provides a single promise-based method `connect($uri)` which can be used to easily notify
48 when the connection is successfully established or the `Connector` gives up and the connection fails.
49
50 ```php
51 $connector->connect('www.google.com:80')->then(function ($stream) {
52 echo 'connection successfully established';
53 $stream->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");
54 $stream->end();
55 }, function ($exception) {
56 echo 'connection attempt failed: ' . $exception->getMessage();
57 });
58
59 ```
60
61 Because everything uses the same simple API, the resulting `Connector` classes can be easily interchanged
62 and be used in places that expect the normal `ConnectorInterface`. This can be used to stack them into each other,
63 like using [timeouts](#timeout) for TCP connections, [delaying](#delay) SSL/TLS connections,
64 [retrying](#repeat) failed connection attempts, [randomly](#random) picking a `Connector` or
65 any combination thereof.
66
67 ## Usage
68
69 This section lists all features of this library along with some examples.
70 The examples assume you've [installed](#install) this library and
71 already [set up a `Socket/Connector` instance `$connector`](https://github.com/reactphp/socket#connector).
72
73 All classes are located in the `ConnectionManager\Extra` namespace.
74
75 ### Repeat
76
77 The `ConnectionManagerRepeat($connector, $tries)` tries connecting to the given location up to a maximum
78 of `$tries` times when the connection fails.
79
80 If you pass a value of `3` to it, it will first issue a normal connection attempt
81 and then retry up to 2 times if the connection attempt fails:
82
83 ```php
84 $connectorRepeater = new ConnectionManagerRepeat($connector, 3);
85
86 $connectorRepeater->connect('www.google.com:80')->then(function ($stream) {
87 echo 'connection successfully established';
88 $stream->close();
89 });
90 ```
91
92 ### Timeout
93
94 The `ConnectionManagerTimeout($connector, $timeout, $loop = null)` sets a maximum `$timeout` in seconds on when to give up
95 waiting for the connection to complete.
96
97 ```php
98 $connector = new ConnectionManagerTimeout($connector, 3.0);
99 ```
100
101 ### Delay
102
103 The `ConnectionManagerDelay($connector, $delay, $loop = null)` sets a fixed initial `$delay` in seconds before actually
104 trying to connect. (Not to be confused with [`ConnectionManagerTimeout`](#timeout) which sets a _maximum timeout_.)
105
106 ```php
107 $delayed = new ConnectionManagerDelayed($connector, 0.5);
108 ```
109
110 ### Reject
111
112 The `ConnectionManagerReject(null|string|callable $reason)` simply rejects every single connection attempt.
113 This is particularly useful for the below [`ConnectionManagerSelective`](#selective) to reject connection attempts
114 to only certain destinations (for example blocking advertisements or harmful sites).
115
116 The constructor accepts an optional rejection reason which will be used for
117 rejecting the resulting promise.
118
119 You can explicitly pass a `string` value which will be used as the message for
120 the `Exception` instance:
121
122 ```php
123 $connector = new ConnectionManagerReject('Blocked');
124 $connector->connect('www.google.com:80')->then(null, function ($e) {
125 assert($e instanceof \Exception);
126 assert($e->getMessage() === 'Blocked');
127 });
128 ```
129
130 You can explicitly pass a `callable` value which will be used to either
131 `throw` or `return` a custom `Exception` instance:
132
133 ```php
134 $connector = new ConnectionManagerReject(function ($uri) {
135 throw new RuntimeException($uri . ' blocked');
136 });
137 $connector->connect('www.google.com:80')->then(null, function ($e) {
138 assert($e instanceof \RuntimeException);
139 assert($e->getMessage() === 'www.google.com:80 blocked');
140 });
141 ```
142
143 ### Swappable
144
145 The `ConnectionManagerSwappable($connector)` is a simple decorator for other `ConnectionManager`s to
146 simplify exchanging the actual `ConnectionManager` during runtime (`->setConnectionManager($connector)`).
147
148 ### Consecutive
149
150 The `ConnectionManagerConsecutive($connectors)` establishes connections by trying to connect through
151 any of the given `ConnectionManager`s in consecutive order until the first one succeeds.
152
153 ```php
154 $consecutive = new ConnectionManagerConsecutive(array(
155 $connector1,
156 $connector2
157 ));
158 ```
159
160 ### Random
161
162 The `ConnectionManagerRandom($connectors)` works much like `ConnectionManagerConsecutive` but instead
163 of using a fixed order, it always uses a randomly shuffled order.
164
165 ```php
166 $random = new ConnectionManagerRandom(array(
167 $connector1,
168 $connector2
169 ));
170 ```
171
172 ### Concurrent
173
174 The `ConnectionManagerConcurrent($connectors)` establishes connections by trying to connect through
175 ALL of the given `ConnectionManager`s at once, until the first one succeeds.
176
177 ```php
178 $concurrent = new ConnectionManagerConcurrent(array(
179 $connector1,
180 $connector2
181 ));
182 ```
183
184 ### Selective
185
186 The `ConnectionManagerSelective($connectors)` manages a list of `Connector`s and
187 forwards each connection through the first matching one.
188 This can be used to implement networking access control lists (ACLs) or firewall
189 rules like a blacklist or whitelist.
190
191 This allows fine-grained control on how to handle outgoing connections, like
192 rejecting advertisements, delaying unencrypted HTTP requests or forwarding HTTPS
193 connection through a foreign country.
194
195 If none of the entries in the list matches, the connection will be rejected.
196 This can be used to implement a very simple whitelist like this:
197
198 ```php
199 $selective = new ConnectionManagerSelective(array(
200 'github.com' => $connector,
201 '*:443' => $connector
202 ));
203 ```
204
205 If you want to implement a blacklist (i.e. reject only certain targets), make
206 sure to add a default target to the end of the list like this:
207
208 ```php
209 $reject = new ConnectionManagerReject();
210 $selective = new ConnectionManagerSelective(array(
211 'ads.example.com' => $reject,
212 '*:80-81' => $reject,
213 '*' => $connector
214 ));
215 ```
216
217 Similarly, you can also combine any of the other connectors to implement more
218 advanced connection setups, such as delaying unencrypted connections only and
219 retrying unreliable hosts:
220
221 ```php
222 // delay connection by 2 seconds
223 $delayed = new ConnectionManagerDelay($connector, 2.0);
224
225 // maximum of 3 tries, each taking no longer than 2.0 seconds
226 $retry = new ConnectionManagerRepeat(
227 new ConnectionManagerTimeout($connector, 2.0),
228 3
229 );
230
231 $selective = new ConnectionManagerSelective(array(
232 '*:80' => $delayed,
233 'unreliable.example.com' => $retry,
234 '*' => $connector
235 ));
236 ```
237
238 Each entry in the list MUST be in the form `host` or `host:port`, where
239 `host` may contain the `*` wildcard character and `port` may be given as
240 either an exact port number or as a range in the form of `min-max`.
241 Passing anything else will result in an `InvalidArgumentException`.
242
243 > Note that the host will be matched exactly as-is otherwise. This means that
244 if you only block `youtube.com`, this has no effect on `www.youtube.com`.
245 You may want to add a second rule for `*.youtube.com` in this case.
246
247 ## Install
248
249 The recommended way to install this library is [through Composer](https://getcomposer.org/).
250 [New to Composer?](https://getcomposer.org/doc/00-intro.md)
251
252 This project follows [SemVer](https://semver.org/).
253 This will install the latest supported version:
254
255 ```bash
256 composer require clue/connection-manager-extra:^1.4
257 ```
258
259 See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
260
261 This project aims to run on any platform and thus does not require any PHP
262 extensions and supports running on legacy PHP 5.3 through current PHP 8+ and
263 HHVM.
264 It's *highly recommended to use the latest supported PHP version* for this project.
265
266 ## Tests
267
268 To run the test suite, you first need to clone this repo and then install all
269 dependencies [through Composer](https://getcomposer.org/):
270
271 ```bash
272 composer install
273 ```
274
275 To run the test suite, go to the project root and run:
276
277 ```bash
278 vendor/bin/phpunit
279 ```
280
281 The test suite is set up to always ensure 100% code coverage across all
282 supported environments. If you have the Xdebug extension installed, you can also
283 generate a code coverage report locally like this:
284
285 ```bash
286 XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text
287 ```
288
289 ## License
290
291 This project is released under the permissive [MIT license](LICENSE).
292
293 > Do you use this project in a commercial setting? Sponsoring with invoicing is
294 available, contact me ([@clue](https://github.com/clue)) for details.