Skip to content
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

fix(Firestore): Custom Multiple Db routing headers #6475

Merged
merged 9 commits into from
Jul 27, 2023
18 changes: 16 additions & 2 deletions Firestore/src/Connection/Grpc.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ class Grpc implements ConnectionInterface
*/
private $resourcePrefixHeader;

/**
* @var string
*/
private $databaseRoutingHeader;

/**
* @var bool
*/
Expand Down Expand Up @@ -113,10 +118,17 @@ public function __construct(array $config = [])
//@codeCoverageIgnoreEnd

$this->firestore = $this->constructGapic(FirestoreClient::class, $grpcConfig);
$projectId = $this->pluck('projectId', $config);
$databaseId = $this->pluck('database', $config);

$this->resourcePrefixHeader = FirestoreClient::databaseRootName(
$this->pluck('projectId', $config),
$this->pluck('database', $config)
$projectId,
$databaseId
);
$this->databaseRoutingHeader = sprintf(
'project_id=%s&database_id=%s',
$projectId,
$databaseId
);
}

Expand Down Expand Up @@ -301,6 +313,7 @@ private function addRequestHeaders(array $args)
];

$args['headers']['google-cloud-resource-prefix'] = [$this->resourcePrefixHeader];
$args['headers']['x-goog-request-params'] = [$this->databaseRoutingHeader];

// Provide authentication header for requests when emulator is enabled.
if ($this->isUsingEmulator) {
Expand Down Expand Up @@ -339,6 +352,7 @@ public function __debugInfo()
'serializer' => get_class($this->serializer),
'firestore' => get_class($this->firestore),
'resourcePrefixHeader' => $this->resourcePrefixHeader,
'databaseRoutingHeader' => $this->databaseRoutingHeader,
'isUsingEmulator' => $this->isUsingEmulator
];
}
Expand Down
119 changes: 119 additions & 0 deletions Firestore/tests/System/FirestoreMultipleDbTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php
/**
* Copyright 2023 Google LLC
*
* 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\Firestore\Tests\System;

use Google\Cloud\Firestore\FieldPath;
use Google\Cloud\Firestore\Query;

/**
* @group firestore
* @group firestore-multipledb
*/
class FirestoreMultipleDbTest extends FirestoreTestCase
{
private $document;

public function setUp(): void
{
$this->document = self::$multiDbCollection->newDocument();
}

public function testInsert()
{
$this->assertFalse($this->document->snapshot()->exists());

self::$multiDbClient->runTransaction(function ($t) {
$t->create($this->document, [
'foo' => 'bar'
]);
});

$this->assertTrue($this->document->snapshot()->exists());
}

public function testUpdate()
{
$this->document->create([
'foo' => 'bar'
]);

self::$multiDbClient->runTransaction(function ($t) {
$t->update($this->document, [
['path' => 'bat', 'value' => 'baz']
]);
});

$this->assertEquals([
'foo' => 'bar',
'bat' => 'baz'
], $this->document->snapshot()->data());
}


public function testCollectionGroup()
{
// Create a random collection name, but make sure
// it starts with 'b' for predictable ordering.
$collectionGroup = 'b' . uniqid(self::COLLECTION_NAME);
$query = $this->createDocuments([
// following doc paths will match based on the collection group id
'abc/123/%s/cg-doc1',
'abc/123/%s/cg-doc2',
'%s/cg-doc3',
'%s/cg-doc4',
'def/456/%s/cg-doc5',
// following doc paths will NOT match with collection group id
'%s/virtual-doc/nested-coll/not-cg-doc', // nested-coll
'x%s/not-cg-doc', // x-prefix
'%sx/not-cg-doc', // x-suffix
'abc/123/%sx/not-cg-doc', // x-prefix
'abc/123/x%s/not-cg-doc', // x-suffix
'abc/%s', // abc
], $collectionGroup);

vishwarajanand marked this conversation as resolved.
Show resolved Hide resolved
$query = self::$multiDbClient->collectionGroup($collectionGroup);
$documentIds = array_map(
fn($doc) => $doc->id(),
// Returns docs only with matching exact collection group id
$query->documents()->rows()
);
$this->assertEqualsCanonicalizing(
['cg-doc1', 'cg-doc2', 'cg-doc3', 'cg-doc4', 'cg-doc5'],
$documentIds
);
}

private function createDocuments(array $paths, $collectionGroupId)
{
foreach ($paths as &$path) {
$path = sprintf($path, $collectionGroupId);
}
$batch = self::$multiDbClient->bulkWriter();

foreach ($paths as $docpath) {
$doc = self::$multiDbClient->document($docpath);
self::$localDeletionQueue->add($doc);
$batch->set($doc, [
'x' => 1
]);
}

$batch->flush();
self::$localDeletionQueue->add($collectionGroupId);
}
}
10 changes: 9 additions & 1 deletion Firestore/tests/System/FirestoreTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@
class FirestoreTestCase extends SystemTestCase
{
const COLLECTION_NAME = 'system-test';
const TEST_DB_NAME = 'system-tests-named-db';

protected static $client;
protected static $multiDbClient;
protected static $collection;
protected static $multiDbCollection;
protected static $localDeletionQueue;
private static $hasSetUp = false;

Expand All @@ -43,9 +46,14 @@ public static function setUpBeforeClass(): void
self::$client = new FirestoreClient([
'keyFilePath' => $keyFilePath
]);
self::$multiDbClient = new FirestoreClient([
'keyFilePath' => $keyFilePath,
'database' => self::TEST_DB_NAME
]);
self::$collection = self::$client->collection(uniqid(self::COLLECTION_NAME));
self::$multiDbCollection = self::$multiDbClient->collection(uniqid(self::COLLECTION_NAME));
self::$localDeletionQueue->add(self::$collection);

self::$localDeletionQueue->add(self::$multiDbCollection);

self::$hasSetUp = true;
}
Expand Down
3 changes: 2 additions & 1 deletion Firestore/tests/Unit/Connection/GrpcTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,8 @@ private function header()
{
return [
"headers" => [
"google-cloud-resource-prefix" => ["projects/test/databases/(default)"]
"google-cloud-resource-prefix" => ["projects/test/databases/(default)"],
"x-goog-request-params" => ["project_id=test&database_id=(default)"]
]
];
}
Expand Down