Skip to content

Commit

Permalink
Merge pull request #18 from valga/gc
Browse files Browse the repository at this point in the history
Reduce memory consumption by avoiding circular reference from stream reader
  • Loading branch information
clue authored Sep 4, 2017
2 parents 06bc84c + a6816e5 commit 7c7dbca
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/ProxyConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,11 @@ public function connect($uri)

// keep buffering data until headers are complete
$buffer = '';
$fn = function ($chunk) use (&$buffer, &$fn, $deferred, $stream) {
$fn = function ($chunk) use (&$buffer, $deferred, $stream) {
$buffer .= $chunk;

$pos = strpos($buffer, "\r\n\r\n");
if ($pos !== false) {
// end of headers received => stop buffering
$stream->removeListener('data', $fn);

// try to parse headers as response message
try {
$response = Psr7\parse_response(substr($buffer, 0, $pos));
Expand Down Expand Up @@ -191,7 +188,11 @@ public function connect($uri)

$stream->write("CONNECT " . $host . ":" . $port . " HTTP/1.1\r\nHost: " . $host . ":" . $port . "\r\n" . $auth . "\r\n");

return $deferred->promise();
return $deferred->promise()->then(function (ConnectionInterface $stream) use ($fn) {
// Stop buffering when connection has been established.
$stream->removeListener('data', $fn);
return new Promise\FulfilledPromise($stream);
});
}, function (Exception $e) use ($proxyUri) {
throw new RuntimeException('Unable to connect to proxy (ECONNREFUSED)', defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111, $e);
});
Expand Down

0 comments on commit 7c7dbca

Please sign in to comment.