Streams & SSE
PAM can send a response while your code is still producing it. Instead of building a 200 MB CSV in a string, you yield it row by row; instead of polling, a browser keeps one connection open and receives Server-Sent Events. Every chunk passes through a bounded queue in Rust, so a slow client makes your producer wait rather than making the worker’s memory grow.
The same ideas apply to raw sockets: the Pam\Stream classes read and write in bounded chunks and suspend the request Fiber while the network catches up.
Streaming Responses
Section titled “Streaming Responses”Response::stream() sends every item of an iterable as a chunk. Generators are the natural fit:
<?php
declare(strict_types=1);
use Pam\Http\Request;use Pam\Http\Response;use Pam\Http\Server;
use function Pam\Async\delay;
Server::create(static function (Request $request, Response $response): Response { return $response->stream((static function (): Generator { foreach (['one', 'two', 'three'] as $word) { yield $word . "\n"; delay(0.05); } })(), 'text/plain; charset=utf-8');})->listen(3000, '127.0.0.1');HTTP/1.1 200 OKcontent-type: text/plain; charset=utf-8transfer-encoding: chunked
onetwothreeThe signature is stream(iterable $chunks, string $contentType = 'application/octet-stream'): Response. Chunks are cast to strings (null becomes an empty string, booleans become true/false). Set the status and any other headers before calling stream(): the headers are sent with the first chunk.
Streaming Output
Section titled “Streaming Output”Existing code that echoes (templates, CSV writers, fpassthru()) can be streamed with streamOutput(). Everything the callable prints is captured by an output buffer and sent in chunks of $chunkBytes (64 KiB by default):
return $response ->header('content-type', 'text/csv') ->header('content-disposition', 'attachment; filename="users.csv"') ->streamOutput(static function () use ($users): void { echo "id,name\n";
foreach ($users->cursor() as $user) { echo "{$user->id},{$user->name}\n"; } });Writing Chunks Directly
Section titled “Writing Chunks Directly”writeChunk(string $chunk) sends one chunk immediately. stream(), sse() and streamOutput() are built on it; use it when your code is already a loop rather than a generator.
Server-Sent Events
Section titled “Server-Sent Events”Response::sse() turns an iterable of events into a text/event-stream. Strings are sent as-is; anything else is JSON-encoded. Each line of the payload becomes a data: line:
use function Pam\Async\delay;
return $response->sse((static function (): Generator { for ($sequence = 1; $sequence <= 3; $sequence++) { yield ['sequence' => $sequence]; delay(1.0); }})());HTTP/1.1 200 OKconnection: keep-alivecache-control: no-cachecontent-type: text/event-stream; charset=utf-8transfer-encoding: chunked
data: {"sequence":1}
data: {"sequence":2}
data: {"sequence":3}On the client, the standard EventSource API receives each object:
const source = new EventSource('/events');source.onmessage = (event) => console.log(JSON.parse(event.data));Long-Lived Streams
Section titled “Long-Lived Streams”An SSE endpoint holds its request Fiber open for as long as the client is connected. Keep a few things in mind:
- The request deadline still applies. A stream that should outlive
requestTimeoutMs(30 seconds by default) needs a larger value in yourlisten()options, or should end and letEventSourcereconnect. - When the client disconnects, PAM cancels the Fiber and runs your
finallyblocks. Put cleanup (unsubscribe, release a lock) there. - Each open stream counts against
maxConcurrentRequests. For thousands of mostly idle subscribers, WebSockets with rooms are usually a better fit.
Backpressure and Limits
Section titled “Backpressure and Limits”Chunks travel from PHP to the client through a bounded queue. When the queue is full because the client reads slowly, the next yield/writeChunk() suspends your Fiber until there is room, so a generator never runs ahead of the network.
These listen() options control it (defaults shown):
| Option | Default | Effect |
|---|---|---|
responseStreamQueueCapacity |
16 |
Chunks buffered between PHP and the socket |
maxResponseBytes |
268435456 (256 MiB) |
Total body limit for one response |
maxResponseChunkBytes |
1048576 (1 MiB) |
Largest single chunk operation |
If a stream exceeds maxResponseBytes after its headers were sent, PAM closes the connection with an error so the client cannot mistake a truncated body for a complete one. HTTP/1.1, HTTP/2 and HTTP/3 all receive chunks incrementally.
$server->listen(3000, '127.0.0.1', [ 'responseStreamQueueCapacity' => 32, 'maxResponseBytes' => 512 * 1024 * 1024,]);Stream Objects
Section titled “Stream Objects”For sockets, pipes and files, the Pam\Stream namespace wraps PHP stream resources with a bounded, suspending API:
| Class | Purpose |
|---|---|
Readable |
read(?int $length = null, ?float $timeout = null), chunks(?float $timeout = null), eof(), close() |
Writable |
write(string $data, ?float $timeout = null): int, close() |
Duplex |
Both, over one resource (a socket) |
Streams |
Factories: readable(), writable(), connect(), pipe() |
Each object has a highWaterMark (64 KiB by default, between 1 byte and 16 MiB): reads return at most that many bytes and writes are split into chunks of that size. Wrapping a resource switches it to non-blocking mode.
Talking to a TCP Service
Section titled “Talking to a TCP Service”use Pam\Stream\Streams;
$socket = Streams::connect('127.0.0.1:9000', timeout: 2.0);$socket->write("PING\n");$reply = $socket->read(timeout: 2.0);$socket->close();Streams::connect(string $address, float $timeout = 10.0, bool $tls = false, int $highWaterMark = 65536) returns a Duplex. Pass tls: true for a TLS connection.
Reading in Chunks
Section titled “Reading in Chunks”use Pam\Stream\Streams;
$readable = Streams::readable(fopen('/var/log/app.log', 'rb'));
foreach ($readable->chunks(timeout: 5.0) as $chunk) { $response->writeChunk($chunk);}Piping
Section titled “Piping”Streams::pipe($source, $destination, ?float $timeout = null): int copies a readable stream into a writable one chunk by chunk and returns the number of bytes written:
use Pam\Stream\Streams;
$copied = Streams::pipe( Streams::readable(fopen('php://stdin', 'rb')), Streams::writable(fopen('/tmp/upload.bin', 'wb')),);Next Steps
Section titled “Next Steps”- WebSockets: bidirectional, room-based messaging.
- Responses: status codes, headers and cookies.
- Async I/O: the socket functions these classes use.