Skip to content

Commit f7b2575

Browse files
committed
Cancel requests
1 parent 71c8793 commit f7b2575

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/ApiClient.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ public function addResultHandler(callable $handler)
4949
* @return int The length of the handled data.
5050
*/
5151
protected function handleStream($curl, $streamData) {
52+
if ($this->shouldAbort) {
53+
return -1;
54+
}
55+
5256
foreach(explode("data: ", $streamData) as $bodyParsed) {
5357
if (!$bodyParsed) continue;
5458

src/Client.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,16 @@ public function combineStreamMessageToResultMessage() : ChatMessage
106106
return $message;
107107
}
108108

109+
public function cancelRequest()
110+
{
111+
$this->driver->cancelRequest();
112+
}
113+
114+
public function isBusy() : bool
115+
{
116+
return $this->driver->isBusy();
117+
}
118+
109119
/**
110120
* Sets the system message in the chat history.
111121
*

src/Traits/WithCurlRequests.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
trait WithCurlRequests
66
{
7+
public bool $shouldAbort = false;
8+
public bool $isBusy = false;
9+
710
/**
811
* Sends a JSON request to a specified URL.
912
*
@@ -14,6 +17,8 @@ trait WithCurlRequests
1417
* @return array|null The parsed JSON response, or null on failure.
1518
*/
1619
protected function sendJsonRequest(string $method, string $url, array $jsonData, array $headers = []) {
20+
$this->isBusy = true;
21+
1722
$curlOptions = [
1823
CURLOPT_URL => $url,
1924
CURLOPT_RETURNTRANSFER => true,
@@ -25,6 +30,11 @@ protected function sendJsonRequest(string $method, string $url, array $jsonData,
2530
CURLOPT_CUSTOMREQUEST => $method,
2631
CURLOPT_POSTFIELDS => json_encode($jsonData),
2732
CURLOPT_HTTPHEADER => $headers,
33+
CURLOPT_WRITEFUNCTION => function ($curl, $streamData) {
34+
if ($this->shouldAbort) {
35+
return -1;
36+
}
37+
}
2838
];
2939

3040
if ($jsonData === []) {
@@ -52,6 +62,18 @@ protected function sendJsonRequest(string $method, string $url, array $jsonData,
5262
$bodyParsed = null;
5363
}
5464

65+
$this->isBusy = false;
66+
5567
return $bodyParsed;
5668
}
69+
70+
public function cancelRequest()
71+
{
72+
$this->shouldAbort = true;
73+
}
74+
75+
public function isBusy() : bool
76+
{
77+
return $this->isBusy;
78+
}
5779
}

0 commit comments

Comments
 (0)