CurlHandler.php
3.04 KB
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
<?php
/*
* This file is part of Raven.
*
* (c) Sentry Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Asynchronous Curl connection manager.
*
* @package raven
*/
// TODO(dcramer): handle ca_cert
class Raven_CurlHandler
{
protected $join_timeout;
protected $multi_handle;
protected $options;
protected $requests;
public function __construct($options, $join_timeout = 5)
{
$this->options = $options;
$this->multi_handle = curl_multi_init();
$this->requests = array();
$this->join_timeout = $join_timeout;
$this->registerShutdownFunction();
}
public function __destruct()
{
$this->join();
}
public function enqueue($url, $data = null, $headers = array())
{
$ch = curl_init();
$new_headers = array();
foreach ($headers as $key => $value) {
array_push($new_headers, $key .': '. $value);
}
// XXX(dcramer): Prevent 100-continue response form server (Fixes GH-216)
$new_headers[] = 'Expect:';
curl_setopt($ch, CURLOPT_HTTPHEADER, $new_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt_array($ch, $this->options);
if (isset($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_multi_add_handle($this->multi_handle, $ch);
$fd = (int)$ch;
$this->requests[$fd] = 1;
$this->select();
return $fd;
}
public function registerShutdownFunction()
{
register_shutdown_function(array($this, 'join'));
}
public function join($timeout = null)
{
if (!isset($timeout)) {
$timeout = $this->join_timeout;
}
$start = time();
do {
$this->select();
if (count($this->requests) === 0) {
break;
}
usleep(10000);
} while ($timeout !== 0 && time() - $start < $timeout);
}
/**
* @doc http://php.net/manual/en/function.curl-multi-exec.php
*/
protected function select()
{
do {
$mrc = curl_multi_exec($this->multi_handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($this->multi_handle) !== -1) {
do {
$mrc = curl_multi_exec($this->multi_handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
} else {
return;
}
}
while ($info = curl_multi_info_read($this->multi_handle)) {
$ch = $info['handle'];
$fd = (int)$ch;
curl_multi_remove_handle($this->multi_handle, $ch);
if (!isset($this->requests[$fd])) {
return;
}
unset($this->requests[$fd]);
}
}
}