-
Notifications
You must be signed in to change notification settings - Fork 59
feat: implement readStream method for streaming file reads #161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -350,6 +350,131 @@ public function read(string $path, int $offset = 0, ?int $length = null): string | |
| return $response->body; | ||
| } | ||
|
|
||
| /** | ||
| * Read file as a stream, yielding chunks. | ||
| * | ||
| * Makes a single HTTP request and yields data as it arrives from the network. | ||
| */ | ||
| public function readStream(string $path, int $offset = 0, int $length = -1): \Generator | ||
| { | ||
| $startTime = microtime(true); | ||
|
|
||
| unset($this->amzHeaders['x-amz-acl']); | ||
| unset($this->amzHeaders['x-amz-content-sha256']); | ||
| unset($this->headers['content-type']); | ||
| $this->headers['content-md5'] = \base64_encode(md5('', true)); | ||
|
|
||
| $uri = ($path !== '') ? '/'.\str_replace('%2F', '/', \rawurlencode($path)) : '/'; | ||
|
|
||
| if ($length > 0) { | ||
| $end = $offset + $length - 1; | ||
| $this->headers['range'] = "bytes=$offset-$end"; | ||
| } elseif ($offset > 0) { | ||
| $this->headers['range'] = "bytes=$offset-"; | ||
| } else { | ||
| unset($this->headers['range']); | ||
| } | ||
|
|
||
| $uri = $this->getAbsolutePath($uri); | ||
| $url = $this->fqdn.$uri.'?'.\http_build_query([], '', '&', PHP_QUERY_RFC3986); | ||
|
|
||
| $buffer = ''; | ||
| $chunkSize = 2 * 1024 * 1024; // 2MB | ||
|
|
||
| $curl = \curl_init(); | ||
| \curl_setopt($curl, CURLOPT_USERAGENT, 'utopia-php/storage'); | ||
| \curl_setopt($curl, CURLOPT_URL, $url); | ||
|
|
||
| $httpHeaders = []; | ||
| $this->amzHeaders['x-amz-date'] = \gmdate('Ymd\THis\Z'); | ||
| $this->amzHeaders['x-amz-content-sha256'] = \hash('sha256', ''); | ||
|
|
||
| foreach ($this->amzHeaders as $header => $value) { | ||
| if (\strlen($value) > 0) { | ||
| $httpHeaders[] = $header.': '.$value; | ||
| } | ||
| } | ||
|
|
||
| $this->headers['date'] = \gmdate('D, d M Y H:i:s T'); | ||
|
|
||
| foreach ($this->headers as $header => $value) { | ||
| if (\strlen($value) > 0) { | ||
| $httpHeaders[] = $header.': '.$value; | ||
| } | ||
| } | ||
|
|
||
| $httpHeaders[] = 'Authorization: '.$this->getSignatureV4(self::METHOD_GET, $uri); | ||
|
|
||
| \curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders); | ||
| \curl_setopt($curl, CURLOPT_HEADER, false); | ||
| \curl_setopt($curl, CURLOPT_RETURNTRANSFER, false); | ||
| \curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); | ||
| \curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::METHOD_GET); | ||
|
|
||
| if ($this->curlHttpVersion != null) { | ||
| \curl_setopt($curl, CURLOPT_HTTP_VERSION, $this->curlHttpVersion); | ||
| } | ||
|
|
||
| \curl_setopt($curl, CURLOPT_WRITEFUNCTION, function ($curl, string $data) use (&$buffer) { | ||
| $buffer .= $data; | ||
|
|
||
| return \strlen($data); | ||
| }); | ||
|
|
||
| $responseHeaders = []; | ||
| \curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($curl, string $header) use (&$responseHeaders) { | ||
| $len = \strlen($header); | ||
| $parts = \explode(':', $header, 2); | ||
| if (\count($parts) >= 2) { | ||
| $responseHeaders[\strtolower(\trim($parts[0]))] = \trim($parts[1]); | ||
| } | ||
|
|
||
| return $len; | ||
| }); | ||
|
|
||
| $mh = \curl_multi_init(); | ||
| \curl_multi_add_handle($mh, $curl); | ||
|
|
||
| try { | ||
| do { | ||
| $status = \curl_multi_exec($mh, $active); | ||
|
|
||
| while (\strlen($buffer) >= $chunkSize) { | ||
| yield \substr($buffer, 0, $chunkSize); | ||
| $buffer = \substr($buffer, $chunkSize); | ||
| } | ||
|
|
||
| if ($active) { | ||
| \curl_multi_select($mh, 1.0); | ||
| } | ||
| } while ($active && $status === CURLM_OK); | ||
|
|
||
| $code = \curl_getinfo($curl, CURLINFO_HTTP_CODE); | ||
|
|
||
| if ($code >= 400) { | ||
| $this->parseAndThrowS3Error($buffer, $code); | ||
| } | ||
|
|
||
| if (\strlen($buffer) > 0) { | ||
| yield $buffer; | ||
| $buffer = ''; | ||
|
Comment on lines
+452
to
+460
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Error response may be partially yielded before detection. The HTTP status code check occurs after the streaming loop completes. If S3 returns an error response (e.g., 404), the error body may be buffered and yielded as a "chunk" before Consider checking for error status earlier, or at minimum, ensure the final buffer isn't yielded when an error is detected: 🔧 Suggested fix $code = \curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code >= 400) {
+ // Don't yield the error response body as content
$this->parseAndThrowS3Error($buffer, $code);
}
- if (\strlen($buffer) > 0) {
+ if ($code < 400 && \strlen($buffer) > 0) {
yield $buffer;
$buffer = '';
}🤖 Prompt for AI Agents |
||
| } | ||
| } finally { | ||
| \curl_multi_remove_handle($mh, $curl); | ||
| \curl_close($curl); | ||
| \curl_multi_close($mh); | ||
|
|
||
| $this->storageOperationTelemetry->record( | ||
| microtime(true) - $startTime, | ||
| [ | ||
| 'storage' => $this->getType(), | ||
| 'operation' => 's3:readStream', | ||
| 'attempts' => 0, | ||
| ] | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Write file by given path. | ||
| * | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: utopia-php/storage
Length of output: 92
🏁 Script executed:
Repository: utopia-php/storage
Length of output: 5551
🏁 Script executed:
Repository: utopia-php/storage
Length of output: 803
Critical:
Telemetryclass will fail at runtime due to missingreadStreamimplementation.The
Telemetryclass (insrc/Storage/Device/Telemetry.php) extendsDevicebut does not implement the new abstractreadStreammethod. SinceTelemetryis a concrete class, PHP will throw a fatal error when the class is loaded or instantiated.Both
S3andLocal(the other concrete Device subclasses) implementreadStream. Add the missing implementation toTelemetry:Note: Standard telemetry wrapping via
measure()won't work for generators since the method returns immediately. Consider whether telemetry timing is needed for streaming operations, or if this delegation suffices.🤖 Prompt for AI Agents