diff --git a/.agents/skills/self-hosted-release/SKILL.md b/.agents/skills/self-hosted-release/SKILL.md index 989b8f4c1a..b4d955c104 100644 --- a/.agents/skills/self-hosted-release/SKILL.md +++ b/.agents/skills/self-hosted-release/SKILL.md @@ -41,7 +41,7 @@ Build and run the target release with the local Docker Compose stack, then test docker compose down -v docker compose up -d --force-recreate --build --wait docker compose exec -T appwrite vars -curl -fsS http://localhost/v1/health/version +curl -fsS http://localhost:9520/v1/health/version ``` 2. Inspect runtime health before running tests: diff --git a/.env b/.env index 02dafe36ff..edc7bb741a 100644 --- a/.env +++ b/.env @@ -11,6 +11,7 @@ _APP_WORKER_PER_CORE=6 _APP_WORKERS_NUM=1 _APP_WORKER_MAX_COROUTINES=1 _APP_WORKER_SCREENSHOTS_ROUTER=http://appwrite +_APP_REALTIME_TAIL_RATE=50 _APP_COMPRESSION_ENABLED=enabled _APP_COMPRESSION_MIN_SIZE_BYTES=1024 _APP_DOMAIN=appwrite.test @@ -151,5 +152,3 @@ _APP_VCS_GITHUB_CLIENT_SECRET= _APP_VCS_GITHUB_PRIVATE_KEY=disabled _APP_VCS_GITHUB_WEBHOOK_SECRET= _APP_WEBHOOK_MAX_FAILED_ATTEMPTS=10 -_TESTS_OAUTH2_GITHUB_CLIENT_ID= -_TESTS_OAUTH2_GITHUB_CLIENT_SECRET= diff --git a/.github/workflows/benchmark-comment.js b/.github/workflows/benchmark-comment.js index f25116c4f2..bdb0055c60 100644 --- a/.github/workflows/benchmark-comment.js +++ b/.github/workflows/benchmark-comment.js @@ -51,42 +51,37 @@ function buildComment(core) { const baseRef = markdownText(process.env.BENCHMARK_BASE_REF || 'base'); const headRef = markdownText(process.env.BENCHMARK_HEAD_REF || 'head'); const rows = benchmarkRows(before, after, beforeSamples, afterSamples); - const topWaits = topSamples(afterSamples, 'appwrite_api_waiting', 3); + const total = rows[0]; + const topWaits = topSamples(afterSamples, 'appwrite_api_waiting', 5); const lines = [ marker, '## :sparkles: Benchmark results', '', - `Comparing ${baseRef} (before) to ${headRef} (after).`, + `Comparing \`${baseRef}\` (before) → \`${headRef}\` (after).`, '', ]; if (before === null) { - lines.push('> Before benchmark did not complete; showing current branch metrics only.', ''); + lines.push('> :warning: Before benchmark did not complete — change column unavailable.', ''); } if (after === null) { - lines.push('> Current branch benchmark did not complete; showing available metrics only.', ''); + lines.push('> :warning: Current branch benchmark did not complete — showing available metrics only.', ''); } lines.push( - '**Before**', - '', - metricTable(rows, 'before'), - '', - '**After**', - '', - metricTable(rows, 'after'), - '', - '**Delta**', - '', - '| Scenario | P95 delta (ms) |', - '| --- | ---: |', - ...rows.map(deltaRow), + ...headlineTable(total), '', '
', - 'Top API waits', + 'Per-scenario breakdown & investigation details', '', '
', '', + '_Metrics below reflect the current branch (after). Δ P95 compares against the base._', + '', + detailTable(rows), + '', + '**Top API waits (after)**', + '', '| API request | Max wait (ms) |', '| --- | ---: |', ...topWaitRows(topWaits), @@ -97,6 +92,46 @@ function buildComment(core) { return `${lines.join('\n')}\n`; } +function headlineTable(total) { + const { before, after } = total; + return [ + '| Metric | Before | After | Change |', + '| --- | ---: | ---: | :--- |', + `| :rocket: Requests/sec | ${formatRate(before?.rps)} | ${formatRate(after?.rps)} | ${changeCell(before?.rps, after?.rps, false)} |`, + `| :stopwatch: Latency P50 | ${formatMsUnit(before?.p50)} | ${formatMsUnit(after?.p50)} | ${changeCell(before?.p50, after?.p50, true)} |`, + `| :stopwatch: Latency P95 | ${formatMsUnit(before?.p95)} | ${formatMsUnit(after?.p95)} | ${changeCell(before?.p95, after?.p95, true)} |`, + ]; +} + +function changeCell(before, after, lowerIsBetter) { + if (before === null || before === undefined || after === null || after === undefined || Number.isNaN(before) || Number.isNaN(after) || before === 0) { + return 'n/a'; + } + + const percent = Number((((after - before) / before) * 100).toFixed(1)); + const label = code(`${percent > 0 ? '+' : ''}${trimNumber(percent)}%`); + + if (Math.abs(percent) <= 5) { + return `:white_circle: ${label}`; + } + + const improved = lowerIsBetter ? percent < 0 : percent > 0; + return `${improved ? ':green_circle:' : ':red_circle:'} ${label}`; +} + +function detailTable(rows) { + return [ + '| Scenario | P50 (ms) | P95 (ms) | Requests | RPS | Δ P95 (ms) |', + '| --- | ---: | ---: | ---: | ---: | ---: |', + ...rows.map(detailRow), + ].join('\n'); +} + +function detailRow(row) { + const values = row.after; + return `| ${row.label} | ${formatMs(values?.p50)} | ${formatMs(values?.p95)} | ${formatCount(values?.iterations)} | ${formatRate(values?.rps)} | ${formatDelta(row.before?.p95, row.after?.p95)} |`; +} + function readSummary(path, core) { if (!fs.existsSync(path)) { return null; @@ -256,23 +291,6 @@ function metricValue(data, metric, stat) { return metricValues(data, metric)?.[stat] ?? null; } -function metricTable(rows, side) { - return [ - '| Scenario | P50 (ms) | P95 (ms) | Requests | RPS |', - '| --- | ---: | ---: | ---: | ---: |', - ...rows.map((row) => metricRow(row, side)), - ].join('\n'); -} - -function metricRow(row, side) { - const values = row[side]; - return `| ${row.label} | ${formatMs(values?.p50)} | ${formatMs(values?.p95)} | ${formatCount(values?.iterations)} | ${formatRate(values?.rps)} |`; -} - -function deltaRow(row) { - return `| ${row.label} | ${formatDelta(row.before?.p95, row.after?.p95)} |`; -} - function topSamples(samples, metric, limit) { const byName = samples.reduce((result, sample) => { if (sample.metric !== metric || typeof sample.data?.value !== 'number') { @@ -310,11 +328,16 @@ function markdownText(value) { } function formatMs(value) { - return formatNumber(value, 2); + return code(formatNumber(value, 2)); +} + +function formatMsUnit(value) { + const formatted = formatNumber(value, 2); + return formatted === 'n/a' ? formatted : code(`${formatted} ms`); } function formatRate(value) { - return formatNumber(value, 2); + return code(formatNumber(value, 2)); } function formatCount(value) { @@ -322,7 +345,7 @@ function formatCount(value) { return 'n/a'; } - return `${Math.round(value)}`; + return code(Math.round(value).toLocaleString('en-US')); } function formatDelta(before, after) { @@ -331,7 +354,8 @@ function formatDelta(before, after) { } const difference = Number((after - before).toFixed(2)); - return `${difference > 0 ? '+' : ''}${trimNumber(difference)}`; + const sign = difference > 0 ? '+' : difference < 0 ? '-' : ''; + return code(`${sign}${formatNumber(Math.abs(difference), 2)}`); } function formatNumber(value, decimals) { @@ -339,7 +363,14 @@ function formatNumber(value, decimals) { return 'n/a'; } - return trimNumber(Number(value).toFixed(decimals)); + return trimNumber(Number(value).toLocaleString('en-US', { + minimumFractionDigits: decimals, + maximumFractionDigits: decimals, + })); +} + +function code(text) { + return text === 'n/a' ? text : `\`${text}\``; } function trimNumber(value) { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba40c73113..7ea66ab452 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,7 @@ on: pull_request: push: branches: + - main - 1.9.x workflow_dispatch: inputs: @@ -668,7 +669,7 @@ jobs: docker tag ${{ env.IMAGE }}:before ${{ env.IMAGE }} docker compose up -d --wait --no-build for attempt in $(seq 1 10); do - if curl -fsS http://localhost/v1/health/version; then + if curl -fsS http://localhost:9520/v1/health/version; then break fi if [ "$attempt" -eq 10 ]; then @@ -685,9 +686,9 @@ jobs: continue-on-error: true uses: grafana/run-k6-action@de51a7390bdf0ac85a3bef493691bd71d4c7c158 # v1.4.0 env: - APPWRITE_ENDPOINT: 'http://localhost/v1' - APPWRITE_BENCHMARK_ITERATIONS: '5' - APPWRITE_BENCHMARK_VUS: '1' + APPWRITE_ENDPOINT: 'http://localhost:9520/v1' + APPWRITE_BENCHMARK_DURATION: '1m' + APPWRITE_BENCHMARK_VUS: '20' APPWRITE_WORKER_TIMEOUT_MS: '120000' APPWRITE_BENCHMARK_SUMMARY_PATH: 'benchmark-before-summary.json' with: @@ -707,7 +708,7 @@ jobs: - name: Wait for benchmark ports if: always() run: | - for port in 80 443 8080 9503; do + for port in 9520 9521 9522 9503; do for attempt in $(seq 1 30); do if ! ss -ltn | awk '{print $4}' | grep -Eq "[:.]${port}$"; then break @@ -732,7 +733,7 @@ jobs: docker tag ${{ env.IMAGE }}:after ${{ env.IMAGE }} docker compose up -d --wait --no-build for attempt in $(seq 1 10); do - if curl -fsS http://localhost/v1/health/version; then + if curl -fsS http://localhost:9520/v1/health/version; then break fi if [ "$attempt" -eq 10 ]; then @@ -746,9 +747,9 @@ jobs: continue-on-error: true uses: grafana/run-k6-action@de51a7390bdf0ac85a3bef493691bd71d4c7c158 # v1.4.0 env: - APPWRITE_ENDPOINT: 'http://localhost/v1' - APPWRITE_BENCHMARK_ITERATIONS: '5' - APPWRITE_BENCHMARK_VUS: '1' + APPWRITE_ENDPOINT: 'http://localhost:9520/v1' + APPWRITE_BENCHMARK_DURATION: '1m' + APPWRITE_BENCHMARK_VUS: '20' APPWRITE_WORKER_TIMEOUT_MS: '120000' APPWRITE_BENCHMARK_PREVIOUS_SUMMARY_PATH: '../../benchmark-before-summary.json' APPWRITE_BENCHMARK_SUMMARY_PATH: 'benchmark-after-summary.json' diff --git a/.gitpod.yml b/.gitpod.yml index 78375bb1f0..82130fa32d 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -17,7 +17,7 @@ tasks: --prefer-dist ports: - - port: 8080 + - port: 9520 visibility: public vscode: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5d7ab96a4f..9dd25edc27 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -281,11 +281,34 @@ Although the Appwrite API is a monolithic app, it has a very clear separation of Each container in Appwrite is a microservice on its own. Each service is an independent process that can scale without regard to any of the other services. -Currently, all the Appwrite microservices are intended to communicate using the TCP protocol over a private network. With the exception of the public-facing port 80 and 443, which by default are used to expose the Appwrite HTTP API, you should **avoid exposing any other services' ports**. +Currently, all the Appwrite microservices are intended to communicate using the TCP protocol over a private network. You should **avoid exposing services' ports** beyond what is needed for local development and debugging. ## Ports -Appwrite dev version uses ports 80 and 443 as an entry point to the Appwrite API and console. We also expose multiple ports in the range of 9500-9504 for debugging some of the Appwrite containers on dev mode. If you have any conflicts with the ports running on your system, you can easily replace them by editing Appwrite's docker-compose.yml file and executing `docker compose up -d` command. +Appwrite server dev publishes all host ports in the **9500–9522** range so the stack can run alongside other local services (including Appwrite Cloud on **9600–9699**). Access the API and console at `http://localhost:9520` (or `https://localhost:9521`). + +| Host port | Service | +|-----------|---------| +| 9520 | Traefik HTTP (API, console, dev hostnames) | +| 9521 | Traefik HTTPS | +| 9522 | Traefik HTTP (alt) | +| 9500 | Traefik dashboard | +| 9501 | Appwrite API only (direct; no console) | +| 9502 | Realtime only (direct; no console) | +| 9503 | Mail catcher | +| 9504 | Request catcher (webhook) | +| 9505 | Embedding | +| 9506 | Adminer | +| 9507 | Request catcher (SMS) | +| 9508 | Mongo Express | +| 9509 | GraphQL explorer | +| 9510 | MariaDB | +| 9511 | MongoDB | +| 9512 | PostgreSQL | +| 9513 | Redis | +| 9514 | Redis Insight | + +Containers still talk to each other on the internal Docker network using standard service ports (for example, `mariadb:3306`). The table above is only for connections from your host machine. If you still have a conflict, change the host side in `docker-compose.yml` or `docker-compose.override.yml` and run `docker compose up -d`. ## Technology Stack diff --git a/app/config/collections/projects.php b/app/config/collections/projects.php index 9ac5c562e3..95f78bcb12 100644 --- a/app/config/collections/projects.php +++ b/app/config/collections/projects.php @@ -1306,7 +1306,7 @@ return [ 'size' => 128, 'signed' => false, 'required' => false, - 'default' => APP_COMPUTE_SPECIFICATION_DEFAULT, + 'default' => APP_SITES_BUILD_SPECIFICATION_DEFAULT, 'filters' => [], ], [ diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 5ecae9c635..36ff0256a2 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -447,13 +447,13 @@ Http::get('/v1/account') contentType: ContentType::JSON )) ->inject('response') - ->inject('user') - ->action(function (Response $response, Document $user) { - if ($user->isEmpty()) { + ->inject('targetUser') + ->action(function (Response $response, User $targetUser) { + if ($targetUser->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); } - $response->dynamic($user, Response::MODEL_ACCOUNT); + $response->dynamic($targetUser, Response::MODEL_ACCOUNT); }); Http::delete('/v1/account') @@ -476,20 +476,20 @@ Http::delete('/v1/account') ], contentType: ContentType::NONE )) - ->inject('user') + ->inject('targetUser') ->inject('project') ->inject('response') ->inject('dbForProject') ->inject('queueForEvents') ->inject('publisherForDeletes') ->inject('authorization') - ->action(function (Document $user, Document $project, Response $response, Database $dbForProject, Event $queueForEvents, DeletePublisher $publisherForDeletes, Authorization $authorization) { - if ($user->isEmpty()) { + ->action(function (User $targetUser, Document $project, Response $response, Database $dbForProject, Event $queueForEvents, DeletePublisher $publisherForDeletes, Authorization $authorization) { + if ($targetUser->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); } if ($project->getId() === 'console') { - $memberships = $user->getAttribute('memberships', []); + $memberships = $targetUser->getAttribute('memberships', []); foreach ($memberships as $membership) { if (!$membership->getAttribute('confirm', false)) { continue; @@ -505,17 +505,17 @@ Http::delete('/v1/account') } } - $dbForProject->deleteDocument('users', $user->getId()); + $dbForProject->deleteDocument('users', $targetUser->getId()); $publisherForDeletes->enqueue(new DeleteMessage( project: $project, type: DELETE_TYPE_DOCUMENT, - document: $user, + document: $targetUser, )); $queueForEvents - ->setParam('userId', $user->getId()) - ->setPayload($response->output($user, Response::MODEL_USER)); + ->setParam('userId', $targetUser->getId()) + ->setPayload($response->output($targetUser, Response::MODEL_USER)); $response->noContent(); }); diff --git a/app/controllers/api/projects.php b/app/controllers/api/projects.php index a39ce3c4bd..a9eec75f8b 100644 --- a/app/controllers/api/projects.php +++ b/app/controllers/api/projects.php @@ -64,6 +64,8 @@ Http::patch('/v1/projects/:projectId/oauth2') ])); }); + $dbForPlatform->purgeCachedDocument('projects', $project->getId()); + $response->dynamic($project, Response::MODEL_PROJECT); }); diff --git a/app/controllers/general.php b/app/controllers/general.php index 9ff704ca20..1a7cfa70ae 100644 --- a/app/controllers/general.php +++ b/app/controllers/general.php @@ -988,7 +988,7 @@ Http::init() * @see https://www.owasp.org/index.php/List_of_useful_HTTP_headers */ Http::init() - ->groups(['api', 'web']) + ->groups(['api', 'web', 'graphql']) ->inject('request') ->inject('response') ->inject('cors') diff --git a/app/controllers/shared/api.php b/app/controllers/shared/api.php index 4b5f7170ff..0eec29b7fa 100644 --- a/app/controllers/shared/api.php +++ b/app/controllers/shared/api.php @@ -18,6 +18,7 @@ use Appwrite\Extend\Exception as AppwriteException; use Appwrite\Functions\EventProcessor; use Appwrite\Platform\Modules\Storage\Config\CacheControl; use Appwrite\Platform\Modules\Storage\Config\StorageCacheControl; +use Appwrite\Reference\Renderer; use Appwrite\SDK\Method; use Appwrite\Usage\Context; use Appwrite\Utopia\Database\Documents\User; @@ -43,47 +44,6 @@ use Utopia\System\System; use Utopia\Telemetry\Adapter as Telemetry; use Utopia\Validator\WhiteList; -$parseLabel = function (string $label, array $responsePayload, array $requestParams, User $user, Document $project) { - preg_match_all('/{(.*?)}/', $label, $matches); - foreach ($matches[1] as $pos => $match) { - $find = $matches[0][$pos]; - $parts = explode('.', $match); - - if (count($parts) !== 2) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, "The server encountered an error while parsing the label: $label. Please create an issue on GitHub to allow us to investigate further https://github.com/appwrite/appwrite/issues/new/choose"); - } - - $namespace = $parts[0]; - $replace = $parts[1]; - - $params = match ($namespace) { - 'user' => (array) $user, - 'project' => $project->getArrayCopy(), - 'request' => $requestParams, - default => $responsePayload, - }; - - if (array_key_exists($replace, $params)) { - $replacement = $params[$replace]; - // Convert to string if it's not already a string - if (! is_string($replacement)) { - if (is_array($replacement)) { - $replacement = json_encode($replacement); - } elseif (is_object($replacement) && method_exists($replacement, '__toString')) { - $replacement = (string) $replacement; - } elseif (is_scalar($replacement)) { - $replacement = (string) $replacement; - } else { - throw new Exception(Exception::GENERAL_SERVER_ERROR, "The server encountered an error while parsing the label: $label. Please create an issue on GitHub to allow us to investigate further https://github.com/appwrite/appwrite/issues/new/choose"); - } - } - $label = \str_replace($find, $replacement, $label); - } - } - - return $label; -}; - Http::init() ->groups(['api']) ->inject('route') @@ -99,7 +59,9 @@ Http::init() ->inject('team') ->inject('apiKey') ->inject('authorization') - ->action(function (Route $route, Request $request, Database $dbForPlatform, Database $dbForProject, AuditContext $auditContext, Document $project, User $user, ?Document $session, array $servers, string $mode, Document $team, ?Key $apiKey, Authorization $authorization) { + ->inject('impersonatorUser') + ->inject('targetUser') + ->action(function (Route $route, Request $request, Database $dbForPlatform, Database $dbForProject, AuditContext $auditContext, Document $project, User $user, ?Document $session, array $servers, string $mode, Document $team, ?Key $apiKey, Authorization $authorization, Document $impersonatorUser, User $targetUser) { /** * Handle user authentication and session validation. @@ -297,7 +259,8 @@ Http::init() elseif (($project->getId() === 'console' && ! $team->isEmpty() && ! $user->isEmpty()) || ($project->getId() !== 'console' && ! $user->isEmpty() && $mode === APP_MODE_ADMIN)) { $teamId = $team->getId(); $adminRoles = []; - $memberships = $user->getAttribute('memberships', []); + $membershipSource = !$impersonatorUser->isEmpty() ? $targetUser : $user; + $memberships = $membershipSource->getAttribute('memberships', []); foreach ($memberships as $membership) { if ($membership->getAttribute('confirm', false) === true && $membership->getAttribute('teamId') === $teamId) { $adminRoles = $membership->getAttribute('roles', []); @@ -353,7 +316,7 @@ Http::init() !$user->isEmpty() && ( $user->getAttribute('impersonator', false) - || $user->getAttribute('impersonatorUserId') + || !$impersonatorUser->isEmpty() ) ) { $scopes[] = 'users.read'; @@ -361,16 +324,33 @@ Http::init() } $authorization->addRole($role); - foreach ($user->getRoles($authorization) as $authRole) { + $rolesSource = $impersonatorUser->isEmpty() ? $user : $targetUser; + foreach ($rolesSource->getRoles($authorization) as $authRole) { $authorization->addRole($authRole); } + $isAdminProjectRequest = ! $user->isEmpty() + && $project->getId() !== 'console' + && $mode === APP_MODE_ADMIN; + $isOAuthAdminKey = ! empty($apiKey) + && $apiKey->getType() === API_KEY_OAUTH2 + && $apiKey->getRole() === User::ROLE_OWNER; + + if ($isAdminProjectRequest && $isOAuthAdminKey) { + $authorization->setDefaultStatus(false); + } + + if (!$impersonatorUser->isEmpty() && !$targetUser->isEmpty()) { + $dbForProject->setMetadata('user', $targetUser->getId()); + $dbForPlatform->setMetadata('user', $targetUser->getId()); + } + /** * We disable authorization checks above to ensure other endpoints (list teams, members, etc.) will continue working. * But, for actions on resources (sites, functions, etc.) in a non-console project, we explicitly check * whether the admin user has necessary permission on the project (sites, functions, etc. don't have permissions associated to them). */ - if (empty($apiKey) && ! $user->isEmpty() && $project->getId() !== 'console' && $mode === APP_MODE_ADMIN) { + if ($isAdminProjectRequest && (empty($apiKey) || $isOAuthAdminKey)) { $input = new Input(Database::PERMISSION_READ, $project->getPermissionsByType(Database::PERMISSION_READ)); $initialStatus = $authorization->getStatus(); $authorization->enable(); @@ -391,11 +371,10 @@ Http::init() } if (! empty($user->getId())) { - $impersonatorUserId = $user->getAttribute('impersonatorUserId'); $accessedAt = $user->getAttribute('accessedAt', 0); // Skip updating accessedAt for impersonated requests so we don't attribute activity to the target user. - if (! $impersonatorUserId && DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_USER_ACCESS)) > $accessedAt) { + if ($impersonatorUser->isEmpty() && DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_USER_ACCESS)) > $accessedAt) { $user->setAttribute('accessedAt', DateTime::now()); if ($project->getId() !== 'console' && $mode !== APP_MODE_ADMIN) { @@ -410,6 +389,8 @@ Http::init() } } + $rolesSource = $impersonatorUser->isEmpty() ? $user : $targetUser; + // Steps 7-9: Access Control - Method, Namespace and Scope Validation $method = $route->getLabel('sdk', false); @@ -425,7 +406,7 @@ Http::init() if ( array_key_exists($namespace, $project->getAttribute('services', [])) && ! $project->getAttribute('services', [])[$namespace] - && ! ($user->isPrivileged($authorization->getRoles()) || $user->isKey($authorization->getRoles())) + && ! ($rolesSource->isPrivileged($authorization->getRoles()) || $rolesSource->isKey($authorization->getRoles())) ) { throw new Exception(Exception::GENERAL_SERVICE_DISABLED); } @@ -435,7 +416,7 @@ Http::init() if ( array_key_exists('rest', $project->getAttribute('apis', [])) && ! $project->getAttribute('apis', [])['rest'] - && ! ($user->isPrivileged($authorization->getRoles()) || $user->isKey($authorization->getRoles())) + && ! ($rolesSource->isPrivileged($authorization->getRoles()) || $rolesSource->isKey($authorization->getRoles())) ) { throw new AppwriteException(AppwriteException::GENERAL_API_DISABLED); } @@ -447,20 +428,20 @@ Http::init() } // Step 10: Check if user is blocked - if ($user->getAttribute('status') === false) { // Account is blocked + if ($rolesSource->getAttribute('status') === false) { // Account is blocked throw new Exception(Exception::USER_BLOCKED); } // Step 11: Verify password status - if ($user->getAttribute('reset')) { + if ($rolesSource->getAttribute('reset')) { throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); } // Step 12: Validate MFA requirements - $mfaEnabled = $user->getAttribute('mfa', false); - $hasVerifiedEmail = $user->getAttribute('emailVerification', false); - $hasVerifiedPhone = $user->getAttribute('phoneVerification', false); - $hasVerifiedAuthenticator = TOTP::getAuthenticatorFromUser($user)?->getAttribute('verified') ?? false; + $mfaEnabled = $rolesSource->getAttribute('mfa', false); + $hasVerifiedEmail = $rolesSource->getAttribute('emailVerification', false); + $hasVerifiedPhone = $rolesSource->getAttribute('phoneVerification', false); + $hasVerifiedAuthenticator = TOTP::getAuthenticatorFromUser($rolesSource)?->getAttribute('verified') ?? false; $hasMoreFactors = $hasVerifiedEmail || $hasVerifiedPhone || $hasVerifiedAuthenticator; $minimumFactors = ($mfaEnabled && $hasMoreFactors) ? 2 : 1; @@ -566,10 +547,13 @@ Http::init() ->inject('platform') ->inject('authorization') ->inject('cacheControlForStorage') - ->action(function (Route $route, Request $request, Response $response, Document $project, User $user, Event $queueForEvents, AuditContext $auditContext, Context $usage, FunctionPublisher $publisherForFunctions, Database $dbForProject, Document $resourceToken, string $mode, ?Key $apiKey, array $plan, Telemetry $telemetry, array $platform, Authorization $authorization, callable $cacheControlForStorage) { + ->inject('impersonatorUser') + ->inject('targetUser') + ->action(function (Route $route, Request $request, Response $response, Document $project, User $user, Event $queueForEvents, AuditContext $auditContext, Context $usage, FunctionPublisher $publisherForFunctions, Database $dbForProject, Document $resourceToken, string $mode, ?Key $apiKey, array $plan, Telemetry $telemetry, array $platform, Authorization $authorization, callable $cacheControlForStorage, Document $impersonatorUser, User $targetUser) { - $response->setUser($user); - $request->setUser($user); + $response->setUser($targetUser); + $response->setImpersonatorUser($impersonatorUser); + $request->setUser($targetUser); $path = $route->getPath(); $databaseType = match (true) { @@ -588,7 +572,7 @@ Http::init() $queueForEvents ->setEvent($route->getLabel('event', '')) ->setProject($project) - ->setUser($user); + ->setUser($targetUser); $auditContext->mode = $mode; $auditContext->userAgent = $request->getUserAgent(''); @@ -596,24 +580,27 @@ Http::init() $auditContext->hostname = $request->getHostname(); $auditContext->event = $route->getLabel('audits.event', ''); $auditContext->project = $project; + $auditContext->impersonatorUser = $impersonatorUser->isEmpty() ? null : $impersonatorUser; - /* If a session exists, use the user associated with the session */ - if (! $user->isEmpty()) { - $userClone = clone $user; + /* If a session exists, use the target user (impersonated target or actor) for audit */ + if (! $targetUser->isEmpty()) { + $userClone = clone $targetUser; // $user doesn't support `type` and can cause unintended effects. - if (empty($user->getAttribute('type'))) { + if (empty($targetUser->getAttribute('type'))) { $userClone->setAttribute('type', $mode === APP_MODE_ADMIN ? ACTOR_TYPE_ADMIN : ACTOR_TYPE_USER); } $auditContext->user = $userClone; } + $rolesSource = $impersonatorUser->isEmpty() ? $user : $targetUser; + $useCache = $route->getLabel('cache', false); $storageCacheOperationsCounter = $telemetry->createCounter('storage.cache.operations.load'); if ($useCache) { $roles = $authorization->getRoles(); - $isAppUser = $user->isKey($roles); + $isAppUser = $rolesSource->isKey($roles); $isImageTransformation = $route->getPath() === '/v1/storage/buckets/:bucketId/files/:fileId/preview'; - $isDisabled = isset($plan['imageTransformations']) && $plan['imageTransformations'] === -1 && ! $user->isPrivileged($roles); + $isDisabled = isset($plan['imageTransformations']) && $plan['imageTransformations'] === -1 && ! $rolesSource->isPrivileged($roles); $key = $request->cacheIdentifier(); Span::add('storage.cache.key', $key); @@ -903,24 +890,31 @@ Http::shutdown() ->inject('response') ->inject('project') ->inject('user') + ->inject('targetUser') ->inject('auditContext') ->inject('publisherForAudits') ->inject('mode') - ->action(function (Route $route, array $params, Request $request, Response $response, Document $project, User $user, AuditContext $auditContext, Audit $publisherForAudits, string $mode) use ($parseLabel) { + ->action(function (Route $route, array $params, Request $request, Response $response, Document $project, User $user, User $targetUser, AuditContext $auditContext, Audit $publisherForAudits, string $mode) { $responsePayload = $response->getPayload(); $pattern = $route->getLabel('audits.resource', null); if (! empty($pattern)) { - $resource = $parseLabel($pattern, $responsePayload, $params, $user, $project); + $renderer = new Renderer(new Document([ + 'user' => (array) $targetUser, + 'project' => $project, + 'request' => $params, + 'response' => $responsePayload, + ])); + $resource = $renderer->render($pattern); if (! empty($resource) && $resource !== $pattern) { $auditContext->resource = $resource; } } - if (! $user->isEmpty()) { - $userClone = clone $user; + if (! $targetUser->isEmpty()) { + $userClone = clone $targetUser; // $user doesn't support `type` and can cause unintended effects. - if (empty($user->getAttribute('type'))) { + if (empty($targetUser->getAttribute('type'))) { $userClone->setAttribute('type', $mode === APP_MODE_ADMIN ? ACTOR_TYPE_ADMIN : ACTOR_TYPE_USER); } $auditContext->user = $userClone; @@ -970,7 +964,7 @@ Http::shutdown() ->inject('user') ->inject('dbForProject') ->inject('authorization') - ->action(function (Route $route, array $params, Request $request, Response $response, Document $project, User $user, Database $dbForProject, Authorization $authorization) use ($parseLabel) { + ->action(function (Route $route, array $params, Request $request, Response $response, Document $project, User $user, Database $dbForProject, Authorization $authorization) { if (! $route->getLabel('cache', false)) { return; } @@ -1000,11 +994,18 @@ Http::shutdown() $resourcePattern = $route->getLabel('cache.resource', null); $resourceTypePattern = $route->getLabel('cache.resourceType', null); + $renderer = new Renderer(new Document([ + 'user' => (array) $user, + 'project' => $project, + 'request' => $requestParams, + 'response' => $data, + ])); + try { $authorization->skip(fn () => $dbForProject->createDocument('cache', new Document([ '$id' => $key, - 'resource' => empty($resourcePattern) ? null : $parseLabel($resourcePattern, $data, $requestParams, $user, $project), - 'resourceType' => empty($resourceTypePattern) ? null : $parseLabel($resourceTypePattern, $data, $requestParams, $user, $project), + 'resource' => empty($resourcePattern) ? null : $renderer->render($resourcePattern), + 'resourceType' => empty($resourceTypePattern) ? null : $renderer->render($resourceTypePattern), 'mimeType' => $response->getContentType(), 'accessedAt' => $now, 'signature' => $signature, diff --git a/app/init/constants.php b/app/init/constants.php index 20a0de1d10..b748b227a9 100644 --- a/app/init/constants.php +++ b/app/init/constants.php @@ -98,6 +98,7 @@ const APP_SOCIAL_YOUTUBE = 'https://www.youtube.com/c/appwrite?sub_confirmation= const APP_COMPUTE_CPUS_DEFAULT = 0.5; const APP_COMPUTE_MEMORY_DEFAULT = 512; const APP_COMPUTE_SPECIFICATION_DEFAULT = Specification::S_1VCPU_512MB; +const APP_SITES_BUILD_SPECIFICATION_DEFAULT = Specification::S_2VCPU_2GB; const APP_COMPUTE_DEPLOYMENT_MAX_RETENTION = 100 * 365; // 100 years const APP_SDK_PLATFORM_SERVER = 'server'; const APP_SDK_PLATFORM_CLIENT = 'client'; @@ -295,6 +296,11 @@ const API_KEY_STANDARD = 'standard'; const API_KEY_EPHEMERAL = 'ephemeral'; const API_KEY_ORGANIZATION = 'organization'; const API_KEY_ACCOUNT = 'account'; +const API_KEY_OAUTH2 = 'oauth2'; + +// Realtime +const CONSOLE_TAIL_CHANNEL_PREFIX = 'console.tail'; + // Usage metrics const METRIC_TEAMS = 'teams'; const METRIC_USERS = 'users'; diff --git a/app/init/realtime/connection.php b/app/init/realtime/connection.php index 397d077aa7..2a0b97bfdd 100644 --- a/app/init/realtime/connection.php +++ b/app/init/realtime/connection.php @@ -271,7 +271,7 @@ return function (Container $container): void { $user = new User([]); } - $authJWT = $request->getHeaderLine('x-appwrite-jwt', ''); + $authJWT = $request->getHeaderLine('x-appwrite-jwt', (string)($request->getParam('jwt', ''))); if (!empty($authJWT) && !$project->isEmpty()) { if (!$user->isEmpty()) { throw new Exception(Exception::USER_JWT_AND_COOKIE_SET); @@ -327,42 +327,76 @@ return function (Container $container): void { } } + $dbForPlatform->setMetadata('user', $user->getId()); + $dbForProject->setMetadata('user', $user->getId()); + + return $user; + }, ['request', 'project', 'console', 'authorization']); + + $container->set('impersonatorUser', function (Request $request, Document $project, Document $user, Authorization $authorization) use ($getMode, $getDbForPlatform, $getDbForProject) { + if ($user->isEmpty() || !$user->getAttribute('impersonator', false)) { + return new Document(); + } + // Query params mirror the header fallback pattern used by ?project= and ?devKey=, // allowing Console to embed impersonation in direct file/image URLs where headers cannot be set. $impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', ''))); $impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', ''))); $impersonatePhone = $request->getHeaderLine('x-appwrite-impersonate-user-phone', (string)($request->getParam('impersonatephone', '') ?: $request->getParam('impersonatePhone', ''))); - if (!$user->isEmpty() && $user->getAttribute('impersonator', false)) { - $userDb = ($mode === APP_MODE_ADMIN || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; - $targetUser = null; - - if (!empty($impersonateUserId)) { - $targetUser = $authorization->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); - } elseif (!empty($impersonateEmail)) { - $targetUser = $authorization->skip(fn () => $userDb->findOne('users', [ - Query::equal('email', [\strtolower($impersonateEmail)]), - ])); - } elseif (!empty($impersonatePhone)) { - $targetUser = $authorization->skip(fn () => $userDb->findOne('users', [ - Query::equal('phone', [$impersonatePhone]), - ])); - } - - if ($targetUser !== null && !$targetUser->isEmpty()) { - $impersonator = clone $user; - $user = clone $targetUser; - $user->setAttribute('impersonatorUserId', $impersonator->getId()); - $user->setAttribute('impersonatorUserInternalId', $impersonator->getSequence()); - $user->setAttribute('impersonatorUserName', $impersonator->getAttribute('name', '')); - $user->setAttribute('impersonatorUserEmail', $impersonator->getAttribute('email', '')); - $user->setAttribute('impersonatorAccessedAt', $impersonator->getAttribute('accessedAt', 0)); - } + if (empty($impersonateUserId) && empty($impersonateEmail) && empty($impersonatePhone)) { + return new Document(); } - $dbForPlatform->setMetadata('user', $user->getId()); - $dbForProject->setMetadata('user', $user->getId()); + $mode = $getMode($request, $project); + $dbForPlatform = $getDbForPlatform($authorization); + $dbForProject = $getDbForProject($project, $authorization); + $userDb = ($mode === APP_MODE_ADMIN || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; + + $targetUser = null; + if (!empty($impersonateUserId)) { + $targetUser = $authorization->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); + } elseif (!empty($impersonateEmail)) { + $targetUser = $authorization->skip(fn () => $userDb->findOne('users', [Query::equal('email', [\strtolower($impersonateEmail)])])); + } elseif (!empty($impersonatePhone)) { + $targetUser = $authorization->skip(fn () => $userDb->findOne('users', [Query::equal('phone', [$impersonatePhone])])); + } + + if ($targetUser === null || $targetUser->isEmpty()) { + return new Document(); + } + + return new Document([ + '$id' => $user->getId(), + '$sequence' => $user->getSequence(), + 'name' => $user->getAttribute('name', ''), + 'email' => $user->getAttribute('email', ''), + 'type' => $user->getAttribute('type', $mode === APP_MODE_ADMIN ? ACTOR_TYPE_ADMIN : ACTOR_TYPE_USER), + ]); + }, ['request', 'project', 'user', 'authorization']); + + $container->set('targetUser', function (Request $request, Document $project, Document $user, Document $impersonatorUser, Authorization $authorization) use ($getMode, $getDbForPlatform, $getDbForProject) { + if ($impersonatorUser->isEmpty()) { + return $user; + } + + $impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', ''))); + $impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', ''))); + $impersonatePhone = $request->getHeaderLine('x-appwrite-impersonate-user-phone', (string)($request->getParam('impersonatephone', '') ?: $request->getParam('impersonatePhone', ''))); + + $mode = $getMode($request, $project); + $dbForPlatform = $getDbForPlatform($authorization); + $dbForProject = $getDbForProject($project, $authorization); + $userDb = ($mode === APP_MODE_ADMIN || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; + + if (!empty($impersonateUserId)) { + return $authorization->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); + } elseif (!empty($impersonateEmail)) { + return $authorization->skip(fn () => $userDb->findOne('users', [Query::equal('email', [\strtolower($impersonateEmail)])])); + } elseif (!empty($impersonatePhone)) { + return $authorization->skip(fn () => $userDb->findOne('users', [Query::equal('phone', [$impersonatePhone])])); + } return $user; - }, ['request', 'project', 'console', 'authorization']); + }, ['request', 'project', 'user', 'impersonatorUser', 'authorization']); }; diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 958f1a211a..ded4f735a6 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -110,6 +110,66 @@ return function (Container $context): void { $context->set('queueForRealtime', fn () => new Realtime(), []); $context->set('usage', fn () => new UsageContext(), []); $context->set('auditContext', fn () => new AuditContext(), []); + + $context->set('impersonatorUser', function (string $mode, Document $project, Document $user, Request $request, Database $dbForProject, Database $dbForPlatform) { + if ($user->isEmpty() || !$user->getAttribute('impersonator', false)) { + return new Document(); + } + + // Query params mirror the header fallback pattern used by ?project= and ?devKey=, + // allowing Console to embed impersonation in direct file/image URLs where headers cannot be set. + $impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', ''))); + $impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', ''))); + $impersonatePhone = $request->getHeaderLine('x-appwrite-impersonate-user-phone', (string)($request->getParam('impersonatephone', '') ?: $request->getParam('impersonatePhone', ''))); + + if (empty($impersonateUserId) && empty($impersonateEmail) && empty($impersonatePhone)) { + return new Document(); + } + + $userDb = (APP_MODE_ADMIN === $mode || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; + $targetUser = null; + if (!empty($impersonateUserId)) { + $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); + } elseif (!empty($impersonateEmail)) { + $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('email', [\strtolower($impersonateEmail)])])); + } elseif (!empty($impersonatePhone)) { + $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('phone', [$impersonatePhone])])); + } + + if ($targetUser === null || $targetUser->isEmpty()) { + return new Document(); + } + + return new Document([ + '$id' => $user->getId(), + '$sequence' => $user->getSequence(), + 'name' => $user->getAttribute('name', ''), + 'email' => $user->getAttribute('email', ''), + 'type' => $user->getAttribute('type', $mode === APP_MODE_ADMIN ? ACTOR_TYPE_ADMIN : ACTOR_TYPE_USER), + ]); + }, ['mode', 'project', 'user', 'request', 'dbForProject', 'dbForPlatform']); + + $context->set('targetUser', function (Document $user, Document $impersonatorUser, string $mode, Document $project, Request $request, Database $dbForProject, Database $dbForPlatform) { + if ($impersonatorUser->isEmpty()) { + return $user; + } + + $impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', ''))); + $impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', ''))); + $impersonatePhone = $request->getHeaderLine('x-appwrite-impersonate-user-phone', (string)($request->getParam('impersonatephone', '') ?: $request->getParam('impersonatePhone', ''))); + + $userDb = (APP_MODE_ADMIN === $mode || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; + if (!empty($impersonateUserId)) { + return $userDb->getAuthorization()->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); + } elseif (!empty($impersonateEmail)) { + return $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('email', [\strtolower($impersonateEmail)])])); + } elseif (!empty($impersonatePhone)) { + return $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('phone', [$impersonatePhone])])); + } + + return $user; + }, ['user', 'impersonatorUser', 'mode', 'project', 'request', 'dbForProject', 'dbForPlatform']); + $context->set('publisherForFunctions', fn (Publisher $publisher) => new FunctionPublisher( $publisher, new Queue(System::getEnv('_APP_FUNCTIONS_QUEUE_NAME', Event::FUNCTIONS_QUEUE_NAME), 'utopia-queue', Event::FUNCTIONS_QUEUE_TTL) @@ -488,33 +548,6 @@ return function (Container $context): void { } } - // Impersonation: if current user has impersonator capability and headers/params are set, act as another user - // Query params mirror the header fallback pattern used by ?project= and ?devKey=, - // allowing Console to embed impersonation in direct file/image URLs where headers cannot be set. - $impersonateUserId = $request->getHeaderLine('x-appwrite-impersonate-user-id', (string)($request->getParam('impersonateuserid', '') ?: $request->getParam('impersonateUserId', ''))); - $impersonateEmail = $request->getHeaderLine('x-appwrite-impersonate-user-email', (string)($request->getParam('impersonateemail', '') ?: $request->getParam('impersonateEmail', ''))); - $impersonatePhone = $request->getHeaderLine('x-appwrite-impersonate-user-phone', (string)($request->getParam('impersonatephone', '') ?: $request->getParam('impersonatePhone', ''))); - if (!$user->isEmpty() && $user->getAttribute('impersonator', false)) { - $userDb = (APP_MODE_ADMIN === $mode || $project->getId() === 'console') ? $dbForPlatform : $dbForProject; - $targetUser = null; - if (!empty($impersonateUserId)) { - $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->getDocument('users', $impersonateUserId)); - } elseif (!empty($impersonateEmail)) { - $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('email', [\strtolower($impersonateEmail)])])); - } elseif (!empty($impersonatePhone)) { - $targetUser = $userDb->getAuthorization()->skip(fn () => $userDb->findOne('users', [Query::equal('phone', [$impersonatePhone])])); - } - if ($targetUser !== null && !$targetUser->isEmpty()) { - $impersonator = clone $user; - $user = clone $targetUser; - $user->setAttribute('impersonatorUserId', $impersonator->getId()); - $user->setAttribute('impersonatorUserInternalId', $impersonator->getSequence()); - $user->setAttribute('impersonatorUserName', $impersonator->getAttribute('name', '')); - $user->setAttribute('impersonatorUserEmail', $impersonator->getAttribute('email', '')); - $user->setAttribute('impersonatorAccessedAt', $impersonator->getAttribute('accessedAt', 0)); - } - } - $dbForProject->setMetadata('user', $user->getId()); $dbForPlatform->setMetadata('user', $user->getId()); diff --git a/app/realtime.php b/app/realtime.php index 39bdf103fe..88cb7404d4 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -9,6 +9,7 @@ use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Network\Validator\Origin; use Appwrite\Presences\State as PresenceState; use Appwrite\PubSub\Adapter\Pool as PubSubPool; +use Appwrite\Realtime\EventTailRegistry; use Appwrite\Realtime\Message\Dispatcher as MessageDispatcher; use Appwrite\Realtime\Message\Handlers\Authentication as AuthenticationHandler; use Appwrite\Realtime\Message\Handlers\Ping as PingHandler; @@ -336,6 +337,9 @@ if (!function_exists('checkForProjectUsage')) { $realtime = getRealtime(); $presenceState = new PresenceState(); +$eventTailRegistry = new EventTailRegistry( + rate: (int) System::getEnv('_APP_REALTIME_TAIL_RATE', 50) +); $messageDispatcher = (new MessageDispatcher()) ->addHandler(new PingHandler()) @@ -496,7 +500,7 @@ $server->onStart(function () use ($stats, $containerId, &$statsDocument) { } }); -$server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $realtime) { +$server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $realtime, $eventTailRegistry) { Console::success('Worker ' . $workerId . ' started successfully'); $telemetry = getTelemetry($workerId); @@ -525,6 +529,13 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $attempts = 0; $start = time(); + // Flush coalesced console live-tail buffers to their connections (~150ms). + // Must run per-worker: the registry is mutated by this worker's subscribe handler + // and pub/sub ingest, which are not visible to the master process. + Timer::tick(150, function () use ($server, $eventTailRegistry) { + $eventTailRegistry->flush($server); + }); + Timer::tick(5000, function () use ($server, $realtime, $stats) { /** * Sending current connections to project channels on the console project every 5 seconds. @@ -634,7 +645,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, Console::error('Pub/sub failed (worker: ' . $workerId . ')'); } - $pubsub->subscribe(['realtime'], function (mixed $redis, string $channel, string $payload) use ($server, $workerId, $stats, $register, $realtime) { + $pubsub->subscribe(['realtime'], function (mixed $redis, string $channel, string $payload) use ($server, $workerId, $stats, $register, $realtime, $eventTailRegistry) { $event = json_decode($payload, true); $eventTimestamp = $event['data']['timestamp'] ?? null; @@ -675,6 +686,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, foreach (\array_keys($connections) as $connection) { $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); $authorization = $realtime->connections[$connection]['authorization'] ?? null; + $impersonatedUserId = $realtime->connections[$connection]['impersonatedUserId'] ?? null; $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; $meta = $realtime->getSubscriptionMetadata($connection); @@ -709,6 +721,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, } if ($authorization !== null && isset($realtime->connections[$connection])) { $realtime->connections[$connection]['authorization'] = $authorization; + $realtime->connections[$connection]['impersonatedUserId'] = $impersonatedUserId; } $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); @@ -716,6 +729,11 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, if ($subscriptionDelta !== 0) { $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); } + + // Tail entries live outside the subscription tree, so the rebuild + // above doesn't touch them. Drop any whose authorizing team role + // the connection no longer holds (membership revoked / project moved). + $eventTailRegistry->revalidateConnection($connection, $roles); } } } @@ -797,6 +815,31 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, triggerStats($metrics, $projectId); } + + } + + // Console live event tail: runs for EVERY firehose event, regardless of + // whether it had regular subscribers ($total). The firehose is published + // unconditionally, so a project tailed from the console with no other + // realtime clients must still be observed here. + // + // Most events carry the owning project in $event['project']. But some + // project-owned events (schema changes, deployments, rules, migrations, + // project settings) are rerouted by fromPayload() to project='console'; + // for those the real project id lives in the `projects.` channel. + // Resolve that so the tail still receives them. + $tailProjectId = $event['project'] ?? ''; + if ($tailProjectId === 'console') { + $tailProjectId = ''; + foreach (($event['data']['channels'] ?? []) as $channel) { + if (\str_starts_with($channel, 'projects.')) { + $tailProjectId = \substr($channel, \strlen('projects.')); + break; + } + } + } + if ($tailProjectId !== '' && $eventTailRegistry->isTailed($tailProjectId)) { + $eventTailRegistry->ingest($tailProjectId, Realtime::toTailMetadata($event), \microtime(true)); } }); } catch (Throwable $th) { @@ -867,14 +910,21 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $timelimit = $connectionContainer->get('timelimit'); $user = $connectionContainer->get('user'); /** @var User $user */ + $impersonatorUser = $connectionContainer->get('impersonatorUser'); /** @var Document $impersonatorUser */ + $targetUser = $connectionContainer->get('targetUser'); /** @var User $targetUser */ + if (!$impersonatorUser->isEmpty()) { + getConsoleDB()->setMetadata('user', $targetUser->getId()); + getProjectDB($project)->setMetadata('user', $targetUser->getId()); + } $logUser = $user; $apis = $project->getAttribute('apis', []); // Websocket is what to check, but realtime is checked too for backwards compatibility $websocketEnabled = $apis['websocket'] ?? $apis['realtime'] ?? true; + $effectiveUser = $impersonatorUser->isEmpty() ? $user : $targetUser; if ( !$websocketEnabled - && !($user->isPrivileged($authorization->getRoles()) || $user->isKey($authorization->getRoles())) + && !($effectiveUser->isPrivileged($authorization->getRoles()) || $effectiveUser->isKey($authorization->getRoles())) ) { throw new AppwriteException(AppwriteException::GENERAL_API_DISABLED); } @@ -917,9 +967,9 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, throw new Exception(Exception::REALTIME_POLICY_VIOLATION, $originValidator->getDescription()); } - $roles = $user->getRoles($authorization); + $roles = $targetUser->getRoles($authorization); - $channels = Realtime::convertChannels($request->getQuery('channels', []), $user->getId()); + $channels = Realtime::convertChannels($request->getQuery('channels', []), $targetUser->getId()); $channelCount = \count($channels); $updateStats = static function (string $projectId, ?string $teamId) use ($register, $stats): void { @@ -944,7 +994,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, */ if (empty($channels)) { // in case of message based 'subscribe' channels will be empty at first and only projectId and roles will be available - $sanitizedUser = empty($user->getId()) ? null : $response->output($user, Response::MODEL_ACCOUNT); + $sanitizedUser = empty($targetUser->getId()) ? null : $response->output($targetUser, Response::MODEL_ACCOUNT); $connectedPayloadJson = json_encode([ 'type' => 'connected', 'data' => [ @@ -954,8 +1004,9 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, ] ]); - $realtime->subscribe($project->getId(), $connection, '', $roles, [], [], $user->getId()); + $realtime->subscribe($project->getId(), $connection, '', $roles, [], [], $targetUser->getId()); $realtime->connections[$connection]['authorization'] = $authorization; + $realtime->connections[$connection]['impersonatedUserId'] = $impersonatorUser->isEmpty() ? null : $targetUser->getId(); $updateStats($project->getId(), $project->getAttribute('teamId')); $server->send([$connection], $connectedPayloadJson); $outboundBytes += \strlen($connectedPayloadJson); @@ -979,7 +1030,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, throw new Exception(Exception::REALTIME_POLICY_VIOLATION, $e->getMessage()); } - $sanitizedUser = empty($user->getId()) ? null : $response->output($user, Response::MODEL_ACCOUNT); + $sanitizedUser = empty($targetUser->getId()) ? null : $response->output($targetUser, Response::MODEL_ACCOUNT); $mapping = []; foreach ($subscriptions as $index => $subscription) { @@ -992,13 +1043,14 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $roles, $subscription['channels'], $subscription['queries'], - $user->getId() + $targetUser->getId() ); $mapping[$index] = $subscriptionId; } $realtime->connections[$connection]['authorization'] = $authorization; + $realtime->connections[$connection]['impersonatedUserId'] = $impersonatorUser->isEmpty() ? null : $targetUser->getId(); $updateStats($project->getId(), $project->getAttribute('teamId')); $subscriptionCount = \count($subscriptions); @@ -1085,7 +1137,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, } }); -$server->onMessage(function (int $connection, string $message) use ($container, $server, $realtime, $containerId, $register, $presenceState, $messageDispatcher) { +$server->onMessage(function (int $connection, string $message) use ($container, $server, $realtime, $containerId, $register, $presenceState, $messageDispatcher, $eventTailRegistry) { $project = null; $authorization = null; $projectId = $realtime->connections[$connection]['projectId'] ?? null; @@ -1123,8 +1175,13 @@ $server->onMessage(function (int $connection, string $message) use ($container, $authorization->addRole($role); } + $impersonatedUserId = $realtime->connections[$connection]['impersonatedUserId'] ?? null; + $database = getConsoleDB(); $database->setAuthorization($authorization); + if ($impersonatedUserId !== null) { + $database->setMetadata('user', $impersonatedUserId); + } if (!empty($projectId) && $projectId !== 'console') { // Negative-cache race: if any prior code path queried projects:$projectId @@ -1145,6 +1202,9 @@ $server->onMessage(function (int $connection, string $message) use ($container, $database = getProjectDB($project); $database->setAuthorization($authorization); + if ($impersonatedUserId !== null) { + $database->setMetadata('user', $impersonatedUserId); + } } else { $project = null; } @@ -1206,6 +1266,8 @@ $server->onMessage(function (int $connection, string $message) use ($container, $messageContainer->set('projectId', fn () => $projectId); $messageContainer->set('queueForEvents', fn () => getQueueForEvents()); $messageContainer->set('queueForRealtime', fn () => getQueueForRealtime()); + $messageContainer->set('eventTailRegistry', fn () => $eventTailRegistry); + $messageContainer->set('dbForConsole', fn () => getConsoleDB()); $responsePayload = $messageDispatcher->dispatch($messageContainer, $message); @@ -1281,7 +1343,7 @@ $server->onMessage(function (int $connection, string $message) use ($container, } }); -$server->onClose(function (int $connection) use ($realtime, $stats, $register, $container, $presenceState) { +$server->onClose(function (int $connection) use ($realtime, $stats, $register, $container, $presenceState, $eventTailRegistry) { $projectId = null; $userId = null; $subscriptionsBeforeClose = 0; @@ -1428,6 +1490,13 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register, $ Span::current()?->setError($th); } + try { + $eventTailRegistry->removeConnection($connection); + } catch (\Throwable $th) { + Console::error('Realtime onClose tail cleanup error: ' . $th->getMessage()); + Span::current()?->setError($th); + } + Span::add('realtime.success', $success); if (!empty($projectId)) { Span::add('project.id', $projectId); diff --git a/composer.json b/composer.json index 2a1499f1a8..aca0e41e97 100644 --- a/composer.json +++ b/composer.json @@ -58,12 +58,12 @@ "utopia-php/analytics": "0.15.*", "utopia-php/audit": "2.6.*", "utopia-php/auth": "^0.7", - "utopia-php/cache": "^3.0", + "utopia-php/cache": "^3.0.0", "utopia-php/cli": "^0.24", "utopia-php/compression": "0.1.*", "utopia-php/config": "1.*", "utopia-php/console": "0.1.*", - "utopia-php/database": "6.0.*", + "utopia-php/database": "^6.0.0", "utopia-php/detector": "0.2.*", "utopia-php/domains": "^2.2", "utopia-php/emails": "0.7.*", diff --git a/composer.lock b/composer.lock index 652b26e041..f719710677 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "508b3e633843d61eb24f864fd8832db0", + "content-hash": "17128527d9ef62968ea12eb43a81fdfb", "packages": [ { "name": "adhocore/jwt", @@ -3369,16 +3369,16 @@ }, { "name": "utopia-php/cache", - "version": "3.0.2", + "version": "3.1.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "086687d7ae23dd1dae67b943161e8cef143539e1" + "reference": "d5048409cf3a8db668b00cd2e6c46a627b16d76a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/086687d7ae23dd1dae67b943161e8cef143539e1", - "reference": "086687d7ae23dd1dae67b943161e8cef143539e1", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/d5048409cf3a8db668b00cd2e6c46a627b16d76a", + "reference": "d5048409cf3a8db668b00cd2e6c46a627b16d76a", "shasum": "" }, "require": { @@ -3417,9 +3417,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/3.0.2" + "source": "https://github.com/utopia-php/cache/tree/3.1.0" }, - "time": "2026-05-19T22:38:16+00:00" + "time": "2026-06-23T10:59:08+00:00" }, { "name": "utopia-php/circuit-breaker", @@ -3676,16 +3676,16 @@ }, { "name": "utopia-php/database", - "version": "6.0.0", + "version": "6.1.0", "source": { "type": "git", "url": "https://github.com/utopia-php/database.git", - "reference": "fff9f0effbd40359ff925741ff9424856d8b4fde" + "reference": "18120ddf0bc656fc448e6c9407d2f16371d6f0a6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/database/zipball/fff9f0effbd40359ff925741ff9424856d8b4fde", - "reference": "fff9f0effbd40359ff925741ff9424856d8b4fde", + "url": "https://api.github.com/repos/utopia-php/database/zipball/18120ddf0bc656fc448e6c9407d2f16371d6f0a6", + "reference": "18120ddf0bc656fc448e6c9407d2f16371d6f0a6", "shasum": "" }, "require": { @@ -3694,7 +3694,7 @@ "ext-pdo": "*", "ext-redis": "*", "php": ">=8.4", - "utopia-php/cache": "^3.0", + "utopia-php/cache": "3.1.*", "utopia-php/console": "0.1.*", "utopia-php/mongo": "1.*", "utopia-php/pools": "1.*", @@ -3730,9 +3730,9 @@ ], "support": { "issues": "https://github.com/utopia-php/database/issues", - "source": "https://github.com/utopia-php/database/tree/6.0.0" + "source": "https://github.com/utopia-php/database/tree/6.1.0" }, - "time": "2026-06-18T10:37:40+00:00" + "time": "2026-06-23T11:28:30+00:00" }, { "name": "utopia-php/detector", @@ -5124,16 +5124,16 @@ }, { "name": "utopia-php/vcs", - "version": "4.2.3", + "version": "4.2.4", "source": { "type": "git", "url": "https://github.com/utopia-php/vcs.git", - "reference": "598cbd2793a5a6394493f1046743e75ec6544a57" + "reference": "f19c61daa1e9594734d85ae25b3e90ba2b350d33" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/598cbd2793a5a6394493f1046743e75ec6544a57", - "reference": "598cbd2793a5a6394493f1046743e75ec6544a57", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/f19c61daa1e9594734d85ae25b3e90ba2b350d33", + "reference": "f19c61daa1e9594734d85ae25b3e90ba2b350d33", "shasum": "" }, "require": { @@ -5167,9 +5167,9 @@ ], "support": { "issues": "https://github.com/utopia-php/vcs/issues", - "source": "https://github.com/utopia-php/vcs/tree/4.2.3" + "source": "https://github.com/utopia-php/vcs/tree/4.2.4" }, - "time": "2026-06-16T12:14:08+00:00" + "time": "2026-06-25T13:27:19+00:00" }, { "name": "utopia-php/websocket", diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 05e31ece94..91625df148 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -10,7 +10,7 @@ services: networks: - appwrite ports: - - "8082:8081" + - "9508:8081" environment: ME_CONFIG_MONGODB_URL: "mongodb://root:${_APP_DB_ROOT_PASS}@appwrite-mongodb:27017/?replicaSet=rs0&directConnection=true" ME_CONFIG_BASICAUTH_USERNAME: ${_APP_DB_USER} @@ -76,7 +76,7 @@ services: - "traefik.http.routers.appwrite_redisinsight_https.service=appwrite_redisinsight" - "traefik.http.routers.appwrite_redisinsight_https.tls=true" ports: - - "8081:5540" + - "9514:5540" graphql-explorer: container_name: appwrite-graphql-explorer @@ -87,7 +87,7 @@ services: ports: - "9509:3000" environment: - - SERVER_URL=http://localhost/v1/graphql + - SERVER_URL=http://localhost:9520/v1/graphql configs: redisinsight-connections.json: diff --git a/docker-compose.yml b/docker-compose.yml index 48f253113e..5538707e41 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,6 +2,15 @@ # This is a development version of THE Appwrite docker-compose.yml file. # Avoid using this file in your production environment. # We're exposing here sensitive ports and mounting code volumes for rapid development and debugging of the server stack. +# +# Development port map (host:container) +# ----------------------------------- +# Entry points: 9520:80 (HTTP), 9521:443 (HTTPS), 9522:80 (HTTP alt) +# Reserve 9600-9699 for Appwrite Cloud dev when running both stacks locally. +# 9500 Traefik dashboard, 9501 Appwrite API, 9502 Realtime, 9503 Mail catcher +# 9504 Request catcher (webhook), 9505 Embedding, 9507 Request catcher (SMS) +# 9510 MariaDB, 9511 MongoDB, 9512 PostgreSQL, 9513 Redis +# Dev tools in docker-compose.override.yml: 9506 Adminer, 9508 Mongo Express, 9509 GraphQL, 9514 Redis Insight x-logging: &x-logging logging: @@ -36,9 +45,9 @@ services: - --entrypoints.appwrite_websecure.address=:443 - --accesslog=true ports: - - 80:80 - - 8080:80 - - 443:443 + - 9520:80 + - 9522:80 + - 9521:443 - 9500:8080 volumes: - /var/run/docker.sock:/var/run/docker.sock @@ -282,7 +291,7 @@ services: image: appwrite-dev restart: unless-stopped ports: - - 9505:80 + - 9502:80 labels: - "traefik.enable=true" - "traefik.constraint-label-stack=appwrite" @@ -311,6 +320,7 @@ services: - _APP_WORKER_PER_CORE - _APP_OPTIONS_ABUSE - _APP_OPTIONS_ROUTER_PROTECTION + - _APP_REALTIME_TAIL_RATE - _APP_OPENSSL_KEY_V1 - _APP_REDIS_HOST - _APP_REDIS_PORT @@ -1359,7 +1369,7 @@ services: volumes: - appwrite-mariadb:/var/lib/mysql:rw ports: - - "3306:3306" + - "9510:3306" environment: - MYSQL_ROOT_PASSWORD=${_APP_DB_ROOT_PASS} - MYSQL_DATABASE=${_APP_DB_SCHEMA} @@ -1386,7 +1396,7 @@ services: - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro - ./mongo-entrypoint.sh:/mongo-entrypoint.sh:ro ports: - - "27017:27017" + - "9511:27017" environment: - MONGO_INITDB_ROOT_USERNAME=root - MONGO_INITDB_ROOT_PASSWORD=${_APP_DB_ROOT_PASS} @@ -1426,7 +1436,7 @@ services: volumes: - appwrite-postgresql:/var/lib/postgresql/18/data:rw ports: - - "5432:5432" + - "9512:5432" environment: - POSTGRES_DB=${_APP_DB_SCHEMA} - POSTGRES_USER=${_APP_DB_USER} @@ -1449,7 +1459,7 @@ services: EMBEDDING_MODELS: ${_APP_EMBEDDING_MODELS:-nomic-embed-text} container_name: appwrite-embedding ports: - - "3000:3000" + - "9505:3000" restart: unless-stopped # persistent for caching models across restarts and preloading volumes: @@ -1467,7 +1477,7 @@ services: --maxmemory-policy allkeys-lru --maxmemory-samples 5 ports: - - "6379:6379" + - "9513:6379" networks: - appwrite volumes: diff --git a/docs/sdks/cli/GETTING_STARTED.md b/docs/sdks/cli/GETTING_STARTED.md index 1cadb1bbda..8b907d298a 100644 --- a/docs/sdks/cli/GETTING_STARTED.md +++ b/docs/sdks/cli/GETTING_STARTED.md @@ -9,7 +9,7 @@ $ appwrite login ? Enter your password ******** ✓ Success ``` -This will also prompt you to enter your Appwrite endpoint ( default: http://localhost/v1 ) +This will also prompt you to enter your Appwrite endpoint ( default: http://localhost:9520/v1 ) * ### Initialising your project Once logged in, the CLI needs to be initialised before you can use it with your Appwrite project. You can do this with the `appwrite init project` command. @@ -139,5 +139,5 @@ $ appwrite client --reset The Appwrite CLI can also work in a CI environment. The initialisation of the CLI works a bit differently in CI. In CI, you set your `endpoint`, `projectId` and `API Key` using ```sh -appwrite client --endpoint http://localhost/v1 --projectId --key +appwrite client --endpoint http://localhost:9520/v1 --projectId --key ``` diff --git a/docs/sdks/flutter/EXAMPLES.md b/docs/sdks/flutter/EXAMPLES.md index d0cb0c2b2a..36537cbf18 100644 --- a/docs/sdks/flutter/EXAMPLES.md +++ b/docs/sdks/flutter/EXAMPLES.md @@ -6,7 +6,7 @@ Init your Appwrite client: Client client = Client(); client - .setEndpoint('https://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('https://localhost:9521/v1') // Your Appwrite Endpoint .setProject('5e8cf4f46b5e8') // Your project ID .setSelfSigned() // Remove in production ; diff --git a/docs/sdks/react-native/GETTING_STARTED.md b/docs/sdks/react-native/GETTING_STARTED.md index a5c6f57c46..08b5c2f266 100644 --- a/docs/sdks/react-native/GETTING_STARTED.md +++ b/docs/sdks/react-native/GETTING_STARTED.md @@ -34,7 +34,7 @@ import { Client } from 'react-native-appwrite'; const client = new Client(); client - .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('http://localhost:9520/v1') // Your Appwrite Endpoint .setProject('455x34dfkj') // Your project ID .setPlatform('com.example.myappwriteapp') // Your application ID or bundle ID. ; @@ -65,7 +65,7 @@ import { Client, Account } from 'react-native-appwrite'; const client = new Client(); client - .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('http://localhost:9520/v1') // Your Appwrite Endpoint .setProject('455x34dfkj') .setPlatform('com.example.myappwriteapp') // YOUR application ID ; diff --git a/docs/sdks/web/GETTING_STARTED.md b/docs/sdks/web/GETTING_STARTED.md index cc75a3d3e5..db02a8428d 100644 --- a/docs/sdks/web/GETTING_STARTED.md +++ b/docs/sdks/web/GETTING_STARTED.md @@ -15,7 +15,7 @@ Initialize your SDK with your Appwrite server API endpoint and project ID which const client = new Client(); client - .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('http://localhost:9520/v1') // Your Appwrite Endpoint .setProject('455x34dfkj') // Your project ID ; ``` @@ -44,7 +44,7 @@ account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien") const client = new Client(); client - .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint + .setEndpoint('http://localhost:9520/v1') // Your Appwrite Endpoint .setProject('455x34dfkj') ; diff --git a/docs/tutorials/add-translations.md b/docs/tutorials/add-translations.md index 68023fcf8b..ef56336799 100644 --- a/docs/tutorials/add-translations.md +++ b/docs/tutorials/add-translations.md @@ -149,13 +149,13 @@ First of all, we need to start a local instance of Appwrite. Thanks to Docker, t docker compose up -d ``` -If this is your first time running Appwrite, it may take up to a few minutes to download all images and start all containers. Once everything is started, you should see Appwrite running on `http://localhost:80`. When you visit this URL, it will ask you to sign up. After that, it will show you your empty dashboard where you need to create a new project - give it any name you want. Then you need to go to `Settings` of the project and copy `Project-ID`. +If this is your first time running Appwrite, it may take up to a few minutes to download all images and start all containers. Once everything is started, you should see Appwrite running on `http://localhost:9520`. When you visit this URL, it will ask you to sign up. After that, it will show you your empty dashboard where you need to create a new project - give it any name you want. Then you need to go to `Settings` of the project and copy `Project-ID`. If you are lost in the Appwrite dashboard, check out our [Article about Appwrite's dashboard](https://dev.to/appwrite/30daysofappwrite-appwrite-dashboard-15cc). Now, let's send the request. We will be editing headers of the request, so you will need a tool to do that, such as Postman or Insomnia. -First, let's see English translations. Let's set request type to `GET`, URL to `https://localhost/v1/locale/countries/eu` and add `X-Appwrite-Project` header. +First, let's see English translations. Let's set request type to `GET`, URL to `https://localhost:9521/v1/locale/countries/eu` and add `X-Appwrite-Project` header. ![English test](images/test-en.png) diff --git a/src/Appwrite/Event/Context/Audit.php b/src/Appwrite/Event/Context/Audit.php index 1d41890476..cb2eab2a1a 100644 --- a/src/Appwrite/Event/Context/Audit.php +++ b/src/Appwrite/Event/Context/Audit.php @@ -9,6 +9,7 @@ class Audit public function __construct( public ?Document $project = null, public ?Document $user = null, + public ?Document $impersonatorUser = null, public string $mode = '', public string $userAgent = '', public string $ip = '', @@ -23,6 +24,7 @@ class Audit { return $this->project === null && $this->user === null + && $this->impersonatorUser === null && $this->mode === '' && $this->userAgent === '' && $this->ip === '' diff --git a/src/Appwrite/Event/Message/Audit.php b/src/Appwrite/Event/Message/Audit.php index ae5831c3b9..20cac964cb 100644 --- a/src/Appwrite/Event/Message/Audit.php +++ b/src/Appwrite/Event/Message/Audit.php @@ -12,6 +12,7 @@ final class Audit extends Base public readonly array $payload, public readonly Document $project = new Document(), public readonly Document $user = new Document(), + public readonly Document $impersonatorUser = new Document(), public readonly string $resource = '', public readonly string $mode = '', public readonly string $ip = '', @@ -29,6 +30,7 @@ final class Audit extends Base 'database' => $this->project->getAttribute('database', ''), ], 'user' => $this->user->getArrayCopy(), + 'impersonatorUser' => $this->impersonatorUser->getArrayCopy(), 'payload' => $this->payload, 'resource' => $this->resource, 'mode' => $this->mode, @@ -46,6 +48,7 @@ final class Audit extends Base payload: $data['payload'] ?? [], project: new Document($data['project'] ?? []), user: new Document($data['user'] ?? []), + impersonatorUser: new Document($data['impersonatorUser'] ?? []), resource: $data['resource'] ?? '', mode: $data['mode'] ?? '', ip: $data['ip'] ?? '', @@ -61,6 +64,7 @@ final class Audit extends Base payload: $context->payload, project: $context->project ?? new Document(), user: $context->user ?? new Document(), + impersonatorUser: $context->impersonatorUser ?? new Document(), resource: $context->resource, mode: $context->mode, ip: $context->ip, diff --git a/src/Appwrite/Functions/Validator/Headers.php b/src/Appwrite/Functions/Validator/Headers.php index 04003d535b..a18660fa2d 100644 --- a/src/Appwrite/Functions/Validator/Headers.php +++ b/src/Appwrite/Functions/Validator/Headers.php @@ -50,13 +50,17 @@ class Headers extends Validator $size = 0; foreach ($value as $key => $val) { - $length = \strlen($key); // Reject non-string keys - if (!\is_string($key) || $length === 0) { + if (!\is_string($key)) { return false; } - $size += $length + \strlen($val); + $length = \strlen($key); + if ($length === 0) { + return false; + } + + $size += $length + \strlen($val ?? ''); if ($size >= $this->maxSize) { return false; } diff --git a/src/Appwrite/Messaging/Adapter/Realtime.php b/src/Appwrite/Messaging/Adapter/Realtime.php index dbb2c826bd..9cf5866d80 100644 --- a/src/Appwrite/Messaging/Adapter/Realtime.php +++ b/src/Appwrite/Messaging/Adapter/Realtime.php @@ -16,6 +16,11 @@ class Realtime extends MessagingAdapter { public const SUPPORTED_ACTIONS = ['create', 'update', 'upsert', 'delete']; + // The database family is published under several event prefixes (legacy `databases` + // plus the per-type projections). They share the same `databases...…` + // shape, so the tail normalizes them to `databases` for consistent metadata + filtering. + public const DATABASE_EVENT_PREFIXES = ['databases', 'tablesdb', 'documentsdb', 'vectorsdb']; + // Resources whose channels receive an action-suffixed sibling at publish time. // The suffix loop in fromPayload() treats any channel whose last OR second-to-last // segment matches an entry here as a candidate for `.{action}` suffixing. @@ -500,6 +505,90 @@ class Realtime extends MessagingAdapter return $receivers; } + /** + * + * @param array $event decoded event published to the `realtime` channel + * @return array + */ + public static function toTailMetadata(array $event): array + { + $events = $event['data']['events'] ?? []; + $name = \is_array($events) ? ($events[0] ?? '') : ''; + $parts = $name === '' ? [] : \explode('.', $name); + $count = \count($parts); + $type = $parts[0] ?? null; + + // The database family is published under several prefixes (databases/tablesdb/ + // documentsdb/vectorsdb). `type` keeps the actual prefix (more informative), but + // scope ids are extracted for all of them so databaseId/collectionId filters work + // across the whole family. + $isDatabaseFamily = \in_array($type, self::DATABASE_EVENT_PREFIXES, true); + + $action = null; + if ($count >= 1 && \in_array($parts[$count - 1], self::SUPPORTED_ACTIONS, true)) { + $action = $parts[$count - 1]; + } elseif ($count >= 2 && \in_array($parts[$count - 2], self::SUPPORTED_ACTIONS, true)) { + $action = $parts[$count - 2]; + } + + $payload = $event['data']['payload'] ?? []; + if (!\is_array($payload)) { + $payload = []; + } + + $metadata = [ + 'event' => $name, + 'type' => $type, + 'action' => $action, + 'userId' => $event['userId'] ?? null, + 'timestamp' => $event['data']['timestamp'] ?? null, + 'resourceId' => $payload['$id'] ?? null, + ]; + + // Attach only the scope ids that belong to this resource type. Derived from the + // (concrete) event name rather than the payload: for a top-level resource event + // (e.g. `teams.T.create`) the payload's id lives at $id, not at a teamId field, + // so a payload lookup would drop the scope and silently break filters. The event + // name encodes the id at every level — parts[1] is the top-level resource id and + // parts[3] the collection/table id. + $scope = []; + if ($isDatabaseFamily) { + if (isset($parts[1])) { + $scope['databaseId'] = $parts[1]; + } + if (isset($parts[2], $parts[3]) && \in_array($parts[2], ['collections', 'tables'], true)) { + $scope['collectionId'] = $parts[3]; + } + } else { + switch ($type) { + case 'buckets': + if (isset($parts[1])) { + $scope['bucketId'] = $parts[1]; + } + break; + case 'functions': + if (isset($parts[1])) { + $scope['functionId'] = $parts[1]; + } + break; + case 'teams': + if (isset($parts[1])) { + $scope['teamId'] = $parts[1]; + } + break; + } + } + + foreach ($scope as $key => $value) { + // Skip wildcard/empty segments (defensive: events[0] is concrete, but guard anyway). + if ($value !== '' && $value !== '*') { + $metadata[$key] = $value; + } + } + + return $metadata; + } + /** * Converts the channels from the Query Params into an array. * Also renames the account channel to account.USER_ID, rewrites action-suffixed diff --git a/src/Appwrite/Platform/Modules/Compute/Base.php b/src/Appwrite/Platform/Modules/Compute/Base.php index 2dfbd3a6fb..b3740787b3 100644 --- a/src/Appwrite/Platform/Modules/Compute/Base.php +++ b/src/Appwrite/Platform/Modules/Compute/Base.php @@ -33,29 +33,38 @@ class Base extends Action * @param array $plan The billing plan configuration * @return string The appropriate default specification */ - protected function getDefaultSpecification(array $plan): string + protected function getDefaultSpecification(array $plan, string $planKey = 'runtimeSpecifications', string $fallback = APP_COMPUTE_SPECIFICATION_DEFAULT, bool $preferFallback = false): string { $specifications = Config::getParam('specifications', []); if (empty($specifications)) { - return APP_COMPUTE_SPECIFICATION_DEFAULT; + return $fallback; } $specificationValidator = new SpecificationValidator( $plan, $specifications, System::getEnv('_APP_COMPUTE_CPUS', 0), - System::getEnv('_APP_COMPUTE_MEMORY', 0) + System::getEnv('_APP_COMPUTE_MEMORY', 0), + $planKey ); $allowedSpecifications = $specificationValidator->getAllowedSpecifications(); + if (empty($allowedSpecifications)) { + return $fallback; + } + + if ($preferFallback && !array_key_exists($planKey, $plan) && \in_array($fallback, $allowedSpecifications)) { + return $fallback; + } + // If there is no plan use the highest specification if (empty($plan)) { - return end($allowedSpecifications) ?? APP_COMPUTE_SPECIFICATION_DEFAULT; + return end($allowedSpecifications); } // Otherwise, use the lowest specification available in the plan - return $allowedSpecifications[0] ?? APP_COMPUTE_SPECIFICATION_DEFAULT; + return $allowedSpecifications[0]; } public function redeployVcsFunction(Request $request, Document $function, Document $project, Document $installation, Database $dbForProject, BuildPublisher $publisherForBuilds, Document $template, GitHub $github, bool $activate, array $platform = [], string $referenceType = 'branch', string $reference = ''): Document diff --git a/src/Appwrite/Platform/Modules/Compute/Validator/Specification.php b/src/Appwrite/Platform/Modules/Compute/Validator/Specification.php index 5c6cf9ce1f..5f1337c97f 100644 --- a/src/Appwrite/Platform/Modules/Compute/Validator/Specification.php +++ b/src/Appwrite/Platform/Modules/Compute/Validator/Specification.php @@ -14,12 +14,15 @@ class Specification extends Validator private int $maxMemory; - public function __construct(array $plan, array $specifications, float $maxCpus, int $maxMemory) + private string $planKey; + + public function __construct(array $plan, array $specifications, float $maxCpus, int $maxMemory, string $planKey = 'runtimeSpecifications') { $this->plan = $plan; $this->specifications = $specifications; $this->maxCpus = $maxCpus; $this->maxMemory = $maxMemory; + $this->planKey = $planKey; } /** @@ -35,8 +38,8 @@ class Specification extends Validator foreach ($this->specifications as $size => $values) { if ((empty($this->maxCpus) || $values['cpus'] <= $this->maxCpus) && (empty($this->maxMemory) || $values['memory'] <= $this->maxMemory)) { - if (!empty($this->plan) && array_key_exists('runtimeSpecifications', $this->plan)) { - if (!\in_array($size, $this->plan['runtimeSpecifications'])) { + if (!empty($this->plan) && array_key_exists($this->planKey, $this->plan)) { + if (!\in_array($size, $this->plan[$this->planKey])) { continue; } } diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Create.php index 11d3ada810..56fc280bec 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Update.php index 5d8e8bf3a5..0ee43634aa 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/BigInt/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Create.php index 475b43f569..ab664a529b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Create.php @@ -43,6 +43,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Update.php index f55482c408..2812c65bc8 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Update.php @@ -42,6 +42,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Create.php index 7a0776751b..2a702bee44 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Create.php @@ -44,6 +44,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Update.php index f059914a3b..43846d1ad4 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Delete.php index 2808a14088..bbf3d3288e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Delete.php @@ -44,6 +44,7 @@ class Delete extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Create.php index 098083bea6..6d4ece9389 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Create.php @@ -44,6 +44,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Update.php index 0322a69250..0df2a4a4b0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Create.php index 602189e881..f8ac680b57 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Update.php index 260f8acb7d..f72e8c8058 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Update.php @@ -44,6 +44,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Create.php index a715b51b5a..e76127dce5 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Update.php index 14723d3ecb..1ac40d9ccc 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Get.php index 4fc251fe51..61c7760eed 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Get.php @@ -45,6 +45,7 @@ class Get extends Action ->desc('Get attribute') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Create.php index 9a142b1a86..9eb9863bfe 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Create.php @@ -44,6 +44,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Update.php index c34208c080..11b2baf31d 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Create.php index 89aefb87e6..4dccbaa38e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php index 3ac6c5dd4f..78de7d2335 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Create.php index d3f82cd109..34a0f76c20 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Create.php @@ -45,6 +45,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Update.php index 6056504659..f308ec61e2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Update.php @@ -44,6 +44,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Create.php index 6dd7492ce9..de69802a6a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Update.php index 6af0578891..d0e1fedb79 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Longtext/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Create.php index 5e49243481..0d9a66aff5 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Update.php index 1672131123..30a89e545a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Mediumtext/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Create.php index 38082b46da..d4c20ea3a8 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Create.php @@ -45,6 +45,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Update.php index be272231e4..c0656c96c1 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Update.php @@ -44,6 +44,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Create.php index 3063d1938a..82dc8af472 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Create.php @@ -45,6 +45,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Update.php index a5c3cb862b..7a6ffff1ff 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Update.php @@ -44,6 +44,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Create.php index c62b89a633..574495a7d2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Update.php index f173afd4b2..df15b12a6d 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Update.php @@ -45,6 +45,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Create.php index a32a3083ab..b1cd839411 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Create.php @@ -48,6 +48,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Update.php index 317d9ee633..34b95eeecb 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Update.php @@ -45,6 +45,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Create.php index 8943c05339..b07a96ad9e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Create.php @@ -46,6 +46,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Update.php index f86e47f36d..3908488b64 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Text/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Create.php index 7338bdbd1d..6b35d7b3b2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Create.php @@ -44,6 +44,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Update.php index f1f612a94f..700f7c1be1 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Create.php index e45b3fed28..c68a04fdaa 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Create.php @@ -48,6 +48,7 @@ class Create extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].create') ->label('audits.event', 'attribute.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Update.php index 1aacd92fd5..3609c4130f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Varchar/Update.php @@ -45,6 +45,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].attributes.[attributeId].update') ->label('audits.event', 'attribute.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/XList.php index 430117188f..6390797407 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/XList.php @@ -40,6 +40,7 @@ class XList extends Action ->desc('List attributes') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Create.php index 35a6692b88..682ba22e33 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Create.php @@ -56,6 +56,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'collection.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{response.$id}') ->label('sdk', new Method( namespace: 'databases', group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Delete.php index 532ad23c67..90fdf85300 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Delete.php @@ -41,6 +41,7 @@ class Delete extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].delete') ->label('audits.event', 'collection.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'databases', group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php index 48c1802038..785552ddcb 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php @@ -52,6 +52,7 @@ class Decrement extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php index 4d4ecc6777..ecef3fa3c2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php @@ -52,6 +52,7 @@ class Increment extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php index 0959acf27c..4390fd60ce 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php @@ -50,6 +50,7 @@ class Delete extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php index bc09c477d8..f85610b153 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php @@ -53,6 +53,7 @@ class Update extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php index 231a2b3a4d..cf483e7139 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php @@ -50,6 +50,7 @@ class Upsert extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php index 676ff46a91..6d281cd807 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php @@ -67,6 +67,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php index 55be2373a6..17cd5b620b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php @@ -51,6 +51,7 @@ class Delete extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].documents.[documentId].delete') ->label('audits.event', 'document.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Get.php index 1c51e38e2e..54fdfc8a5b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Get.php @@ -43,6 +43,7 @@ class Get extends Action ->groups(['api', 'database']) ->label('scope', 'documents.read') ->label('resourceType', RESOURCE_TYPE_DATABASES) + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php index 7c80a578ff..914a8cc6a9 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php @@ -53,6 +53,7 @@ class Update extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php index 73fcf35b7b..a9f4c5eb0a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php @@ -54,6 +54,7 @@ class Upsert extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.upsert') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php index fd1d5b53d4..c7e3c18db6 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php @@ -51,6 +51,7 @@ class XList extends Action ->groups(['api', 'database']) ->label('scope', 'documents.read') ->label('resourceType', RESOURCE_TYPE_DATABASES) + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/documents') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Get.php index 43364413db..64667f52c0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Get.php @@ -34,6 +34,7 @@ class Get extends Action ->desc('Get collection') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Create.php index 2a2fffcc07..3ba3a4b0b2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Create.php @@ -52,6 +52,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'index.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Delete.php index f88f833764..b982cd4c80 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Delete.php @@ -47,6 +47,7 @@ class Delete extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].indexes.[indexId].update') ->label('audits.event', 'index.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Get.php index 763fd86f7b..39e951e100 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Get.php @@ -35,6 +35,7 @@ class Get extends Action ->desc('Get index') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/XList.php index c4d70c5fb6..506b45a890 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/XList.php @@ -41,6 +41,7 @@ class XList extends Action ->desc('List indexes') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Update.php index 6ba8b67bd4..5e4bcc1226 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Update.php @@ -44,6 +44,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].collections.[collectionId].update') ->label('audits.event', 'collection.update') ->label('audits.resource', 'database/{request.databaseId}/collections/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collections/{request.collectionId}') ->label('sdk', new Method( namespace: 'databases', group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/XList.php index 5d1ccbd45f..5731fd9aff 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/XList.php @@ -42,6 +42,7 @@ class XList extends Action ->desc('List collections') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Create.php index 870ee4116e..09b1c274ec 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Create.php @@ -147,6 +147,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'database.create') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', [ new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Delete.php index 6394e2667e..bbdd172e0c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Delete.php @@ -35,6 +35,7 @@ class Delete extends Action ->label('event', 'databases.[databaseId].delete') ->label('audits.event', 'database.delete') ->label('audits.resource', 'database/{request.databaseId}') + ->label('usage.resource', 'database/{request.databaseId}') ->label('sdk', [ new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Get.php index 5ee8e2f5e3..d5e2a3eabf 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Get.php @@ -28,6 +28,7 @@ class Get extends Action ->desc('Get database') ->groups(['api', 'database']) ->label('scope', 'databases.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', [ new Method( diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Get.php index dc20349e7c..d31c2fb48b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Get.php @@ -33,6 +33,7 @@ class Get extends Action ->desc('Get transaction') ->groups(['api', 'database', 'transactions']) ->label('scope', 'rows.read') + ->label('usage.resource', 'transaction/{request.transactionId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Update.php index c681d0b3f3..c6373757be 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Update.php @@ -35,6 +35,7 @@ class Update extends Action ->label('event', 'databases.[databaseId].update') ->label('audits.event', 'database.update') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', [ new Method( namespace: 'databases', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Create.php index d1e91addf7..090a39ef2c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Create.php @@ -43,6 +43,7 @@ class Create extends CollectionCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'collections.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{response.$id}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Delete.php index 043f74998d..07c14b5bc3 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Delete.php @@ -35,6 +35,7 @@ class Delete extends CollectionDelete ->label('event', 'databases.[databaseId].collections.[collectionId].delete') ->label('audits.event', 'collection.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Decrement.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Decrement.php index 6d986fc6b1..44c67e4451 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Decrement.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Decrement.php @@ -37,6 +37,7 @@ class Decrement extends DecrementDocumentAttribute ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Increment.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Increment.php index 09def76941..81cbeb303f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Increment.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Attribute/Increment.php @@ -37,6 +37,7 @@ class Increment extends IncrementDocumentAttribute ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Delete.php index 6b2910aac4..fcc32ca6f3 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Delete.php @@ -36,6 +36,7 @@ class Delete extends DocumentsDelete ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Update.php index f395d0b490..a40a3b42fb 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Update.php @@ -37,6 +37,7 @@ class Update extends DocumentsUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Upsert.php index 5acc4626af..b996f8f036 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Bulk/Upsert.php @@ -36,6 +36,7 @@ class Upsert extends DocumentsUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php index 2df96958ad..b4a2816ba3 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php @@ -51,6 +51,7 @@ class Create extends DocumentCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Delete.php index 0253c287aa..b0aa5eb218 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Delete.php @@ -41,6 +41,7 @@ class Delete extends DocumentDelete ->label('event', 'databases.[databaseId].collections.[collectionId].documents.[documentId].delete') ->label('audits.event', 'document.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Get.php index 47d352bf98..ec02abe2aa 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Get.php @@ -33,6 +33,7 @@ class Get extends DocumentGet ->desc('Get document') ->groups(['api', 'database']) ->label('scope', 'documents.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Update.php index 9e79bb5464..e62b62d801 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Update.php @@ -38,6 +38,7 @@ class Update extends DocumentUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Upsert.php index 448c2d44bc..017935aec1 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Upsert.php @@ -38,6 +38,7 @@ class Upsert extends DocumentUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.upsert') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/XList.php index 51c0d67e8a..f2da8d262b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/XList.php @@ -35,6 +35,7 @@ class XList extends DocumentXList ->desc('List documents') ->groups(['api', 'database']) ->label('scope', 'documents.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Get.php index 53120dd636..d112f919e2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Get.php @@ -31,6 +31,7 @@ class Get extends CollectionGet ->desc('Get collection') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Create.php index 65002e2f30..eb5f329734 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Create.php @@ -42,6 +42,7 @@ class Create extends IndexCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'index.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'documentsDB', group: $this->getSdkGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Delete.php index 1e3c012b4f..39082c5bb5 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Delete.php @@ -40,6 +40,7 @@ class Delete extends IndexDelete ->label('event', 'databases.[databaseId].collections.[collectionId].indexes.[indexId].update') ->label('audits.event', 'index.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'documentsDB', group: $this->getSdkGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Get.php index 7fa75b6ed9..567abaefed 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/Get.php @@ -32,6 +32,7 @@ class Get extends IndexGet ->desc('Get index') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/XList.php index 1e16155f76..93ffb8fb55 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Indexes/XList.php @@ -33,6 +33,7 @@ class XList extends IndexXList ->desc('List indexes') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Update.php index 3acedc0379..8624cd6d61 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Update.php @@ -38,6 +38,7 @@ class Update extends CollectionUpdate ->label('event', 'databases.[databaseId].collections.[collectionId].update') ->label('audits.event', 'collection.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/XList.php index 638244145b..2fde8aa50b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/XList.php @@ -34,6 +34,7 @@ class XList extends CollectionXList ->desc('List collections') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Create.php index f9b425b3e6..5dadeb738c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Create.php @@ -33,6 +33,7 @@ class Create extends DatabaseCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'database.create') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'documentsdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Delete.php index 5e63ab8a7f..d79fa3460a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Delete.php @@ -31,6 +31,7 @@ class Delete extends DatabaseDelete ->label('event', 'databases.[databaseId].delete') ->label('audits.event', 'database.delete') ->label('audits.resource', 'database/{request.databaseId}') + ->label('usage.resource', 'database/{request.databaseId}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'documentsdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Get.php index 309a3b867e..d2a1f65779 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Get.php @@ -27,6 +27,7 @@ class Get extends DatabaseGet ->desc('Get database') ->groups(['api', 'database']) ->label('scope', 'databases.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Transactions/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Transactions/Get.php index 7def4f0b9a..c2f4b85881 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Transactions/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Transactions/Get.php @@ -31,6 +31,7 @@ class Get extends TransactionsGet ->desc('Get transaction') ->groups(['api', 'database', 'transactions']) ->label('scope', 'documents.read') + ->label('usage.resource', 'transaction/{request.transactionId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'documentsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Update.php index 4bf5747b54..da8a14ffc7 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Update.php @@ -33,6 +33,7 @@ class Update extends DatabaseUpdate ->label('event', 'databases.[databaseId].update') ->label('audits.event', 'database.update') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'documentsDB', group: 'documentsdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Create.php index eb2293dc28..996351c062 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Create.php @@ -33,6 +33,7 @@ class Create extends DatabaseCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'database.create') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'tablesDB', group: 'tablesdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Delete.php index 70dc8430f2..7d0d8953cd 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Delete.php @@ -31,6 +31,7 @@ class Delete extends DatabaseDelete ->label('event', 'databases.[databaseId].delete') ->label('audits.event', 'database.delete') ->label('audits.resource', 'database/{request.databaseId}') + ->label('usage.resource', 'database/{request.databaseId}') ->label('sdk', new Method( namespace: 'tablesDB', group: 'tablesdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Get.php index 5fad045dda..a7171c9691 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Get.php @@ -27,6 +27,7 @@ class Get extends DatabaseGet ->desc('Get database') ->groups(['api', 'database']) ->label('scope', 'databases.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'tablesDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Create.php index 9d882e09a6..0cabf0db82 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Create.php @@ -39,6 +39,7 @@ class Create extends BigIntCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Update.php index b2754a2b7d..b0e6ff9dbd 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/BigInt/Update.php @@ -40,6 +40,7 @@ class Update extends BigIntUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Create.php index 334c8b5124..8319d969f3 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Create.php @@ -38,6 +38,7 @@ class Create extends BooleanCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Update.php index 1e0fe04bdc..a0d1106a51 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Update.php @@ -39,6 +39,7 @@ class Update extends BooleanUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Create.php index 922e071f35..912726c60e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Create.php @@ -39,6 +39,7 @@ class Create extends DatetimeCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Update.php index c4ff9055fb..be53844c29 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Update.php @@ -40,6 +40,7 @@ class Update extends DatetimeUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Delete.php index 8e0abf211f..8d79304d65 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Delete.php @@ -38,6 +38,7 @@ class Delete extends AttributesDelete ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.delete') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Create.php index 072e334b4b..3e7e30a382 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Create.php @@ -39,6 +39,7 @@ class Create extends EmailCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Update.php index c116d8c5b1..579834d1bf 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Update.php @@ -40,6 +40,7 @@ class Update extends EmailUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Create.php index 9d24f310bd..77cf1ff42c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Create.php @@ -40,6 +40,7 @@ class Create extends EnumCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Update.php index 208fa9c8cf..f9a3333b55 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Update.php @@ -41,6 +41,7 @@ class Update extends EnumUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Create.php index d68b3a4921..930d612aa9 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Create.php @@ -39,6 +39,7 @@ class Create extends FloatCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Update.php index 9ab61e642b..35d6eee993 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Update.php @@ -40,6 +40,7 @@ class Update extends FloatUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Get.php index b0ef9e8a85..9885f44ca4 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Get.php @@ -43,6 +43,7 @@ class Get extends AttributesGet ->desc('Get column') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read', 'columns.read', 'attributes.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Create.php index ff5828e749..cd3bfe1537 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Create.php @@ -39,6 +39,7 @@ class Create extends IPCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Update.php index dcc4160580..3d5cbe2b23 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Update.php @@ -40,6 +40,7 @@ class Update extends IPUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Create.php index dec399cdb2..bb50426c7a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Create.php @@ -39,6 +39,7 @@ class Create extends IntegerCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php index 58dea7c848..4e8e1db70c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php @@ -40,6 +40,7 @@ class Update extends IntegerUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Create.php index 71548c74da..2277c8ef62 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Create.php @@ -39,6 +39,7 @@ class Create extends LineCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Update.php index e2e8c59121..82dcbb9a56 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Update.php @@ -40,6 +40,7 @@ class Update extends LineUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Create.php index ec0f633400..0418c0fe0f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Create.php @@ -38,6 +38,7 @@ class Create extends LongtextCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Update.php index 9b90b745a2..aecbcea09f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Longtext/Update.php @@ -39,6 +39,7 @@ class Update extends LongtextUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Create.php index 2728caa58f..baf3c3964f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Create.php @@ -38,6 +38,7 @@ class Create extends MediumtextCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Update.php index 03009da25c..f87aacb2e6 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Mediumtext/Update.php @@ -39,6 +39,7 @@ class Update extends MediumtextUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Create.php index 601e19299b..c1489b0683 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Create.php @@ -39,6 +39,7 @@ class Create extends PointCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Update.php index 66fb451a1f..81455b32b0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Update.php @@ -40,6 +40,7 @@ class Update extends PointUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Create.php index 36972d5da2..7711e903af 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Create.php @@ -39,6 +39,7 @@ class Create extends PolygonCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Update.php index 7a2fd8a5de..d36bb12555 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Update.php @@ -40,6 +40,7 @@ class Update extends PolygonUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Create.php index db8b17473c..3055a80743 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Create.php @@ -40,6 +40,7 @@ class Create extends RelationshipCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Update.php index 0ec8f4ba07..9619ae01e0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Update.php @@ -40,6 +40,7 @@ class Update extends RelationshipUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Create.php index 8151b3e8da..052c723fb8 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Create.php @@ -42,6 +42,7 @@ class Create extends StringCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Update.php index 2ec806d4fe..39fc773fd9 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Update.php @@ -42,6 +42,7 @@ class Update extends StringUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Create.php index bffdc96001..aa1a5cdd70 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Create.php @@ -38,6 +38,7 @@ class Create extends TextCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Update.php index 4c1477fb9e..16017b884b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Text/Update.php @@ -39,6 +39,7 @@ class Update extends TextUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Create.php index 2edf4a62f6..d506bac1b7 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Create.php @@ -39,6 +39,7 @@ class Create extends URLCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Update.php index d680389d9e..14949135ee 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Update.php @@ -40,6 +40,7 @@ class Update extends URLUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Create.php index 307a1fd5e3..c51b0c7566 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Create.php @@ -40,6 +40,7 @@ class Create extends VarcharCreate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].create') ->label('audits.event', 'column.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Update.php index dd170a0a19..315836880b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Varchar/Update.php @@ -41,6 +41,7 @@ class Update extends VarcharUpdate ->label('event', 'databases.[databaseId].tables.[tableId].columns.[columnId].update') ->label('audits.event', 'column.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/XList.php index 56c436a13e..643ff94db4 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/XList.php @@ -34,6 +34,7 @@ class XList extends AttributesXList ->desc('List columns') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read', 'columns.read', 'attributes.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Create.php index 48f1136b09..643ab1909c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Create.php @@ -43,6 +43,7 @@ class Create extends CollectionCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'table.create') ->label('audits.resource', 'database/{request.databaseId}/table/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/table/{response.$id}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: 'tables', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Delete.php index 3a6d6666f2..3e380daa13 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Delete.php @@ -36,6 +36,7 @@ class Delete extends CollectionDelete ->label('event', 'databases.[databaseId].tables.[tableId].delete') ->label('audits.event', 'table.delete') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: 'tables', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Get.php index ca104f05c4..f7d61f0ebe 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Get.php @@ -32,6 +32,7 @@ class Get extends CollectionGet ->desc('Get table') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Create.php index d6c2bf29f3..1ebc0664db 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Create.php @@ -42,6 +42,7 @@ class Create extends IndexCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'index.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Delete.php index 6cd5cfe78f..fa7ffc9954 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Delete.php @@ -41,6 +41,7 @@ class Delete extends IndexDelete ->label('event', 'databases.[databaseId].tables.[tableId].indexes.[indexId].update') ->label('audits.event', 'index.delete') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Get.php index 9918bcb2b8..96e185e01a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/Get.php @@ -33,6 +33,7 @@ class Get extends IndexGet ->desc('Get index') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read', 'indexes.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/XList.php index 5fe3be4c05..b67ea60f44 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Indexes/XList.php @@ -34,6 +34,7 @@ class XList extends IndexXList ->desc('List indexes') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read', 'indexes.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Delete.php index 8315a8d04b..42e49db646 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Delete.php @@ -38,6 +38,7 @@ class Delete extends DocumentsDelete ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'rows.delete') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php index a31ebc15e0..bc15c0e22b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php @@ -39,6 +39,7 @@ class Update extends DocumentsUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'rows.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Upsert.php index 543de8c4bc..e9edf8deb1 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Upsert.php @@ -38,6 +38,7 @@ class Upsert extends DocumentsUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'row.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Decrement.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Decrement.php index ea1bfa163d..f6174ec518 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Decrement.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Decrement.php @@ -39,6 +39,7 @@ class Decrement extends DecrementDocumentAttribute ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'rows.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Increment.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Increment.php index 2f8be876d7..36761c44a7 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Increment.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Increment.php @@ -39,6 +39,7 @@ class Increment extends IncrementDocumentAttribute ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'rows.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php index ea9e3e0b03..36cf0485a6 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php @@ -46,6 +46,7 @@ class Create extends DocumentCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'row.create') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php index 06aee2cb30..12b8ba510c 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php @@ -43,6 +43,7 @@ class Delete extends DocumentDelete ->label('event', 'databases.[databaseId].tables.[tableId].rows.[rowId].delete') ->label('audits.event', 'row.delete') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{request.rowId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{request.rowId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Get.php index 65ae238a1a..4b5b427f88 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Get.php @@ -35,6 +35,7 @@ class Get extends DocumentGet ->desc('Get row') ->groups(['api', 'database']) ->label('scope', ['rows.read', 'documents.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php index 93ec5d3b58..817125b3eb 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php @@ -39,6 +39,7 @@ class Update extends DocumentUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'row.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php index 472a49cf64..52f12a9337 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php @@ -39,6 +39,7 @@ class Upsert extends DocumentUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'row.upsert') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}/row/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/XList.php index 87e276719e..b951fec8f8 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/XList.php @@ -37,6 +37,7 @@ class XList extends DocumentXList ->desc('List rows') ->groups(['api', 'database']) ->label('scope', ['rows.read', 'documents.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Update.php index d10380a0e8..fb60ac19cb 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Update.php @@ -40,6 +40,7 @@ class Update extends CollectionUpdate ->label('event', 'databases.[databaseId].tables.[tableId].update') ->label('audits.event', 'table.update') ->label('audits.resource', 'database/{request.databaseId}/table/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/table/{request.tableId}') ->label('sdk', new Method( namespace: $this->getSDKNamespace(), group: 'tables', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/XList.php index 30ebbab409..fd8e51b467 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/XList.php @@ -35,6 +35,7 @@ class XList extends CollectionXList ->desc('List tables') ->groups(['api', 'database']) ->label('scope', ['tables.read', 'collections.read']) + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: $this->getSDKNamespace(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Transactions/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Transactions/Get.php index d81d3e579d..cfb621d28d 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Transactions/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Transactions/Get.php @@ -32,6 +32,7 @@ class Get extends TransactionsGet ->desc('Get transaction') ->groups(['api', 'database', 'transactions']) ->label('scope', ['documents.read', 'rows.read']) + ->label('usage.resource', 'transaction/{request.transactionId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'tablesDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Update.php index e5e6fa6f34..d72a3326be 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Update.php @@ -33,6 +33,7 @@ class Update extends DatabaseUpdate ->label('event', 'databases.[databaseId].update') ->label('audits.event', 'database.update') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'tablesDB', group: 'tablesdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Create.php index 49de7f7cc5..ff175e03d9 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Create.php @@ -52,6 +52,7 @@ class Create extends CollectionAction ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'collection.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{response.$id}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Delete.php index 6ee83b2530..0b289cadf0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Delete.php @@ -35,6 +35,7 @@ class Delete extends CollectionDelete ->label('event', 'databases.[databaseId].collections.[collectionId].delete') ->label('audits.event', 'collection.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Delete.php index 4c7d97aa55..d5a9a44f13 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Delete.php @@ -36,6 +36,7 @@ class Delete extends DocumentsDelete ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Update.php index 18e441ede7..2734e5d002 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Update.php @@ -37,6 +37,7 @@ class Update extends DocumentsUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'documents.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Upsert.php index c26e61d716..d0ac2a2ba6 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Bulk/Upsert.php @@ -36,6 +36,7 @@ class Upsert extends DocumentsUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php index dee8d8e85f..c771d61fa3 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php @@ -45,6 +45,7 @@ class Create extends DocumentCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Delete.php index e81e34e1e5..653e032a69 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Delete.php @@ -41,6 +41,7 @@ class Delete extends DocumentDelete ->label('event', 'databases.[databaseId].collections.[collectionId].documents.[documentId].delete') ->label('audits.event', 'document.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{request.documentId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Get.php index 73f7a55026..35dc3f178a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Get.php @@ -33,6 +33,7 @@ class Get extends DocumentGet ->desc('Get document') ->groups(['api', 'database']) ->label('scope', 'documents.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Update.php index 8a8b9d89ae..1e9d6a24e4 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Update.php @@ -38,6 +38,7 @@ class Update extends DocumentUpdate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Upsert.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Upsert.php index f8f17d33d9..a7125db2a7 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Upsert.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Upsert.php @@ -39,6 +39,7 @@ class Upsert extends DocumentUpsert ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'document.upsert') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}/document/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/XList.php index c9ed05ac02..1b11b282fd 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/XList.php @@ -35,6 +35,7 @@ class XList extends DocumentXList ->desc('List documents') ->groups(['api', 'database']) ->label('scope', 'documents.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Get.php index 9619bb5048..73c0a9d3dc 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Get.php @@ -31,6 +31,7 @@ class Get extends CollectionGet ->desc('Get collection') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Create.php index e7e8c8cb1f..f7b05690dd 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Create.php @@ -42,6 +42,7 @@ class Create extends IndexCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'index.create') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.tableId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.tableId}') ->label('sdk', new Method( namespace: 'vectorsDB', group: $this->getSdkGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Delete.php index 67e13dd26a..c780fb928e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Delete.php @@ -40,6 +40,7 @@ class Delete extends IndexDelete ->label('event', 'databases.[databaseId].collections.[collectionId].indexes.[indexId].update') ->label('audits.event', 'index.delete') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'vectorsDB', group: $this->getSdkGroup(), diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Get.php index 4cf646acba..3d1b492ff9 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/Get.php @@ -32,6 +32,7 @@ class Get extends IndexGet ->desc('Get index') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/XList.php index acc46fb570..8475349979 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Indexes/XList.php @@ -33,6 +33,7 @@ class XList extends IndexXList ->desc('List indexes') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Update.php index 12b680496a..d4f70707d0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Update.php @@ -44,6 +44,7 @@ class Update extends CollectionAction ->label('event', 'databases.[databaseId].collections.[collectionId].update') ->label('audits.event', 'collection.update') ->label('audits.resource', 'database/{request.databaseId}/collection/{request.collectionId}') + ->label('usage.resource', 'database/{request.databaseId}/collection/{request.collectionId}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'collections', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/XList.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/XList.php index 7ba26b8b6a..ac6a20c457 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/XList.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/XList.php @@ -34,6 +34,7 @@ class XList extends CollectionXList ->desc('List collections') ->groups(['api', 'database']) ->label('scope', 'collections.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Create.php index cc2914fc10..15a60df913 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Create.php @@ -32,6 +32,7 @@ class Create extends DatabaseCreate ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('audits.event', 'database.create') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'vectorsdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Delete.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Delete.php index a33eedccd5..3da226560f 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Delete.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Delete.php @@ -30,6 +30,7 @@ class Delete extends DatabaseDelete ->label('event', 'databases.[databaseId].delete') ->label('audits.event', 'database.delete') ->label('audits.resource', 'database/{request.databaseId}') + ->label('usage.resource', 'database/{request.databaseId}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'vectorsdb', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Embeddings/Text/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Embeddings/Text/Create.php index 6cf2f47910..a77cc51f1b 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Embeddings/Text/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Embeddings/Text/Create.php @@ -50,6 +50,7 @@ class Create extends CreateDocumentAction ->label('resourceType', RESOURCE_TYPE_EMBEDDINGS_TEXT) ->label('audits.event', 'embedding.create') ->label('audits.resource', 'vectorsdb/embeddings/text') + ->label('usage.resource', 'database/embeddings/text') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT * 2) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Get.php index a79632b105..606fb7150a 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Get.php @@ -26,6 +26,7 @@ class Get extends DatabaseGet ->desc('Get database') ->groups(['api', 'database']) ->label('scope', 'databases.read') + ->label('usage.resource', 'database/{request.databaseId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Transactions/Get.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Transactions/Get.php index fa4cc86cdd..5b1a227844 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Transactions/Get.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Transactions/Get.php @@ -31,6 +31,7 @@ class Get extends TransactionsGet ->desc('Get transaction') ->groups(['api', 'database', 'transactions']) ->label('scope', 'documents.read') + ->label('usage.resource', 'transaction/{request.transactionId}') ->label('resourceType', RESOURCE_TYPE_DATABASES) ->label('sdk', new Method( namespace: 'vectorsDB', diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Update.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Update.php index 0b10d6d98b..f35ffb7139 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Update.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Update.php @@ -32,6 +32,7 @@ class Update extends DatabaseUpdate ->label('event', 'databases.[databaseId].update') ->label('audits.event', 'database.update') ->label('audits.resource', 'database/{response.$id}') + ->label('usage.resource', 'database/{response.$id}') ->label('sdk', new Method( namespace: 'vectorsDB', group: 'vectorsdb', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Create.php index 0269c3df19..fbc07bb89b 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Create.php @@ -55,6 +55,7 @@ class Create extends Action ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('audits.event', 'deployment.create') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php index 6862b0d776..0f26d518d3 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php @@ -41,6 +41,7 @@ class Delete extends Action ->label('event', 'functions.[functionId].deployments.[deploymentId].delete') ->label('audits.event', 'deployment.delete') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Download/Get.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Download/Get.php index 2d57ec5525..70d20fc0d9 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Download/Get.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Download/Get.php @@ -36,6 +36,7 @@ class Get extends Action ->groups(['api', 'functions']) ->desc('Get deployment download') ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 93f34ebb05..9b344b749f 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -41,6 +41,7 @@ class Create extends Action ->label('event', 'functions.[functionId].deployments.[deploymentId].update') ->label('audits.event', 'deployment.update') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Get.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Get.php index 57c4421928..31a395341b 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Get.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Get.php @@ -29,6 +29,7 @@ class Get extends Action ->desc('Get deployment') ->groups(['api', 'functions']) ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Status/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Status/Update.php index 85d93c14c1..e0f60e40cc 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Status/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Status/Update.php @@ -38,6 +38,7 @@ class Update extends Action ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('audits.event', 'deployment.update') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Template/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Template/Create.php index 136549e9c9..e710da13cc 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Template/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Template/Create.php @@ -48,6 +48,7 @@ class Create extends Base ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('audits.event', 'deployment.create') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Vcs/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Vcs/Create.php index 4a9ae4051f..c3d9fbdfae 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Vcs/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Vcs/Create.php @@ -43,6 +43,7 @@ class Create extends Base ->label('event', 'functions.[functionId].deployments.[deploymentId].create') ->label('audits.event', 'deployment.create') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/XList.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/XList.php index e8e9ea9a18..581dea3d12 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/XList.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/XList.php @@ -40,6 +40,7 @@ class XList extends Base ->desc('List deployments') ->groups(['api', 'functions']) ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php index aaa068feb9..303bf1484b 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php @@ -66,6 +66,7 @@ class Create extends Base ->label('scope', ['executions.write', 'execution.write']) ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('event', 'functions.[functionId].executions.[executionId].create') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'executions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Delete.php b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Delete.php index 9ecb5c0bf0..227793f264 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Delete.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Delete.php @@ -40,6 +40,7 @@ class Delete extends Base ->label('event', 'functions.[functionId].executions.[executionId].delete') ->label('audits.event', 'executions.delete') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'executions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Get.php b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Get.php index 9908669f84..027ff51166 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Executions/Get.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Executions/Get.php @@ -32,6 +32,7 @@ class Get extends Base ->desc('Get execution') ->groups(['api', 'functions']) ->label('scope', ['executions.read', 'execution.read']) + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Executions/XList.php b/src/Appwrite/Platform/Modules/Functions/Http/Executions/XList.php index bf31fa0ced..29bed70cd0 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Executions/XList.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Executions/XList.php @@ -40,6 +40,7 @@ class XList extends Base ->desc('List executions') ->groups(['api', 'functions']) ->label('scope', ['executions.read', 'execution.read']) + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index e989316488..e674b935c9 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -64,6 +64,7 @@ class Create extends Base ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('audits.event', 'function.create') ->label('audits.resource', 'function/{response.$id}') + ->label('usage.resource', 'function/{response.$id}') ->label('sdk', new Method( namespace: 'functions', group: 'functions', @@ -98,11 +99,12 @@ class Create extends Base ->param('providerRootDirectory', '', new Text(128, 0), 'Path to function code in the linked repo.', true) ->param('providerBranches', [], new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE), 'List of branch name patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all branches.', true) ->param('providerPaths', [], new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE), 'List of file path patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all file changes.', true) - ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( + ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan, 'buildSpecifications'), fn (array $plan) => new Specification( $plan, Config::getParam('specifications', []), System::getEnv('_APP_COMPUTE_CPUS', 0), - System::getEnv('_APP_COMPUTE_MEMORY', 0) + System::getEnv('_APP_COMPUTE_MEMORY', 0), + 'buildSpecifications' ), 'Build specification for the function deployments.', true, ['plan']) ->param('runtimeSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( $plan, diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Delete.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Delete.php index 1517ee7793..cf7ce831ae 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Delete.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Delete.php @@ -41,6 +41,7 @@ class Delete extends Base ->label('event', 'functions.[functionId].delete') ->label('audits.event', 'function.delete') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Deployment/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Deployment/Update.php index 6b6eda36ab..dd5e576f02 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Deployment/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Deployment/Update.php @@ -40,6 +40,7 @@ class Update extends Base ->label('event', 'functions.[functionId].deployments.[deploymentId].update') ->label('audits.event', 'deployment.update') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Get.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Get.php index 9fab8afef8..449413cb10 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Get.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Get.php @@ -30,6 +30,7 @@ class Get extends Base ->desc('Get function') ->groups(['api', 'functions']) ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('sdk', new Method( namespace: 'functions', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index 81ec55722a..5a6f3f8045 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -56,6 +56,7 @@ class Update extends Base ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label('audits.event', 'function.update') ->label('audits.resource', 'function/{response.$id}') + ->label('usage.resource', 'function/{response.$id}') ->label('sdk', new Method( namespace: 'functions', group: 'functions', @@ -90,12 +91,13 @@ class Update extends Base ->param('providerRootDirectory', '', new Text(128, 0), 'Path to function code in the linked repo.', true) ->param('providerBranches', null, new Nullable(new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'List of branch name patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all branches.', true) ->param('providerPaths', null, new Nullable(new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'List of file path patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all file changes.', true) - ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( + ->param('buildSpecification', null, fn (array $plan) => new Nullable(new Specification( $plan, Config::getParam('specifications', []), System::getEnv('_APP_COMPUTE_CPUS', 0), - System::getEnv('_APP_COMPUTE_MEMORY', 0) - ), 'Build specification for the function deployments.', true, ['plan']) + System::getEnv('_APP_COMPUTE_MEMORY', 0), + 'buildSpecifications' + )), 'Build specification for the function deployments.', true, ['plan']) ->param('runtimeSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( $plan, Config::getParam('specifications', []), @@ -137,7 +139,7 @@ class Update extends Base string $providerRootDirectory, ?array $providerBranches, ?array $providerPaths, - string $buildSpecification, + ?string $buildSpecification, string $runtimeSpecification, int $deploymentRetention, Request $request, @@ -173,6 +175,8 @@ class Update extends Base $runtime = $function->getAttribute('runtime'); } + $buildSpecification ??= $function->getAttribute('buildSpecification', APP_COMPUTE_SPECIFICATION_DEFAULT); + $repositoryId = $function->getAttribute('repositoryId', ''); $repositoryInternalId = $function->getAttribute('repositoryInternalId', ''); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Specifications/XList.php b/src/Appwrite/Platform/Modules/Functions/Http/Specifications/XList.php index d76584534d..8cbff906fa 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Specifications/XList.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Specifications/XList.php @@ -12,6 +12,7 @@ use Utopia\Database\Document; use Utopia\Platform\Action; use Utopia\Platform\Scope\HTTP; use Utopia\System\System; +use Utopia\Validator\WhiteList; class XList extends Base { @@ -46,21 +47,23 @@ class XList extends Base ) ] )) + ->param('type', 'runtimes', new WhiteList(['runtimes', 'builds']), 'Specification type to list. Can be one of: runtimes, builds.', true) ->inject('response') ->inject('plan') ->callback($this->action(...)); } - public function action(Response $response, array $plan) + public function action(string $type, Response $response, array $plan) { $allSpecs = Config::getParam('specifications', []); + $planKey = $type === 'builds' ? 'buildSpecifications' : 'runtimeSpecifications'; $specs = []; foreach ($allSpecs as $spec) { $spec['enabled'] = true; - if (array_key_exists('runtimeSpecifications', $plan)) { - $spec['enabled'] = in_array($spec['slug'], $plan['runtimeSpecifications']); + if (array_key_exists($planKey, $plan)) { + $spec['enabled'] = in_array($spec['slug'], $plan[$planKey]); } $maxCpus = System::getEnv('_APP_COMPUTE_CPUS', 0); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Create.php index de572cd41e..c1852ea377 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Create.php @@ -43,6 +43,7 @@ class Create extends Base ->label('event', 'variables.[variableId].create') ->label('audits.event', 'variable.create') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'variables', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Delete.php b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Delete.php index fa9f19ba8f..3605f3089e 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Delete.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Delete.php @@ -39,6 +39,7 @@ class Delete extends Base ->label('event', 'variables.[variableId].delete') ->label('audits.event', 'variable.delete') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'variables', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Get.php index 13ce73e751..41decb1a48 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Get.php @@ -30,6 +30,7 @@ class Get extends Base ->desc('Get variable') ->groups(['api', 'functions']) ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label( 'sdk', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Update.php index 6413b29f82..6cf99017b3 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Variables/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Variables/Update.php @@ -42,6 +42,7 @@ class Update extends Base ->label('event', 'variables.[variableId].update') ->label('audits.event', 'variable.update') ->label('audits.resource', 'function/{request.functionId}') + ->label('usage.resource', 'function/{request.functionId}') ->label('sdk', new Method( namespace: 'functions', group: 'variables', diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Variables/XList.php b/src/Appwrite/Platform/Modules/Functions/Http/Variables/XList.php index b330812b96..bf6ba67190 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Variables/XList.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Variables/XList.php @@ -37,6 +37,7 @@ class XList extends Base ->desc('List variables') ->groups(['api', 'functions']) ->label('scope', 'functions.read') + ->label('usage.resource', 'function/{request.functionId}') ->label('resourceType', RESOURCE_TYPE_FUNCTIONS) ->label( 'sdk', diff --git a/src/Appwrite/Platform/Modules/Functions/Workers/BuildException.php b/src/Appwrite/Platform/Modules/Functions/Workers/BuildException.php new file mode 100644 index 0000000000..1496fd7b72 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Functions/Workers/BuildException.php @@ -0,0 +1,23 @@ +getCollection()) { 'functions' => 'functionId', @@ -215,7 +216,7 @@ class Builds extends Action } if ($isResourceBlocked($project, $resource->getCollection() === 'functions' ? RESOURCE_TYPE_FUNCTIONS : RESOURCE_TYPE_SITES, $resource->getId())) { - throw new \Exception('Resource is blocked'); + throw new BuildException('Resource is blocked'); } $log->addTag('deploymentId', $deployment->getId()); @@ -226,7 +227,7 @@ class Builds extends Action } if ($resource->getCollection() === 'functions' && empty($deployment->getAttribute('entrypoint', ''))) { - throw new \Exception('Entrypoint for your Appwrite Function is missing. Please specify it when making deployment or update the entrypoint under your function\'s "Settings" > "Configuration" > "Entrypoint".'); + throw new BuildException('Entrypoint for your Appwrite Function is missing. Please specify it when making deployment or update the entrypoint under your function\'s "Settings" > "Configuration" > "Entrypoint".'); } $version = $this->getVersion($resource); @@ -294,9 +295,20 @@ class Builds extends Action $privateKey = System::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY'); $githubAppId = System::getEnv('_APP_VCS_GITHUB_APP_ID'); - $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId); + try { + $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId); + } catch (\Exception $e) { + if ($e->getCode() === 404 + && $resource->getAttribute('installationId', '') === $installationId) { + $this->disconnectVcs($resource, $dbForProject, $dbForPlatform); + } + throw $e; + } } + Span::add('timings.setup', \round(\microtime(true) - $phaseStart, 3)); + $phaseStart = \microtime(true); + try { if (! $isVcsEnabled) { // Non-VCS + Template @@ -406,7 +418,7 @@ class Builds extends Action $exit = Console::execute($gitCloneCommand, '', $stdout, $stderr); if ($exit !== 0) { - throw new \Exception('Unable to clone code repository: ' . $stderr); + throw new BuildException('Unable to clone code repository: ' . $stderr); } // Local refactoring for function folder with spaces @@ -501,7 +513,7 @@ class Builds extends Action } if ($directorySize > $sizeLimit && $sizeLimit !== 0) { - throw new \Exception('Repository directory size should be less than ' . number_format($sizeLimit / (1000 * 1000), 2) . ' MBs.'); + throw new BuildException('Repository directory size should be less than ' . number_format($sizeLimit / (1000 * 1000), 2) . ' MBs.'); } Console::execute('find ' . \escapeshellarg($tmpDirectory) . ' -type d -name ".git" -exec rm -rf {} +', '', $stdout, $stderr); @@ -539,6 +551,9 @@ class Builds extends Action $this->runGitAction('processing', $github, $providerCommitHash, $owner, $repositoryName, $project, $resource, $deployment->getId(), $dbForProject, $dbForPlatform, $queueForRealtime, $platform); } + Span::add('timings.source', \round(\microtime(true) - $phaseStart, 3)); + $phaseStart = \microtime(true); + /** Request the executor to build the code... */ $updated = $dbForProject->updateDocuments('deployments', new Document([ 'status' => 'building', @@ -741,7 +756,7 @@ class Builds extends Action $span?->set('build.runtime.timed_out', true); $span?->set('build.runtime.error_type', $error::class); $span?->set('build.runtime.error_message', $error->getMessage()); - $err = new AppwriteException(AppwriteException::BUILD_TIMEOUT, previous: $error); + $err = new BuildException(type: AppwriteException::BUILD_TIMEOUT, previous: $error); } catch (\Throwable $error) { $span?->set('build.runtime.error_type', $error::class); $span?->set('build.runtime.error_message', $error->getMessage()); @@ -851,6 +866,9 @@ class Builds extends Action }), ]); + Span::add('timings.build', \round(\microtime(true) - $phaseStart, 3)); + $phaseStart = \microtime(true); + $latestDeployment = $dbForProject->getDocument('deployments', $deploymentId); if ($latestDeployment->getAttribute('status') === 'canceled') { $this->finalizeCanceledDeployment($deployment->getId(), $dbForProject, $queueForRealtime); @@ -867,7 +885,7 @@ class Builds extends Action $buildSizeLimit = $plan['buildSize'] * 1000 * 1000; } if ($response['size'] > $buildSizeLimit && $buildSizeLimit !== 0) { - throw new \Exception('Build size should be less than ' . number_format($buildSizeLimit / (1000 * 1000), 2) . ' MBs.'); + throw new BuildException('Build size should be less than ' . number_format($buildSizeLimit / (1000 * 1000), 2) . ' MBs.'); } $deployment->setAttribute('buildPath', $response['path']); @@ -898,7 +916,7 @@ class Builds extends Action Span::add('build.adapter', $deployment->getAttribute('adapter')); Span::add('build.fallback_file', $deployment->getAttribute('fallbackFile')); } elseif ($adapter === 'ssr' && $detection->getName() === 'static') { - throw new \Exception('Adapter mismatch. Detected: ' . $detection->getName() . ' does not match with the set adapter: ' . $adapter); + throw new BuildException('Adapter mismatch. Detected: ' . $detection->getName() . ' does not match with the set adapter: ' . $adapter); } } @@ -1129,6 +1147,8 @@ class Builds extends Action Span::add('build.screenshot_queued', true); } + + Span::add('timings.finalize', \round(\microtime(true) - $phaseStart, 3)); } catch (\Throwable $th) { if ($dbForProject->getDocument('deployments', $deploymentId)->getAttribute('status') === 'canceled') { $this->finalizeCanceledDeployment($deployment->getId(), $dbForProject, $queueForRealtime); @@ -1136,14 +1156,19 @@ class Builds extends Action return; } - Span::add('build.error.stage', 'deployment'); - Span::add('build.error.type', $th::class); - Span::add('build.error.message', $th->getMessage()); - Span::add('build.error.file', $th->getFile()); - Span::add('build.error.line', $th->getLine()); + $isUserFacing = $th instanceof BuildException; + $message = $isUserFacing + ? $th->getMessage() + : 'An internal error occurred while building. Please try again, and contact support if the problem persists.'; + + // Record user-facing failures on the span here, since they're not + // re-raised to the harness (which records internal errors via setError). + if ($isUserFacing) { + Span::add('build.exception.type', $th->getType()); + Span::add('build.exception.message', $th->getMessage()); + } // Color message red - $message = $th->getMessage(); if (! \str_contains($message, '')) { $message = '' . $message; } @@ -1183,6 +1208,11 @@ class Builds extends Action if ($isVcsEnabled) { $this->runGitAction('failed', $github, $providerCommitHash, $owner, $repositoryName, $project, $resource, $deployment->getId(), $dbForProject, $dbForPlatform, $queueForRealtime, $platform, true); } + + // Let the worker harness record internal errors via the span and logger. + if (! $isUserFacing) { + throw $th; + } } finally { $queueForRealtime ->setPayload($deployment->getArrayCopy()) @@ -1279,7 +1309,7 @@ class Builds extends Action default => null }; if (\is_null($runtime)) { - throw new \Exception('Runtime "' . $resource->getAttribute('runtime', '') . '" is not supported'); + throw new BuildException('Runtime "' . $resource->getAttribute('runtime', '') . '" is not supported'); } return $runtime; @@ -1535,6 +1565,24 @@ class Builds extends Action } } + protected function disconnectVcs(Document $resource, Database $dbForProject, Database $dbForPlatform): void + { + $repositoryId = $resource->getAttribute('repositoryId', ''); + if (!empty($repositoryId)) { + $dbForPlatform->deleteDocument('repositories', $repositoryId); + } + $dbForProject->updateDocument($resource->getCollection(), $resource->getId(), new Document([ + 'installationId' => '', + 'installationInternalId' => '', + 'providerRepositoryId' => '', + 'providerBranch' => '', + 'providerSilentMode' => false, + 'providerRootDirectory' => '', + 'repositoryId' => '', + 'repositoryInternalId' => '', + ])); + } + private function updateLatestDeployment(Database $dbForProject, Document $resource): Document { $latestDeployment = $dbForProject->findOne('deployments', [ diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Templates/Email/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Templates/Email/Update.php index 8186931c5f..22e3e931d6 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Templates/Email/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Templates/Email/Update.php @@ -90,46 +90,63 @@ class Update extends Action ) { $locale = $locale ?: System::getEnv('_APP_LOCALE', 'en'); - // Prevent template update if custom SMTP is not configured - $smtp = $project->getAttribute('smtp', []); - if (($smtp['enabled'] ?? false) !== true) { - throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'SMTP must be enabled on the project to configure custom email templates.'); - } + $templateKey = "email.{$templateId}-{$locale}"; + $changes = [ + 'senderName' => $senderName, + 'senderEmail' => $senderEmail, + 'replyToEmail' => $replyToEmail, + 'replyToName' => $replyToName, + 'message' => $message, + 'subject' => $subject, + ]; - // Fetch current configuration - $templates = $project->getAttribute('templates', []); - $template = $templates['email.' . $templateId . '-' . $locale] ?? []; + $project = $dbForPlatform->withTransaction(function () use ($dbForPlatform, $authorization, $project, $templateKey, $changes) { + $project = $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $project->getId(), forUpdate: true)); - // Apply changes — null means "not provided, keep existing". - // Empty string explicitly clears a previously-set value. - $keys = ['senderName', 'senderEmail', 'replyToEmail', 'replyToName', 'message', 'subject']; - foreach ($keys as $key) { - if (!\is_null(${$key})) { - $template[$key] = ${$key}; + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); } - } - // Backwards compatibility - if (!\is_null($template['replyTo'] ?? null)) { - $template['replyToEmail'] = $template['replyToEmail'] ?? $template['replyTo'] ?? ''; - } - - // Ensure required fields are set - $requiredKeys = ['subject', 'message']; - foreach ($requiredKeys as $key) { - if (empty($template[$key])) { - throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Param "' . $key . '" is not optional.'); + // Prevent template update if custom SMTP is not configured + $smtp = $project->getAttribute('smtp', []); + if (($smtp['enabled'] ?? false) !== true) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'SMTP must be enabled on the project to configure custom email templates.'); } - } - // Save configuration - $templates['email.' . $templateId . '-' . $locale] = $template; - $updates = new Document([ - 'templates' => $templates, - ]); + // Fetch current configuration from the locked row so concurrent updates + // to other locale/template entries are preserved. + $templates = $project->getAttribute('templates', []); + $template = $templates[$templateKey] ?? []; - $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); - $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); + // Apply changes: null means "not provided, keep existing". + // Empty string explicitly clears a previously-set value. + foreach ($changes as $key => $value) { + if ($value !== null) { + $template[$key] = $value; + } + } + + // Backwards compatibility + if (($template['replyTo'] ?? null) !== null) { + $template['replyToEmail'] ??= $template['replyTo'] ?? ''; + } + + // Ensure required fields are set + $requiredKeys = ['subject', 'message']; + foreach ($requiredKeys as $key) { + if (empty($template[$key])) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Param "' . $key . '" is not optional.'); + } + } + + $templates[$templateKey] = $template; + + return $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([ + 'templates' => $templates, + ]))); + }); + + $template = $project->getAttribute('templates', [])[$templateKey] ?? []; $queueForEvents->setParam('templateId', $templateId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Create.php index 253abbb495..79164c4999 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Create.php @@ -55,6 +55,7 @@ class Create extends Action ->label('event', 'sites.[siteId].deployments.[deploymentId].create') ->label('audits.event', 'deployment.create') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php index a1ccf6cad5..f847a2a344 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php @@ -41,6 +41,7 @@ class Delete extends Action ->label('event', 'sites.[siteId].deployments.[deploymentId].delete') ->label('audits.event', 'deployment.delete') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Download/Get.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Download/Get.php index fa84b2f22f..79ef3d2b1d 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Download/Get.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Download/Get.php @@ -35,6 +35,7 @@ class Get extends Action ->desc('Get deployment download') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label('sdk', new Method( namespace: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index e575fbbf07..b0eb8d343c 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -41,6 +41,7 @@ class Create extends Action ->label('event', 'sites.[siteId].deployments.[deploymentId].update') ->label('audits.event', 'deployment.update') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Get.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Get.php index 56aaa3640b..6c6384e2a0 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Get.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Get.php @@ -29,6 +29,7 @@ class Get extends Action ->desc('Get deployment') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label('sdk', new Method( namespace: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Status/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Status/Update.php index a28a7465e6..c698a2d5f6 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Status/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Status/Update.php @@ -36,6 +36,7 @@ class Update extends Action ->label('scope', 'sites.write') ->label('audits.event', 'deployment.update') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Template/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Template/Create.php index 2d6b441616..aebac55154 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Template/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Template/Create.php @@ -49,6 +49,7 @@ class Create extends Base ->label('event', 'sites.[siteId].deployments.[deploymentId].create') ->label('audits.event', 'deployment.create') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Vcs/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Vcs/Create.php index d4bf42cffe..04ea985a32 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Vcs/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Vcs/Create.php @@ -44,6 +44,7 @@ class Create extends Base ->label('event', 'sites.[siteId].deployments.[deploymentId].create') ->label('audits.event', 'deployment.create') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'deployments', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/XList.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/XList.php index 3dccd687ea..8dd25fdd55 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/XList.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/XList.php @@ -40,6 +40,7 @@ class XList extends Base ->desc('List deployments') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label('sdk', new Method( namespace: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Logs/Delete.php b/src/Appwrite/Platform/Modules/Sites/Http/Logs/Delete.php index f5d7265c88..88927b9fb4 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Logs/Delete.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Logs/Delete.php @@ -35,6 +35,7 @@ class Delete extends Base ->label('event', 'sites.[siteId].logs.[logId].delete') ->label('audits.event', 'logs.delete') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'logs', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index a774c31a0f..3c51c57420 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -47,6 +47,7 @@ class Create extends Base ->label('event', 'sites.[siteId].create') ->label('audits.event', 'site.create') ->label('audits.resource', 'site/{response.$id}') + ->label('usage.resource', 'site/{response.$id}') ->label('sdk', new Method( namespace: 'sites', group: 'sites', @@ -82,11 +83,12 @@ class Create extends Base ->param('providerRootDirectory', '', new Text(128, 0), 'Path to site code in the linked repo.', true) ->param('providerBranches', [], new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE), 'List of branch name patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all branches.', true) ->param('providerPaths', [], new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE), 'List of file path patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all file changes.', true) - ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( + ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan, 'buildSpecifications', APP_SITES_BUILD_SPECIFICATION_DEFAULT, true), fn (array $plan) => new Specification( $plan, Config::getParam('specifications', []), System::getEnv('_APP_COMPUTE_CPUS', 0), - System::getEnv('_APP_COMPUTE_MEMORY', 0) + System::getEnv('_APP_COMPUTE_MEMORY', 0), + 'buildSpecifications' ), 'Build specification for the site deployments.', true, ['plan']) ->param('runtimeSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( $plan, diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Delete.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Delete.php index 50b070d098..9e33965ef3 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Delete.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Delete.php @@ -38,6 +38,7 @@ class Delete extends Base ->label('event', 'sites.[siteId].delete') ->label('audits.event', 'site.delete') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Deployment/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Deployment/Update.php index 18f80ca53f..13620ebcf7 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Deployment/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Deployment/Update.php @@ -38,6 +38,7 @@ class Update extends Base ->label('event', 'sites.[siteId].deployments.[deploymentId].update') ->label('audits.event', 'deployment.update') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Get.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Get.php index d685f2082d..508bcf0120 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Get.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Get.php @@ -30,6 +30,7 @@ class Get extends Base ->desc('Get site') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label('sdk', new Method( namespace: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index 1edc5ce87c..532c92a428 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -51,6 +51,7 @@ class Update extends Base ->label('event', 'sites.[siteId].update') ->label('audits.event', 'sites.update') ->label('audits.resource', 'site/{response.$id}') + ->label('usage.resource', 'site/{response.$id}') ->label('sdk', new Method( namespace: 'sites', group: 'sites', @@ -86,12 +87,13 @@ class Update extends Base ->param('providerRootDirectory', '', new Text(128, 0), 'Path to site code in the linked repo.', true) ->param('providerBranches', null, new Nullable(new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'List of branch name patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all branches.', true) ->param('providerPaths', null, new Nullable(new ArrayList(new Text(128), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'List of file path patterns to trigger automatic deployments. Supports wildcards. Leave empty to deploy on all file changes.', true) - ->param('buildSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( + ->param('buildSpecification', null, fn (array $plan) => new Nullable(new Specification( $plan, Config::getParam('specifications', []), System::getEnv('_APP_COMPUTE_CPUS', 0), - System::getEnv('_APP_COMPUTE_MEMORY', 0) - ), 'Build specification for the site deployments.', true, ['plan']) + System::getEnv('_APP_COMPUTE_MEMORY', 0), + 'buildSpecifications' + )), 'Build specification for the site deployments.', true, ['plan']) ->param('runtimeSpecification', fn (array $plan) => $this->getDefaultSpecification($plan), fn (array $plan) => new Specification( $plan, Config::getParam('specifications', []), @@ -133,7 +135,7 @@ class Update extends Base string $providerRootDirectory, ?array $providerBranches, ?array $providerPaths, - string $buildSpecification, + ?string $buildSpecification, string $runtimeSpecification, int $deploymentRetention, Request $request, @@ -177,6 +179,8 @@ class Update extends Base $framework = $site->getAttribute('framework'); } + $buildSpecification ??= $site->getAttribute('buildSpecification', APP_SITES_BUILD_SPECIFICATION_DEFAULT); + $repositoryId = $site->getAttribute('repositoryId', ''); $repositoryInternalId = $site->getAttribute('repositoryInternalId', ''); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Specifications/XList.php b/src/Appwrite/Platform/Modules/Sites/Http/Specifications/XList.php index 4bda37df73..a4f865d859 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Specifications/XList.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Specifications/XList.php @@ -12,6 +12,7 @@ use Utopia\Database\Document; use Utopia\Platform\Action; use Utopia\Platform\Scope\HTTP; use Utopia\System\System; +use Utopia\Validator\WhiteList; class XList extends Base { @@ -46,21 +47,23 @@ class XList extends Base ) ] )) + ->param('type', 'runtimes', new WhiteList(['runtimes', 'builds']), 'Specification type to list. Can be one of: runtimes, builds.', true) ->inject('response') ->inject('plan') ->callback($this->action(...)); } - public function action(Response $response, array $plan) + public function action(string $type, Response $response, array $plan) { $allSpecs = Config::getParam('specifications', []); + $planKey = $type === 'builds' ? 'buildSpecifications' : 'runtimeSpecifications'; $specs = []; foreach ($allSpecs as $spec) { $spec['enabled'] = true; - if (array_key_exists('runtimeSpecifications', $plan)) { - $spec['enabled'] = in_array($spec['slug'], $plan['runtimeSpecifications']); + if (array_key_exists($planKey, $plan)) { + $spec['enabled'] = in_array($spec['slug'], $plan[$planKey]); } $maxCpus = System::getEnv('_APP_COMPUTE_CPUS', 0); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Create.php index edd3412b8f..74f0743040 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Create.php @@ -41,6 +41,7 @@ class Create extends Base ->label('event', 'variables.[variableId].create') ->label('audits.event', 'variable.create') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'variables', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Delete.php b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Delete.php index 74c638bddc..53e5bffeee 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Delete.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Delete.php @@ -37,6 +37,7 @@ class Delete extends Base ->label('event', 'variables.[variableId].delete') ->label('audits.event', 'variable.delete') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('sdk', new Method( namespace: 'sites', group: 'variables', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Get.php index 2fcb051996..50e10fe4c9 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Get.php @@ -30,6 +30,7 @@ class Get extends Base ->desc('Get variable') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label( 'sdk', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Update.php index 0ed7414b9d..65da54a7df 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Variables/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Variables/Update.php @@ -39,6 +39,7 @@ class Update extends Base ->label('event', 'variables.[variableId].update') ->label('audits.event', 'variable.update') ->label('audits.resource', 'site/{request.siteId}') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label('sdk', new Method( namespace: 'sites', diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Variables/XList.php b/src/Appwrite/Platform/Modules/Sites/Http/Variables/XList.php index 1270fe4925..9637c0e8e0 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Variables/XList.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Variables/XList.php @@ -37,6 +37,7 @@ class XList extends Base ->desc('List variables') ->groups(['api', 'sites']) ->label('scope', 'sites.read') + ->label('usage.resource', 'site/{request.siteId}') ->label('resourceType', RESOURCE_TYPE_SITES) ->label( 'sdk', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Create.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Create.php index 8f288c45d1..e13666ae91 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Create.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Create.php @@ -49,6 +49,7 @@ class Create extends Action ->label('event', 'buckets.[bucketId].create') ->label('audits.event', 'bucket.create') ->label('audits.resource', 'bucket/{response.$id}') + ->label('usage.resource', 'bucket/{response.$id}') ->label('sdk', new Method( namespace: 'storage', group: 'buckets', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Delete.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Delete.php index 2581a2163d..1b33e7d9d1 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Delete.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Delete.php @@ -37,6 +37,7 @@ class Delete extends Action ->label('audits.event', 'bucket.delete') ->label('event', 'buckets.[bucketId].delete') ->label('audits.resource', 'bucket/{request.bucketId}') + ->label('usage.resource', 'bucket/{request.bucketId}') ->label('sdk', new Method( namespace: 'storage', group: 'buckets', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php index c5252a299f..cf934575c0 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php @@ -62,6 +62,7 @@ class Create extends Action ->label('audits.event', 'file.create') ->label('event', 'buckets.[bucketId].files.[fileId].create') ->label('audits.resource', 'file/{response.$id}') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{response.$id}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId},chunkId:{chunkId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Delete.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Delete.php index c16b374c78..6b631230c7 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Delete.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Delete.php @@ -42,6 +42,7 @@ class Delete extends Action ->label('event', 'buckets.[bucketId].files.[fileId].delete') ->label('audits.event', 'file.delete') ->label('audits.resource', 'file/{request.fileId}') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) @@ -145,7 +146,11 @@ class Delete extends Action } if (!$deleted) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove file from DB'); + $exists = $authorization->skip(fn () => $dbForProject->getDocument('bucket_' . $bucket->getSequence(), $fileId)); + if (!$exists->isEmpty()) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove file from DB'); + } + throw new Exception(Exception::STORAGE_FILE_NOT_FOUND); } } else { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to delete file from device'); diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Download/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Download/Get.php index ed02a295c8..e5d82c7aa1 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Download/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Download/Get.php @@ -43,6 +43,7 @@ class Get extends Action ->desc('Get file for download') ->groups(['api', 'storage']) ->label('scope', 'files.read') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('sdk', new Method( namespace: 'storage', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Get.php index d997fe3cc0..53ce6fad4f 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Get.php @@ -32,6 +32,7 @@ class Get extends Action ->desc('Get file') ->groups(['api', 'storage']) ->label('scope', 'files.read') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('sdk', new Method( namespace: 'storage', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index 2a2686b544..d856c0456d 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -53,6 +53,7 @@ class Get extends Action ->desc('Get file preview') ->groups(['api', 'storage']) ->label('scope', 'files.read') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('cache', true) ->label('cache.resourceType', 'bucket/{request.bucketId}') diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Push/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Push/Get.php index 2b2d23c1fa..637d1b22e6 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Push/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Push/Get.php @@ -40,6 +40,7 @@ class Get extends Action ->desc('Get file for push notification') ->groups(['api', 'storage']) ->label('scope', 'public') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->param('bucketId', '', new UID(), 'Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).') ->param('fileId', '', new UID(), 'File ID.') diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php index fb1245d29c..c917e21ce8 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php @@ -43,6 +43,7 @@ class Update extends Action ->label('event', 'buckets.[bucketId].files.[fileId].update') ->label('audits.event', 'file.update') ->label('audits.resource', 'file/{response.$id}') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{response.$id}') ->label('sdk', new Method( namespace: 'storage', group: 'files', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/View/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/View/Get.php index 01e8b56fbe..8214cdbfa1 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/View/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/View/Get.php @@ -44,6 +44,7 @@ class Get extends Action ->desc('Get file for view') ->groups(['api', 'storage']) ->label('scope', 'files.read') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('sdk', new Method( namespace: 'storage', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/XList.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/XList.php index 28dfa87c5d..de61ea5910 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/XList.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/XList.php @@ -41,6 +41,7 @@ class XList extends Action ->desc('List files') ->groups(['api', 'storage']) ->label('scope', 'files.read') + ->label('usage.resource', 'bucket/{request.bucketId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('sdk', new Method( namespace: 'storage', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php index 4e75de27c8..0418ef8b45 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php @@ -32,6 +32,7 @@ class Get extends Action ->desc('Get bucket') ->groups(['api', 'storage']) ->label('scope', 'buckets.read') + ->label('usage.resource', 'bucket/{request.bucketId}') ->label('resourceType', RESOURCE_TYPE_BUCKETS) ->label('sdk', new Method( namespace: 'storage', diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Update.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Update.php index 3549c035f1..aae383c79a 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Update.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Update.php @@ -46,6 +46,7 @@ class Update extends Action ->label('event', 'buckets.[bucketId].update') ->label('audits.event', 'bucket.update') ->label('audits.resource', 'bucket/{response.$id}') + ->label('usage.resource', 'bucket/{response.$id}') ->label('sdk', new Method( namespace: 'storage', group: 'buckets', diff --git a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php index 28bfa769ee..35297710af 100644 --- a/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php +++ b/src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php @@ -66,7 +66,7 @@ class Update extends Action ->param('secret', '', new Text(256), 'Secret key.') ->inject('request') ->inject('response') - ->inject('user') + ->inject('targetUser') ->inject('dbForProject') ->inject('authorization') ->inject('project') @@ -79,7 +79,7 @@ class Update extends Action ->callback($this->action(...)); } - public function action(string $teamId, string $membershipId, string $userId, string $secret, Request $request, Response $response, Document $user, Database $dbForProject, Authorization $authorization, $project, Reader $geodb, Event $queueForEvents, Store $store, Token $proofForToken, bool $domainVerification, ?string $cookieDomain) + public function action(string $teamId, string $membershipId, string $userId, string $secret, Request $request, Response $response, Document $targetUser, Database $dbForProject, Authorization $authorization, $project, Reader $geodb, Event $queueForEvents, Store $store, Token $proofForToken, bool $domainVerification, ?string $cookieDomain) { $protocol = $request->getProtocol(); @@ -104,16 +104,16 @@ class Update extends Action } if ($userId !== $membership->getAttribute('userId')) { - throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')'); + throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $targetUser->getAttribute('email') . ')'); } - $hasSession = !$user->isEmpty(); + $hasSession = !$targetUser->isEmpty(); if (!$hasSession) { - $user->setAttributes($dbForProject->getDocument('users', $userId)->getArrayCopy()); // Get user + $targetUser->setAttributes($dbForProject->getDocument('users', $userId)->getArrayCopy()); // Get user } - if ($membership->getAttribute('userInternalId') !== $user->getSequence()) { - throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')'); + if ($membership->getAttribute('userInternalId') !== $targetUser->getSequence()) { + throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $targetUser->getAttribute('email') . ')'); } if ($membership->getAttribute('confirm') === true) { @@ -125,11 +125,12 @@ class Update extends Action ->setAttribute('confirm', true) ; - $authorization->skip(fn () => $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('emailVerification', true))); + $targetUser->setAttribute('emailVerification', true); + $authorization->skip(fn () => $dbForProject->updateDocument('users', $targetUser->getId(), new Document(['emailVerification' => true]))); // Create session for the user if not logged in if (!$hasSession) { - $authorization->addRole(Role::user($user->getId())->toString()); + $authorization->addRole(Role::user($targetUser->getId())->toString()); $detector = new Detector($request->getUserAgent('UNKNOWN')); $record = $geodb->get($request->getIP()); @@ -139,14 +140,14 @@ class Update extends Action $session = new Document(array_merge([ '$id' => ID::unique(), '$permissions' => [ - Permission::read(Role::user($user->getId())), - Permission::update(Role::user($user->getId())), - Permission::delete(Role::user($user->getId())), + Permission::read(Role::user($targetUser->getId())), + Permission::update(Role::user($targetUser->getId())), + Permission::delete(Role::user($targetUser->getId())), ], - 'userId' => $user->getId(), - 'userInternalId' => $user->getSequence(), + 'userId' => $targetUser->getId(), + 'userInternalId' => $targetUser->getSequence(), 'provider' => SESSION_PROVIDER_EMAIL, - 'providerUid' => $user->getAttribute('email'), + 'providerUid' => $targetUser->getAttribute('email'), 'secret' => $proofForToken->hash($secret), // One way hash encryption to protect DB leak 'userAgent' => $request->getUserAgent('UNKNOWN'), 'ip' => $request->getIP(), @@ -160,7 +161,7 @@ class Update extends Action $authorization->addRole(Role::user($userId)->toString()); $encoded = $store - ->setProperty('id', $user->getId()) + ->setProperty('id', $targetUser->getId()) ->setProperty('secret', $secret) ->encode(); @@ -193,12 +194,12 @@ class Update extends Action $membership = $dbForProject->updateDocument('memberships', $membership->getId(), new Document(['joined' => $membership->getAttribute('joined'), 'confirm' => true])); - $dbForProject->purgeCachedDocument('users', $user->getId()); + $dbForProject->purgeCachedDocument('users', $targetUser->getId()); $authorization->skip(fn () => $dbForProject->increaseDocumentAttribute('teams', $team->getId(), 'total', 1)); $queueForEvents - ->setParam('userId', $user->getId()) + ->setParam('userId', $targetUser->getId()) ->setParam('teamId', $team->getId()) ->setParam('membershipId', $membership->getId()) ; @@ -206,8 +207,8 @@ class Update extends Action $response->dynamic( $membership ->setAttribute('teamName', $team->getAttribute('name')) - ->setAttribute('userName', $user->getAttribute('name')) - ->setAttribute('userEmail', $user->getAttribute('email')), + ->setAttribute('userName', $targetUser->getAttribute('name')) + ->setAttribute('userEmail', $targetUser->getAttribute('email')), Response::MODEL_MEMBERSHIP ); } diff --git a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/Create.php b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/Create.php index 1c2bd692ef..ceb73f0079 100644 --- a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/Create.php +++ b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/Create.php @@ -42,6 +42,7 @@ class Create extends Action ->label('audits.resource', 'token/{response.$id}') ->label('usage.metric', 'tokens.{scope}.requests.create') ->label('usage.params', ['resourceId:{request.resourceId}', 'resourceType:{request.resourceType}']) + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}') ->label('abuse-limit', APP_LIMIT_WRITE_RATE_DEFAULT) ->label('abuse-time', APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT) diff --git a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/XList.php b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/XList.php index 5a93a06f26..65ab108e65 100644 --- a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/XList.php +++ b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/XList.php @@ -37,6 +37,7 @@ class XList extends Action ->groups(['api', 'tokens']) ->label('scope', 'tokens.read') ->label('usage.metric', 'tokens.requests.read') + ->label('usage.resource', 'bucket/{request.bucketId}/file/{request.fileId}') ->label('sdk', new Method( namespace: 'tokens', group: 'files', diff --git a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Delete.php b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Delete.php index a71f2ec726..4fca85e2a2 100644 --- a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Delete.php +++ b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Delete.php @@ -8,6 +8,7 @@ use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; +use Appwrite\Usage\Context; use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Validator\UID; @@ -58,16 +59,25 @@ class Delete extends Action ->inject('response') ->inject('dbForProject') ->inject('queueForEvents') + ->inject('usage') ->callback($this->action(...)); } - public function action(string $tokenId, Response $response, Database $dbForProject, Event $queueForEvents) + public function action(string $tokenId, Response $response, Database $dbForProject, Event $queueForEvents, Context $usage) { $token = $dbForProject->getDocument('resourceTokens', $tokenId); if ($token->isEmpty()) { throw new Exception(Exception::TOKEN_NOT_FOUND); } + if ($token->getAttribute('resourceType') === TOKENS_RESOURCE_TYPE_FILES) { + $resourceId = (string) $token->getAttribute('resourceId', ''); + [$bucketId, $fileId] = explode(':', $resourceId, 2) + ['', '']; + if ($bucketId !== '' && $fileId !== '') { + $usage->setResourcePath('bucket/' . $bucketId . '/file/' . $fileId); + } + } + $dbForProject->deleteDocument('resourceTokens', $tokenId); $queueForEvents diff --git a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Get.php b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Get.php index 0a364683ca..a3a540552c 100644 --- a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Get.php +++ b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Get.php @@ -7,6 +7,7 @@ use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; +use Appwrite\Usage\Context; use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Validator\UID; @@ -50,10 +51,11 @@ class Get extends Action ->param('tokenId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Token ID.', false, ['dbForProject']) ->inject('response') ->inject('dbForProject') + ->inject('usage') ->callback($this->action(...)); } - public function action(string $tokenId, Response $response, Database $dbForProject) + public function action(string $tokenId, Response $response, Database $dbForProject, Context $usage) { $token = $dbForProject->getDocument('resourceTokens', $tokenId); @@ -61,6 +63,14 @@ class Get extends Action throw new Exception(Exception::TOKEN_NOT_FOUND); } + if ($token->getAttribute('resourceType') === TOKENS_RESOURCE_TYPE_FILES) { + $resourceId = (string) $token->getAttribute('resourceId', ''); + [$bucketId, $fileId] = explode(':', $resourceId, 2) + ['', '']; + if ($bucketId !== '' && $fileId !== '') { + $usage->setResourcePath('bucket/' . $bucketId . '/file/' . $fileId); + } + } + $response->dynamic($token, Response::MODEL_RESOURCE_TOKEN); } } diff --git a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Update.php b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Update.php index 444f49de62..63b2fb098b 100644 --- a/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Update.php +++ b/src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Update.php @@ -8,6 +8,7 @@ use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; +use Appwrite\Usage\Context; use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Validator\Datetime as DatetimeValidator; @@ -61,10 +62,11 @@ class Update extends Action ->inject('response') ->inject('dbForProject') ->inject('queueForEvents') + ->inject('usage') ->callback($this->action(...)); } - public function action(string $tokenId, ?string $expire, Response $response, Database $dbForProject, Event $queueForEvents) + public function action(string $tokenId, ?string $expire, Response $response, Database $dbForProject, Event $queueForEvents, Context $usage) { $token = $dbForProject->getDocument('resourceTokens', $tokenId); @@ -72,6 +74,14 @@ class Update extends Action throw new Exception(Exception::TOKEN_NOT_FOUND); } + if ($token->getAttribute('resourceType') === TOKENS_RESOURCE_TYPE_FILES) { + $resourceId = (string) $token->getAttribute('resourceId', ''); + [$bucketId, $fileId] = explode(':', $resourceId, 2) + ['', '']; + if ($bucketId !== '' && $fileId !== '') { + $usage->setResourcePath('bucket/' . $bucketId . '/file/' . $fileId); + } + } + $token->setAttribute('expire', $expire); $token = $dbForProject->updateDocument('resourceTokens', $tokenId, $token); diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php index d172fdc688..d312cc3a56 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php @@ -237,6 +237,8 @@ trait Deployment $comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, $commentPreviewUrl); $latestCommentId = \strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment())); + } catch (\Throwable $e) { + Console::warning("Failed to update PR comment '{$latestCommentId}': " . $e->getMessage()); } finally { $authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId)); } @@ -308,6 +310,8 @@ trait Deployment $comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, ''); $latestCommentId = \strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment())); + } catch (\Throwable $e) { + Console::warning("Failed to update PR comment '{$latestCommentId}': " . $e->getMessage()); } finally { $authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId)); } @@ -526,6 +530,8 @@ trait Deployment $comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, $previewUrl); $github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment()); } + } catch (\Throwable $e) { + Console::warning("Failed to update PR comment '{$latestCommentId}': " . $e->getMessage()); } finally { $authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId)); } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php index 420715ddc6..53f67f34b0 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php @@ -8,6 +8,7 @@ use Appwrite\Platform\Action; use Appwrite\Platform\Modules\VCS\Http\GitHub\Deployment; use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; +use Utopia\Console; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Query; @@ -77,7 +78,7 @@ class Create extends Action $parsedPayload = $github->getEvent($event, $payload); match ($event) { - $github::EVENT_INSTALLATION => $this->handleInstallationEvent($parsedPayload, $dbForPlatform, $authorization), + $github::EVENT_INSTALLATION => $this->handleInstallationEvent($parsedPayload, $dbForPlatform, $authorization, $getProjectDB), $github::EVENT_PUSH => $this->handlePushEvent($parsedPayload, $githubAppId, $privateKey, $github, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), $github::EVENT_PULL_REQUEST => $this->handlePullRequestEvent($parsedPayload, $privateKey, $githubAppId, $github, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), default => null, @@ -91,35 +92,89 @@ class Create extends Action return; } - private function handleInstallationEvent( + protected function handleInstallationEvent( array $parsedPayload, Database $dbForPlatform, Authorization $authorization, + callable $getProjectDB, ) { if ($parsedPayload["action"] !== "deleted") { return; } - // TODO: Use worker for this job instead (update function/site as well) $providerInstallationId = $parsedPayload["installationId"]; - $installations = $dbForPlatform->find('installations', [ - Query::equal('providerInstallationId', [$providerInstallationId]), - Query::limit(1000) - ]); + $installationCursor = null; + do { + $installationQueries = [ + Query::equal('providerInstallationId', [$providerInstallationId]), + Query::limit(1000), + ]; + if ($installationCursor !== null) { + $installationQueries[] = Query::cursorAfter($installationCursor); + } + $installations = $authorization->skip(fn () => $dbForPlatform->find('installations', $installationQueries)); - foreach ($installations as $installation) { - $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ - Query::equal('installationInternalId', [$installation->getSequence()]), - Query::limit(1000) - ])); + foreach ($installations as $installation) { + $projectId = $installation->getAttribute('projectId', ''); + $project = $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $projectId)); - foreach ($repositories as $repository) { - $authorization->skip(fn () => $dbForPlatform->deleteDocument('repositories', $repository->getId())); + if (!$project->isEmpty()) { + $dbForProject = $getProjectDB($project); + + foreach (['functions', 'sites'] as $collection) { + $cursor = null; + do { + $queries = [ + Query::equal('installationInternalId', [$installation->getSequence()]), + Query::limit(1000), + ]; + if ($cursor !== null) { + $queries[] = Query::cursorAfter($cursor); + } + $resources = $authorization->skip(fn () => $dbForProject->find($collection, $queries)); + + foreach ($resources as $resource) { + $authorization->skip(fn () => $dbForProject->updateDocument($collection, $resource->getId(), new Document([ + 'installationId' => '', + 'installationInternalId' => '', + 'providerRepositoryId' => '', + 'providerBranch' => '', + 'providerSilentMode' => false, + 'providerRootDirectory' => '', + 'repositoryId' => '', + 'repositoryInternalId' => '', + ]))); + } + + $cursor = count($resources) === 1000 ? $resources[array_key_last($resources)] : null; + } while ($cursor !== null); + } + } + + $cursor = null; + do { + $queries = [ + Query::equal('installationInternalId', [$installation->getSequence()]), + Query::limit(1000), + ]; + if ($cursor !== null) { + $queries[] = Query::cursorAfter($cursor); + } + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', $queries)); + + foreach ($repositories as $repository) { + $authorization->skip(fn () => $dbForPlatform->deleteDocument('repositories', $repository->getId())); + } + + $cursor = count($repositories) === 1000 ? $repositories[array_key_last($repositories)] : null; + } while ($cursor !== null); + + $authorization->skip(fn () => $dbForPlatform->deleteDocument('installations', $installation->getId())); } - $authorization->skip(fn () => $dbForPlatform->deleteDocument('installations', $installation->getId())); - } + $installationCursor = count($installations) === 1000 ? $installations[array_key_last($installations)] : null; + } while ($installationCursor !== null); } private function handlePushEvent( @@ -207,7 +262,12 @@ class Create extends Action $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId); - $commitDetails = $github->getCommit($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash); + try { + $commitDetails = $github->getCommit($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash); + } catch (\Throwable $e) { + Console::warning("Failed to fetch commit '{$providerCommitHash}': " . $e->getMessage()); + $commitDetails = []; + } $providerCommitAuthor = $commitDetails["commitAuthor"] ?? ''; $providerCommitMessage = $commitDetails["commitMessage"] ?? ''; diff --git a/src/Appwrite/Platform/Workers/Audits.php b/src/Appwrite/Platform/Workers/Audits.php index 6c45aa63f3..27d2629ce6 100644 --- a/src/Appwrite/Platform/Workers/Audits.php +++ b/src/Appwrite/Platform/Workers/Audits.php @@ -74,19 +74,14 @@ class Audits extends Action $userAgent = $auditMessage->userAgent; $ip = $auditMessage->ip; $user = $auditMessage->user; + $impersonatorUser = $auditMessage->impersonatorUser; - $impersonatorUserId = $user->getAttribute('impersonatorUserId'); - $actorUserId = $impersonatorUserId ?: $user->getId(); - $actorUserInternalId = $impersonatorUserId - ? $user->getAttribute('impersonatorUserInternalId') - : $user->getSequence(); - $actorUserName = $impersonatorUserId - ? $user->getAttribute('impersonatorUserName', '') - : $user->getAttribute('name', ''); - $actorUserEmail = $impersonatorUserId - ? $user->getAttribute('impersonatorUserEmail', '') - : $user->getAttribute('email', ''); - $userType = $user->getAttribute('type', ACTOR_TYPE_USER); + $isImpersonated = !$impersonatorUser->isEmpty(); + $actorUserId = $isImpersonated ? $impersonatorUser->getId() : $user->getId(); + $actorUserInternalId = $isImpersonated ? $impersonatorUser->getSequence() : $user->getSequence(); + $actorUserName = $isImpersonated ? $impersonatorUser->getAttribute('name', '') : $user->getAttribute('name', ''); + $actorUserEmail = $isImpersonated ? $impersonatorUser->getAttribute('email', '') : $user->getAttribute('email', ''); + $userType = $isImpersonated ? $impersonatorUser->getAttribute('type', ACTOR_TYPE_USER) : $user->getAttribute('type', ACTOR_TYPE_USER); // Create event data $eventData = [ @@ -106,7 +101,7 @@ class Audits extends Action 'time' => date("Y-m-d H:i:s", $message->getTimestamp()), ]; - if (!empty($impersonatorUserId)) { + if ($isImpersonated) { $eventData['data']['data'] = \is_array($auditPayload) ? \array_merge($auditPayload, [ 'impersonatedUserId' => $user->getId(), diff --git a/src/Appwrite/Realtime/EventTailRegistry.php b/src/Appwrite/Realtime/EventTailRegistry.php new file mode 100644 index 0000000000..2a35666efd --- /dev/null +++ b/src/Appwrite/Realtime/EventTailRegistry.php @@ -0,0 +1,247 @@ +, + * tokens:float, + * lastRefill:float, + * dropped:int, + * delivered:int, + * buffer:array> + * }>>> connId => subId => projectId => state */ + private array $entries = []; + + /** @var array>> projectId => connId => set of subIds */ + private array $projectIndex = []; + + private int $rate; + + private int $batchMax; + + /** + * @param int $rate tokens per second per subscription + * @param int $batchMax max frames per flushed websocket frame (kept under setPackageMaxLength) + */ + public function __construct(int $rate = 50, int $batchMax = 200) + { + $this->rate = \max(1, $rate); + $this->batchMax = \max(1, $batchMax); + } + + /** + * Build the tail channel string for a project. + */ + public static function channel(string $projectId): string + { + return CONSOLE_TAIL_CHANNEL_PREFIX . '.' . $projectId; + } + + /** + * Extract the projectId from a `console.tail.` channel, or null if the + * channel isn't a tail channel. + */ + public static function projectFromChannel(string $channel): ?string + { + $prefix = CONSOLE_TAIL_CHANNEL_PREFIX . '.'; + if (!\str_starts_with($channel, $prefix)) { + return null; + } + $projectId = \substr($channel, \strlen($prefix)); + return $projectId === '' ? null : $projectId; + } + + /** + * Register a tail of one project under (connId, subId). Additive, mirroring the + * realtime adapter's subscribe(): adding a new channel never drops channels already + * associated with the subscription id. Re-adding the SAME (connId, subId, projectId) + * overwrites in place with fresh state — that's how a reused subscription id updates + * its filter without leaving a stale entry behind. Entries are dropped only by + * remove()/removeConnection() (i.e. unsubscribe or disconnect), matching the tree. + * + * @param array $filters result of RuntimeQuery::compile() + * @param string $role the team role this tail was authorized with + */ + public function add(int $connId, string $subId, string $projectId, array $filters, float $now, string $role = ''): void + { + $this->entries[$connId][$subId][$projectId] = [ + 'role' => $role, + 'filters' => $filters, + 'tokens' => (float) $this->rate, + 'lastRefill' => $now, + 'dropped' => 0, + 'delivered' => 0, + 'buffer' => [], + ]; + $this->projectIndex[$projectId][$connId][$subId] = true; + } + + /** + * Remove every entry for a (connId, subId) — covers a subscription that tailed + * multiple projects. No-op for unknown subscriptions. + */ + public function remove(int $connId, string $subId): void + { + foreach (\array_keys($this->entries[$connId][$subId] ?? []) as $projectId) { + $this->detachEntry($connId, $subId, (string) $projectId); + } + } + + public function removeConnection(int $connId): void + { + foreach (\array_keys($this->entries[$connId] ?? []) as $subId) { + $this->remove($connId, (string) $subId); + } + } + + /** + * Drop any tail whose authorizing team role the connection no longer holds. Called + * from the permissions-changed path (which already recomputes a connection's roles + * and rebuilds its tree) so a membership revocation or project transfer stops the + * tail mid-connection instead of streaming until disconnect. + * + * @param array $roles the connection's current roles + */ + public function revalidateConnection(int $connId, array $roles): void + { + foreach (($this->entries[$connId] ?? []) as $subId => $byProject) { + foreach ($byProject as $projectId => $entry) { + $role = $entry['role']; + if ($role !== '' && !\in_array($role, $roles, true)) { + $this->detachEntry($connId, (string) $subId, (string) $projectId); + } + } + } + } + + private function detachEntry(int $connId, string $subId, string $projectId): void + { + unset($this->projectIndex[$projectId][$connId][$subId]); + if (empty($this->projectIndex[$projectId][$connId])) { + unset($this->projectIndex[$projectId][$connId]); + } + if (empty($this->projectIndex[$projectId])) { + unset($this->projectIndex[$projectId]); + } + + unset($this->entries[$connId][$subId][$projectId]); + if (empty($this->entries[$connId][$subId])) { + unset($this->entries[$connId][$subId]); + } + if (empty($this->entries[$connId])) { + unset($this->entries[$connId]); + } + } + + /** + * O(1) gate for the hot path: does THIS worker hold any tail for the project? + */ + public function isTailed(string $projectId): bool + { + return !empty($this->projectIndex[$projectId]); + } + + /** + * For one decoded firehose event: filter FIRST, then sample into each matching + * entry's buffer. The sampling budget is therefore spent only on events that pass + * the filter. + * + * @param array $payload compact metadata from Realtime::toTailMetadata() + */ + public function ingest(string $projectId, array $payload, float $now): void + { + foreach (($this->projectIndex[$projectId] ?? []) as $connId => $subs) { + foreach (\array_keys($subs) as $subId) { + $entry = &$this->entries[$connId][$subId][$projectId]; + + // 1) FILTER FIRST — reuse RuntimeQuery against the compact frame + if (RuntimeQuery::filter($entry['filters'], $payload) === null) { + unset($entry); + continue; + } + + // 2) THEN SAMPLE — lazy token-bucket refill + consume. + // tokens is a fractional value that refills with elapsed time, capped at rate. + $elapsed = \max(0.0, $now - $entry['lastRefill']); + $entry['tokens'] = \min((float) $this->rate, $entry['tokens'] + $elapsed * $this->rate); + $entry['lastRefill'] = $now; + + if ($entry['tokens'] >= 1.0) { + $entry['tokens'] -= 1.0; + $entry['buffer'][] = $payload; + $entry['delivered']++; + } else { + $entry['dropped']++; + } + + unset($entry); + } + } + } + + /** + * Flush all non-empty buffers as one (or more) batched websocket frame(s) per + * entry, plus a counter frame whenever events were dropped. Call from a Timer::tick + * inside onWorkerStart. + */ + public function flush(Server $server): void + { + foreach ($this->entries as $connId => $bySub) { + foreach ($bySub as $subId => $byProject) { + foreach (\array_keys($byProject) as $projectId) { + $entry = &$this->entries[$connId][$subId][$projectId]; + $channel = self::channel((string) $projectId); + + if (!empty($entry['buffer'])) { + // Chunk so a single frame stays under the websocket package max length. + foreach (\array_chunk($entry['buffer'], $this->batchMax) as $chunk) { + $server->send([$connId], (string) \json_encode([ + 'type' => 'event', + 'data' => [ + 'channels' => [$channel], + 'events' => ['console.tail'], + 'subscriptions' => [(string) $subId], + 'payload' => $chunk, + ], + ])); + } + $entry['buffer'] = []; + } + + // Counter frame — emit the true rate vs dropped count when sampling kicked in. + if ($entry['dropped'] > 0) { + $server->send([$connId], (string) \json_encode([ + 'type' => 'event', + 'data' => [ + 'channels' => [$channel], + 'events' => ['console.tail.stats'], + 'subscriptions' => [(string) $subId], + 'payload' => [ + '$type' => 'tail.stats', + 'delivered' => $entry['delivered'], + 'dropped' => $entry['dropped'], + ], + ], + ])); + } + + // Reset counters every flush window (~150ms). + $entry['delivered'] = 0; + $entry['dropped'] = 0; + unset($entry); + } + } + } + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/Authentication.php b/src/Appwrite/Realtime/Message/Handlers/Authentication.php index 9065e586d3..cf46f7ccb7 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Authentication.php +++ b/src/Appwrite/Realtime/Message/Handlers/Authentication.php @@ -69,7 +69,12 @@ class Authentication extends Action $roles = $user->getRoles($database->getAuthorization()); $authorization = $realtime->connections[$connectionId]['authorization'] ?? null; + $impersonatedUserId = $realtime->connections[$connectionId]['impersonatedUserId'] ?? null; $projectId = $realtime->connections[$connectionId]['projectId'] ?? null; + + if ($impersonatedUserId !== null) { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Cannot re-authenticate on an impersonated connection.'); + } // Capture the pre-auth userId before unsubscribe() clears the connection entry, // so we can rebind any account channels that were stored under it. $previousUserId = $realtime->connections[$connectionId]['userId'] ?? ''; @@ -102,6 +107,7 @@ class Authentication extends Action if ($authorization !== null) { $realtime->connections[$connectionId]['authorization'] = $authorization; + $realtime->connections[$connectionId]['impersonatedUserId'] = $impersonatedUserId; } $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index 140cd800c3..013e6bf864 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -4,8 +4,11 @@ namespace Appwrite\Realtime\Message\Handlers; use Appwrite\Extend\Exception; use Appwrite\Messaging\Adapter\Realtime; +use Appwrite\Realtime\EventTailRegistry; use Appwrite\Realtime\Message\Dispatcher; use Appwrite\Realtime\Message\Validators\SubscribePayload as SubscribePayloadValidator; +use Appwrite\Utopia\Database\RuntimeQuery; +use Utopia\Database\Database; use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -26,6 +29,8 @@ class Subscribe extends Action ->inject('realtime') ->inject('register') ->inject('projectId') + ->inject('eventTailRegistry') + ->inject('dbForConsole') ->callback($this->action(...)); } @@ -39,6 +44,8 @@ class Subscribe extends Action Realtime $realtime, Registry $register, ?string $projectId, + EventTailRegistry $eventTailRegistry, + Database $dbForConsole, ): array { $roles = $realtime->connections[$connectionId]['roles'] ?? [Role::guests()->toString()]; $userId = $realtime->connections[$connectionId]['userId'] ?? ''; @@ -69,6 +76,64 @@ class Subscribe extends Action ]; } + // Console live event tail: authorize every `console.tail.` channel + // FIRST — before any subscription state is mutated — so a batch mixing authorized + // and unauthorized tails can't leave partial state behind. Each tail is authorized + // by team membership of the target project's owning team, with ownership resolved + // fresh (projects can be transferred between teams, so a cached teamId could + // authorize the wrong team). + $now = \microtime(true); + $pendingTails = []; + foreach ($parsedPayloads as $parsedPayload) { + $compiled = null; + foreach ($parsedPayload['convertedChannels'] as $channel) { + $targetProjectId = EventTailRegistry::projectFromChannel($channel); + if ($targetProjectId === null) { + continue; + } + + // Tail channels are console-only. A normal project websocket (even for a + // team member) must not tail — that would expose compact metadata for + // resources the user could not read through the project API. Only a + // connection to the `console` project may register a tail. + if ($projectId !== 'console') { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Console live tail is only available on the console connection.' + ); + } + + // Resolve ownership fresh (projects can move between teams). Treat any + // lookup failure (missing/invalid project) as a policy violation so the + // connection is closed with 1008, consistent with an unauthorized tail — + // rather than leaking a raw not-found error and staying open. + try { + $project = $dbForConsole->getAuthorization()->skip( + fn () => $dbForConsole->getDocument('projects', $targetProjectId) + ); + } catch (\Throwable) { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Not authorized to tail project "' . $targetProjectId . '".' + ); + } + $teamId = (string) $project->getAttribute('teamId', ''); + $requiredRole = Role::team($teamId)->toString(); + + if ($teamId === '' || !\in_array($requiredRole, $roles, true)) { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Not authorized to tail project "' . $targetProjectId . '".' + ); + } + + $compiled ??= RuntimeQuery::compile($parsedPayload['queries']); + // Carry the authorizing role so the tail can be revoked if the viewer + // later loses team membership (or the project is transferred). + $pendingTails[] = [$parsedPayload['subscriptionId'], $targetProjectId, $compiled, $requiredRole]; + } + } + foreach ($parsedPayloads as $parsedPayload) { $realtime->subscribe( $projectId, @@ -80,6 +145,14 @@ class Subscribe extends Action ); } + // All tail channels passed authorization above — register them additively. The + // registry is keyed by (connId, subId, projectId): re-subscribing the same channel + // overwrites its filter in place, while a reused subscription id that names a new + // tail channel keeps the ones already registered (mirrors the tree). + foreach ($pendingTails as [$subId, $targetProjectId, $compiled, $role]) { + $eventTailRegistry->add($connectionId, $subId, $targetProjectId, $compiled, $now, $role); + } + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; $subscriptionsRequested = \count($parsedPayloads); diff --git a/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php index e1bc163f68..6e2ad5ea63 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php @@ -3,6 +3,7 @@ namespace Appwrite\Realtime\Message\Handlers; use Appwrite\Messaging\Adapter\Realtime; +use Appwrite\Realtime\EventTailRegistry; use Appwrite\Realtime\Message\Dispatcher; use Appwrite\Realtime\Message\Validators\UnsubscribePayload as UnsubscribePayloadValidator; use Utopia\Platform\Action; @@ -21,6 +22,7 @@ class Unsubscribe extends Action ->inject('connectionId') ->inject('realtime') ->inject('register') + ->inject('eventTailRegistry') ->callback($this->action(...)); } @@ -33,6 +35,7 @@ class Unsubscribe extends Action int $connectionId, Realtime $realtime, Registry $register, + EventTailRegistry $eventTailRegistry, ): array { $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connectionId)); @@ -43,6 +46,9 @@ class Unsubscribe extends Action 'subscriptionId' => $subscriptionId, 'removed' => $realtime->unsubscribeSubscription($connectionId, $subscriptionId), ]; + // No-op if it wasn't a tail subscription. Connection-scoped: subscription + // IDs are only unique within a connection. + $eventTailRegistry->remove($connectionId, $subscriptionId); } $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); diff --git a/src/Appwrite/Reference/Renderer.php b/src/Appwrite/Reference/Renderer.php new file mode 100644 index 0000000000..841560dd1a --- /dev/null +++ b/src/Appwrite/Reference/Renderer.php @@ -0,0 +1,77 @@ +context->getAttribute('response', [])); + + preg_match_all('/{([^}]+)}/', $template, $matches); + foreach ($matches[1] as $pos => $match) { + $find = $matches[0][$pos]; + $parts = explode('.', $match, 2); + if (count($parts) !== 2) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, "Invalid resource reference template: {$template}"); + } + + [$namespace, $key] = $parts; + $bag = self::asArray($this->context->getAttribute($namespace, $fallback)); + if (!array_key_exists($key, $bag)) { + continue; + } + + $value = $bag[$key]; + if (!is_string($value)) { + if (is_array($value)) { + $value = json_encode($value); + } elseif (is_object($value) && method_exists($value, '__toString')) { + $value = (string) $value; + } elseif (is_scalar($value)) { + $value = (string) $value; + } else { + throw new Exception(Exception::GENERAL_SERVER_ERROR, "Cannot stringify reference value: {$template}"); + } + } + + $template = str_replace($find, $value, $template); + } + + return $template; + } + + /** + * @return array + */ + private static function asArray(mixed $value): array + { + if (is_array($value)) { + return $value; + } + if ($value instanceof Document) { + return $value->getArrayCopy(); + } + if (is_object($value)) { + return (array) $value; + } + return []; + } +} diff --git a/src/Appwrite/Task/Validator/Cron.php b/src/Appwrite/Task/Validator/Cron.php index 18f3333a57..9e6fcd92a1 100644 --- a/src/Appwrite/Task/Validator/Cron.php +++ b/src/Appwrite/Task/Validator/Cron.php @@ -39,10 +39,19 @@ class Cron extends Validator } try { + \set_error_handler(static function (int $severity, string $message): bool { + if (($severity & E_WARNING) === E_WARNING) { + throw new \RuntimeException($message); + } + + return false; + }); (new CronExpression($value))->getNextRunDate(); return true; } catch (\RuntimeException) { return false; + } finally { + \restore_error_handler(); } } diff --git a/src/Appwrite/Usage/Context.php b/src/Appwrite/Usage/Context.php index 7283cff836..f095eb4981 100644 --- a/src/Appwrite/Usage/Context.php +++ b/src/Appwrite/Usage/Context.php @@ -61,6 +61,16 @@ class Context return empty($this->metrics) && empty($this->reduce); } + public function setResourcePath(string $path): self + { + return $this; + } + + public function getResourcePath(): string + { + return ''; + } + /** * Reset the context */ diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index 3048373a73..a596135840 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -475,6 +475,16 @@ class Response extends SwooleResponse */ public function dynamic(Document $document, string $model): void { + if ( + $this->impersonatorUser !== null + && $model === self::MODEL_ACCOUNT + && $this->user !== null + && $document->getId() === $this->user->getId() + ) { + $document = clone $document; + $document->setAttribute('impersonatorUserId', $this->impersonatorUser->getId()); + } + $output = $this->output(clone $document, $model); $output = $this->applyFilters($output, $model, raw: clone $document); @@ -779,6 +789,7 @@ class Response extends SwooleResponse private ?Authorization $authorization = null; private ?DBUser $user = null; + private ?Document $impersonatorUser = null; public function setAuthorization(Authorization $authorization): void { @@ -789,4 +800,14 @@ class Response extends SwooleResponse { $this->user = $user; } + + public function setImpersonatorUser(Document $impersonatorUser): void + { + $this->impersonatorUser = $impersonatorUser->isEmpty() ? null : $impersonatorUser; + } + + public function getImpersonatorUser(): ?Document + { + return $this->impersonatorUser; + } } diff --git a/src/Appwrite/Utopia/Response/Model/Account.php b/src/Appwrite/Utopia/Response/Model/Account.php index fb03bdb155..769284d714 100644 --- a/src/Appwrite/Utopia/Response/Model/Account.php +++ b/src/Appwrite/Utopia/Response/Model/Account.php @@ -155,7 +155,7 @@ class Account extends Model 'type' => self::TYPE_STRING, 'description' => 'ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data.', 'required' => false, - 'default' => '', + 'default' => null, 'example' => '5e5ea5c16897e', ]) ; diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index f255519bfd..da1f7fe5fc 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -185,7 +185,7 @@ class User extends Model 'type' => self::TYPE_STRING, 'description' => 'ID of the original actor performing the impersonation. Present only when the current request is impersonating another user. Internal audit logs attribute the action to this user, while the impersonated target is recorded only in internal audit payload data.', 'required' => false, - 'default' => '', + 'default' => null, 'example' => '5e5ea5c16897e', ]) ; diff --git a/tests/benchmarks/bulk-operations/LargeDocumentCreation.js b/tests/benchmarks/bulk-operations/LargeDocumentCreation.js index c903ed2dba..138c68c4d1 100644 --- a/tests/benchmarks/bulk-operations/LargeDocumentCreation.js +++ b/tests/benchmarks/bulk-operations/LargeDocumentCreation.js @@ -1,6 +1,6 @@ import { check, sleep } from "k6"; import http from "k6/http"; -import { provisionProject, provisionDatabase, cleanup, unique } from "./utils.js"; +import { provisionProject, provisionDatabase, cleanup, unique, ENDPOINT } from "./utils.js"; const millionRecords = 1_000_000; const batchSize = 10_000; @@ -8,7 +8,7 @@ const numBatches = millionRecords / batchSize; export function setup() { const resources = provisionProject({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, email: 'test@test.com', password: 'password123', name: 'Test User', @@ -16,7 +16,7 @@ export function setup() { }); const { databaseId, collectionId } = provisionDatabase({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, apiHeaders: resources.apiHeaders }); @@ -31,7 +31,7 @@ export function setup() { attributes: ["name", "email"] }; - const indexRes = http.post(`http://localhost/v1/databases/${databaseId}/collections/${collectionId}/indexes`, + const indexRes = http.post(`${ENDPOINT}/databases/${databaseId}/collections/${collectionId}/indexes`, JSON.stringify(index), { headers: resources.apiHeaders }); @@ -57,7 +57,7 @@ export function setup() { })); requests.push({ method: "POST", - url: `http://localhost/v1/databases/${databaseId}/collections/${collectionId}/documents`, + url: `${ENDPOINT}/databases/${databaseId}/collections/${collectionId}/documents`, body: JSON.stringify({ documents: docs }), params: { headers: resources.apiHeaders, @@ -96,7 +96,7 @@ export default function (data) { const payload = JSON.stringify({ documents: docs }); const res = http.post( - `http://localhost/v1/databases/${data.databaseId}/collections/${data.collectionId}/documents`, + `${ENDPOINT}/databases/${data.databaseId}/collections/${data.collectionId}/documents`, payload, { headers: data.apiHeaders, diff --git a/tests/benchmarks/bulk-operations/documentCreation.js b/tests/benchmarks/bulk-operations/documentCreation.js index 730b6bb541..94ba690c0f 100644 --- a/tests/benchmarks/bulk-operations/documentCreation.js +++ b/tests/benchmarks/bulk-operations/documentCreation.js @@ -1,12 +1,12 @@ import { check, sleep } from "k6"; import http from "k6/http"; -import { provisionProject, provisionDatabase, cleanup, unique } from "./utils.js"; +import { provisionProject, provisionDatabase, cleanup, unique, ENDPOINT } from "./utils.js"; const amount = 10_000; export function setup() { const resources = provisionProject({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, email: 'test@test.com', password: 'password123', name: 'Test User', @@ -14,7 +14,7 @@ export function setup() { }); const { databaseId, collectionId } = provisionDatabase({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, apiHeaders: resources.apiHeaders }); @@ -54,7 +54,7 @@ export default function (data) { }); const res = http.post( - `http://localhost/v1/databases/${data.databaseId}/collections/${data.collectionId}/documents`, + `${ENDPOINT}/databases/${data.databaseId}/collections/${data.collectionId}/documents`, payload, { headers: data.apiHeaders diff --git a/tests/benchmarks/bulk-operations/noisyNeighbor.js b/tests/benchmarks/bulk-operations/noisyNeighbor.js index 4bfec4e564..3cb4c62510 100644 --- a/tests/benchmarks/bulk-operations/noisyNeighbor.js +++ b/tests/benchmarks/bulk-operations/noisyNeighbor.js @@ -1,7 +1,7 @@ import { check, sleep } from "k6"; import http from "k6/http"; import { Trend } from "k6/metrics"; -import { provisionProject, provisionDatabase, cleanup, unique } from "./utils.js"; +import { provisionProject, provisionDatabase, cleanup, unique, ENDPOINT } from "./utils.js"; // Custom Trend metric for light response time tracking export const lightResponseTime = new Trend("light_response_time", true); @@ -12,7 +12,7 @@ const LIGHT_AMOUNT = 10; // Light operation amount export function setup() { // Set up two separate projects - one for bulk operations (noisy neighbor) and one for light operations const heavyResources = provisionProject({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, email: 'heavy@test.com', password: 'password123', name: 'Heavy User', @@ -20,7 +20,7 @@ export function setup() { }); const lightResources = provisionProject({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, email: 'light@test.com', password: 'password123', name: 'Light User', @@ -29,12 +29,12 @@ export function setup() { // Set up databases for both projects const heavy = provisionDatabase({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, apiHeaders: heavyResources.apiHeaders }); const light = provisionDatabase({ - endpoint: 'http://localhost/v1', + endpoint: ENDPOINT, apiHeaders: lightResources.apiHeaders }); @@ -84,7 +84,7 @@ export function heavy(data) { const payload = JSON.stringify({ documents }); const res = http.post( - `http://localhost/v1/databases/${data.heavy.databaseId}/collections/${data.heavy.collectionId}/documents`, + `${ENDPOINT}/databases/${data.heavy.databaseId}/collections/${data.heavy.collectionId}/documents`, payload, { headers: data.heavy.apiHeaders @@ -103,7 +103,7 @@ export function light(data) { const startTime = new Date(); const res = http.post( - `http://localhost/v1/databases/${data.light.databaseId}/collections/${data.light.collectionId}/documents`, + `${ENDPOINT}/databases/${data.light.databaseId}/collections/${data.light.collectionId}/documents`, payload, { headers: data.light.apiHeaders diff --git a/tests/benchmarks/bulk-operations/utils.js b/tests/benchmarks/bulk-operations/utils.js index 5b8bbc6c67..56771e7acc 100644 --- a/tests/benchmarks/bulk-operations/utils.js +++ b/tests/benchmarks/bulk-operations/utils.js @@ -1,5 +1,8 @@ import http from 'k6/http'; import { check } from 'k6'; +import { ENDPOINT } from '../config.js'; + +export { ENDPOINT }; /** * @typedef {Object} AuthHeaders @@ -47,7 +50,7 @@ function assert(response, checkName, condition) { * - API Key creation * * @param {Object} config Configuration object - * @param {string} config.endpoint Base endpoint URL (e.g., 'http://localhost:80/v1') + * @param {string} config.endpoint Base endpoint URL (e.g., 'http://localhost:9520/v1') * @param {string} config.email Email for account creation * @param {string} config.password Password for account creation * @param {string} config.name Name for account creation @@ -165,7 +168,7 @@ export function provisionProject(config) { * Example usage: * * const config = { - * endpoint: 'http://localhost:80/v1', + * endpoint: 'http://localhost:9520/v1', * email: 'test@example.com', * password: 'complex-password', * name: 'Test User', diff --git a/tests/benchmarks/config.js b/tests/benchmarks/config.js new file mode 100644 index 0000000000..cb7b22677a --- /dev/null +++ b/tests/benchmarks/config.js @@ -0,0 +1,2 @@ +export const ENDPOINT = (__ENV.APPWRITE_ENDPOINT || 'http://localhost:9520/v1').replace(/\/+$/, ''); +export const REALTIME_URL = (__ENV.APPWRITE_REALTIME_URL || `${ENDPOINT.replace(/^http/, 'ws')}/realtime`).replace(/\/+$/, ''); diff --git a/tests/benchmarks/graphql/account/graphql-full-selection.js b/tests/benchmarks/graphql/account/graphql-full-selection.js index 84d41328d6..85521547c1 100644 --- a/tests/benchmarks/graphql/account/graphql-full-selection.js +++ b/tests/benchmarks/graphql/account/graphql-full-selection.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.post('http://localhost/v1/graphql', JSON.stringify({ + http.post(`${ENDPOINT}/graphql`, JSON.stringify({ query: `query { accountGet { _id diff --git a/tests/benchmarks/graphql/account/graphql-selection-set.js b/tests/benchmarks/graphql/account/graphql-selection-set.js index fd605121e9..befc161fbc 100644 --- a/tests/benchmarks/graphql/account/graphql-selection-set.js +++ b/tests/benchmarks/graphql/account/graphql-selection-set.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.post('http://localhost/v1/graphql', JSON.stringify({ + http.post(`${ENDPOINT}/graphql`, JSON.stringify({ query: `query { accountGet { _id email } }` }), { headers: { diff --git a/tests/benchmarks/graphql/account/rest.js b/tests/benchmarks/graphql/account/rest.js index 04037c28f1..2f60892b09 100644 --- a/tests/benchmarks/graphql/account/rest.js +++ b/tests/benchmarks/graphql/account/rest.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.get('http://localhost/v1/account', { + http.get(`${ENDPOINT}/account`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', diff --git a/tests/benchmarks/graphql/locale/graphql-batched.js b/tests/benchmarks/graphql/locale/graphql-batched.js index b2c633d49a..0dfd933f6d 100644 --- a/tests/benchmarks/graphql/locale/graphql-batched.js +++ b/tests/benchmarks/graphql/locale/graphql-batched.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.post('http://localhost/v1/graphql', JSON.stringify([{ + http.post(`${ENDPOINT}/graphql`, JSON.stringify([{ query: 'query { localeGetCountries { total countries { code } } }', }, { query: 'query { localeGetContinents { total continents { code } } }', diff --git a/tests/benchmarks/graphql/locale/graphql-full-selection.js b/tests/benchmarks/graphql/locale/graphql-full-selection.js index d66d6c44a7..219a78d0e9 100644 --- a/tests/benchmarks/graphql/locale/graphql-full-selection.js +++ b/tests/benchmarks/graphql/locale/graphql-full-selection.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.post('http://localhost/v1/graphql', JSON.stringify({ + http.post(`${ENDPOINT}/graphql`, JSON.stringify({ query: 'query { localeGetCountries { total countries { code name } } }', }), { headers: { diff --git a/tests/benchmarks/graphql/locale/graphql-selection-set.js b/tests/benchmarks/graphql/locale/graphql-selection-set.js index 46c6dcaa53..59f00e47e3 100644 --- a/tests/benchmarks/graphql/locale/graphql-selection-set.js +++ b/tests/benchmarks/graphql/locale/graphql-selection-set.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.post('http://localhost/v1/graphql', JSON.stringify({ + http.post(`${ENDPOINT}/graphql`, JSON.stringify({ query: 'query { localeGetCountries { total } }', }), { headers: { diff --git a/tests/benchmarks/graphql/locale/rest-serial.js b/tests/benchmarks/graphql/locale/rest-serial.js index 22f0c48ab0..acad4bcbc9 100644 --- a/tests/benchmarks/graphql/locale/rest-serial.js +++ b/tests/benchmarks/graphql/locale/rest-serial.js @@ -1,37 +1,38 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.get('http://localhost/v1/locale/countries', { + http.get(`${ENDPOINT}/locale/countries`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', } }) - http.get('http://localhost/v1/locale/continents', { + http.get(`${ENDPOINT}/locale/continents`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', } }) - http.get('http://localhost/v1/locale/countries/eu', { + http.get(`${ENDPOINT}/locale/countries/eu`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', } }) - http.get('http://localhost/v1/locale/countries/phones', { + http.get(`${ENDPOINT}/locale/countries/phones`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', } }) - http.get('http://localhost/v1/locale/languages', { + http.get(`${ENDPOINT}/locale/languages`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', } }) -} \ No newline at end of file +} diff --git a/tests/benchmarks/graphql/locale/rest.js b/tests/benchmarks/graphql/locale/rest.js index 0c9c57355f..d830fe58dc 100644 --- a/tests/benchmarks/graphql/locale/rest.js +++ b/tests/benchmarks/graphql/locale/rest.js @@ -1,10 +1,11 @@ import http from 'k6/http'; +import { ENDPOINT } from '../../config.js'; export const options = { vus: 20, duration: '60s', }; export default function () { - http.get('http://localhost/v1/locale/countries', { + http.get(`${ENDPOINT}/locale/countries`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': 'test', diff --git a/tests/benchmarks/http-local.sh b/tests/benchmarks/http-local.sh index 734c825fda..15c4b64cbe 100755 --- a/tests/benchmarks/http-local.sh +++ b/tests/benchmarks/http-local.sh @@ -5,7 +5,7 @@ export K6_WEB_DASHBOARD="${K6_WEB_DASHBOARD:-true}" export K6_WEB_DASHBOARD_HOST="${K6_WEB_DASHBOARD_HOST:-127.0.0.1}" export K6_WEB_DASHBOARD_PORT="${K6_WEB_DASHBOARD_PORT:-5665}" export K6_WEB_DASHBOARD_EXPORT="${K6_WEB_DASHBOARD_EXPORT:-/tmp/appwrite-k6-report.html}" -export APPWRITE_ENDPOINT="${APPWRITE_ENDPOINT:-http://localhost/v1}" +export APPWRITE_ENDPOINT="${APPWRITE_ENDPOINT:-http://localhost:9520/v1}" export APPWRITE_WORKER_TIMEOUT_MS="${APPWRITE_WORKER_TIMEOUT_MS:-120000}" export APPWRITE_BENCHMARK_SUMMARY_PATH="${APPWRITE_BENCHMARK_SUMMARY_PATH:-/tmp/appwrite-k6-summary.json}" diff --git a/tests/benchmarks/http.js b/tests/benchmarks/http.js index ef42e99663..a41b4778df 100644 --- a/tests/benchmarks/http.js +++ b/tests/benchmarks/http.js @@ -1,3 +1,5 @@ +import { ENDPOINT } from './config.js'; + /* * Run locally: * Requires k6 and a running Appwrite instance. @@ -11,14 +13,14 @@ import { check, group, sleep } from 'k6'; import encoding from 'k6/encoding'; import { Counter, Trend } from 'k6/metrics'; -const ENDPOINT = (__ENV.APPWRITE_ENDPOINT || 'http://localhost/v1').replace(/\/+$/, ''); const CONSOLE_PROJECT = __ENV.APPWRITE_CONSOLE_PROJECT || 'console'; const REGION = __ENV.APPWRITE_REGION || 'default'; const REDIRECT_URL = __ENV.APPWRITE_BENCHMARK_REDIRECT_URL || 'http://localhost'; const PASSWORD = __ENV.APPWRITE_BENCHMARK_PASSWORD || 'Password123!'; const WORKER_TIMEOUT_MS = Number(__ENV.APPWRITE_WORKER_TIMEOUT_MS || 120000); -const ITERATIONS = Number(__ENV.APPWRITE_BENCHMARK_ITERATIONS || 1); const VUS = Number(__ENV.APPWRITE_BENCHMARK_VUS || 1); +const DURATION = __ENV.APPWRITE_BENCHMARK_DURATION || '1m'; +const ROWS_PER_FLOW = Number(__ENV.APPWRITE_BENCHMARK_ROWS || 5); const SUMMARY_PATH = __ENV.APPWRITE_BENCHMARK_SUMMARY_PATH || '/tmp/appwrite-k6-summary.json'; const PREVIOUS_SUMMARY_PATH = __ENV.APPWRITE_BENCHMARK_PREVIOUS_SUMMARY_PATH || ''; const PREVIOUS_SUMMARY = PREVIOUS_SUMMARY_PATH ? loadPreviousSummary(PREVIOUS_SUMMARY_PATH) : null; @@ -31,16 +33,14 @@ export const flowFailures = new Counter('appwrite_benchmark_flow_failures'); export const options = { scenarios: { curated_flows: { - executor: 'shared-iterations', + executor: 'constant-vus', exec: 'curatedFlows', vus: VUS, - iterations: ITERATIONS, - maxDuration: __ENV.APPWRITE_BENCHMARK_MAX_DURATION || '30m', + duration: DURATION, }, }, thresholds: { http_req_failed: ['rate<0.05'], - appwrite_api_duration: ['p(95)<2000'], appwrite_benchmark_flow_failures: ['count<1'], }, }; @@ -173,6 +173,7 @@ export function setup() { }, apiHeaders, [201, 409], 'setup.project.platforms.web.create'); const tablesDb = setupTablesDb(apiHeaders); + const users = setupUsers(projectId, VUS); return { runId, @@ -182,10 +183,41 @@ export function setup() { tableId: tablesDb.tableId, consoleSessionHeaders, apiHeaders, + users, platformStatus: platform.status, }; } +// Pre-create one signed-in user per VU so password hashing happens once +// during setup (excluded from metrics) instead of in every iteration. +function setupUsers(projectId, count) { + const headers = projectHeaders(projectId); + const users = []; + + for (let index = 0; index < count; index++) { + const email = `bench-user-${unique('mail')}@example.com`; + setupApi('POST', '/account', { + userId: unique('user'), + email, + password: PASSWORD, + name: 'Benchmark User', + }, headers, [201], 'setup.account.create'); + + const session = setupApi('POST', '/account/sessions/email', { + email, + password: PASSWORD, + }, headers, [201], 'setup.account.session'); + + users.push({ sessionHeaders: { ...headers, Cookie: cookieHeader(session) } }); + + // Drop the auto-stored session cookie so the next user can sign in; + // setup() runs in a single iteration, so the jar is not reset for us. + http.cookieJar().clear(ENDPOINT); + } + + return users; +} + function setupTablesDb(apiHeaders) { const databaseId = unique('tdb'); const tableId = unique('tbl'); @@ -219,7 +251,8 @@ function setupTablesDb(apiHeaders) { } export function curatedFlows(data) { - const ctx = { ...data }; + const user = data.users[(__VU - 1) % data.users.length]; + const ctx = { ...data, sessionHeaders: user.sessionHeaders }; try { group('account flow', () => accountFlow(ctx)); @@ -243,62 +276,42 @@ export function teardown(data) { } function accountFlow(ctx) { - const userId = unique('user'); - const email = `bench-user-${unique('mail')}@example.com`; - const headers = projectHeaders(ctx.projectId); + requireSession(ctx, 'accountFlow'); - api('POST', '/account', { - userId, - email, - password: PASSWORD, - name: 'Benchmark User', - }, headers, [201], 'account.create'); - - const session = api('POST', '/account/sessions/email', { - email, - password: PASSWORD, - }, headers, [201], 'account.sessions.email.create'); - - const sessionHeaders = { - ...headers, - Cookie: cookieHeader(session), - }; - - ctx.userId = userId; - ctx.userEmail = email; - ctx.sessionHeaders = sessionHeaders; - - api('GET', '/account', null, sessionHeaders, [200], 'account.get'); - api('GET', '/account/logs', null, sessionHeaders, [200], 'account.logs.list'); - api('PATCH', '/account/prefs', { prefs: { benchmark: true, runId: ctx.runId } }, sessionHeaders, [200], 'account.prefs.update'); - api('PATCH', '/account/name', { name: 'Benchmark User Updated' }, sessionHeaders, [200], 'account.name.update'); - api('PATCH', '/account/password', { password: `${PASSWORD}2`, oldPassword: PASSWORD }, sessionHeaders, [200], 'account.password.update'); + api('GET', '/account', null, ctx.sessionHeaders, [200], 'account.get'); + api('GET', '/account/logs', null, ctx.sessionHeaders, [200], 'account.logs.list'); + api('PATCH', '/account/prefs', { prefs: { benchmark: true, runId: ctx.runId } }, ctx.sessionHeaders, [200], 'account.prefs.update'); + api('PATCH', '/account/name', { name: 'Benchmark User Updated' }, ctx.sessionHeaders, [200], 'account.name.update'); } function tablesDbFlow(ctx) { requireSession(ctx, 'tablesDbFlow'); - const databaseId = ctx.databaseId; - const tableId = ctx.tableId; - const rowId = unique('row'); + const { databaseId, tableId, sessionHeaders } = ctx; + const base = `/tablesdb/${databaseId}/tables/${tableId}/rows`; + const rowIds = []; - api('POST', `/tablesdb/${databaseId}/tables/${tableId}/rows`, { - rowId, - data: tablePayload(), - permissions: ITEM_PERMISSIONS, - }, ctx.sessionHeaders, [201], 'tablesdb.rows.create'); - api('GET', `/tablesdb/${databaseId}/tables/${tableId}/rows`, null, ctx.sessionHeaders, [200], 'tablesdb.rows.list'); - api('GET', `/tablesdb/${databaseId}/tables/${tableId}/rows/${rowId}`, null, ctx.sessionHeaders, [200], 'tablesdb.rows.get'); - api('PATCH', `/tablesdb/${databaseId}/tables/${tableId}/rows/${rowId}`, { - data: { title: 'Benchmark Row Updated' }, - }, ctx.sessionHeaders, [200], 'tablesdb.rows.update'); - api('PATCH', `/tablesdb/${databaseId}/tables/${tableId}/rows/${rowId}/quantity/increment`, { - value: 1, - }, ctx.sessionHeaders, [200], 'tablesdb.rows.increment'); - api('PATCH', `/tablesdb/${databaseId}/tables/${tableId}/rows/${rowId}/quantity/decrement`, { - value: 1, - }, ctx.sessionHeaders, [200], 'tablesdb.rows.decrement'); - api('DELETE', `/tablesdb/${databaseId}/tables/${tableId}/rows/${rowId}`, null, ctx.sessionHeaders, [204], 'tablesdb.rows.delete'); + for (let index = 0; index < ROWS_PER_FLOW; index++) { + const rowId = unique('row'); + rowIds.push(rowId); + api('POST', base, { + rowId, + data: tablePayload(), + permissions: ITEM_PERMISSIONS, + }, sessionHeaders, [201], 'tablesdb.rows.create'); + } + + api('GET', base, null, sessionHeaders, [200], 'tablesdb.rows.list'); + + for (const rowId of rowIds) { + api('GET', `${base}/${rowId}`, null, sessionHeaders, [200], 'tablesdb.rows.get'); + api('PATCH', `${base}/${rowId}`, { + data: { title: 'Benchmark Row Updated' }, + }, sessionHeaders, [200], 'tablesdb.rows.update'); + api('PATCH', `${base}/${rowId}/quantity/increment`, { value: 1 }, sessionHeaders, [200], 'tablesdb.rows.increment'); + api('PATCH', `${base}/${rowId}/quantity/decrement`, { value: 1 }, sessionHeaders, [200], 'tablesdb.rows.decrement'); + api('DELETE', `${base}/${rowId}`, null, sessionHeaders, [204], 'tablesdb.rows.delete'); + } } function storageFlow(ctx) { diff --git a/tests/benchmarks/ws.js b/tests/benchmarks/ws.js index 916458856f..0b657f6e4e 100644 --- a/tests/benchmarks/ws.js +++ b/tests/benchmarks/ws.js @@ -3,6 +3,7 @@ import { URL } from 'https://jslib.k6.io/url/1.0.0/index.js'; import ws from 'k6/ws'; import { check } from 'k6'; +import { REALTIME_URL } from './config.js'; export let options = { stages: [ @@ -20,7 +21,7 @@ export let options = { export default function () { // const url = new URL('wss://appwrite-realtime.monitor-api.com/v1/realtime'); // url.searchParams.append('project', '604249e6b1a9f'); - const url = new URL('ws://localhost/v1/realtime'); + const url = new URL(REALTIME_URL); url.searchParams.append('project', 'console'); url.searchParams.append('channels[]', 'files'); diff --git a/tests/e2e/General/UsageTest.php b/tests/e2e/General/UsageTest.php index dde1346991..42321395cc 100644 --- a/tests/e2e/General/UsageTest.php +++ b/tests/e2e/General/UsageTest.php @@ -1466,8 +1466,6 @@ final class UsageTest extends Scope $collectionsTotal = $data['vectordbCollectionsTotal']; $documentsTotal = $data['vectordbDocumentsTotal']; - $this->assertProjectRequestsAtLeastGlobal(); - // Project-wide scalars: vectorsdbDatabasesTotal counts ONLY VectorsDB instances // (not relational databases), vectorsdbDocumentsTotal is the sum of all vector // documents across this project. Both are produced exclusively by @@ -1871,7 +1869,7 @@ final class UsageTest extends Scope $this->validateDates($response['body']['executions']); $this->assertEquals($executionTime, $response['body']['executionsTime'][array_key_last($response['body']['executionsTime'])]['value']); $this->validateDates($response['body']['executionsTime']); - }); + }, 60000, 500); $this->assertEventually(function () use ($executions, $executionTime) { $response = $this->client->call( @@ -1903,7 +1901,7 @@ final class UsageTest extends Scope $this->validateDates($response['body']['executionsTime']); $this->assertGreaterThan(0, $response['body']['buildsTime'][array_key_last($response['body']['buildsTime'])]['value']); $this->validateDates($response['body']['buildsTime']); - }); + }, 60000, 500); } public function testCustomDomainsFunctionStats(): void diff --git a/tests/e2e/Services/Functions/FunctionsBase.php b/tests/e2e/Services/Functions/FunctionsBase.php index 458359bbe9..05f2e52c1a 100644 --- a/tests/e2e/Services/Functions/FunctionsBase.php +++ b/tests/e2e/Services/Functions/FunctionsBase.php @@ -494,11 +494,11 @@ trait FunctionsBase return $deployment; } - protected function listSpecifications(): mixed + protected function listSpecifications(array $params = []): mixed { $specifications = $this->client->call(Client::METHOD_GET, '/functions/specifications', array_merge([ 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders())); + ], $this->getHeaders()), $params); return $specifications; } diff --git a/tests/e2e/Services/Functions/FunctionsCustomServerTest.php b/tests/e2e/Services/Functions/FunctionsCustomServerTest.php index 1aba466944..0e98be1d25 100644 --- a/tests/e2e/Services/Functions/FunctionsCustomServerTest.php +++ b/tests/e2e/Services/Functions/FunctionsCustomServerTest.php @@ -200,7 +200,7 @@ final class FunctionsCustomServerTest extends Scope public function testListSpecs(): void { - $specifications = $this->listSpecifications(); + $specifications = $this->listSpecifications(['type' => 'runtimes']); $this->assertEquals(200, $specifications['headers']['status-code']); $this->assertGreaterThanOrEqual(2, $specifications['body']['total']); $this->assertArrayHasKey(0, $specifications['body']['specifications']); @@ -214,20 +214,25 @@ final class FunctionsCustomServerTest extends Scope $this->assertArrayHasKey('enabled', $specifications['body']['specifications'][1]); $this->assertArrayHasKey('slug', $specifications['body']['specifications'][1]); + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + $this->assertEquals(200, $buildSpecifications['headers']['status-code']); + $this->assertEquals($specifications['body']['total'], $buildSpecifications['body']['total']); + $buildSpecification = $buildSpecifications['body']['specifications'][0]['slug']; + $function = $this->createFunction([ 'functionId' => ID::unique(), 'name' => 'Specs function', 'runtime' => 'node-22', - 'buildSpecification' => $specifications['body']['specifications'][0]['slug'], + 'buildSpecification' => $buildSpecification, 'runtimeSpecification' => $specifications['body']['specifications'][1]['slug'], ]); $this->assertEquals(201, $function['headers']['status-code']); - $this->assertEquals($specifications['body']['specifications'][0]['slug'], $function['body']['buildSpecification']); + $this->assertEquals($buildSpecification, $function['body']['buildSpecification']); $this->assertEquals($specifications['body']['specifications'][1]['slug'], $function['body']['runtimeSpecification']); $function = $this->getFunction($function['body']['$id']); $this->assertEquals(200, $function['headers']['status-code']); - $this->assertEquals($specifications['body']['specifications'][0]['slug'], $function['body']['buildSpecification']); + $this->assertEquals($buildSpecification, $function['body']['buildSpecification']); $this->assertEquals($specifications['body']['specifications'][1]['slug'], $function['body']['runtimeSpecification']); $this->cleanupFunction($function['body']['$id']); diff --git a/tests/e2e/Services/Project/TemplatesBase.php b/tests/e2e/Services/Project/TemplatesBase.php index 9e329dfc3b..40f93e19a4 100644 --- a/tests/e2e/Services/Project/TemplatesBase.php +++ b/tests/e2e/Services/Project/TemplatesBase.php @@ -221,27 +221,33 @@ trait TemplatesBase { $this->ensureSMTPEnabled(); + $runId = \uniqid(); + $firstSubject = "First subject {$runId}"; + $firstBody = "First body {$runId}"; + $secondSubject = "Second subject {$runId}"; + $secondBody = "Second body {$runId}"; + $first = $this->updateEmailTemplate( templateId: 'otpSession', locale: 'en', - subject: 'First subject', - message: 'First body', + subject: $firstSubject, + message: $firstBody, ); $this->assertSame(200, $first['headers']['status-code']); $second = $this->updateEmailTemplate( templateId: 'otpSession', locale: 'en', - subject: 'Second subject', - message: 'Second body', + subject: $secondSubject, + message: $secondBody, ); $this->assertSame(200, $second['headers']['status-code']); - $this->assertSame('Second subject', $second['body']['subject']); - $this->assertSame('Second body', $second['body']['message']); + $this->assertSame($secondSubject, $second['body']['subject']); + $this->assertSame($secondBody, $second['body']['message']); $get = $this->getEmailTemplate('otpSession', 'en'); - $this->assertSame('Second subject', $get['body']['subject']); - $this->assertSame('Second body', $get['body']['message']); + $this->assertSame($secondSubject, $get['body']['subject']); + $this->assertSame($secondBody, $get['body']['message']); } public function testUpdateEmailTemplatePartialAfterSeed(): void @@ -281,32 +287,36 @@ trait TemplatesBase { $this->ensureSMTPEnabled(); + $runId = \uniqid(); + $enSubject = "English subject {$runId}"; + $frSubject = "Sujet francais {$runId}"; + $enUpdate = $this->updateEmailTemplate( templateId: 'invitation', locale: 'en', - subject: 'English subject', + subject: $enSubject, message: 'English body', ); $this->assertSame(200, $enUpdate['headers']['status-code']); $this->assertSame('en', $enUpdate['body']['locale']); - $this->assertSame('English subject', $enUpdate['body']['subject']); + $this->assertSame($enSubject, $enUpdate['body']['subject']); $frUpdate = $this->updateEmailTemplate( templateId: 'invitation', locale: 'fr', - subject: 'Sujet francais', + subject: $frSubject, message: 'Corps francais', ); $this->assertSame(200, $frUpdate['headers']['status-code']); $this->assertSame('fr', $frUpdate['body']['locale']); - $this->assertSame('Sujet francais', $frUpdate['body']['subject']); + $this->assertSame($frSubject, $frUpdate['body']['subject']); // Locales remain independent. $enGet = $this->getEmailTemplate('invitation', 'en'); - $this->assertSame('English subject', $enGet['body']['subject']); + $this->assertSame($enSubject, $enGet['body']['subject']); $frGet = $this->getEmailTemplate('invitation', 'fr'); - $this->assertSame('Sujet francais', $frGet['body']['subject']); + $this->assertSame($frSubject, $frGet['body']['subject']); } public function testUpdateEmailTemplateResponseModel(): void @@ -729,19 +739,21 @@ trait TemplatesBase $response = $this->listEmailTemplates(); $this->assertSame(200, $response['headers']['status-code']); - $foundEn = false; - $foundFr = false; - foreach ($response['body']['templates'] as $template) { - if ($template['templateId'] === 'recovery' && $template['locale'] === 'en' && $template['subject'] === $enSubject) { - $foundEn = true; - } - if ($template['templateId'] === 'recovery' && $template['locale'] === 'fr' && $template['subject'] === $frSubject) { - $foundFr = true; - } - } + $foundEn = \array_filter( + $response['body']['templates'], + fn ($template) => $template['templateId'] === 'recovery' + && $template['locale'] === 'en' + && $template['subject'] === $enSubject + ); + $foundFr = \array_filter( + $response['body']['templates'], + fn ($template) => $template['templateId'] === 'recovery' + && $template['locale'] === 'fr' + && $template['subject'] === $frSubject + ); - $this->assertTrue($foundEn, 'recovery/en must appear in the list'); - $this->assertTrue($foundFr, 'recovery/fr must appear in the list'); + $this->assertNotEmpty($foundEn, 'recovery/en must appear in the list'); + $this->assertNotEmpty($foundFr, 'recovery/fr must appear in the list'); } public function testListEmailTemplatesUpdateDoesNotDuplicate(): void diff --git a/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php b/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php index 13a7d549dc..92e30a9596 100644 --- a/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php +++ b/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php @@ -13,6 +13,7 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use WebSocket\Client as WebSocketClient; +use WebSocket\ConnectionException; use WebSocket\TimeoutException; final class RealtimeCustomClientQueryTestWithMessage extends Scope @@ -657,6 +658,90 @@ final class RealtimeCustomClientQueryTestWithMessage extends Scope ); } + public function testConnectionJWT(): void + { + $user = $this->getUser(); + $userId = $user['$id'] ?? ''; + $session = $user['session'] ?? ''; + $projectId = $this->getProject()['$id']; + + // Mint a JWT for the authenticated user. + $response = $this->client->call(Client::METHOD_POST, '/account/jwt', [ + 'origin' => 'http://localhost', + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'cookie' => 'a_session_' . $projectId . '=' . $session, + ]); + + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['jwt']); + $jwt = $response['body']['jwt']; + + /** + * Test for SUCCESS - JWT via x-appwrite-jwt header. + * Connection authenticates at handshake time; the `connected` payload carries the user. + */ + $client = $this->getWebsocketWithCustomQuery([ + 'project' => $projectId, + ], [ + 'origin' => 'http://localhost', + 'x-appwrite-jwt' => $jwt, + ]); + $connected = \json_decode($client->receive(), true); + + $this->assertEquals('connected', $connected['type'] ?? null); + $this->assertNotEmpty($connected['data']['user']); + $this->assertEquals($userId, $connected['data']['user']['$id']); + + // The authenticated user can subscribe to their account channel. + $subscribe = $this->sendSubscribeMessage($client, [[ + 'channels' => ['account'], + ]]); + $this->assertContains('account', $subscribe['data']['subscriptions'][0]['channels']); + + $client->close(); + + /** + * Test for SUCCESS - JWT via ?jwt= query string. + */ + $client = $this->getWebsocketWithCustomQuery([ + 'project' => $projectId, + 'jwt' => $jwt, + ], [ + 'origin' => 'http://localhost', + ]); + $connected = \json_decode($client->receive(), true); + + $this->assertEquals('connected', $connected['type'] ?? null); + $this->assertNotEmpty($connected['data']['user']); + $this->assertEquals($userId, $connected['data']['user']['$id']); + + $subscribe = $this->sendSubscribeMessage($client, [[ + 'channels' => ['account'], + ]]); + $this->assertContains('account', $subscribe['data']['subscriptions'][0]['channels']); + + $client->close(); + + /** + * Test for FAILURE - invalid JWT via query string is rejected at handshake. + */ + $client = $this->getWebsocketWithCustomQuery([ + 'project' => $projectId, + 'jwt' => 'invalid-token', + ], [ + 'origin' => 'http://localhost', + ]); + $error = \json_decode($client->receive(), true); + + $this->assertEquals('error', $error['type'] ?? null); + $this->assertEquals(401, $error['data']['code']); // USER_JWT_INVALID + + \usleep(250000); // 250ms + $this->expectException(ConnectionException::class); // server should disconnect + $client->close(); + } + public function testProjectChannelWithHeaderOnly(): void { $user = $this->getUser(); @@ -810,4 +895,345 @@ final class RealtimeCustomClientQueryTestWithMessage extends Scope $client->close(); } + + /** + * Create a database + collection (Role::any) with a string attribute, BEFORE the + * tail connection opens, so the setup events don't appear in the tail. + * + * @return array{databaseId:string, collectionId:string} + */ + private function setupTailCollection(): array + { + $headers = [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + 'x-appwrite-key' => $this->getProject()['apiKey'], + ]; + + $database = $this->client->call(Client::METHOD_POST, '/databases', $headers, [ + 'databaseId' => ID::unique(), + 'name' => 'Tail DB', + ]); + $this->assertEquals(201, $database['headers']['status-code']); + $databaseId = $database['body']['$id']; + + $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $headers, [ + 'collectionId' => ID::unique(), + 'name' => 'Actors', + 'permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + ]); + $this->assertEquals(201, $collection['headers']['status-code']); + $collectionId = $collection['body']['$id']; + + $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', $headers, [ + 'key' => 'name', + 'size' => 256, + 'required' => true, + ]); + + $this->assertEventually(function () use ($databaseId, $collectionId, $headers) { + $attribute = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/name', $headers); + $this->assertEquals(200, $attribute['headers']['status-code']); + $this->assertEquals('available', $attribute['body']['status']); + }, 120000, 500); + + return ['databaseId' => $databaseId, 'collectionId' => $collectionId]; + } + + /** + * Open a console connection (root session) in message mode and subscribe to a + * `console.tail.` channel with optional filter queries. + * + * @param array $queries + */ + private function openConsoleTail(string $targetProjectId, array $queries = [], string $subscriptionId = 'tail-1'): WebSocketClient + { + $queryString = \http_build_query(['project' => 'console']); + $client = new WebSocketClient( + 'ws://appwrite.test/v1/realtime?' . $queryString, + [ + 'headers' => [ + 'origin' => 'http://localhost', + 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + ], + 'timeout' => 10, + ] + ); + + $connected = \json_decode($client->receive(), true); + $this->assertEquals('connected', $connected['type'] ?? null); + + $sub = ['channels' => ['console.tail.' . $targetProjectId], 'subscriptionId' => $subscriptionId]; + if (!empty($queries)) { + $sub['queries'] = $queries; + } + + $client->send(\json_encode(['type' => 'subscribe', 'data' => [$sub]])); + + $response = \json_decode($client->receive(), true); + $this->assertEquals('response', $response['type'] ?? null); + $this->assertEquals('subscribe', $response['data']['to'] ?? null); + $this->assertTrue($response['data']['success'] ?? false); + + return $client; + } + + /** + * Receive frames until a `console.tail` event arrives, returning its payload (an + * array of compact frames). Skips the periodic `console.tail.stats` counter frames. + * + * @return array> + */ + private function receiveTailFrames(WebSocketClient $client, int $maxFrames = 5): array + { + for ($i = 0; $i < $maxFrames; $i++) { + $message = \json_decode($client->receive(), true); + $this->assertEquals('event', $message['type']); + if (($message['data']['events'][0] ?? null) === 'console.tail') { + return $message['data']['payload']; + } + } + $this->fail('No console.tail event frame received.'); + } + + public function testConsoleTailReceivesCompactMetadata(): void + { + ['databaseId' => $databaseId, 'collectionId' => $collectionId] = $this->setupTailCollection(); + + $projectId = $this->getProject()['$id']; + $client = $this->openConsoleTail($projectId); + + $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $this->getProject()['apiKey'], + ], [ + 'documentId' => ID::unique(), + 'data' => ['name' => 'Spiderman'], + ]); + $this->assertEquals(201, $document['headers']['status-code']); + $documentId = $document['body']['$id']; + + $frames = $this->receiveTailFrames($client); + + $match = null; + foreach ($frames as $frame) { + if (($frame['resourceId'] ?? null) === $documentId) { + $match = $frame; + break; + } + } + + $this->assertNotNull($match, 'document.create not present in tail: ' . \json_encode($frames)); + $this->assertSame('databases', $match['type']); + $this->assertSame('create', $match['action']); + $this->assertSame($databaseId, $match['databaseId']); + $this->assertSame($collectionId, $match['collectionId']); + // Compact: no full document body, and no scope ids from other resource types. + $this->assertArrayNotHasKey('name', $match); + $this->assertArrayNotHasKey('functionId', $match); + $this->assertArrayNotHasKey('bucketId', $match); + + $client->close(); + } + + public function testConsoleTailServerSideFilter(): void + { + ['databaseId' => $databaseId, 'collectionId' => $collectionId] = $this->setupTailCollection(); + + $projectId = $this->getProject()['$id']; + // Only deletes should reach this tail. + $client = $this->openConsoleTail($projectId, [Query::equal('action', ['delete'])->toString()]); + + $headers = [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $this->getProject()['apiKey'], + ]; + + // create — must be filtered out (never reaches the token bucket). + $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', $headers, [ + 'documentId' => ID::unique(), + 'data' => ['name' => 'Ironman'], + ]); + $this->assertEquals(201, $document['headers']['status-code']); + $documentId = $document['body']['$id']; + + // delete — must pass the filter. + $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $documentId, $headers); + $this->assertEquals(204, $deleted['headers']['status-code']); + + $frames = $this->receiveTailFrames($client); + + foreach ($frames as $frame) { + $this->assertSame('delete', $frame['action'], 'filter leaked a non-delete event: ' . \json_encode($frame)); + } + $deleteFrames = \array_filter($frames, fn ($f) => ($f['resourceId'] ?? null) === $documentId); + $this->assertNotEmpty($deleteFrames, 'expected the delete event in the tail'); + + $client->close(); + } + + public function testConsoleTailUnauthorizedProjectIsRejected(): void + { + $queryString = \http_build_query(['project' => 'console']); + $client = new WebSocketClient( + 'ws://appwrite.test/v1/realtime?' . $queryString, + [ + 'headers' => [ + 'origin' => 'http://localhost', + 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + ], + 'timeout' => 10, + ] + ); + + $connected = \json_decode($client->receive(), true); + $this->assertEquals('connected', $connected['type'] ?? null); + + // A project the console user's team does not own (does not exist) → policy violation. + $client->send(\json_encode([ + 'type' => 'subscribe', + 'data' => [['channels' => ['console.tail.nonexistentproject'], 'subscriptionId' => 'tail-x']], + ])); + + // A 1008 policy violation sends the error frame and then closes the connection. + // Depending on flush/close timing the client may read the error frame, or the + // socket may already be dead — both are valid rejections. What must NOT happen + // is a successful `response` subscription. + try { + $response = \json_decode($client->receive(), true); + $this->assertEquals('error', $response['type'] ?? null); + $this->assertEquals(1008, $response['data']['code'] ?? null); + } catch (ConnectionException) { + $this->addToAssertionCount(1); + } + + // close() can itself throw on an already-closed socket — best effort. + try { + $client->close(); + } catch (ConnectionException) { + // already closed by the server + } + } + + public function testConsoleTailSeesEventsNotReadableByTheConsoleUser(): void + { + // The tail authorizes the *viewer* by team membership at subscribe time and then + // forwards every project event regardless of the resource's read ACL. A document + // readable only by some OTHER user (not `any`, not the console user) must still + // appear in the console tail. + $projectId = $this->getProject()['$id']; + $headers = [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $this->getProject()['apiKey'], + ]; + + $database = $this->client->call(Client::METHOD_POST, '/databases', $headers, [ + 'databaseId' => ID::unique(), + 'name' => 'Tail ACL DB', + ]); + $this->assertEquals(201, $database['headers']['status-code']); + $databaseId = $database['body']['$id']; + + // documentSecurity ON and NO read(any) at the collection level, so the only read + // grant comes from the document's own (restricted) permission. + $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $headers, [ + 'collectionId' => ID::unique(), + 'name' => 'Secrets', + 'documentSecurity' => true, + 'permissions' => [Permission::create(Role::any())], + ]); + $this->assertEquals(201, $collection['headers']['status-code']); + $collectionId = $collection['body']['$id']; + + $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', $headers, [ + 'key' => 'name', + 'size' => 256, + 'required' => true, + ]); + $this->assertEventually(function () use ($databaseId, $collectionId, $headers) { + $attribute = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/name', $headers); + $this->assertEquals(200, $attribute['headers']['status-code']); + $this->assertEquals('available', $attribute['body']['status']); + }, 120000, 500); + + $client = $this->openConsoleTail($projectId); + + // Read restricted to a user that is NOT the console user → the console viewer + // could never read this document directly, yet the tail must surface its event. + $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', $headers, [ + 'documentId' => ID::unique(), + 'data' => ['name' => 'top secret'], + 'permissions' => [Permission::read(Role::user('not-the-console-user'))], + ]); + $this->assertEquals(201, $document['headers']['status-code']); + $documentId = $document['body']['$id']; + + $frames = $this->receiveTailFrames($client); + + $match = null; + foreach ($frames as $frame) { + if (($frame['resourceId'] ?? null) === $documentId) { + $match = $frame; + break; + } + } + + $this->assertNotNull($match, 'restricted-read document.create not present in tail: ' . \json_encode($frames)); + $this->assertSame('databases', $match['type']); + $this->assertSame('create', $match['action']); + $this->assertArrayNotHasKey('name', $match); // still no document body + + $client->close(); + } + + public function testProjectConnectionCannotTail(): void + { + // A normal project websocket (not the console project) must not be able to tail, + // even for a team member — only the console connection may. Expect a 1008 reject. + $user = $this->getUser(); + $session = $user['session'] ?? ''; + $projectId = $this->getProject()['$id']; + + $queryString = \http_build_query(['project' => $projectId]); // NOT console + $client = new WebSocketClient( + 'ws://appwrite.test/v1/realtime?' . $queryString, + [ + 'headers' => [ + 'origin' => 'http://localhost', + 'cookie' => 'a_session_' . $projectId . '=' . $session, + ], + 'timeout' => 10, + ] + ); + + $connected = \json_decode($client->receive(), true); + $this->assertEquals('connected', $connected['type'] ?? null); + + $client->send(\json_encode([ + 'type' => 'subscribe', + 'data' => [['channels' => ['console.tail.' . $projectId], 'subscriptionId' => 'tail-proj']], + ])); + + try { + $response = \json_decode($client->receive(), true); + $this->assertEquals('error', $response['type'] ?? null); + $this->assertEquals(1008, $response['data']['code'] ?? null); + } catch (ConnectionException) { + $this->addToAssertionCount(1); + } + + try { + $client->close(); + } catch (ConnectionException) { + // already closed by the server + } + } } diff --git a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php index c623bdfd90..ce241ab91c 100644 --- a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php +++ b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php @@ -276,6 +276,89 @@ final class RealtimeCustomClientTest extends Scope $client->close(); } + public function testConnectionJWT() + { + $user = $this->getUser(); + $userId = $user['$id'] ?? ''; + $session = $user['session'] ?? ''; + $projectId = $this->getProject()['$id']; + + // Mint a JWT for the authenticated user. + $response = $this->client->call(Client::METHOD_POST, '/account/jwt', [ + 'origin' => 'http://localhost', + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'cookie' => 'a_session_' . $projectId . '=' . $session, + ]); + + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['jwt']); + $jwt = $response['body']['jwt']; + + /** + * Test for SUCCESS - JWT via x-appwrite-jwt header + */ + $client = $this->getWebsocket(['account'], [ + 'origin' => 'http://localhost', + 'x-appwrite-jwt' => $jwt, + ]); + $response = json_decode($client->receive(), true); + + $this->assertArrayHasKey('type', $response); + $this->assertArrayHasKey('data', $response); + $this->assertEquals('connected', $response['type']); + $this->assertNotEmpty($response['data']); + $this->assertNotEmpty($response['data']['user']); + $this->assertEquals($userId, $response['data']['user']['$id']); + $this->assertContains('account', $response['data']['channels']); + $this->assertContains('account.' . $userId, $response['data']['channels']); + + $client->close(); + + /** + * Test for SUCCESS - JWT via ?jwt= query string + */ + $client = $this->getWebsocketWithCustomQuery([ + 'project' => $projectId, + 'channels' => ['account'], + 'jwt' => $jwt, + ], [ + 'origin' => 'http://localhost', + ]); + $response = json_decode($client->receive(), true); + + $this->assertArrayHasKey('type', $response); + $this->assertArrayHasKey('data', $response); + $this->assertEquals('connected', $response['type']); + $this->assertNotEmpty($response['data']); + $this->assertNotEmpty($response['data']['user']); + $this->assertEquals($userId, $response['data']['user']['$id']); + $this->assertContains('account', $response['data']['channels']); + $this->assertContains('account.' . $userId, $response['data']['channels']); + + $client->close(); + + /** + * Test for FAILURE - invalid JWT via query string + */ + $client = $this->getWebsocketWithCustomQuery([ + 'project' => $projectId, + 'channels' => ['account'], + 'jwt' => 'invalid-token', + ], [ + 'origin' => 'http://localhost', + ]); + $response = json_decode($client->receive(), true); + + $this->assertArrayHasKey('type', $response); + $this->assertEquals('error', $response['type']); + $this->assertEquals(401, $response['data']['code']); // USER_JWT_INVALID + + \usleep(250000); // 250ms + $this->expectException(ConnectionException::class); // server should disconnect + $client->close(); + } + public function testConnectionPlatform() { /** diff --git a/tests/e2e/Services/Sites/SitesBase.php b/tests/e2e/Services/Sites/SitesBase.php index 54344f649a..f6a29f82ab 100644 --- a/tests/e2e/Services/Sites/SitesBase.php +++ b/tests/e2e/Services/Sites/SitesBase.php @@ -489,11 +489,11 @@ trait SitesBase return $deployment; } - protected function listSpecifications(): mixed + protected function listSpecifications(array $params = []): mixed { $specifications = $this->client->call(Client::METHOD_GET, '/sites/specifications', array_merge([ 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders())); + ], $this->getHeaders()), $params); return $specifications; } diff --git a/tests/e2e/Services/Sites/SitesCustomServerTest.php b/tests/e2e/Services/Sites/SitesCustomServerTest.php index 1413a5ffb9..7a5f578492 100644 --- a/tests/e2e/Services/Sites/SitesCustomServerTest.php +++ b/tests/e2e/Services/Sites/SitesCustomServerTest.php @@ -26,7 +26,7 @@ final class SitesCustomServerTest extends Scope public function testListSpecs(): void { - $specifications = $this->listSpecifications(); + $specifications = $this->listSpecifications(['type' => 'runtimes']); $this->assertEquals(200, $specifications['headers']['status-code']); $this->assertGreaterThanOrEqual(2, $specifications['body']['total']); $this->assertArrayHasKey(0, $specifications['body']['specifications']); @@ -40,21 +40,26 @@ final class SitesCustomServerTest extends Scope $this->assertArrayHasKey('enabled', $specifications['body']['specifications'][1]); $this->assertArrayHasKey('slug', $specifications['body']['specifications'][1]); + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + $this->assertEquals(200, $buildSpecifications['headers']['status-code']); + $this->assertEquals($specifications['body']['total'], $buildSpecifications['body']['total']); + $buildSpecification = $buildSpecifications['body']['specifications'][0]['slug']; + $site = $this->createSite([ 'buildRuntime' => 'node-22', 'framework' => 'other', 'name' => 'Specs site', 'siteId' => ID::unique(), - 'buildSpecification' => $specifications['body']['specifications'][0]['slug'], + 'buildSpecification' => $buildSpecification, 'runtimeSpecification' => $specifications['body']['specifications'][1]['slug'], ]); $this->assertEquals(201, $site['headers']['status-code']); - $this->assertEquals($specifications['body']['specifications'][0]['slug'], $site['body']['buildSpecification']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); $this->assertEquals($specifications['body']['specifications'][1]['slug'], $site['body']['runtimeSpecification']); $site = $this->getSite($site['body']['$id']); $this->assertEquals(200, $site['headers']['status-code']); - $this->assertEquals($specifications['body']['specifications'][0]['slug'], $site['body']['buildSpecification']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); $this->assertEquals($specifications['body']['specifications'][1]['slug'], $site['body']['runtimeSpecification']); $this->cleanupSite($site['body']['$id']); @@ -80,11 +85,15 @@ final class SitesCustomServerTest extends Scope public function testCreateSite(): void { + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + $buildSpecification = $buildSpecifications['body']['specifications'][0]['slug']; + /** * Test for SUCCESS */ $site = $this->createSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecification, 'fallbackFile' => '', 'framework' => 'other', 'name' => 'Test Site', @@ -102,6 +111,7 @@ final class SitesCustomServerTest extends Scope $this->assertEquals(true, $dateValidator->isValid($site['body']['$createdAt'])); $this->assertEquals(true, $dateValidator->isValid($site['body']['$updatedAt'])); $this->assertEquals('node-22', $site['body']['buildRuntime']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); $this->assertEquals(null, $site['body']['fallbackFile']); $this->assertEquals('./', $site['body']['outputDirectory']); @@ -716,11 +726,14 @@ final class SitesCustomServerTest extends Scope public function testListSites(): void { + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + /** * Test for SUCCESS */ $siteId = $this->setupSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecifications['body']['specifications'][0]['slug'], 'fallbackFile' => '', 'framework' => 'analog', 'name' => 'Test List Sites', @@ -862,8 +875,11 @@ final class SitesCustomServerTest extends Scope public function testGetSite(): void { + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + $siteId = $this->setupSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecifications['body']['specifications'][0]['slug'], 'fallbackFile' => '', 'framework' => 'other', 'name' => 'Test Site', @@ -1650,8 +1666,12 @@ final class SitesCustomServerTest extends Scope public function testUpdateSpecs(): void { + $buildSpecifications = $this->listSpecifications(['type' => 'builds']); + $buildSpecification = $buildSpecifications['body']['specifications'][0]['slug']; + $siteId = $this->setupSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecification, 'fallbackFile' => '', 'framework' => 'other', 'name' => 'Test Site', @@ -1667,6 +1687,7 @@ final class SitesCustomServerTest extends Scope // Change the function specs $site = $this->updateSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecification, 'fallbackFile' => '', 'framework' => 'other', 'name' => 'Test Site', @@ -1679,11 +1700,30 @@ final class SitesCustomServerTest extends Scope $this->assertEquals(200, $site['headers']['status-code']); $this->assertNotEmpty($site['body']['$id']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); + $this->assertEquals(Specification::S_1VCPU_1GB, $site['body']['runtimeSpecification']); + + $site = $this->updateSite([ + 'buildRuntime' => 'node-22', + 'fallbackFile' => '', + 'framework' => 'other', + 'name' => 'Test Site', + 'outputDirectory' => './', + 'providerBranch' => 'main', + 'providerRootDirectory' => './', + '$id' => $siteId, + 'runtimeSpecification' => Specification::S_1VCPU_1GB, + ]); + + $this->assertEquals(200, $site['headers']['status-code']); + $this->assertNotEmpty($site['body']['$id']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); $this->assertEquals(Specification::S_1VCPU_1GB, $site['body']['runtimeSpecification']); // Change the specs to 1vcpu 512mb $site = $this->updateSite([ 'buildRuntime' => 'node-22', + 'buildSpecification' => $buildSpecification, 'fallbackFile' => '', 'framework' => 'other', 'name' => 'Test Site', @@ -1696,6 +1736,7 @@ final class SitesCustomServerTest extends Scope $this->assertEquals(200, $site['headers']['status-code']); $this->assertNotEmpty($site['body']['$id']); + $this->assertEquals($buildSpecification, $site['body']['buildSpecification']); $this->assertEquals(Specification::S_1VCPU_512MB, $site['body']['runtimeSpecification']); /** diff --git a/tests/extensions/SwooleCleanupSubscriber.php b/tests/extensions/SwooleCleanupSubscriber.php new file mode 100644 index 0000000000..8f14290211 --- /dev/null +++ b/tests/extensions/SwooleCleanupSubscriber.php @@ -0,0 +1,17 @@ +registerSubscriber(new TestPreparationStartedSubscriber()); $facade->registerSubscriber(new TestFinishedSubscriber(self::MAX_SECONDS_ALLOWED)); $facade->registerSubscriber(new RetrySubscriber()); + $facade->registerSubscriber(new SwooleCleanupSubscriber()); } } diff --git a/tests/unit/Functions/BuildsTest.php b/tests/unit/Functions/BuildsTest.php index b757856c83..36515d2f5b 100644 --- a/tests/unit/Functions/BuildsTest.php +++ b/tests/unit/Functions/BuildsTest.php @@ -8,6 +8,7 @@ use Appwrite\Platform\Modules\Functions\Workers\Builds; use PHPUnit\Framework\TestCase; use ReflectionMethod; use Utopia\Config\Config; +use Utopia\Database\Database; use Utopia\Database\Document; final class BuildsTest extends TestCase @@ -87,6 +88,62 @@ final class BuildsTest extends TestCase $this->assertNull($detection->getFallbackFile()); } + public function testDisconnectVcsClearsAllFieldsAndDeletesRepository(): void + { + $resource = new Document([ + '$id' => 'func123', + '$collection' => 'functions', + 'repositoryId' => 'repo456', + 'installationId' => 'install789', + 'installationInternalId' => 'install789internal', + 'providerRepositoryId' => 'gh123', + 'providerBranch' => 'main', + 'providerRootDirectory' => 'functions/my-func', + 'providerSilentMode' => true, + 'repositoryInternalId' => 'repo456internal', + ]); + + $dbForProject = $this->createMock(Database::class); + $dbForPlatform = $this->createMock(Database::class); + + $dbForPlatform->expects($this->once()) + ->method('deleteDocument') + ->with('repositories', 'repo456'); + + $dbForProject->expects($this->once()) + ->method('updateDocument') + ->with('functions', 'func123', $this->callback(function (Document $doc) { + $this->assertSame('', $doc->getAttribute('installationId')); + $this->assertSame('', $doc->getAttribute('installationInternalId')); + $this->assertSame('', $doc->getAttribute('providerRepositoryId')); + $this->assertSame('', $doc->getAttribute('providerBranch')); + $this->assertSame('', $doc->getAttribute('providerRootDirectory')); + $this->assertFalse($doc->getAttribute('providerSilentMode')); + $this->assertSame('', $doc->getAttribute('repositoryId')); + $this->assertSame('', $doc->getAttribute('repositoryInternalId')); + return true; + })); + + $this->callBuilds('disconnectVcs', $resource, $dbForProject, $dbForPlatform); + } + + public function testDisconnectVcsSkipsRepositoryDeletionWhenRepositoryIdEmpty(): void + { + $resource = new Document([ + '$id' => 'func123', + '$collection' => 'functions', + 'repositoryId' => '', + ]); + + $dbForProject = $this->createMock(Database::class); + $dbForPlatform = $this->createMock(Database::class); + + $dbForPlatform->expects($this->never())->method('deleteDocument'); + $dbForProject->expects($this->once())->method('updateDocument'); + + $this->callBuilds('disconnectVcs', $resource, $dbForProject, $dbForPlatform); + } + private function callBuilds(string $method, mixed ...$arguments): mixed { return (new ReflectionMethod($this->builds, $method))->invoke($this->builds, ...$arguments); diff --git a/tests/unit/Platform/Modules/Compute/Validator/SpecificationTest.php b/tests/unit/Platform/Modules/Compute/Validator/SpecificationTest.php index 2fc6657d01..abc6296d0a 100644 --- a/tests/unit/Platform/Modules/Compute/Validator/SpecificationTest.php +++ b/tests/unit/Platform/Modules/Compute/Validator/SpecificationTest.php @@ -74,4 +74,26 @@ final class SpecificationTest extends TestCase $this->assertContains(SpecificationConstants::S_05VCPU_512MB, $allowed); $this->assertContains(SpecificationConstants::S_1VCPU_512MB, $allowed); } + + public function testGetAllowedSpecificationsWithBuildPlanLimits(): void + { + $plan = [ + 'buildSpecifications' => [ + SpecificationConstants::S_1VCPU_1GB, + SpecificationConstants::S_2VCPU_2GB, + ] + ]; + $validator = new Specification( + plan: $plan, + specifications: $this->specifications, + maxCpus: 0, + maxMemory: 0, + planKey: 'buildSpecifications' + ); + + $allowed = $validator->getAllowedSpecifications(); + $this->assertCount(2, $allowed); + $this->assertContains(SpecificationConstants::S_1VCPU_1GB, $allowed); + $this->assertContains(SpecificationConstants::S_2VCPU_2GB, $allowed); + } } diff --git a/tests/unit/Realtime/EventTailRegistryTest.php b/tests/unit/Realtime/EventTailRegistryTest.php new file mode 100644 index 0000000000..f41c8e1365 --- /dev/null +++ b/tests/unit/Realtime/EventTailRegistryTest.php @@ -0,0 +1,581 @@ +> $sent + */ + private function server(array &$sent): Server + { + // A stub (not a mock): we only capture sends, no expectations to verify. + $server = $this->createStub(Server::class); + $server->method('send')->willReturnCallback( + function (array $connections, string $message) use (&$sent): void { + $sent[] = json_decode($message, true); + } + ); + return $server; + } + + /** + * Like server(), but records the target connection id alongside each frame so tests + * can assert per-connection isolation. + * + * @param array}> $sent + */ + private function serverWithConn(array &$sent): Server + { + $server = $this->createStub(Server::class); + $server->method('send')->willReturnCallback( + function (array $connections, string $message) use (&$sent): void { + $sent[] = ['connId' => $connections[0] ?? null, 'frame' => json_decode($message, true)]; + } + ); + return $server; + } + + /** @param array $queries */ + private function compile(array $queries): array + { + return RuntimeQuery::compile($queries); + } + + // ---- Realtime::toTailMetadata ---- + + public function testTailMetadataDocumentEvent(): void + { + $event = [ + 'userId' => 'user-1', + 'data' => [ + 'events' => ['databases.main.collections.posts.documents.p1.create'], + 'timestamp' => '2026-06-06T00:00:00.000+00:00', + 'payload' => ['$id' => 'p1', '$databaseId' => 'main', '$collectionId' => 'posts', 'title' => 'hello'], + ], + ]; + + $meta = Realtime::toTailMetadata($event); + + $this->assertSame('databases.main.collections.posts.documents.p1.create', $meta['event']); + $this->assertSame('databases', $meta['type']); + $this->assertSame('create', $meta['action']); + $this->assertSame('user-1', $meta['userId']); + $this->assertSame('p1', $meta['resourceId']); + $this->assertSame('main', $meta['databaseId']); + $this->assertSame('posts', $meta['collectionId']); + // No full document body leaks through. + $this->assertArrayNotHasKey('title', $meta); + // Scope is type-specific: a databases event carries no bucket/function ids. + $this->assertArrayNotHasKey('bucketId', $meta); + $this->assertArrayNotHasKey('functionId', $meta); + } + + public function testTailMetadataScopeIsTypeSpecific(): void + { + $fn = Realtime::toTailMetadata([ + 'userId' => 'u1', + 'data' => [ + 'events' => ['functions.fn1.deployments.d1.create'], + 'payload' => ['$id' => 'd1', 'functionId' => 'fn1'], + ], + ]); + $this->assertSame('functions', $fn['type']); + $this->assertSame('fn1', $fn['functionId']); + $this->assertArrayNotHasKey('databaseId', $fn); + $this->assertArrayNotHasKey('bucketId', $fn); + + $file = Realtime::toTailMetadata([ + 'userId' => 'u1', + 'data' => [ + 'events' => ['buckets.b1.files.f1.create'], + 'payload' => ['$id' => 'f1', 'bucketId' => 'b1'], + ], + ]); + $this->assertSame('buckets', $file['type']); + $this->assertSame('b1', $file['bucketId']); + $this->assertArrayNotHasKey('functionId', $file); + $this->assertArrayNotHasKey('collectionId', $file); + + // Scope comes from the event name, so it's present even when the payload (here an + // execution doc) carries no functionId field — resourceId is the leaf ($id). + $exec = Realtime::toTailMetadata([ + 'data' => ['events' => ['functions.fn1.executions.e1.create'], 'payload' => ['$id' => 'e1']], + ]); + $this->assertSame('fn1', $exec['functionId']); + $this->assertSame('e1', $exec['resourceId']); + } + + public function testTailMetadataTopLevelResourceEventsCarryScope(): void + { + // Top-level resource events: the payload is the resource doc itself (id at $id, + // not at a teamId/bucketId/functionId field). Scope must still be present so a + // filter like equal('teamId', ['T']) matches the team's own create/update events. + $teamCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['teams.T.create'], 'payload' => ['$id' => 'T', 'name' => 'Acme']], + ]); + $this->assertSame('teams', $teamCreate['type']); + $this->assertSame('T', $teamCreate['teamId']); + $this->assertSame('T', $teamCreate['resourceId']); + + // Nested membership event: same teamId scope, leaf resourceId is the membership. + $membership = Realtime::toTailMetadata([ + 'data' => ['events' => ['teams.T.memberships.M.create'], 'payload' => ['$id' => 'M', 'teamId' => 'T']], + ]); + $this->assertSame('T', $membership['teamId']); + $this->assertSame('M', $membership['resourceId']); + + $bucketCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['buckets.B.create'], 'payload' => ['$id' => 'B']], + ]); + $this->assertSame('B', $bucketCreate['bucketId']); + + $functionCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['functions.F.create'], 'payload' => ['$id' => 'F']], + ]); + $this->assertSame('F', $functionCreate['functionId']); + } + + public function testTailMetadataTablesUsesTableIdAsCollection(): void + { + $meta = Realtime::toTailMetadata([ + 'userId' => 'u1', + 'data' => [ + 'events' => ['databases.main.tables.t1.rows.r1.create'], + 'payload' => ['$id' => 'r1', '$databaseId' => 'main', '$tableId' => 't1'], + ], + ]); + $this->assertSame('databases', $meta['type']); + $this->assertSame('main', $meta['databaseId']); + $this->assertSame('t1', $meta['collectionId']); + } + + public function testTailMetadataExtractsScopeForAllDatabasePrefixes(): void + { + // The database family is published under several prefixes. `type` keeps the + // actual prefix, and databaseId/collectionId are extracted for every one of them + // (so scope filters work across the whole family regardless of the variant). + foreach (['databases', 'tablesdb', 'documentsdb', 'vectorsdb'] as $prefix) { + $meta = Realtime::toTailMetadata([ + 'userId' => 'u1', + 'data' => [ + 'events' => ["{$prefix}.main.collections.posts.documents.p1.create"], + 'payload' => ['$id' => 'p1'], + ], + ]); + $this->assertSame($prefix, $meta['type'], 'type preserves the actual prefix'); + $this->assertSame('main', $meta['databaseId']); + $this->assertSame('posts', $meta['collectionId']); + } + + // `tables` sub-resource under a projected prefix still maps to collectionId. + $rows = Realtime::toTailMetadata([ + 'data' => ['events' => ['tablesdb.main.tables.t1.rows.r1.create'], 'payload' => ['$id' => 'r1']], + ]); + $this->assertSame('tablesdb', $rows['type']); + $this->assertSame('main', $rows['databaseId']); + $this->assertSame('t1', $rows['collectionId']); + } + + public function testTailMetadataAttributeTrailingAction(): void + { + // `users.U.update.email` — action is the second-to-last segment. + $meta = Realtime::toTailMetadata([ + 'userId' => 'u9', + 'data' => ['events' => ['users.u9.update.email'], 'payload' => ['$id' => 'u9']], + ]); + + $this->assertSame('users', $meta['type']); + $this->assertSame('update', $meta['action']); + $this->assertSame('u9', $meta['resourceId']); + } + + public function testTailMetadataHandlesMissingPayload(): void + { + $meta = Realtime::toTailMetadata(['data' => ['events' => ['functions.f1.executions.e1.delete']]]); + + $this->assertSame('functions', $meta['type']); + $this->assertSame('delete', $meta['action']); + $this->assertNull($meta['userId']); + $this->assertNull($meta['resourceId']); + } + + // ---- channel helpers ---- + + public function testChannelHelpers(): void + { + $this->assertSame('console.tail.proj1', EventTailRegistry::channel('proj1')); + $this->assertSame('proj1', EventTailRegistry::projectFromChannel('console.tail.proj1')); + $this->assertNull(EventTailRegistry::projectFromChannel('documents')); + $this->assertNull(EventTailRegistry::projectFromChannel('console.tail.')); + } + + // ---- filter THEN sample ---- + + public function testFilterIsAppliedBeforeSampling(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'sub-a', 'projX', $this->compile([Query::equal('type', ['databases'])]), 0.0); + + $registry->ingest('projX', ['type' => 'databases', 'action' => 'create'], 0.0); + $registry->ingest('projX', ['type' => 'buckets', 'action' => 'create'], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + + // Exactly one event frame, carrying only the databases frame; no stats frame + // because the filtered-out bucket event never consumed a token. + $this->assertCount(1, $sent); + $this->assertSame(['console.tail'], $sent[0]['data']['events']); + $this->assertCount(1, $sent[0]['data']['payload']); + $this->assertSame('databases', $sent[0]['data']['payload'][0]['type']); + } + + public function testTokenBucketDropsExcessAndEmitsCounter(): void + { + $registry = new EventTailRegistry(rate: 5); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); // selectAll + + for ($i = 0; $i < 20; $i++) { + $registry->ingest('projX', ['type' => 'databases', 'seq' => $i], 0.0); + } + + $sent = []; + $registry->flush($this->server($sent)); + + $eventFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail'])); + $statsFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail.stats'])); + + $this->assertCount(1, $eventFrames); + $this->assertCount(5, $eventFrames[0]['data']['payload'], 'rate=5 → only 5 delivered at the same instant'); + + $this->assertCount(1, $statsFrames); + $this->assertSame('tail.stats', $statsFrames[0]['data']['payload']['$type']); + $this->assertSame(5, $statsFrames[0]['data']['payload']['delivered']); + $this->assertSame(15, $statsFrames[0]['data']['payload']['dropped']); + // delivered + dropped accounts for every ingested event. + $this->assertSame(20, $statsFrames[0]['data']['payload']['delivered'] + $statsFrames[0]['data']['payload']['dropped']); + } + + public function testNoCounterFrameWhenNothingDropped(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + + $registry->ingest('projX', ['type' => 'databases'], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + + // Only the event frame — no stats frame because nothing was dropped. + $this->assertCount(1, $sent); + $this->assertSame(['console.tail'], $sent[0]['data']['events']); + } + + public function testDroppedAccumulatesAcrossIngestsInWindow(): void + { + $registry = new EventTailRegistry(rate: 2); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + + // Three separate ingests at the same instant: 2 delivered, 1 dropped. + $registry->ingest('projX', ['type' => 'databases', 'seq' => 1], 0.0); + $registry->ingest('projX', ['type' => 'databases', 'seq' => 2], 0.0); + $registry->ingest('projX', ['type' => 'databases', 'seq' => 3], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + + $statsFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail.stats'])); + $this->assertCount(1, $statsFrames); + $this->assertSame(2, $statsFrames[0]['data']['payload']['delivered']); + $this->assertSame(1, $statsFrames[0]['data']['payload']['dropped']); + } + + public function testCounterResetsBetweenWindows(): void + { + $registry = new EventTailRegistry(rate: 1); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + + // Window 1: 3 events at t=0 → 1 delivered, 2 dropped → stats frame emitted. + for ($i = 0; $i < 3; $i++) { + $registry->ingest('projX', ['type' => 'databases', 'seq' => $i], 0.0); + } + $sent = []; + $registry->flush($this->server($sent)); + $statsFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail.stats'])); + $this->assertCount(1, $statsFrames); + $this->assertSame(2, $statsFrames[0]['data']['payload']['dropped']); + + // Window 2: a single event well after refill → delivered, nothing dropped → no stats frame + // and the previous window's dropped count does not carry over. + $registry->ingest('projX', ['type' => 'databases'], 100.0); + $sent = []; + $registry->flush($this->server($sent)); + $statsFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail.stats'])); + $this->assertCount(0, $statsFrames); + } + + public function testLargeBufferIsChunkedAcrossFrames(): void + { + // rate high enough to admit all, batchMax forces splitting on flush. + $registry = new EventTailRegistry(rate: 100, batchMax: 2); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + + for ($i = 0; $i < 5; $i++) { + $registry->ingest('projX', ['type' => 'databases', 'seq' => $i], 0.0); + } + + $sent = []; + $registry->flush($this->server($sent)); + + $eventFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail'])); + // 5 buffered frames, batchMax 2 → 3 websocket frames (2 + 2 + 1). + $this->assertCount(3, $eventFrames); + $this->assertCount(2, $eventFrames[0]['data']['payload']); + $this->assertCount(2, $eventFrames[1]['data']['payload']); + $this->assertCount(1, $eventFrames[2]['data']['payload']); + // No event is lost across the chunk boundaries. + $total = array_sum(array_map(fn ($f) => count($f['data']['payload']), $eventFrames)); + $this->assertSame(5, $total); + } + + public function testTokensRefillOverTime(): void + { + $registry = new EventTailRegistry(rate: 5); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + + // Drain the bucket at t=0. + for ($i = 0; $i < 10; $i++) { + $registry->ingest('projX', ['type' => 'databases'], 0.0); + } + $sent = []; + $registry->flush($this->server($sent)); // resets the per-window counters + + // One second later, the bucket has refilled to the cap (rate=5). + for ($i = 0; $i < 10; $i++) { + $registry->ingest('projX', ['type' => 'databases'], 1.0); + } + $sent = []; + $registry->flush($this->server($sent)); + + $eventFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail'])); + $this->assertCount(5, $eventFrames[0]['data']['payload']); + } + + public function testFlushClearsBufferBetweenWindows(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'sub-a', 'projX', $this->compile([]), 0.0); + $registry->ingest('projX', ['type' => 'databases'], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + $this->assertCount(1, $sent); + + // Nothing new ingested → second flush sends nothing. + $sent = []; + $registry->flush($this->server($sent)); + $this->assertCount(0, $sent); + } + + public function testRemoveConnectionStopsDelivery(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(7, 'sub-a', 'projX', $this->compile([]), 0.0); + $registry->add(7, 'sub-b', 'projY', $this->compile([]), 0.0); + + $this->assertTrue($registry->isTailed('projX')); + $this->assertTrue($registry->isTailed('projY')); + + $registry->removeConnection(7); + + $this->assertFalse($registry->isTailed('projX')); + $this->assertFalse($registry->isTailed('projY')); + + $registry->ingest('projX', ['type' => 'databases'], 0.0); + $sent = []; + $registry->flush($this->server($sent)); + $this->assertCount(0, $sent); + } + + public function testRemoveSingleSubscription(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(7, 'sub-a', 'projX', $this->compile([]), 0.0); + $registry->add(7, 'sub-b', 'projX', $this->compile([]), 0.0); + + $registry->remove(7, 'sub-a'); + $this->assertTrue($registry->isTailed('projX'), 'sub-b still tails projX'); + + $registry->remove(7, 'sub-b'); + $this->assertFalse($registry->isTailed('projX')); + + // Removing an unknown subscription is a no-op. + $registry->remove(7, 'does-not-exist'); + $this->assertFalse($registry->isTailed('projX')); + } + + public function testSameSubscriptionIdOnDifferentConnectionsIsolated(): void + { + // Subscription IDs are only unique within a connection. Two connections both + // using 'dup' must stay fully isolated — no cross-project/connection leakage. + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'dup', 'projA', $this->compile([]), 0.0); + $registry->add(2, 'dup', 'projB', $this->compile([]), 0.0); + + $registry->ingest('projA', ['type' => 'databases', 'resourceId' => 'a1'], 0.0); + $registry->ingest('projB', ['type' => 'databases', 'resourceId' => 'b1'], 0.0); + + $sent = []; + $registry->flush($this->serverWithConn($sent)); + + $byConn = []; + foreach ($sent as $s) { + $byConn[$s['connId']][] = $s['frame']['data']['channels'][0]; + } + // Connection 1 only ever receives projA's channel; connection 2 only projB's. + $this->assertSame(['console.tail.projA'], $byConn[1] ?? []); + $this->assertSame(['console.tail.projB'], $byConn[2] ?? []); + + // Removing one connection's 'dup' must not touch the other's. + $registry->remove(1, 'dup'); + $this->assertFalse($registry->isTailed('projA')); + $this->assertTrue($registry->isTailed('projB')); + } + + public function testMultipleProjectsUnderOneSubscription(): void + { + // A subscription naming several tail channels tails each project independently; + // none overwrites another, and removing the subscription clears them all. + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'sub-multi', 'projA', $this->compile([]), 0.0); + $registry->add(1, 'sub-multi', 'projB', $this->compile([]), 0.0); + + $this->assertTrue($registry->isTailed('projA')); + $this->assertTrue($registry->isTailed('projB')); + + $registry->ingest('projA', ['type' => 'databases', 'resourceId' => 'a1'], 0.0); + $registry->ingest('projB', ['type' => 'databases', 'resourceId' => 'b1'], 0.0); + + $sent = []; + $registry->flush($this->serverWithConn($sent)); + + $channels = array_map(fn ($s) => $s['frame']['data']['channels'][0], $sent); + $this->assertContains('console.tail.projA', $channels); + $this->assertContains('console.tail.projB', $channels); + // Both frames carry the same (real) subscription id. + foreach ($sent as $s) { + $this->assertSame(['sub-multi'], $s['frame']['data']['subscriptions']); + } + + $registry->remove(1, 'sub-multi'); + $this->assertFalse($registry->isTailed('projA')); + $this->assertFalse($registry->isTailed('projB')); + } + + public function testReAddingSameChannelOverwritesFilterWithoutStaleEntry(): void + { + // Reusing a subscription id on the SAME tail channel updates its filter in place + // (keyed by connId/subId/projectId) — no stale entry, no duplicate delivery. + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'x', 'projA', $this->compile([Query::equal('action', ['create'])]), 0.0); + $registry->add(1, 'x', 'projA', $this->compile([Query::equal('action', ['delete'])]), 0.0); + + $registry->ingest('projA', ['action' => 'create', 'resourceId' => 'c1'], 0.0); + $registry->ingest('projA', ['action' => 'delete', 'resourceId' => 'd1'], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + + $eventFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail'])); + // A lingering create-filter entry would surface the create and/or add a 2nd frame. + $this->assertCount(1, $eventFrames); + $this->assertCount(1, $eventFrames[0]['data']['payload']); + $this->assertSame('delete', $eventFrames[0]['data']['payload'][0]['action']); + $this->assertSame('d1', $eventFrames[0]['data']['payload'][0]['resourceId']); + } + + public function testAddingChannelPreservesExistingTail(): void + { + // Review scenario: subscribe id 'x' to tail A, later add tail B under the same id. + // Registration is additive (mirrors Realtime::subscribe()), so A must keep delivering. + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'x', 'projA', $this->compile([]), 0.0); + + // ... later, the same subscription id also tails projB. + $registry->add(1, 'x', 'projB', $this->compile([]), 0.0); + + $this->assertTrue($registry->isTailed('projA'), 'projA must remain tailed after adding projB'); + $this->assertTrue($registry->isTailed('projB')); + + $registry->ingest('projA', ['type' => 'databases', 'resourceId' => 'a1'], 0.0); + $registry->ingest('projB', ['type' => 'databases', 'resourceId' => 'b1'], 0.0); + + $sent = []; + $registry->flush($this->serverWithConn($sent)); + + $channels = array_map(fn ($s) => $s['frame']['data']['channels'][0], $sent); + $this->assertContains('console.tail.projA', $channels, 'projA stopped delivering after projB was added'); + $this->assertContains('console.tail.projB', $channels); + } + + public function testRateClampedToAtLeastOne(): void + { + // A misconfigured non-positive rate must not disable the tail entirely. + foreach ([0, -5] as $badRate) { + $registry = new EventTailRegistry(rate: $badRate); + $registry->add(1, 'x', 'projA', $this->compile([]), 0.0); + $registry->ingest('projA', ['type' => 'databases'], 0.0); + + $sent = []; + $registry->flush($this->server($sent)); + + $eventFrames = array_values(array_filter($sent, fn ($f) => $f['data']['events'] === ['console.tail'])); + $this->assertCount(1, $eventFrames, "rate {$badRate} must clamp to >=1 so events still flow"); + $this->assertCount(1, $eventFrames[0]['data']['payload']); + } + } + + public function testRevalidateConnectionDropsTailsWithRevokedRole(): void + { + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'x', 'projA', $this->compile([]), 0.0, 'team:teamA'); + $registry->add(1, 'y', 'projB', $this->compile([]), 0.0, 'team:teamB'); + $this->assertTrue($registry->isTailed('projA')); + $this->assertTrue($registry->isTailed('projB')); + + // The connection keeps teamB membership but loses teamA. + $registry->revalidateConnection(1, ['user:u1', 'team:teamB']); + + $this->assertFalse($registry->isTailed('projA'), 'tail for the revoked team must be dropped'); + $this->assertTrue($registry->isTailed('projB'), 'tail for the still-held team must remain'); + } + + public function testRevalidateConnectionKeepsEntriesWithoutRole(): void + { + // Entries registered without an authorizing role are never pruned (defensive). + $registry = new EventTailRegistry(rate: 100); + $registry->add(1, 'x', 'projA', $this->compile([]), 0.0); + + $registry->revalidateConnection(1, ['user:u1']); + + $this->assertTrue($registry->isTailed('projA')); + } +} diff --git a/tests/unit/Reference/RendererTest.php b/tests/unit/Reference/RendererTest.php new file mode 100644 index 0000000000..ac284103cc --- /dev/null +++ b/tests/unit/Reference/RendererTest.php @@ -0,0 +1,67 @@ + ['databaseId' => 'db1'], + 'response' => ['$id' => 'col9'], + ])); + + $this->assertSame( + 'database/db1/collection/col9', + $renderer->render('database/{request.databaseId}/collection/{response.$id}'), + ); + } + + public function testFallsBackToResponseForUnknownNamespace(): void + { + $renderer = new Renderer(new Document([ + 'response' => ['id' => 'r1'], + ])); + + $this->assertSame('thing/r1', $renderer->render('thing/{unknown.id}')); + } + + public function testSupportsUserAndProjectNamespaces(): void + { + $renderer = new Renderer(new Document([ + 'user' => ['$id' => 'usr1'], + 'project' => new Document(['$id' => 'prj1']), + ])); + + $this->assertSame( + 'user/usr1/project/prj1', + $renderer->render('user/{user.$id}/project/{project.$id}'), + ); + } + + public function testLeavesUnresolvedTokensIntact(): void + { + $renderer = new Renderer(new Document([ + 'request' => [], + ])); + + $this->assertSame( + 'database/{request.databaseId}', + $renderer->render('database/{request.databaseId}'), + ); + } + + public function testShortCircuitsWhenNoTemplate(): void + { + $renderer = new Renderer(new Document([])); + + $this->assertSame('database/db1', $renderer->render('database/db1')); + $this->assertSame('', $renderer->render('')); + } +} diff --git a/tests/unit/Vcs/GitHubInstallationEventTest.php b/tests/unit/Vcs/GitHubInstallationEventTest.php new file mode 100644 index 0000000000..045ac5d9d6 --- /dev/null +++ b/tests/unit/Vcs/GitHubInstallationEventTest.php @@ -0,0 +1,160 @@ +handler = new Create(); + } + + public function testHandleInstallationEventIgnoresNonDeletedActions(): void + { + $dbForPlatform = $this->createMock(Database::class); + $authorization = $this->createStub(Authorization::class); + + $dbForPlatform->expects($this->never())->method('find'); + $dbForPlatform->expects($this->never())->method('deleteDocument'); + + $result = $this->callHandler('handleInstallationEvent', [ + 'action' => 'created', + 'installationId' => '123', + ], $dbForPlatform, $authorization, fn () => null); + + $this->assertNull($result); + } + + public function testHandleInstallationEventDisconnectsFunctionsAndSites(): void + { + $installation = new Document([ + '$id' => 'install1', + '$sequence' => 'install1seq', + 'projectId' => 'project1', + 'providerInstallationId' => 'gh-install-123', + ]); + + $function = new Document([ + '$id' => 'func1', + '$collection' => 'functions', + 'installationId' => 'install1', + 'installationInternalId' => 'install1seq', + 'providerRepositoryId' => 'repo123', + 'providerBranch' => 'main', + 'providerRootDirectory' => 'functions/my-func', + 'providerSilentMode' => true, + 'repositoryId' => 'repo1', + 'repositoryInternalId' => 'repo1seq', + ]); + + $project = new Document(['$id' => 'project1']); + + $dbForProject = $this->createMock(Database::class); + $dbForPlatform = $this->createMock(Database::class); + $authorization = $this->createMock(Authorization::class); + + $dbForPlatform->expects($this->exactly(2)) + ->method('find') + ->willReturnCallback(fn (string $collection): array => match ($collection) { + 'installations' => [$installation], + 'repositories' => [], + default => [], + }); + + $dbForPlatform->expects($this->once()) + ->method('getDocument') + ->with('projects', 'project1') + ->willReturn($project); + + $dbForProject->expects($this->exactly(2)) + ->method('find') + ->willReturnCallback(fn (string $collection): array => $collection === 'functions' ? [$function] : []); + + $dbForProject->expects($this->once()) + ->method('updateDocument') + ->with('functions', 'func1', $this->callback(function (Document $doc) { + $this->assertSame('', $doc->getAttribute('installationId')); + $this->assertSame('', $doc->getAttribute('installationInternalId')); + $this->assertSame('', $doc->getAttribute('providerRepositoryId')); + $this->assertSame('', $doc->getAttribute('providerBranch')); + $this->assertSame('', $doc->getAttribute('providerRootDirectory')); + $this->assertFalse($doc->getAttribute('providerSilentMode')); + $this->assertSame('', $doc->getAttribute('repositoryId')); + $this->assertSame('', $doc->getAttribute('repositoryInternalId')); + return true; + })); + + // 1: find(installations), 2: getDocument(projects), 3: find(functions), 4: updateDocument(func1), + // 5: find(sites), 6: find(repositories), 7: deleteDocument(installations) + $authorization->expects($this->exactly(7)) + ->method('skip') + ->willReturnCallback(fn (callable $fn): mixed => $fn()); + + $dbForPlatform->expects($this->once()) + ->method('deleteDocument') + ->with('installations', 'install1'); + + $getProjectDB = fn () => $dbForProject; + + $this->callHandler('handleInstallationEvent', [ + 'action' => 'deleted', + 'installationId' => 'gh-install-123', + ], $dbForPlatform, $authorization, $getProjectDB); + } + + public function testHandleInstallationEventSkipsDisconnectWhenProjectNotFound(): void + { + $installation = new Document([ + '$id' => 'install1', + '$sequence' => 'install1seq', + 'projectId' => 'project1', + 'providerInstallationId' => 'gh-install-123', + ]); + + $dbForPlatform = $this->createMock(Database::class); + $authorization = $this->createMock(Authorization::class); + + $dbForPlatform->expects($this->exactly(2)) + ->method('find') + ->willReturnCallback(fn (string $collection): array => match ($collection) { + 'installations' => [$installation], + 'repositories' => [], + default => [], + }); + + $dbForPlatform->expects($this->once()) + ->method('getDocument') + ->with('projects', 'project1') + ->willReturn(new Document()); + + // 1: find(installations), 2: getDocument(projects), 3: find(repositories), 4: deleteDocument(installations) + $authorization->expects($this->exactly(4)) + ->method('skip') + ->willReturnCallback(fn (callable $fn): mixed => $fn()); + + $dbForPlatform->expects($this->once()) + ->method('deleteDocument') + ->with('installations', 'install1'); + + $this->callHandler('handleInstallationEvent', [ + 'action' => 'deleted', + 'installationId' => 'gh-install-123', + ], $dbForPlatform, $authorization, fn () => null); + } + + private function callHandler(string $method, mixed ...$arguments): mixed + { + return (new ReflectionMethod($this->handler, $method))->invoke($this->handler, ...$arguments); + } +}