Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Storage/src/Connection/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

use Google\Auth\GetUniverseDomainInterface;
use Google\Cloud\Core\RequestBuilder;
use Google\Cloud\Core\RequestWrapper;
use Google\Cloud\Core\RestTrait;
use Google\Cloud\Core\Retry;
use Google\Cloud\Core\Upload\AbstractUploader;
Expand Down Expand Up @@ -141,7 +140,7 @@ public function __construct(array $config = [])

$this->apiEndpoint = $this->getApiEndpoint(null, $config, self::DEFAULT_API_ENDPOINT_TEMPLATE);

$this->setRequestWrapper(new RequestWrapper($config));
$this->setRequestWrapper(new StorageRequestWrapper($config));
$this->setRequestBuilder(new RequestBuilder(
$config['serviceDefinitionPath'],
$this->apiEndpoint
Expand Down
95 changes: 95 additions & 0 deletions Storage/src/Connection/StorageRequestWrapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

/**
* Copyright 2024 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Storage\Connection;

use Google\Cloud\Core\RequestWrapper;
use Psr\Http\Message\RequestInterface;
use Ramsey\Uuid\Uuid;

/**
* A wrapper for requests which adds an Idempotency Token.
*
* @internal
*/
class StorageRequestWrapper extends RequestWrapper
{
/**
* @param RequestInterface $request A PSR-7 request.
* @param array $options [optional]
* @return mixed
*/
public function send(RequestInterface $request, array $options = [])
{
$options = $this->addToken($request, $options);
return parent::send($request, $options);
}

/**
* @param RequestInterface $request A PSR-7 request.
* @param array $options [optional]
* @return mixed
*/
public function sendAsync(RequestInterface $request, array $options = [])
{
$options = $this->addToken($request, $options);
return parent::sendAsync($request, $options);
}

/**
* Helper to inject the token.
*
* @param RequestInterface $request
* @param array $options
* @return array
*/
private function addToken(RequestInterface $request, array $options)
{
$method = strtoupper($request->getMethod());
if ($method === 'GET' || $method === 'HEAD' || $method === 'OPTIONS') {
return $options;
}

$hasTokenInOptions = false;
if (isset($options['restOptions']['headers'])) {
foreach ($options['restOptions']['headers'] as $key => $value) {
if (strtolower($key) === 'x-goog-gcs-idempotency-token') {
$hasTokenInOptions = true;
break;
}
}
}

if (!$hasTokenInOptions && !$request->hasHeader('x-goog-gcs-idempotency-token')) {
$token = Uuid::uuid4()->toString();
if (isset($options['retryHeaders'])) {
foreach ($options['retryHeaders'] as $header) {
if (strpos($header, 'gccl-invocation-id/') === 0) {
$extractedToken = substr($header, 19);
if ($extractedToken !== false && $extractedToken !== '') {
$token = $extractedToken;
}
break;
}
}
}
$options['restOptions']['headers']['x-goog-gcs-idempotency-token'] = $token;
}
return $options;
}
}
125 changes: 100 additions & 25 deletions Storage/tests/System/ManageObjectsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function testListsObjects()
public function testListsObjectsWithMatchGlob()
{
$bucket = self::createBucket(self::$client, uniqid('matchglob-'));
$objectsToCreate = ["foo/bar", "foo/baz", "foo/foobar", "foobar"];
$objectsToCreate = ['foo/bar', 'foo/baz', 'foo/foobar', 'foobar'];
$matchGlobCases = [
'foo*bar' => ['foobar'],
'foo**bar' => ['foo/bar', 'foo/foobar', 'foobar'],
Expand Down Expand Up @@ -92,8 +92,8 @@ public function testObjectRetentionLockedMode()
]);

// Test create object with object retention enabled
$objectName = "object-retention-lock";
$time = (new \DateTime)->add(
$objectName = 'object-retention-lock';
$time = (new \DateTime())->add(
\DateInterval::createFromDateString('+2 hours')
);
$object = $bucket->upload(self::DATA, [
Expand All @@ -105,7 +105,7 @@ public function testObjectRetentionLockedMode()
]);
$this->assertEquals('Locked', $object->info()['retention']['mode']);

$laterTime = (new \DateTime)->add(
$laterTime = (new \DateTime())->add(
\DateInterval::createFromDateString('+4 hours')
);

Expand Down Expand Up @@ -174,8 +174,8 @@ public function testObjectRetentionUnlockedMode()
$this->assertEquals('Enabled', $bucket->info()['objectRetention']['mode']);

// Test create object with object retention enabled
$objectName = "object-retention-lock";
$expires = (new \DateTime)->add(
$objectName = 'object-retention-lock';
$expires = (new \DateTime())->add(
\DateInterval::createFromDateString('+2 hours')
);
$uploader = $bucket->getStreamableUploader('initial contents', [
Expand Down Expand Up @@ -320,7 +320,7 @@ public function testGetContextsWithServerTime()
$object = $this->createObjectWithContexts($initialContexts);
$info = $object->info();
$this->assertArrayHasKey('contexts', $info);

$context = $info['contexts']['custom'];
$this->assertEquals('temp', $context['temp-key']['value']);
$this->assertArrayHasKey(
Expand Down Expand Up @@ -348,7 +348,7 @@ public function testClearAllExistingContexts()
$this->assertArrayHasKey('contexts', $info);
$this->assertEquals('temp', $info['contexts']['custom']['temp-key']['value']);
$this->assertEquals('to-be-cleared', $info['contexts']['custom']['status']['value']);

$object->update([
'contexts' => null
]);
Expand Down Expand Up @@ -377,13 +377,13 @@ public function testRewriteObjectWithContexts()
'name' => 'override-' . uniqid(),
'contexts' => ['custom' => [$overrideKey => ['value' => $overrideVal]]]
]);

$info = $overridden->info();
$this->assertEquals($overrideVal, $info['contexts']['custom'][$overrideKey]['value']);
$this->assertArrayNotHasKey('tag', $info['contexts']['custom']);
$object->delete();
}

public function testOverrideContextsDuringCopy()
{
$initialContexts = [
Expand Down Expand Up @@ -414,7 +414,7 @@ public function testComposeObjectWithOverrideAndInheritContexts()
'tag' => ['value' => 'file1'],
],
];

$source1 = $this->createObjectWithContexts($initialContexts);
$bucket = self::$client->bucket($source1->info()['bucket']);
$s2Key = 's2-key';
Expand Down Expand Up @@ -464,7 +464,7 @@ public function testListObjectsWithContextFilters()
$noneFile = $bucket->upload('content', [
'name' => 'test-none.txt'
]);

// Should list all objects matching a prefix
$objects = iterator_to_array($bucket->objects());
$this->assertCount(3, $objects);
Expand Down Expand Up @@ -542,6 +542,81 @@ public function testUploadAsync()
$this->assertInstanceOf(StorageObject::class, $resp);
}

public function testIdempotencyTokenRetries()
{
$name = uniqid(self::TESTING_PREFIX);
$object = self::$bucket->upload('test data', [
'name' => $name
]);

$uuid = \Ramsey\Uuid\Uuid::uuid4()->toString();

// First delete will succeed
$object->delete([
'restOptions' => [
'headers' => [
'x-goog-gcs-idempotency-token' => $uuid
]
]
]);

// Second delete uses the exact same UUID, simulating a network retry.
// It should NOT throw a NotFoundException because the GCS backend
// will recognize the token and return the cached success response.
$object->delete([
'restOptions' => [
'headers' => [
'x-goog-gcs-idempotency-token' => $uuid
]
]
]);

$this->assertFalse($object->exists());
}

public function testIdempotencyTokenUpdateRetriesWithPrecondition()
{
$name = uniqid(self::TESTING_PREFIX);
$object = self::$bucket->upload('test data', [
'name' => $name
]);

$info = $object->info();
$metageneration = $info['metageneration'];

$uuid = \Ramsey\Uuid\Uuid::uuid4()->toString();

$metadata = [
'metadata' => [
'location' => 'test'
]
];

// First update will succeed and increment the metageneration
$object->update($metadata, [
'ifMetagenerationMatch' => $metageneration,
'restOptions' => [
'headers' => [
'x-goog-gcs-idempotency-token' => $uuid
]
]
]);

// Second update uses the exact same UUID, simulating a network retry.
// Even though the metageneration has changed, the backend recognizes
// the idempotency token and returns 200 OK instead of 412 Precondition Failed.

@gurusai-voleti gurusai-voleti Jul 20, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ensure the idempotency token is resused in retry, don't change anyother header, add the scenario in unit tests

@salilg-eng salilg-eng Jul 23, 2026

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I push the new test case please look.

  • The exact same x-goog-gcs-idempotency-token UUID is reused on the second retry attempt.
  • No other custom headers (e.g., Content-Type, X-Custom-Header) are stripped, modified, or overwritten during the retry process.

$object->update($metadata, [
'ifMetagenerationMatch' => $metageneration,
'restOptions' => [
'headers' => [
'x-goog-gcs-idempotency-token' => $uuid
]
]
]);

$this->assertEquals('test', $object->info()['metadata']['location']);
}

public function testUpdateObject()
{
$metadata = [
Expand Down Expand Up @@ -677,7 +752,7 @@ public function testComposeObjectsWithDeleteSourceObjectsNull()

public function testSoftDeleteObject()
{
$softDeleteBucketName = "soft-delete-bucket-" . uniqid();
$softDeleteBucketName = 'soft-delete-bucket-' . uniqid();
$softDeleteBucket = self::createBucket(
self::$client,
$softDeleteBucketName,
Expand Down Expand Up @@ -706,14 +781,14 @@ public function testSoftDeleteObject()

public function testSoftDeleteHNSObject()
{
$softDeleteBucketName = "soft-delete-hns-bucket-" . uniqid();
$softDeleteBucketName = 'soft-delete-hns-bucket-' . uniqid();
$softDeleteHNSBucket = self::createBucket(
self::$client,
$softDeleteBucketName,
[
'location' => 'us-west1',
'softDeletePolicy' => ['retentionDurationSeconds' => 8 * 24 * 60 * 60],
'hierarchicalNamespace' => ['enabled' => true,],
'hierarchicalNamespace' => ['enabled' => true, ],
'iamConfiguration' => ['uniformBucketLevelAccess' => ['enabled' => true]]
]
);
Expand Down Expand Up @@ -750,7 +825,7 @@ public function testSoftDeleteHNSObject()
*/
public function testMoveObject(bool $hnEnabled)
{
$name = "move-object-bucket-" . uniqid();
$name = 'move-object-bucket-' . uniqid();
$sourceObjectName = uniqid(self::TESTING_PREFIX);
$destinationObjectName = uniqid(self::TESTING_PREFIX);
$sourceBucket = self::createBucket(
Expand Down Expand Up @@ -898,8 +973,8 @@ public function testStringNormalization()
$bucket = self::$client->bucket(self::NORMALIZATION_TEST_BUCKET);

$cases = [
["Caf\xC3\xA9", "Normalization Form C"],
["Cafe\xCC\x81", "Normalization Form D"],
["Caf\xC3\xA9", 'Normalization Form C'],
["Cafe\xCC\x81", 'Normalization Form D'],
];

foreach ($cases as list($name, $expectedContent)) {
Expand All @@ -913,7 +988,7 @@ public function testStringNormalization()
public function testDownloadsWithDefaultCrc32cValidationSuccess()
{
$object = self::$bucket->upload('system-test-data', ['name' => uniqid(self::TESTING_PREFIX)]);

// Automatic CRC32C validation runs under the hood
$content = $object->downloadAsString();
$this->assertEquals('system-test-data', $content);
Expand All @@ -924,7 +999,7 @@ public function testDownloadsWithDefaultCrc32cValidationSuccess()
public function testDownloadsWithExplicitMd5ValidationSuccess()
{
$object = self::$bucket->upload('system-test-data', ['name' => uniqid(self::TESTING_PREFIX)]);

// Explicitly opt-in to MD5 validation
$content = $object->downloadAsString(['validate' => 'md5']);
$this->assertEquals('system-test-data', $content);
Expand All @@ -935,7 +1010,7 @@ public function testDownloadsWithExplicitMd5ValidationSuccess()
public function testDownloadsWithValidationDisabledSuccess()
{
$object = self::$bucket->upload('system-test-data', ['name' => uniqid(self::TESTING_PREFIX)]);

// Explicitly disable validation
$content = $object->downloadAsString(['validate' => false]);
$this->assertEquals('system-test-data', $content);
Expand All @@ -947,7 +1022,7 @@ public function testDownloadsWithRangeBypassesValidation()
{
$data = 'system-test-range-data';
$object = self::$bucket->upload($data, ['name' => uniqid(self::TESTING_PREFIX)]);

// Default validate is 'crc32', but we pass a Range header inside restOptions.
// This should successfully download the slice 'system' without throwing a mismatch exception.
$content = $object->downloadAsString([
Expand All @@ -966,12 +1041,12 @@ public function testDownloadToFileWithDefaultValidationSuccess()
{
$data = 'system-test-to-file-data';
$object = self::$bucket->upload($data, ['name' => uniqid(self::TESTING_PREFIX)]);

$tempFile = tempnam(sys_get_temp_dir(), 'gcs-test');
$object->downloadToFile($tempFile);

$this->assertEquals($data, file_get_contents($tempFile));

unlink($tempFile);
$object->delete();
}
Expand Down
Loading
Loading