Merge branch 'main' of https://github.com/appwrite/appwrite into bump-database-7.3.4

This commit is contained in:
fogelito committed 2026-09-03 10:18:13 +03:00
commit cc6b1c5dbc
25 files changed
+879 -58

No files matched your search

+3 -17
View File
@@ -109,20 +109,6 @@ $container->set('authorization', fn () => new Authorization(), []);
$container->set('publisher', fn (Group $pools) => new BrokerPool(publisher: $pools->get('publisher')), ['pools']);
$container->set('publisherDatabases', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherFunctions', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherMigrations', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherMails', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherDeletes', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherMessaging', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherWebhooks', fn (Publisher $publisher) => $publisher, ['publisher']);
$container->set('publisherForAudits', fn (Publisher $publisher) => new AuditPublisher(
$publisher,
new Queue(System::getEnv('_APP_AUDITS_QUEUE_NAME', Event::AUDITS_QUEUE_NAME))
@@ -204,10 +190,10 @@ $container->set('publisherForJobs', fn (Publisher $publisher) => new JobsPublish
new Queue(System::getEnv('_APP_JOBS_QUEUE_NAME', Event::JOBS_QUEUE_NAME))
), ['publisher']);
$container->set('publisherForDatabase', fn (Publisher $publisherDatabases) => new DatabasePublisher(
$publisherDatabases,
$container->set('publisherForDatabase', fn (Publisher $publisher) => new DatabasePublisher(
$publisher,
new Queue(System::getEnv('_APP_DATABASE_QUEUE_NAME', Event::DATABASE_QUEUE_NAME))
), ['publisherDatabases']);
), ['publisher']);
$container->set('publisherForDeletes', fn (Publisher $publisher) => new DeletePublisher(
$publisher,
+4 -4
View File
@@ -672,7 +672,7 @@ return function (Container $context): void {
return;
}, ['user', 'store', 'proofForToken']);
$context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Publisher $publisherFunctions, Publisher $publisherWebhooks, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) {
$context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) {
if ($project->isEmpty() || $project->getId() === 'console') {
return $dbForPlatform;
}
@@ -796,7 +796,7 @@ return function (Container $context): void {
// Clone the queues, to prevent events triggered by the database listener
// from overwriting the events that are supposed to be triggered in the shutdown hook.
$queueForEventsClone = new Event($publisher);
$queueForWebhooks = new Webhook($publisherWebhooks);
$queueForWebhooksClone = clone $queueForWebhooks;
$queueForRealtime = new Realtime();
$database
@@ -811,7 +811,7 @@ return function (Container $context): void {
$response,
$queueForEventsClone->from($queueForEvents),
$publisherForFunctions,
$queueForWebhooks->from($queueForEvents),
$queueForWebhooksClone->from($queueForEvents),
$queueForRealtime->from($queueForEvents)
))
->on(Database::EVENT_DOCUMENT_CREATE, 'purge-function-events-cache', fn ($event, $document) => $functionsEventsCacheListener($event, $document, $project, $database))
@@ -819,7 +819,7 @@ return function (Container $context): void {
->on(Database::EVENT_DOCUMENT_DELETE, 'purge-function-events-cache', fn ($event, $document) => $functionsEventsCacheListener($event, $document, $project, $database));
return $database;
}, ['databaseFactory', 'dbForPlatform', 'project', 'response', 'publisher', 'publisherFunctions', 'publisherWebhooks', 'queueForEvents', 'publisherForFunctions', 'queueForWebhooks', 'queueForRealtime', 'usage', 'request']);
}, ['databaseFactory', 'dbForPlatform', 'project', 'response', 'publisher', 'queueForEvents', 'publisherForFunctions', 'queueForWebhooks', 'queueForRealtime', 'usage', 'request']);
$context->set('schema', function ($utopia, $dbForProject, $authorization) {
+1 -1
View File
@@ -1145,7 +1145,7 @@ services:
environment:
- _APP_ENV
- _APP_WORKERS_NUM=1
- _APP_WORKER_MAX_COROUTINES=1
- _APP_WORKER_MAX_COROUTINES=6
- _APP_WORKER_PER_CORE
- _APP_POOL_ADAPTER
- _APP_OPENSSL_KEY_V1
+2
View File
@@ -30,6 +30,8 @@ final class Audit extends Base
'$id' => $this->project->getId(),
'$sequence' => $this->project->getSequence(),
'database' => $this->project->getAttribute('database', ''),
'teamId' => $this->project->getAttribute('teamId', ''),
'teamInternalId' => $this->project->getAttribute('teamInternalId', ''),
],
'user' => $this->user->getArrayCopy(),
'impersonatorUser' => $this->impersonatorUser->getArrayCopy(),
+3 -2
View File
@@ -11,7 +11,7 @@ use Utopia\Locale\Locale;
class Geo
{
public const CACHE_SIZE = 10_000;
public const CACHE_VALUE_SIZE = 512;
public const CACHE_VALUE_SIZE = 1024;
public function __construct(
private ?Client $client,
@@ -77,7 +77,8 @@ class Geo
'weatherCode' => $record['weatherCode'] ?? null,
'postalCode' => $record['postalCode'] ?? null,
'city' => $record['city']['en'] ?? null,
'state' => $record['subdivision']['en'] ?? $record['subdivisions'][0]['en'] ?? null,
'state' => $record['subdivision']['en'] ?? $record['subdivisions'][0]['en'] ?? $record['subdivisions'][0]['names']['en'] ?? null,
'subdivisions' => $record['subdivisions'] ?? null,
'autonomousSystemNumber' => $autonomousSystemNumber === null ? null : (string) $autonomousSystemNumber,
'autonomousSystemOrganization' => $record['autonomousSystemOrganization'] ?? null,
'connectionType' => $record['connection'] ?? null,
@@ -76,6 +76,7 @@ class Create extends DocumentCreate
new Parameter('documentId', optional: false),
new Parameter('data', optional: false),
new Parameter('permissions', optional: true),
new Parameter('transactionId', optional: true),
]
),
new Method(
@@ -96,6 +97,7 @@ class Create extends DocumentCreate
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documents', optional: false),
new Parameter('transactionId', optional: true),
]
)
])
@@ -70,6 +70,7 @@ class Create extends DocumentCreate
new Parameter('documentId', optional: false),
new Parameter('data', optional: false),
new Parameter('permissions', optional: true),
new Parameter('transactionId', optional: true),
]
),
new Method(
@@ -90,6 +91,7 @@ class Create extends DocumentCreate
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documents', optional: false),
new Parameter('transactionId', optional: true),
]
)
])
@@ -153,7 +153,16 @@ class Create extends Action
$bucket = $dbForProject->getDocument('buckets', $bucketId);
$dbForProject->createCollection('bucket_' . $bucket->getSequence(), $attributes, $indexes, permissions: $permissions, documentSecurity: $fileSecurity);
// The files collection is DDL and cannot share a transaction with the
// document insert above, and its name needs the document's sequence,
// so the document is committed first. A bucket without its collection
// can never hold a file: remove it rather than leave an orphan.
try {
$dbForProject->createCollection('bucket_' . $bucket->getSequence(), $attributes, $indexes, permissions: $permissions, documentSecurity: $fileSecurity);
} catch (\Throwable $th) {
$dbForProject->deleteDocument('buckets', $bucketId);
throw $th;
}
} catch (DuplicateException) {
throw new Exception(Exception::STORAGE_BUCKET_ALREADY_EXISTS);
}
@@ -55,7 +55,7 @@ abstract class Base extends Action
->label('scope', 'public')
->label('error', APP_VIEWS_DIR . '/general/error.phtml')
->param('code', '', new Text(2048, 0), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.', true)
->param('state', '', new Text(2048), 'OAuth2 state. Contains info sent when starting authorization flow.', true)
->param('state', '', new Text(4096, 0), 'OAuth2 state. Contains info sent when starting authorization flow.', true)
->inject('response')
->inject('dbForPlatform')
->inject('platform')
@@ -104,9 +104,8 @@ abstract class Base extends Action
'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations",
];
$state = \array_merge($defaultState, $state);
$redirectSuccess = $state['success'] ?? '';
$redirectFailure = $state['failure'] ?? '';
$redirectSuccess = empty($state['success']) ? $defaultState['success'] : $state['success'];
$redirectFailure = empty($state['failure']) ? $defaultState['failure'] : $state['failure'];
if (empty($code)) {
$this->failure($response, $redirectFailure, 'OAuth2 authorization code is missing.');
@@ -38,7 +38,7 @@ class Get extends Action
->label('error', APP_VIEWS_DIR . '/general/error.phtml')
->param('installation_id', '', new Text(256, 0), 'GitHub installation ID', true)
->param('setup_action', '', new Text(256, 0), 'GitHub setup action type', true)
->param('state', '', new Text(2048), 'GitHub state. Contains info sent when starting authorization flow.', true)
->param('state', '', new Text(4096, 0), 'GitHub state. Contains info sent when starting authorization flow.', true)
->param('code', '', new Text(2048, 0), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.', true)
->inject('vcsFactory')
->inject('project')
@@ -60,11 +60,10 @@ class Get extends Action
array $platform
) {
if (empty($state)) {
$error = 'Installation requests from organisation members for the Appwrite GitHub App are currently unsupported. To proceed with the installation, login to the Appwrite Console and install the GitHub App.';
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, $error);
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'This installation was completed on GitHub, so it could not be connected to a project. Open your project\'s settings in the Appwrite Console and connect GitHub from there.');
}
$state = \json_decode($state, true);
$state = \json_decode($state, true) ?? [];
$redirectFailure = $state['failure'] ?? '';
$projectId = $state['projectId'] ?? '';
@@ -74,7 +73,7 @@ class Get extends Action
$error = 'Project with the ID from state could not be found.';
if (!empty($redirectFailure)) {
$separator = \str_contains($redirectFailure, '?') ? '&' : ':';
$separator = \str_contains($redirectFailure, '?') ? '&' : '?';
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Pragma', 'no-cache')
@@ -94,10 +93,8 @@ class Get extends Action
'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations",
];
$state = \array_merge($defaultState, $state ?? []);
$redirectSuccess = $state['success'] ?? '';
$redirectFailure = $state['failure'] ?? '';
$redirectSuccess = empty($state['success']) ? $defaultState['success'] : $state['success'];
$redirectFailure = empty($state['failure']) ? $defaultState['failure'] : $state['failure'];
// Create / Update installation
if (!empty($providerInstallationId)) {
@@ -165,10 +162,19 @@ class Get extends Action
]));
}
} else {
$error = 'Installation of the Appwrite GitHub App on organization accounts is restricted to organization owners. As a member of the organization, you do not have the necessary permissions to install this GitHub App. Please contact the organization owner to create the installation from the Appwrite console.';
// GitHub sends setup_action=install on a completed installation,
// update from the app's Configure page, and request when a member
// asked the owners for approval. install and update should always
// carry an installation_id, so without one they mean the caller
// lacked permission to install.
$error = match ($setupAction) {
'request' => 'Your request was sent to the organization owners. An owner must complete the installation from the Appwrite Console; approving the request on GitHub is not enough.',
'install', 'update', '' => 'Installation of the Appwrite GitHub App on organization accounts is restricted to organization owners. As a member of the organization, you do not have the necessary permissions to install this GitHub App. Please contact the organization owner to create the installation from the Appwrite Console.',
default => 'Unexpected setup action "' . $setupAction . '" received from GitHub. Please restart the installation from the Appwrite Console.',
};
if (!empty($redirectFailure)) {
$separator = \str_contains($redirectFailure, '?') ? '&' : ':';
$separator = \str_contains($redirectFailure, '?') ? '&' : '?';
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Pragma', 'no-cache')
@@ -59,6 +59,7 @@ class XList extends Action
->inject('installationTokens')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -70,7 +71,8 @@ class XList extends Action
VcsFactory $vcsFactory,
InstallationTokens $installationTokens,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
try {
$queries = Query::parseQueries($queries);
@@ -84,6 +86,10 @@ class XList extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$vcs = $vcsFactory->fromInstallation($installation);
@@ -55,6 +55,7 @@ class Get extends Action
->inject('installationTokens')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -66,7 +67,8 @@ class Get extends Action
VcsFactory $vcsFactory,
InstallationTokens $installationTokens,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
$installation = $dbForPlatform->getDocument('installations', $installationId);
@@ -74,6 +76,10 @@ class Get extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$vcs = $vcsFactory->fromInstallation($installation);
@@ -57,6 +57,7 @@ class Create extends Action
->inject('user')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -69,7 +70,8 @@ class Create extends Action
InstallationTokens $installationTokens,
Document $user,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
$installation = $dbForPlatform->getDocument('installations', $installationId);
@@ -77,6 +79,10 @@ class Create extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$provider = $installation->getAttribute('provider', 'github');
if ($installation->getAttribute('personal', false) === true) {
@@ -98,6 +98,7 @@ class Create extends Action
->inject('installationTokens')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -109,7 +110,8 @@ class Create extends Action
VcsFactory $vcsFactory,
InstallationTokens $installationTokens,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
$installation = $dbForPlatform->getDocument('installations', $installationId);
@@ -117,6 +119,10 @@ class Create extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$vcs = $vcsFactory->fromInstallation($installation);
@@ -53,6 +53,7 @@ class Get extends Action
->inject('installationTokens')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -62,7 +63,8 @@ class Get extends Action
VcsFactory $vcsFactory,
InstallationTokens $installationTokens,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
$installation = $dbForPlatform->getDocument('installations', $installationId);
@@ -70,6 +72,10 @@ class Get extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$vcs = $vcsFactory->fromInstallation($installation);
@@ -100,6 +100,7 @@ class XList extends Action
->inject('installationTokens')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->callback($this->action(...));
}
@@ -111,7 +112,8 @@ class XList extends Action
VcsFactory $vcsFactory,
InstallationTokens $installationTokens,
Response $response,
Database $dbForPlatform
Database $dbForPlatform,
Document $project
) {
if (empty($search)) {
$search = "";
@@ -123,6 +125,10 @@ class XList extends Action
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
if ($installation->getAttribute('projectInternalId') !== $project->getSequence()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$vcs = $vcsFactory->fromInstallation($installation);
@@ -37,7 +37,7 @@ class Get extends Action
->label('error', APP_VIEWS_DIR . '/general/error.phtml')
->param('installation_id', '', new Text(256, 0), 'Origin installation ID', true)
->param('installation_receipt', '', new Text(8192, 0), 'Origin installation receipt JWT, signed by Cursor.', true)
->param('state', '', new Text(2048, 0), 'Origin state. Contains info sent when starting the installation flow.', true)
->param('state', '', new Text(4096, 0), 'Origin state. Contains info sent when starting the installation flow.', true)
->inject('response')
->inject('dbForPlatform')
->inject('platform')
@@ -731,9 +731,9 @@ class OpenAPI3 extends Format
$node['schema']['format'] = 'url';
$node['schema']['example'] = ($param['example'] ?? '') !== '' ? $param['example'] : 'https://example.com';
break;
case \Utopia\Validator\JSON::class:
case \Utopia\Validator\JSON\ObjectValidator::class:
case \Utopia\Validator\Assoc::class:
// Assoc reports TYPE_ARRAY, so only an explicit case publishes
// it as an object. TYPE_OBJECT is handled by the default.
$node['schema']['type'] = 'object';
$node['schema']['default'] = (empty($param['default'])) ? new \stdClass() : $param['default'];
$node['schema']['example'] = ($param['example'] ?? '') !== '' ? $param['example'] : '{}';
@@ -943,6 +943,13 @@ class OpenAPI3 extends Format
}
break;
default:
if ($validator->getType() === Validator::TYPE_OBJECT) {
$node['schema']['type'] = 'object';
$node['schema']['default'] = empty($param['default']) ? new \stdClass() : $param['default'];
$node['schema']['example'] = ($param['example'] ?? '') !== '' ? $param['example'] : '{}';
break;
}
$node['schema']['type'] = 'string';
if (($param['example'] ?? '') !== '') {
$node['schema']['example'] = $param['example'];
@@ -177,6 +177,12 @@ class Operation extends Validator
$this->description = "Key 'queries' must be an array for {$action}";
return false;
}
foreach ($value['data']['queries'] as $query) {
if (!\is_string($query)) {
$this->description = "Key 'data.queries' must contain only strings for {$action}";
return false;
}
}
}
// BulkUpdate requires both queries and data
+1
View File
@@ -255,6 +255,7 @@ trait ProjectCustom
return [
'$id' => $project['body']['$id'],
'name' => $project['body']['name'],
'region' => $project['body']['region'],
'apiKey' => $key['body']['secret'],
'webhookId' => $webhook['body']['$id'],
'signatureKey' => $webhook['body']['secret'],
@@ -1785,6 +1785,26 @@ trait TransactionsBase
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertEquals('Created via normal route', $response['body']['name']);
/**
* Test for FAILURE
*/
$unknown = $this->client->call(Client::METHOD_POST, $this->getRecordUrl($databaseId, $collectionId, null), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
$this->getRecordIdParam() => 'doc_unknown_txn',
'data' => [
'name' => 'Unknown transaction',
'counter' => 1,
'category' => 'test'
],
'transactionId' => ID::unique()
]);
$this->assertEquals(404, $unknown['headers']['status-code']);
$this->assertEquals(Exception::TRANSACTION_NOT_FOUND, $unknown['body']['type']);
}
/**
@@ -2267,6 +2287,27 @@ trait TransactionsBase
$this->assertEquals("Bulk created {$i}", $response['body']['name']);
$this->assertEquals('bulk_created', $response['body']['category']);
}
/**
* Test for FAILURE
*/
$unknown = $this->client->call(Client::METHOD_POST, $this->getRecordUrl($databaseId, $collectionId, null), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
$this->getRecordResource() => [
[
'$id' => 'bulk_unknown_txn',
'name' => 'Unknown transaction',
'category' => 'bulk_unknown'
]
],
'transactionId' => ID::unique()
]);
$this->assertEquals(404, $unknown['headers']['status-code']);
$this->assertEquals(Exception::TRANSACTION_NOT_FOUND, $unknown['body']['type']);
}
/**
@@ -2668,6 +2709,128 @@ trait TransactionsBase
$this->assertEquals(0, $response['body']['total']);
}
/**
* Reject bulkUpdate/bulkDelete with decoded query arrays.
*/
public function testCreateBulkOperationsWithArrayQueries(): void
{
// Test for FAILURE
$database = $this->client->call(Client::METHOD_POST, $this->getDatabaseUrl(), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'databaseId' => ID::unique(),
'name' => 'BulkArrayQueriesTestDB'
]);
$databaseId = $database['body']['$id'];
$collection = $this->client->call(Client::METHOD_POST, $this->getContainerUrl($databaseId), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
$this->getContainerIdParam() => ID::unique(),
'name' => 'TestCollection',
'permissions' => [
Permission::create(Role::any()),
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
]);
$collectionId = $collection['body']['$id'];
if ($this->getSupportForAttributes()) {
$this->client->call(Client::METHOD_POST, $this->getSchemaUrl($databaseId, $collectionId, "string", null), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'key' => 'name',
'size' => 256,
'required' => true,
]);
$this->client->call(Client::METHOD_POST, $this->getSchemaUrl($databaseId, $collectionId, "string", null), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'key' => 'category',
'size' => 256,
'required' => false,
]);
$this->waitForAllAttributes($databaseId, $collectionId);
}
foreach (['keep_1', 'keep_2', 'drop_1', 'drop_2'] as $id) {
$category = \str_starts_with($id, 'keep') ? 'keep' : 'drop';
$this->client->call(Client::METHOD_POST, $this->getRecordUrl($databaseId, $collectionId, null), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
$this->getRecordIdParam() => $id,
'data' => [
'name' => $id,
'category' => $category,
]
]);
}
$transaction = $this->client->call(Client::METHOD_POST, $this->getTransactionUrl(), array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()));
$this->assertEquals(201, $transaction['headers']['status-code']);
$transactionId = $transaction['body']['$id'];
$response = $this->client->call(Client::METHOD_POST, $this->getTransactionUrl($transactionId) . "/operations", array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'operations' => [
[
'databaseId' => $databaseId,
$this->getContainerIdParam() => $collectionId,
'action' => 'bulkUpdate',
'data' => [
'queries' => [Query::equal('category', ['keep'])->toArray()],
'data' => ['name' => 'updated'],
],
],
]
]);
$this->assertEquals(400, $response['headers']['status-code']);
$this->assertEquals('general_argument_invalid', $response['body']['type']);
$response = $this->client->call(Client::METHOD_POST, $this->getTransactionUrl($transactionId) . "/operations", array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'operations' => [
[
'databaseId' => $databaseId,
$this->getContainerIdParam() => $collectionId,
'action' => 'bulkDelete',
'data' => [
'queries' => [Query::equal('category', ['drop'])->toArray()],
],
],
]
]);
$this->assertEquals(400, $response['headers']['status-code']);
$this->assertEquals('general_argument_invalid', $response['body']['type']);
}
/**
* Test multiple single route operations in one transaction
*/
@@ -2,6 +2,7 @@
namespace Tests\E2E\Services\Databases\VectorsDB\Transactions;
use Appwrite\Extend\Exception;
use Tests\E2E\Client;
use Utopia\Database\Database;
use Utopia\Database\Helpers\ID;
@@ -1489,6 +1490,27 @@ trait TransactionsBase
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertEquals('Created via normal route', $response['body']['metadata']['name']);
/**
* Test for FAILURE
*/
$unknown = $this->client->call(Client::METHOD_POST, "/vectorsdb/{$databaseId}/collections/{$collectionId}/documents", array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'documentId' => 'doc_unknown_txn',
'data' => [
'embeddings' => $this->generateEmbeddings(3),
'metadata' => [
'name' => 'Unknown transaction',
]
],
'transactionId' => ID::unique()
]);
$this->assertEquals(404, $unknown['headers']['status-code']);
$this->assertEquals(Exception::TRANSACTION_NOT_FOUND, $unknown['body']['type']);
}
/**
@@ -1933,6 +1955,29 @@ trait TransactionsBase
$this->assertEquals("Bulk created {$i}", $response['body']['metadata']['name']);
$this->assertEquals('bulk_created', $response['body']['metadata']['category']);
}
/**
* Test for FAILURE
*/
$unknown = $this->client->call(Client::METHOD_POST, "/vectorsdb/{$databaseId}/collections/{$collectionId}/documents", array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'x-appwrite-key' => $this->getProject()['apiKey']
]), [
'documents' => [
[
'$id' => 'bulk_unknown_txn',
'embeddings' => $this->generateEmbeddings(3),
'metadata' => [
'name' => 'Unknown transaction',
]
]
],
'transactionId' => ID::unique()
]);
$this->assertEquals(404, $unknown['headers']['status-code']);
$this->assertEquals(Exception::TRANSACTION_NOT_FOUND, $unknown['body']['type']);
}
/**
@@ -22,6 +22,7 @@ final class VCSGiteaConsoleClientTest extends Scope
// Admin user created by gitea-bootstrap (docker-compose.override.yml, `gitea` profile)
private const GITEA_USERNAME = 'appwrite';
private const GITEA_PASSWORD = 'password';
private const GITEA_USERNAME_SECOND = 'appwrite2';
private array $giteaCookies = [];
@@ -113,17 +114,24 @@ final class VCSGiteaConsoleClientTest extends Scope
* Walk the full OAuth2 dance against the local Gitea and return the
* resulting installation, asserting every hop on the way.
*/
private function createInstallationHelper(): array
private function createInstallationHelper(?string $projectId = null, ?array $headers = null, string $username = self::GITEA_USERNAME, string $password = self::GITEA_PASSWORD, bool $redirects = true): array
{
$projectId = $this->getProject()['$id'];
$consoleUrl = 'http://localhost/console/project-default-' . $projectId . '/settings/git-installations';
$projectId ??= $this->getProject()['$id'];
$headers ??= $this->getHeaders();
// Each dance starts from a fresh jar; Gitea reuses session cookies, so
// a stale jar would silently keep the previous user logged in.
/** @var array<string, string> $cookies */
$cookies = [];
$this->giteaCookies = $cookies;
$consoleUrl = $this->gitInstallationsUrl($projectId);
$authorize = $this->client->call(Client::METHOD_GET, '/vcs/gitea/authorize', \array_merge([
'x-appwrite-project' => $projectId,
], $this->getHeaders()), [
], $headers), $redirects ? [
'success' => $consoleUrl,
'failure' => $consoleUrl,
], true, false);
] : [], true, false);
$this->assertEquals(301, $authorize['headers']['status-code']);
@@ -146,8 +154,8 @@ final class VCSGiteaConsoleClientTest extends Scope
$login = $this->giteaCallHelper($gitea, Client::METHOD_POST, '/user/login', [
'_csrf' => $this->giteaCookies['_csrf'],
'user_name' => self::GITEA_USERNAME,
'password' => self::GITEA_PASSWORD,
'user_name' => $username,
'password' => $password,
]);
$this->assertContains($login['headers']['status-code'], [302, 303], 'Gitea login failed.');
$this->assertNotEmpty($this->giteaCookies['i_like_gitea'] ?? '', 'Gitea did not issue a session cookie.');
@@ -184,7 +192,7 @@ final class VCSGiteaConsoleClientTest extends Scope
$callback = $this->client->call(Client::METHOD_GET, '/vcs/gitea/callback', \array_merge([
'x-appwrite-project' => $projectId,
], $this->getHeaders()), [
], $headers), [
'code' => $callbackQuery['code'],
'state' => $callbackQuery['state'],
], true, false);
@@ -194,7 +202,7 @@ final class VCSGiteaConsoleClientTest extends Scope
$installations = $this->client->call(Client::METHOD_GET, '/vcs/installations', \array_merge([
'x-appwrite-project' => $projectId,
], $this->getHeaders()));
], $headers));
$this->assertEquals(200, $installations['headers']['status-code']);
$this->assertGreaterThanOrEqual(1, $installations['body']['total']);
@@ -329,4 +337,393 @@ final class VCSGiteaConsoleClientTest extends Scope
$this->assertEquals('completed', $execution['body']['status'] ?? '', \json_encode($execution['body']));
$this->assertEquals($output, $execution['body']['responseBody'] ?? '');
}
private function buildGiteaState(string $projectId, string $success, string $failure): string
{
return (string) \json_encode([
'projectId' => $projectId,
'success' => $success,
'failure' => $failure,
'signature' => \hash_hmac('sha256', \json_encode([$projectId, $success, $failure]), System::getEnv('_APP_OPENSSL_KEY_V1', '')),
]);
}
/**
* @param array<string, string> $params
* @return array<string, mixed>
*/
private function callGiteaCallbackHelper(array $params): array
{
return $this->client->call(Client::METHOD_GET, '/vcs/gitea/callback', \array_merge([
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), $params, true, false);
}
public function testCreateInstallationWithoutState(): void
{
$response = $this->callGiteaCallbackHelper(['code' => 'unused']);
$this->assertEquals(400, $response['headers']['status-code']);
}
public function testCreateInstallationWithEmptyState(): void
{
$response = $this->callGiteaCallbackHelper(['code' => 'unused', 'state' => '']);
$this->assertEquals(400, $response['headers']['status-code']);
}
public function testCreateInstallationWithTamperedState(): void
{
$projectId = $this->getProject()['$id'];
$consoleUrl = $this->gitInstallationsUrl($projectId);
$state = \json_decode($this->buildGiteaState($projectId, $consoleUrl, $consoleUrl), true);
$state['projectId'] = 'victim-project';
$response = $this->callGiteaCallbackHelper([
'code' => 'unused',
'state' => (string) \json_encode($state),
]);
$this->assertEquals(400, $response['headers']['status-code']);
}
public function testCreateInstallationWithoutCode(): void
{
$projectId = $this->getProject()['$id'];
$consoleUrl = $this->gitInstallationsUrl($projectId);
// Signed state, no code: the failure redirect carries the error as a query string
$response = $this->callGiteaCallbackHelper([
'state' => $this->buildGiteaState($projectId, $consoleUrl, $consoleUrl),
]);
$this->assertEquals(301, $response['headers']['status-code']);
$this->assertStringStartsWith($consoleUrl . '?error=', (string) $response['headers']['location']);
}
public function testCreateInstallationWithEmptyRedirects(): void
{
$projectId = $this->getProject()['$id'];
// Authorize signs empty redirect URLs when none were given, so the
// callback has to fall back to the computed console URL instead of
// redirecting nowhere.
$response = $this->callGiteaCallbackHelper([
'state' => $this->buildGiteaState($projectId, '', ''),
]);
$this->assertEquals(301, $response['headers']['status-code']);
$this->assertStringStartsWith($this->gitInstallationsUrl($projectId) . '?error=', (string) $response['headers']['location']);
}
public function testCreateInstallationWithInvalidState(): void
{
$response = $this->callGiteaCallbackHelper(['code' => 'unused', 'state' => 'not-json']);
$this->assertEquals(400, $response['headers']['status-code']);
}
public function testCreateInstallationWithUnknownProject(): void
{
$consoleUrl = $this->gitInstallationsUrl('missing');
$response = $this->callGiteaCallbackHelper([
'code' => 'unused',
'state' => $this->buildGiteaState('missing-project', $consoleUrl, $consoleUrl),
]);
$this->assertEquals(301, $response['headers']['status-code']);
$this->assertStringStartsWith($consoleUrl . '?error=', (string) $response['headers']['location']);
}
public function testCreateInstallationWithLongState(): void
{
$projectId = $this->getProject()['$id'];
$consoleUrl = $this->gitInstallationsUrl($projectId);
// Past the old 2048 cap: redirect URLs are not length-limited, so the
// authorize endpoint can produce a state this size itself.
$failure = $consoleUrl . '?pad=' . \str_repeat('a', 2400);
$response = $this->callGiteaCallbackHelper([
'state' => $this->buildGiteaState($projectId, $consoleUrl, $failure),
]);
$this->assertEquals(301, $response['headers']['status-code']);
$this->assertStringStartsWith($failure, (string) $response['headers']['location']);
}
public function testCreateInstallationWithoutRedirects(): void
{
// Authorize signs empty success and failure URLs when none are given;
// the helper asserts the callback still lands on the console default
// rather than redirecting to an empty location.
$installation = $this->createInstallationHelper(redirects: false);
$this->assertNotEmpty($installation['$id']);
}
/**
* The callback builds its fallback redirect from the project's region, so the
* expected URL follows the region the scope's project was created in: Cloud
* CI creates projects in a region other than default.
*/
private function gitInstallationsUrl(string $projectId): string
{
$region = $this->getProject()['region'];
return "http://localhost/console/project-{$region}-{$projectId}/settings/git-installations";
}
/**
* @return array{userId: string, email: string, session: string, teamId: string, projectId: string, headers: array<string, string>}
*/
private function createTenantHelper(): array
{
$email = \uniqid('tenant-', true) . \getmypid() . \bin2hex(\random_bytes(4)) . '@localhost.test';
$password = 'password';
$user = $this->client->call(Client::METHOD_POST, '/account', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
], [
'userId' => ID::unique(),
'email' => $email,
'password' => $password,
'name' => 'VCS Tenant',
]);
$this->assertEquals(201, $user['headers']['status-code']);
$session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
], [
'email' => $email,
'password' => $password,
]);
$this->assertEquals(201, $session['headers']['status-code']);
$sessionCookie = $session['cookies']['a_session_console'];
// Sessions propagate slowly under parallel load, so retry 401s
$team = null;
for ($i = 0; $i < 5; $i++) {
$team = $this->client->call(Client::METHOD_POST, '/teams', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'cookie' => 'a_session_console=' . $sessionCookie,
'x-appwrite-project' => 'console',
], [
'teamId' => ID::unique(),
'name' => 'VCS Tenant Team',
]);
if ($team['headers']['status-code'] !== 401) {
break;
}
\usleep(500000);
}
$this->assertEquals(201, $team['headers']['status-code']);
$project = null;
for ($i = 0; $i < 5; $i++) {
$project = $this->client->call(Client::METHOD_POST, '/projects', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'cookie' => 'a_session_console=' . $sessionCookie,
'x-appwrite-project' => 'console',
], [
'projectId' => ID::unique(),
'region' => System::getEnv('_APP_REGION', 'default'),
'name' => 'VCS Tenant Project',
'teamId' => $team['body']['$id'],
]);
if ($project['headers']['status-code'] !== 401) {
break;
}
\usleep(500000);
}
$this->assertEquals(201, $project['headers']['status-code']);
return [
'userId' => $user['body']['$id'],
'email' => $email,
'session' => $sessionCookie,
'teamId' => $team['body']['$id'],
'projectId' => $project['body']['$id'],
'headers' => [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'cookie' => 'a_session_console=' . $sessionCookie,
'x-appwrite-mode' => 'admin',
],
];
}
private function createGiteaUserHelper(string $username, string $password): void
{
$response = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/admin/users', [
'username' => $username,
'email' => $username . '@localhost.test',
'password' => $password,
// Defaults to true, which redirects the OAuth2 authorize to the change-password page
'must_change_password' => false,
]);
// 422 means the user survived a previous run; the Gitea volume persists.
$this->assertContains($response['headers']['status-code'], [201, 422], \json_encode($response['body']));
}
/**
* @param array{projectId: string, session: string} $tenant
* @return array<string, string>
*/
private function getTenantHeaders(array $tenant, ?string $projectId = null): array
{
return [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'cookie' => 'a_session_console=' . $tenant['session'],
'x-appwrite-mode' => 'admin',
'x-appwrite-project' => $projectId ?? $tenant['projectId'],
];
}
public function testListRepositoriesRejectsForeignInstallation(): void
{
$this->createGiteaUserHelper(self::GITEA_USERNAME_SECOND, self::GITEA_PASSWORD);
$a = $this->createTenantHelper();
$b = $this->createTenantHelper();
$installationA = $this->createInstallationHelper($a['projectId'], $a['headers']);
$installationB = $this->createInstallationHelper($b['projectId'], $b['headers'], self::GITEA_USERNAME_SECOND, self::GITEA_PASSWORD);
$this->assertNotEquals($installationA['$id'], $installationB['$id']);
// Different Gitea accounts make a leak visible as the other owner's repositories
$this->assertNotEquals($installationA['organization'], $installationB['organization']);
// Foreign installation id on the caller's own project never reaches the
// provider: the ownership guard answers before any Gitea call.
$foreign = $this->client->call(Client::METHOD_GET, '/vcs/github/installations/' . $installationA['$id'] . '/providerRepositories', $this->getTenantHeaders($b), [
'type' => 'runtime',
]);
$this->assertEquals(404, $foreign['headers']['status-code']);
$this->assertEquals('installation_not_found', $foreign['body']['type']);
$foreign = $this->client->call(Client::METHOD_GET, '/vcs/github/installations/' . $installationB['$id'] . '/providerRepositories', $this->getTenantHeaders($a), [
'type' => 'runtime',
]);
$this->assertEquals(404, $foreign['headers']['status-code']);
$this->assertEquals('installation_not_found', $foreign['body']['type']);
// Addressing the other tenant's project directly dies earlier, on team
// membership, before any VCS code runs.
$foreignProject = $this->client->call(Client::METHOD_GET, '/vcs/github/installations/' . $installationA['$id'] . '/providerRepositories', $this->getTenantHeaders($b, $a['projectId']), [
'type' => 'runtime',
]);
$this->assertEquals(401, $foreignProject['headers']['status-code']);
$own = $this->client->call(Client::METHOD_GET, '/vcs/github/installations/' . $installationA['$id'] . '/providerRepositories', $this->getTenantHeaders($a), [
'type' => 'runtime',
]);
$this->assertEquals(200, $own['headers']['status-code']);
$own = $this->client->call(Client::METHOD_GET, '/vcs/github/installations/' . $installationB['$id'] . '/providerRepositories', $this->getTenantHeaders($b), [
'type' => 'runtime',
]);
$this->assertEquals(200, $own['headers']['status-code']);
}
public function testRepositoryEndpointsRejectForeignInstallation(): void
{
$a = $this->createTenantHelper();
$b = $this->createTenantHelper();
$installationA = $this->createInstallationHelper($a['projectId'], $a['headers']);
$base = '/vcs/github/installations/' . $installationA['$id'];
// Dummy repository ids are safe: the ownership guard answers before any provider call
$probes = [
[Client::METHOD_GET, $base . '/providerRepositories/1', []],
[Client::METHOD_GET, $base . '/providerRepositories/1/branches', []],
[Client::METHOD_GET, $base . '/providerRepositories/1/contents', []],
[Client::METHOD_POST, $base . '/providerRepositories', ['name' => 'cross-' . \uniqid(), 'private' => true]],
[Client::METHOD_POST, $base . '/detections', ['providerRepositoryId' => '1', 'type' => 'runtime']],
];
foreach ($probes as [$method, $path, $params]) {
$response = $this->client->call($method, $path, $this->getTenantHeaders($b), $params);
$this->assertEquals(404, $response['headers']['status-code'], $method . ' ' . $path);
$this->assertEquals('installation_not_found', $response['body']['type'], $method . ' ' . $path);
}
// On the owning project the guard must pass; whatever the provider
// answers about the dummy repository, it is not installation_not_found.
foreach ($probes as [$method, $path, $params]) {
$response = $this->client->call($method, $path, $this->getTenantHeaders($a), $params);
$this->assertNotEquals('installation_not_found', $response['body']['type'] ?? '', $method . ' ' . $path);
}
}
public function testInvitedMemberCanUseInstallation(): void
{
$a = $this->createTenantHelper();
$b = $this->createTenantHelper();
$installationA = $this->createInstallationHelper($a['projectId'], $a['headers']);
$path = '/vcs/github/installations/' . $installationA['$id'] . '/providerRepositories';
$before = $this->client->call(Client::METHOD_GET, $path, $this->getTenantHeaders($b, $a['projectId']), [
'type' => 'runtime',
]);
$this->assertEquals(401, $before['headers']['status-code']);
$membership = $this->client->call(Client::METHOD_POST, '/teams/' . $a['teamId'] . '/memberships', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
'cookie' => 'a_session_console=' . $a['session'],
], [
'userId' => $b['userId'],
'roles' => ['developer'],
'url' => 'http://localhost:5000/join-us#title',
]);
$this->assertEquals(201, $membership['headers']['status-code']);
$email = $this->getLastEmailByAddress($b['email'], fn ($email) => $this->assertStringContainsString('/join-us', (string) ($email['html'] ?? '')));
$params = $this->extractQueryParamsFromEmailLink($email['html']);
$this->assertNotEmpty($params['secret'] ?? '');
$accept = $this->client->call(Client::METHOD_PATCH, '/teams/' . $a['teamId'] . '/memberships/' . $membership['body']['$id'] . '/status', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
], [
'userId' => $b['userId'],
'secret' => $params['secret'],
]);
$this->assertEquals(200, $accept['headers']['status-code']);
// Membership in the team now authorizes B on project A, where the installation lives
$after = $this->client->call(Client::METHOD_GET, $path, $this->getTenantHeaders($b, $a['projectId']), [
'type' => 'runtime',
]);
$this->assertEquals(200, $after['headers']['status-code']);
// Membership does not launder the installation into B's own project.
$stillForeign = $this->client->call(Client::METHOD_GET, $path, $this->getTenantHeaders($b), [
'type' => 'runtime',
]);
$this->assertEquals(404, $stillForeign['headers']['status-code']);
$this->assertEquals('installation_not_found', $stillForeign['body']['type']);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Geo;
use Appwrite\Geo\Client;
use Appwrite\Geo\Geo;
use PHPUnit\Framework\TestCase;
use Swoole\Table;
use Utopia\Config\Config;
use Utopia\Locale\Locale;
final class GeoTest extends TestCase
{
public function testCachePreservesPremiumGeoAttributes(): void
{
Config::setParam('locale-eu', []);
Config::setParam('locale-currencies', []);
Locale::setLanguageFromArray('en', []);
$client = $this->createMock(Client::class);
$client->expects($this->once())
->method('lookup')
->with('203.0.113.10')
->willReturn([
'countryCode' => 'DE',
'continentCode' => 'EU',
'city' => ['en' => 'Frankfurt'],
'subdivisions' => [
['iso_code' => 'HE', 'names' => ['en' => 'Hesse']],
],
'isp' => 'Example ISP',
]);
$cache = new Table(16);
$cache->column('value', Table::TYPE_STRING, Geo::CACHE_VALUE_SIZE);
$cache->create();
$geo = new Geo($client, new Locale('en'), $cache);
$geo->get('203.0.113.10');
$cached = $geo->get('203.0.113.10');
$this->assertSame('Frankfurt', $cached->getAttribute('city'));
$this->assertSame('Hesse', $cached->getAttribute('subdivisions')[0]['names']['en']);
$this->assertSame('Example ISP', $cached->getAttribute('isp'));
}
}
+111
View File
@@ -2,6 +2,7 @@
namespace Tests\Unit\SDK\Specification;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Parameter;
@@ -1210,4 +1211,114 @@ final class FormatTest extends TestCase
$this->assertSame('example.com', $properties['domain']['example']);
$this->assertSame('FFFFFF', $properties['background']['example']);
}
public function testExplicitMethodParametersAreTheSdkMethodList(): void
{
Method::$processed = [];
Method::$errors = [];
$route = $this->createDocumentsRoute(
createDocument: [
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documentId', optional: false),
new Parameter('data', optional: false),
new Parameter('permissions', optional: true),
new Parameter('transactionId', optional: true),
],
createDocuments: [
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documents', optional: false),
new Parameter('transactionId', optional: true),
],
);
$methods = $this->sdkMethods((new OpenAPI3(new Container(), [], [$route], [], [], 0, 'console'))->parse());
$this->assertContains('transactionId', $methods['createDocument']);
$this->assertContains('transactionId', $methods['createDocuments']);
}
public function testOmittedMethodParametersAreDroppedFromTheSdkMethodList(): void
{
Method::$processed = [];
Method::$errors = [];
$route = $this->createDocumentsRoute(
createDocument: [
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documentId', optional: false),
new Parameter('data', optional: false),
new Parameter('permissions', optional: true),
],
createDocuments: [
new Parameter('databaseId', optional: false),
new Parameter('collectionId', optional: false),
new Parameter('documents', optional: false),
],
);
$methods = $this->sdkMethods((new OpenAPI3(new Container(), [], [$route], [], [], 0, 'console'))->parse());
$this->assertNotContains('transactionId', $methods['createDocument']);
$this->assertNotContains('transactionId', $methods['createDocuments']);
}
/**
* @param list<Parameter> $createDocument
* @param list<Parameter> $createDocuments
*/
private function createDocumentsRoute(array $createDocument, array $createDocuments): Route
{
return (new Route('POST', '/v1/documentsdb/:databaseId/collections/:collectionId/documents'))
->desc('Create document')
->label('sdk', [
new Method(
namespace: 'documentsDB',
group: 'documents',
name: 'createDocument',
description: 'Create document.',
auth: [AuthType::ADMIN],
responses: [],
parameters: $createDocument,
),
new Method(
namespace: 'documentsDB',
group: 'documents',
name: 'createDocuments',
description: 'Create documents.',
auth: [AuthType::ADMIN],
responses: [],
parameters: $createDocuments,
),
])
->param('databaseId', '', new Text(256), 'Database ID.')
->param('collectionId', '', new Text(256), 'Collection ID.')
->param('documentId', '', new Text(256), 'Document ID.', true)
->param('data', [], new JSON(), 'Document data.', true)
->param('permissions', null, new Nullable(new Text(256)), 'Permissions.', true)
->param('documents', [], new JSON(), 'Documents.', true)
->param('transactionId', null, new Nullable(new Text(256)), 'Transaction ID.', true);
}
/**
* @return array<string, list<string>>
*/
private function sdkMethods(array $openApi): array
{
$path = '/documentsdb/{databaseId}/collections/{collectionId}/documents';
$this->assertArrayHasKey($path, $openApi['paths']);
$methods = [];
foreach ($openApi['paths'][$path]['post']['x-appwrite']['methods'] as $method) {
$methods[$method['name']] = $method['parameters'];
}
$this->assertArrayHasKey('createDocument', $methods);
$this->assertArrayHasKey('createDocuments', $methods);
return $methods;
}
}