3use Psr\Log\LoggerInterface;
95 $params[
'segmentationSize'] = $params[
'segmentationSize'] ?? INF;
96 if ( empty( $params[
'url'] ) ) {
97 throw new InvalidArgumentException(
'URL parameter is required' );
100 if ( empty( $params[
'client'] ) ) {
106 foreach ( [
'caBundlePath',
'proxy' ] as $key ) {
107 if ( isset( $params[$key] ) ) {
108 $clientParams[$key] = $params[$key];
113 $this->client = $params[
'client'];
116 $this->httpParams[
'writeMethod'] = $params[
'httpParams'][
'writeMethod'] ??
'PUT';
117 $this->httpParams[
'readHeaders'] = $params[
'httpParams'][
'readHeaders'] ?? [];
118 $this->httpParams[
'writeHeaders'] = $params[
'httpParams'][
'writeHeaders'] ?? [];
119 $this->httpParams[
'deleteHeaders'] = $params[
'httpParams'][
'deleteHeaders'] ?? [];
120 $this->extendedErrorBodyFields = $params[
'extendedErrorBodyFields'] ?? [];
121 $this->serializationType = $params[
'serialization_type'] ??
'PHP';
122 $this->hmacKey = $params[
'hmac_key'] ??
'';
125 parent::__construct( $params );
128 $this->url = rtrim( $params[
'url'],
'/' ) .
'/';
135 $this->client->setLogger(
$logger );
138 protected function doGet( $key, $flags = 0, &$casToken =
null ) {
139 $getToken = ( $casToken === self::PASS_BY_REF );
144 'url' => $this->url . rawurlencode( $key ),
145 'headers' => $this->httpParams[
'readHeaders'],
150 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
151 if ( $rcode === 200 && is_string( $rbody ) ) {
153 $valueSize = strlen( $rbody );
155 if ( $getToken && $value !==
false ) {
158 } elseif ( $rcode === 0 || ( $rcode >= 400 && $rcode != 404 ) ) {
159 $this->
handleError(
"Failed to fetch $key", $rcode, $rerr, $rhdrs, $rbody );
162 $this->
updateOpStats( self::METRIC_OP_GET, [ $key => [
null, $valueSize ] ] );
167 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
171 'method' => $this->httpParams[
'writeMethod'],
172 'url' => $this->url . rawurlencode( $key ),
174 'headers' => $this->httpParams[
'writeHeaders'],
177 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
178 $res = ( $rcode === 200 || $rcode === 201 || $rcode === 204 );
180 $this->
handleError(
"Failed to store $key", $rcode, $rerr, $rhdrs, $rbody );
183 $this->
updateOpStats( self::METRIC_OP_SET, [ $key => [ strlen( $rbody ),
null ] ] );
188 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
190 if ( $this->
get( $key ) ===
false ) {
191 return $this->
set( $key, $value, $exptime, $flags );
200 'method' =>
'DELETE',
201 'url' => $this->url . rawurlencode( $key ),
202 'headers' => $this->httpParams[
'deleteHeaders'],
205 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
206 $res = in_array( $rcode, [ 200, 204, 205, 404, 410 ] );
208 $this->
handleError(
"Failed to delete $key", $rcode, $rerr, $rhdrs, $rbody );
216 public function incr( $key, $value = 1, $flags = 0 ) {
220 $n = max( $n + (
int)$value, 0 );
222 return $this->
set( $key, $n ) ? $n :
false;
228 public function decr( $key, $value = 1, $flags = 0 ) {
229 return $this->
incr( $key, -$value, $flags );
247 $pieces = explode(
'.', $body, 3 );
248 if ( count( $pieces ) !== 3 || $pieces[0] !== $this->serializationType ) {
252 if ( $this->hmacKey !==
'' ) {
253 $checkHmac = hash_hmac(
'sha256',
$serialized, $this->hmacKey,
true );
254 if ( !hash_equals( $checkHmac, base64_decode( $hmac ) ) ) {
259 switch ( $this->serializationType ) {
262 return ( json_last_error() === JSON_ERROR_NONE ) ? $value :
false;
268 throw new \DomainException(
269 "Unknown serialization type: $this->serializationType"
282 switch ( $this->serializationType ) {
284 $value = json_encode( $body );
285 if ( $value ===
false ) {
286 throw new InvalidArgumentException( __METHOD__ .
": body could not be encoded." );
295 throw new \DomainException(
296 "Unknown serialization type: $this->serializationType"
300 if ( $this->hmacKey !==
'' ) {
301 $hmac = base64_encode(
302 hash_hmac(
'sha256', $value, $this->hmacKey,
true )
307 return $this->serializationType .
'.' . $hmac .
'.' . $value;
318 protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody ) {
319 $message =
"$msg : ({code}) {error}";
325 if ( $this->extendedErrorBodyFields !== [] ) {
329 foreach ( $this->extendedErrorBodyFields as $field ) {
330 if ( isset( $body[$field] ) ) {
331 $extraFields .=
" : ({$field}) {$body[$field]}";
334 if ( $extraFields !==
'' ) {
335 $message .=
" {extra_fields}";
336 $context[
'extra_fields'] = $extraFields;
341 $this->logger->error( $message, $context );
const READ_LATEST
Bitfield constants for get()/getMulti(); these are only advisory.
genericKeyFromComponents(... $components)
At a minimum, there must be a keyspace and collection name component.
string $keyspace
Default keyspace; used by makeKey()
Storage medium specific cache for storing items (e.g.
updateOpStats(string $op, array $keyInfo)
isInteger( $value)
Check if a value is an integer.
setLastError( $err)
Set the "last error" registry.
Class to handle multiple HTTP requests.
Interface to key-value storage behind an HTTP server.
array $httpParams
http parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod
string $serializationType
Optional serialization type to use.
convertGenericKey( $key)
Convert a "generic" reversible cache key into one for this cache.
setLogger(LoggerInterface $logger)
decr( $key, $value=1, $flags=0)
Decrease stored value of $key by $value while preserving its TTL.
const DEFAULT_CONN_TIMEOUT
Default connection timeout in seconds.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
decodeBody( $body)
Processes the response body.
makeKeyInternal( $keyspace, $components)
Make a cache key for the given keyspace and components.
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
const DEFAULT_REQ_TIMEOUT
Default request timeout.
doGet( $key, $flags=0, &$casToken=null)
doDelete( $key, $flags=0)
Delete an item.
array $extendedErrorBodyFields
additional body fields to log on error, if possible
incr( $key, $value=1, $flags=0)
Increase stored value of $key by $value while preserving its TTL.
string $hmacKey
Optional HMAC Key for protecting the serialized blob.
encodeBody( $body)
Prepares the request body (the "value" portion of our key/value store) for transmission.
handleError( $msg, $rcode, $rerr, $rhdrs, $rbody)
Handle storage error.
string $url
REST URL to use for storage.
foreach( $res as $row) $serialized