summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/protocol-jsonrpc/src/JsonRpcConnection.php
blob: 88c6f5b32ff4495b33b74e0fb1457c9ef3cdbc97 (plain)
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
<?php

namespace gipfl\Protocol\JsonRpc;

use Evenement\EventEmitterTrait;
use Exception;
use gipfl\Json\JsonEncodeException;
use gipfl\Protocol\JsonRpc\Handler\JsonRpcHandler;
use InvalidArgumentException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use React\Promise\Deferred;
use React\Promise\Promise;
use React\Stream\DuplexStreamInterface;
use React\Stream\Util;
use RuntimeException;
use function mt_rand;
use function React\Promise\reject;
use function React\Promise\resolve;

class JsonRpcConnection implements LoggerAwareInterface
{
    use EventEmitterTrait;
    use LoggerAwareTrait;

    /** @var DuplexStreamInterface */
    protected $connection;

    /** @var ?JsonRpcHandler */
    protected $handler;

    /** @var Deferred[] */
    protected $pending = [];

    protected $unknownErrorCount = 0;

    public function __construct(DuplexStreamInterface $connection, JsonRpcHandler $handler = null)
    {
        $this->setLogger(new NullLogger());
        $this->connection = $connection;
        $this->setHandler($handler);
        $this->connection->on('data', function ($data) {
            try {
                $this->handlePacket(Packet::decode($data));
            } catch (\Exception $error) {
                $this->logger->error($error->getMessage());
                $this->unknownErrorCount++;
                if ($this->unknownErrorCount === 3) {
                    // e.g.: decoding errors
                    // TODO: should we really close? Or just send error responses for every Exception?
                    $this->close();
                }
                $response = new Response();
                $response->setError(Error::forException($error));
                $this->connection->write($response->toString());
            }
        });
        $connection->on('close', function () {
            $this->rejectAllPendingRequests('Connection closed');
        });
        // Hint: Util::pipe takes care of the pipe event
        Util::forwardEvents($connection, $this, ['end', 'error', 'close', 'drain']);
    }

    /**
     * @param Packet $packet
     */
    protected function handlePacket(Packet $packet)
    {
        if ($packet instanceof Response) {
            $this->handleResponse($packet);
        } elseif ($packet instanceof Request) {
            if ($this->handler) {
                $result = $this->handler->processRequest($packet);
            } else {
                $result = new Error(Error::METHOD_NOT_FOUND);
                $result->setMessage($result->getMessage() . ': ' . $packet->getMethod());
            }
            $this->sendResultForRequest($packet, $result);
        } elseif ($packet instanceof Notification) {
            if ($this->handler) {
                $this->handler->processNotification($packet);
            }
        } else {
            // Will not happen as long as there is no bug in Packet
            throw new RuntimeException('Packet was neither Request/Notification nor Response');
        }
    }

    protected function handleResponse(Response $response)
    {
        $id = $response->getId();
        if (isset($this->pending[$id])) {
            $promise = $this->pending[$id];
            unset($this->pending[$id]);
            $promise->resolve($response);
        } else {
            $this->handleUnmatchedResponse($response);
        }
    }

    protected function handleUnmatchedResponse(Response $response)
    {
        $this->logger->error('Unmatched Response: ' . $response->toString());
    }

    protected function sendResultForRequest(Request $request, $result)
    {
        if ($result instanceof Error) {
            $response = Response::forRequest($request);
            $response->setError($result);
            if ($this->connection && $this->connection->isWritable()) {
                $this->connection->write($response->toString());
            } else {
                $this->logger->error('Failed to send response, have no writable connection');
            }
        } elseif ($result instanceof Promise) {
            $result->then(function ($result) use ($request) {
                $this->sendResultForRequest($request, $result);
            }, function ($error) use ($request) {
                $response = Response::forRequest($request);
                if ($error instanceof Exception || $error instanceof \Throwable) {
                    $response->setError(Error::forException($error));
                } else {
                    $response->setError(new Error(Error::INTERNAL_ERROR, $error));
                }
                // TODO: Double-check, this used to loop
                $this->connection->write($response->toString());
            })->done();
        } else {
            $response = Response::forRequest($request);
            $response->setResult($result);
            if ($this->connection && $this->connection->isWritable()) {
                $this->connection->write($response->toString());
            } else {
                $this->logger->error('Failed to send response, have no writable connection');
            }
        }
    }

    /**
     * @param Request $request
     * @return \React\Promise\PromiseInterface
     */
    public function sendRequest(Request $request)
    {
        $id = $request->getId();
        if ($id === null) {
            $id = $this->getNextRequestId();
            $request->setId($id);
        }
        if (isset($this->pending[$id])) {
            throw new InvalidArgumentException(
                "A request with id '$id' is already pending"
            );
        }
        if (!$this->connection->isWritable()) {
            return reject(new Exception('Cannot write to socket'));
        }
        try {
            $this->connection->write($request->toString());
        } catch (JsonEncodeException $e) {
            return reject($e->getMessage());
        }
        $deferred = new Deferred(function () use ($id) {
            unset($this->pending[$id]);
        });
        $this->pending[$id] = $deferred;

        return $deferred->promise()->then(function (Response $response) {
            if ($response->isError()) {
                return reject(new RuntimeException($response->getError()->getMessage()));
            }

            return resolve($response->getResult());
        });
    }

    public function request($method, $params = null)
    {
        return $this->sendRequest(new Request($method, $this->getNextRequestId(), $params));
    }

    protected function getNextRequestId()
    {
        for ($i = 0; $i < 100; $i++) {
            $id = mt_rand(1, 1000000000);
            if (!isset($this->pending[$id])) {
                return $id;
            }
        }

        throw new RuntimeException('Unable to generate a free random request ID, gave up after 100 attempts');
    }

    /**
     * @param Notification $packet
     */
    public function sendNotification(Notification $packet)
    {
        $this->connection->write($packet->toString());
    }

    /**
     * @param string $method
     * @param null $params
     */
    public function notification($method, $params = null)
    {
        $notification = new Notification($method, $params);
        $this->sendNotification($notification);
    }

    /**
     * @param PacketHandler $handler
     * @return $this
     */
    public function setHandler(JsonRpcHandler $handler = null)
    {
        $this->handler = $handler;
        return $this;
    }

    protected function rejectAllPendingRequests($message)
    {
        foreach ($this->pending as $pending) {
            $pending->reject(new Exception($message));
        }
        $this->pending = [];
    }

    public function close()
    {
        if ($this->connection) {
            $this->connection->close();
            $this->handler = null;
            $this->connection = null;
        }
    }
}