PHP Client interacting with cde container API.
To install this package run composer require productsupcom/container-api-client in your project root dir.
Code is mostly generated from openapi specs for container api, but Productsup\CDE\ContainerApi\ContainerApi class is
an abstraction that is holding all the operations you might need with container api. The class is dependent on 2
services:
Productsup\CDE\ContainerApi\BaseClient\ClientMonolog\Formatter\FormatterInterface
Once you instantiate it you can use it to communicate with container api.
Productsup\CDE\ContainerApi\BaseClient\Client
which is an autogenerated client for container api. You can instantiate it like this:
$httpClient = new \GuzzleHttp\Client([
'base_uri' => 'http://cde-container-api', //client container runs in a container alongside your connector container
]);
$client = Client::create($httpClient);NOTE: We use guzzle as http client, but you can use any of the clients
implementing Psr\Http\Client\ClientInterface
This argument is nullable, so if you don't want to use custom log formatting you can leave it null and it will
use Monolog\Formatter\NormalizerFormatter. If you wish to format the logs sent to container api you can inject any
implementation of the Monolog\Formatter\FormatterInterface
Guzzle downloads a whole response body before it returns the response, so streamFromFile() yields its first row only
once the whole file has arrived. To read the file stream as it arrives, push GuzzleLazyFileStream::middleware() onto
the Guzzle HandlerStack you pass to Client::create():
$handlerStack = \GuzzleHttp\HandlerStack::create();
$handlerStack->push(\Productsup\CDE\ContainerApi\Stream\GuzzleLazyFileStream::middleware());
$httpClient = new \GuzzleHttp\Client([
'base_uri' => 'http://cde-container-api',
'handler' => $handlerStack,
'timeout' => 3600,
]);
$client = Client::create($httpClient);The middleware sets Guzzle's stream option on the request of streamFromFile() only, so Guzzle's default handler
sends it through its StreamHandler instead of cURL. Every other request stays on cURL, the storage-key downloads
included: StreamHandler does not notice a body that ends early, and only the file stream carries an END frame that
does. Under StreamHandler the file stream transfers differently:
StreamHandleraddsConnection: close, so each file stream opens a new connection.- container-api sends the response headers only after it has downloaded the input file and run the first query.
timeoutbounds that wait and the connect; without it,default_socket_timeout(60 seconds unless configured) does. Each read of the body is bounded byread_timeoutwhen you set it, and by that same limit otherwise. Under cURL, the sametimeoutlimits the whole transfer of every other request,streamToFile()included, so set it to fit your largest file. connect_timeoutapplies only under cURL, where it defaults to 300 seconds;StreamHandlerignores it.- A timeout that expires while waiting for the response headers surfaces as Guzzle's
ConnectException("Connection refused for URI …"), insideFileStreamTruncated.
The middleware needs allow_url_fopen, which PHP enables by default. With it off, Guzzle ignores the stream option
and buffers the file stream as before.
Writes (streamToFile()) need ext-curl. Without it, Guzzle sends every request through StreamHandler, which reads
the whole request body into memory before sending it and wraps an exception your items generator throws in
FileStreamTruncated.
Client::create() without a client may discover Symfony's Psr18Client, whose response bodies are already lazy.
$containerApi = new \Productsup\CDE\ContainerApi\ContainerApi($client);
foreach ($containerApi->streamFromFile('input') as $item) {
// process the item
}streamFromFile() reads every item of a file in one request. The file is input, or one of the delta files new,
modified, unchanged and deleted. The optional second argument takes two query parameters: show-hidden (bool) adds
the columns whose names start with ___, and classification-id (int) is for CSA export-delta files, for example
streamFromFile('input', ['show-hidden' => true]).
$containerApi = new \Productsup\CDE\ContainerApi\ContainerApi($client);
$containerApi->streamToFile('output', (static function (): \Generator {
yield ['id' => 1, 'name' => 'Item 1', 'size' => 'm'];
yield ['id' => 2, 'name' => 'Item 2', 'description' => 'New fancy item'];
})());streamToFile() writes every item the generator yields to output or feedback in one request. A generator that yields
nothing sends no request.
$containerApi->streamToFile('output', (static function () use ($containerApi): \Generator {
foreach ($containerApi->streamFromFile('input') as $item) {
yield $item + ['processed' => 'yes'];
}
})());The write request sends each item as the generator yields it. With the lazy file stream above, the input is read as it arrives too, so the connector starts on the first item and never keeps a copy of the whole file.
streamFrom(), streamFromInput(), streamTo() and streamToOutput() are deprecated for files: they read and write in
batches of requests. Use streamFromFile() and streamToFile(). A connector whose input or output is a data store keeps
the deprecated methods for it: the file streams answer it with a 400 (FileStreamRejected).
You can log message on different levels. Please check SpecificLogTrait.php
DEBUG level is for internal purpose and is not visible on Platform.
$containerApi = new \Productsup\CDE\ContainerApi\ContainerApi($client);
$containerApi->info('Info message');
$containerApi->error('Error message');use Productsup\CDE\ContainerApi\Exception\FileStreamRejected;
$items = (static function (): \Generator {
yield ['id' => 1, 'name' => 'Item 1'];
})();
try {
$containerApi->streamToFile('output', $items);
} catch (FileStreamRejected $rejection) {
$containerApi->error(\sprintf('The container API rejected the stream (%d): %s', $rejection->status(), $rejection->serverMessage()));
throw $rejection;
}ApiFailureException - Container API answered with an error status (4xx or 5xx). getCode() returns the HTTP status, and getPrevious() returns the cause, which carries the response body: as its message when it is an UnexpectedStatusCodeException, or through its getResponse() when it is one of the generated per-status exceptions, such as ReadInputFileNextBatchBadRequestException. Some methods also throw it when the request did not complete or the answer could not be used.
FileNotFoundException - the file from which we are reading the data does not exist
FileStreamRejected - the container API answered the file stream with an error status (4xx or 5xx) instead of starting
it. status() returns the status and serverMessage() the reason, for example a 400 for a connector whose input or output
is a data store.
FileStreamTruncated - the file stream stopped early: the response ended before its end frame, or the transfer failed or
timed out.
FileStreamFailed - the container API failed while sending the file; serverMessage() returns its message.
FileStreamCorrupted - the response does not follow the file stream format.
The four FileStream* exceptions extend ApiFailureException, so catching it catches them too, but their details come from
their own methods: only FileStreamRejected sets getCode() to the HTTP status, and getPrevious() carries no response
body. FileStreamFailed and FileStreamCorrupted come only from streamFromFile().
BaseClient/ is generated by Jane 7.12.0, with php-cs-fixer 3.95.30 and php-parser 5.9.0 formatting the output. Do not use vendor/bin/jane-openapi: composer.json allows Jane 7.14, whose output differs from the committed BaseClient/ (new exception base classes, additional-properties traits on every model), so a regen with it mixes generator changes into the spec change.
- Get JSON from https://cde.productsup.com/docs/api/#/ContainerApi/show_container_api_version_docs
- Run the generator on the current
/config/container-api.json;git statusmust stay clean, which proves it still reproduces the committed code:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app --entrypoint sh composer:2 -c 'mkdir -p /tmp/jane && composer --working-dir=/tmp/jane require --no-interaction jane-php/open-api-3:7.12.0 jane-php/open-api-common:7.12.0 jane-php/json-schema:7.12.0 jane-php/json-schema-runtime:7.12.0 jane-php/open-api-runtime:7.12.0 friendsofphp/php-cs-fixer:3.95.30 nikic/php-parser:5.9.0 && php /tmp/jane/vendor/bin/jane-openapi generate --config-file=config/client_config.php'The command runs the generator in the public composer:2 image (checked on PHP 8.5.12), with the repository mounted at
/app; it installs the pinned generator in the container's /tmp/jane, leaving your vendor/ alone, and --user keeps
the generated files owned by you. Without Docker, run the part inside the quotes with PHP 8.2 or newer and Composer; PHP
8.2 and 8.5 both reproduce the committed code. Under PHP 8.5, Jane prints deprecation notices about array_key_exists();
they do not change the generated code.
- Update
/config/container-api.jsonfile with latest open-api documentation and run the command again.
Update Productsup\CDE\ContainerApi\ContainerApi if there are changes in filters or endpoints.