mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Merge branch '1.9.x' into realtime-tail-logs
This commit is contained in:
204 files changed
+6070
-7693
No files matched your search
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: appwrite-testing
|
||||
description: Choose, write, and review tests in the Appwrite server repository using a pragmatic test pyramid. Use when adding or changing PHPUnit tests, deciding between unit and e2e coverage, moving duplicated high-level coverage lower, testing API endpoints, workers, queues, permissions, auth/scopes, persistence, serialization, retry logic, validators, security regressions, or Swoole-sensitive behavior.
|
||||
---
|
||||
|
||||
# Appwrite Testing
|
||||
|
||||
## Core Rule
|
||||
|
||||
Keep the test suite pyramid-shaped: many fast unit tests, fewer service/API e2e tests, and very few broad workflow tests. Push each assertion to the lowest level that still proves the behavior.
|
||||
|
||||
Prefer fast feedback over formal labels. A narrow integration-style unit test with deterministic fakes is better than a slow e2e test when it proves the same behavior.
|
||||
|
||||
## Choose The Test Level
|
||||
|
||||
Use `tests/unit/...` for:
|
||||
|
||||
- Pure validators, helpers, mappers, parsers, filters, retry classifiers, event builders, URL/security checks, and branching logic.
|
||||
- Worker building blocks that can be called with fake adapters, in-memory collaborators, or scripted test doubles.
|
||||
- Regression cases where inputs and observable outputs can be asserted without HTTP, Docker services, queues, Swoole coroutines, or real network calls.
|
||||
- Boundary serialization/deserialization when the external side can be represented with a deterministic fake response or document.
|
||||
|
||||
Use `tests/e2e/Services/{Service}` for:
|
||||
|
||||
- HTTP route behavior, status codes, headers, cookies, response shape, SDK-visible contracts, and request validation through the real API path.
|
||||
- Auth, scope, permission, project mode, platform, and side-specific behavior that depends on Appwrite's request lifecycle.
|
||||
- Persistence, queue-visible behavior, worker integration, database adapter behavior, and DI/wiring that unit tests cannot prove.
|
||||
- A small number of high-value service workflows that represent user-visible behavior across multiple Appwrite subsystems.
|
||||
|
||||
Avoid broad e2e coverage for every edge case. Cover edge cases in unit tests and keep e2e focused on the integration contract that lower layers cannot exercise.
|
||||
|
||||
## Appwrite Patterns
|
||||
|
||||
Structure tests as Arrange, Act, Assert. Test observable behavior, not the order of private calls or internal implementation details.
|
||||
|
||||
Write unit tests with `PHPUnit\Framework\TestCase` under the matching namespace in `tests/unit`. Use data providers for matrices. Prefer named fake classes over anonymous mocks when PHPStan clarity matters.
|
||||
|
||||
Write service e2e tests with `Tests\E2E\Client` and the existing scope traits such as `Scope`, `ProjectCustom`, `SideClient`, `SideServer`, or `ProjectConsole`. Reuse local service base traits when they exist.
|
||||
|
||||
Use deterministic test doubles for network, queue, mail, storage, database, and third-party boundaries whenever the point of the test is local behavior. Never call production third-party services from automated tests.
|
||||
|
||||
Generate unique IDs, emails, and names for e2e data to survive parallel runs. Cache setup data only when the test does not require precise counts or fresh state.
|
||||
|
||||
Keep assertions precise: status code, body fields, error type/message, permission outcome, retry count, adapter call count, or persisted value. Avoid asserting incidental full documents when a sparse behavior assertion is enough.
|
||||
|
||||
## Duplication Policy
|
||||
|
||||
If a higher-level test finds a bug and no lower-level test fails, add a lower-level regression test where practical.
|
||||
|
||||
Do not repeat all conditional branches at e2e level once unit tests cover them. The e2e test should prove routing, auth, serialization, persistence, or wiring only.
|
||||
|
||||
Delete or avoid high-level tests that no longer add confidence beyond lower-level coverage. Keep tests readable even if that means some local duplication in setup.
|
||||
|
||||
## Swoole And Workers
|
||||
|
||||
Be careful with Swoole coroutines in unit tests. Do not run coroutine integrations inside the shared unit process unless existing nearby tests prove the pattern is safe.
|
||||
|
||||
For workers, unit-test pure pieces such as batching, classification, cursor construction, retry/backoff decisions, and adapter interaction with fakes. Cover coroutine scheduling, queues, and full worker lifecycle through e2e or existing integration patterns.
|
||||
|
||||
Avoid sleeps and timing-sensitive assertions. If timing is unavoidable, isolate it, make it generous, and prefer polling helpers already used in the suite.
|
||||
|
||||
## Commands
|
||||
|
||||
Run focused checks first:
|
||||
|
||||
```bash
|
||||
docker compose exec appwrite test tests/unit/
|
||||
docker compose exec appwrite test tests/e2e/Services/[Service]
|
||||
docker compose exec appwrite test tests/e2e/Services/[Service] --filter=[Method]
|
||||
composer lint <file>
|
||||
composer analyze
|
||||
```
|
||||
|
||||
Use the narrowest command that validates the change, then broaden only when the touched behavior crosses module, API, worker, or shared-helper boundaries.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Appwrite Testing"
|
||||
short_description: "Choose and write Appwrite tests using a pragmatic test pyramid."
|
||||
default_prompt: "Use the Appwrite testing skill to choose the right test level and add focused PHPUnit coverage for this change."
|
||||
+154
-269
@@ -1,17 +1,19 @@
|
||||
name: CI
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
COMPOSE_FILE: docker-compose.yml
|
||||
IMAGE: appwrite-dev
|
||||
REGISTRY_IMAGE: ghcr.io/${{ github.repository }}/appwrite-dev
|
||||
K6_VERSION: '0.53.0'
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- 1.9.x
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
response_format:
|
||||
@@ -89,111 +91,13 @@ jobs:
|
||||
sarif_file: 'trivy-fs-results.sarif'
|
||||
category: 'trivy-source'
|
||||
|
||||
composer:
|
||||
name: Checks / Composer
|
||||
checks:
|
||||
name: Checks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0
|
||||
with:
|
||||
php-version: '8.3'
|
||||
tools: composer:v2
|
||||
coverage: none
|
||||
|
||||
- name: Validate
|
||||
run: composer validate
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
|
||||
|
||||
- name: Audit
|
||||
env:
|
||||
COMPOSER_NO_AUDIT: 0
|
||||
run: composer audit
|
||||
|
||||
format:
|
||||
name: Checks / Format
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- run: git checkout HEAD^2
|
||||
if: github.event_name == 'pull_request'
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0
|
||||
with:
|
||||
php-version: '8.3'
|
||||
tools: composer:v2
|
||||
coverage: none
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
|
||||
|
||||
- name: Run Linter
|
||||
run: composer lint
|
||||
|
||||
refactor:
|
||||
name: Checks / Refactor
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0
|
||||
with:
|
||||
php-version: '8.3'
|
||||
tools: composer:v2
|
||||
coverage: none
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
|
||||
|
||||
- name: Run Rector
|
||||
run: composer refactor:check
|
||||
|
||||
analyze:
|
||||
name: Checks / Analyze
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0
|
||||
with:
|
||||
php-version: '8.3'
|
||||
tools: composer:v2
|
||||
coverage: none
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
|
||||
|
||||
- name: Cache PHPStan result cache
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: .phpstan-cache
|
||||
key: phpstan-${{ github.sha }}
|
||||
restore-keys: |
|
||||
phpstan-
|
||||
|
||||
- name: Run PHPStan
|
||||
run: composer analyze -- --no-progress
|
||||
|
||||
specs:
|
||||
name: Checks / Specs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0
|
||||
with:
|
||||
@@ -202,10 +106,42 @@ jobs:
|
||||
tools: composer:v2
|
||||
coverage: none
|
||||
|
||||
- name: Validate composer.json
|
||||
run: composer validate
|
||||
|
||||
- name: Install dependencies
|
||||
id: install
|
||||
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
|
||||
|
||||
- name: Cache PHPStan result cache
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: .phpstan-cache
|
||||
key: phpstan-${{ github.sha }}
|
||||
restore-keys: |
|
||||
phpstan-
|
||||
|
||||
- name: Audit dependencies
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
env:
|
||||
COMPOSER_NO_AUDIT: 0
|
||||
run: composer audit
|
||||
|
||||
- name: Run Linter
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
run: composer lint
|
||||
|
||||
- name: Run Rector
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
run: composer refactor:check
|
||||
|
||||
- name: Run PHPStan
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
run: composer analyze -- --no-progress
|
||||
|
||||
- name: Generate specs
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
|
||||
run: _APP_STORAGE_LIMIT=5368709120 php app/cli.php specs --version=latest --git=no
|
||||
|
||||
locale:
|
||||
@@ -229,48 +165,78 @@ jobs:
|
||||
outputs:
|
||||
databases: ${{ steps.generate.outputs.databases }}
|
||||
modes: ${{ steps.generate.outputs.modes }}
|
||||
services: ${{ steps.generate.outputs.services }}
|
||||
steps:
|
||||
- name: Generate matrix
|
||||
id: generate
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const allDatabases = ['MariaDB', 'PostgreSQL', 'MongoDB'];
|
||||
const allModes = ['dedicated', 'shared'];
|
||||
const runner4 = `runs-on=${context.runId}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache`;
|
||||
const runner8 = `runs-on=${context.runId}/runner=8cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache`;
|
||||
|
||||
const defaultDatabases = ['MongoDB'];
|
||||
const defaultModes = ['dedicated'];
|
||||
const services = [
|
||||
{ name: 'Account', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Avatars', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Console', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Databases', runner: runner8, functional: false, processes: 3, timeout: 15 },
|
||||
{ name: 'TablesDB', runner: runner8, functional: false, processes: 3, timeout: 15 },
|
||||
{ name: 'Functions', runner: runner4, functional: false, processes: null, timeout: 15 },
|
||||
{ name: 'FunctionsSchedule', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'GraphQL', runner: runner4, functional: false, processes: null, timeout: 15 },
|
||||
{ name: 'Health', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Advisor', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Locale', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Projects', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Realtime', runner: runner4, functional: false, processes: null, timeout: 15 },
|
||||
{ name: 'Sites', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Proxy', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Storage', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Tokens', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Teams', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Users', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'ProjectWebhooks', runner: runner4, functional: false, processes: null, timeout: 15 },
|
||||
{ name: 'Webhooks', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'VCS', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Messaging', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Migrations', runner: runner4, functional: true, processes: 1, timeout: 15 },
|
||||
{ name: 'Project', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Presences', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
];
|
||||
core.setOutput('services', JSON.stringify(services));
|
||||
|
||||
const pr = context.payload.pull_request;
|
||||
if (!pr) {
|
||||
core.setOutput('databases', JSON.stringify(allDatabases));
|
||||
core.setOutput('modes', JSON.stringify(allModes));
|
||||
|
||||
const isDatabaseVersionChanged = async () => {
|
||||
const getContent = (ref) => github.rest.repos.getContent({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
path: 'composer.lock',
|
||||
ref,
|
||||
});
|
||||
|
||||
const getDbVersion = (lock) => lock.packages?.find(p => p.name === 'utopia-php/database')?.version;
|
||||
const [{ data: base }, { data: head }] = await Promise.all([
|
||||
getContent(pr.base.sha),
|
||||
getContent(pr.head.sha),
|
||||
]);
|
||||
|
||||
const decode = (content) => JSON.parse(Buffer.from(content, 'base64').toString());
|
||||
return getDbVersion(decode(base.content)) !== getDbVersion(decode(head.content));
|
||||
};
|
||||
|
||||
if (!pr || await isDatabaseVersionChanged()) {
|
||||
core.setOutput('databases', JSON.stringify(['MariaDB', 'PostgreSQL', 'MongoDB']));
|
||||
core.setOutput('modes', JSON.stringify(['dedicated', 'shared']));
|
||||
return;
|
||||
}
|
||||
|
||||
const getContent = (ref) => github.rest.repos.getContent({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
path: 'composer.lock',
|
||||
ref,
|
||||
});
|
||||
|
||||
const getDbVersion = (lock) => lock.packages?.find(p => p.name === 'utopia-php/database')?.version;
|
||||
|
||||
const [{ data: base }, { data: head }] = await Promise.all([
|
||||
getContent(pr.base.sha),
|
||||
getContent(pr.head.sha),
|
||||
]);
|
||||
|
||||
const decode = (content) => JSON.parse(Buffer.from(content, 'base64').toString());
|
||||
const databaseChanged = getDbVersion(decode(base.content)) !== getDbVersion(decode(head.content));
|
||||
|
||||
core.setOutput('databases', JSON.stringify(databaseChanged ? allDatabases : defaultDatabases));
|
||||
core.setOutput('modes', JSON.stringify(databaseChanged ? allModes : defaultModes));
|
||||
core.setOutput('databases', JSON.stringify(['MongoDB']));
|
||||
core.setOutput('modes', JSON.stringify(['dedicated']));
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+s3-cache+ecr-cache
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -283,13 +249,6 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
|
||||
@@ -298,9 +257,9 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
cache-from: type=s3,blobs_prefix=cache/${{ github.repository }}/,manifests_prefix=cache/${{ github.repository }}/,region=${{ env.RUNS_ON_AWS_REGION }},bucket=${{ env.RUNS_ON_S3_BUCKET_CACHE }}
|
||||
cache-to: type=s3,blobs_prefix=cache/${{ github.repository }}/,manifests_prefix=cache/${{ github.repository }}/,region=${{ env.RUNS_ON_AWS_REGION }},bucket=${{ env.RUNS_ON_S3_BUCKET_CACHE }},mode=max
|
||||
target: development
|
||||
build-args: |
|
||||
DEBUG=false
|
||||
@@ -309,7 +268,7 @@ jobs:
|
||||
|
||||
unit:
|
||||
name: Tests / Unit
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache
|
||||
needs: build
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -325,17 +284,10 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Docker Image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
|
||||
- name: Load and Start Appwrite
|
||||
timeout-minutes: 5
|
||||
@@ -347,9 +299,10 @@ jobs:
|
||||
run: docker compose exec -T appwrite vars
|
||||
|
||||
- name: Run Unit Tests
|
||||
uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3
|
||||
timeout-minutes: 15
|
||||
uses: itznotabug/php-retry@60547503cb2126eddaa082d0999e99cfca2b3856 # v4
|
||||
with:
|
||||
max_attempts: 2
|
||||
max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }}
|
||||
retry_wait_seconds: 60
|
||||
timeout_minutes: 15
|
||||
job_id: ${{ job.check_run_id }}
|
||||
@@ -362,7 +315,7 @@ jobs:
|
||||
|
||||
e2e_general:
|
||||
name: Tests / E2E / General
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache
|
||||
needs: build
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -378,17 +331,10 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Docker Image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
|
||||
- name: Load and Start Appwrite
|
||||
timeout-minutes: 5
|
||||
@@ -399,15 +345,16 @@ jobs:
|
||||
- name: Wait for Open Runtimes
|
||||
timeout-minutes: 3
|
||||
run: |
|
||||
while ! docker compose logs openruntimes-executor | grep -q "Executor is ready."; do
|
||||
while ! docker logs exc1 | grep -q "Executor is ready."; do
|
||||
echo "Waiting for Executor to come online"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Run General Tests
|
||||
uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3
|
||||
timeout-minutes: 15
|
||||
uses: itznotabug/php-retry@60547503cb2126eddaa082d0999e99cfca2b3856 # v4
|
||||
with:
|
||||
max_attempts: 2
|
||||
max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }}
|
||||
retry_wait_seconds: 60
|
||||
timeout_minutes: 15
|
||||
job_id: ${{ job.check_run_id }}
|
||||
@@ -425,8 +372,8 @@ jobs:
|
||||
docker compose logs
|
||||
|
||||
e2e_service:
|
||||
name: Tests / E2E / ${{ matrix.database }} (${{ matrix.mode }}) / ${{ matrix.service }}
|
||||
runs-on: ${{ matrix.runner || format('runs-on={0}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel', github.run_id) }}
|
||||
name: Tests / E2E / ${{ matrix.database }} (${{ matrix.mode }}) / ${{ matrix.service.name }}
|
||||
runs-on: ${{ matrix.service.runner }}
|
||||
needs: [build, matrix]
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -437,45 +384,7 @@ jobs:
|
||||
matrix:
|
||||
database: ${{ fromJSON(needs.matrix.outputs.databases) }}
|
||||
mode: ${{ fromJSON(needs.matrix.outputs.modes) }}
|
||||
service: [
|
||||
Account,
|
||||
Avatars,
|
||||
Console,
|
||||
Databases,
|
||||
TablesDB,
|
||||
Functions,
|
||||
FunctionsSchedule,
|
||||
GraphQL,
|
||||
Health,
|
||||
Advisor,
|
||||
Locale,
|
||||
Projects,
|
||||
Realtime,
|
||||
Sites,
|
||||
Proxy,
|
||||
Storage,
|
||||
Tokens,
|
||||
Teams,
|
||||
Users,
|
||||
ProjectWebhooks,
|
||||
Webhooks,
|
||||
VCS,
|
||||
Messaging,
|
||||
Migrations,
|
||||
Project,
|
||||
Presences
|
||||
]
|
||||
include:
|
||||
- service: Databases
|
||||
runner: runs-on=${{ github.run_id }}/runner=8cpu-linux-x64/volume=120g/spot=false/extras=otel
|
||||
paratest_processes: 3
|
||||
timeout_minutes: 30
|
||||
- service: TablesDB
|
||||
runner: runs-on=${{ github.run_id }}/runner=8cpu-linux-x64/volume=120g/spot=false/extras=otel
|
||||
paratest_processes: 3
|
||||
timeout_minutes: 30
|
||||
- service: Migrations
|
||||
paratest_processes: 1
|
||||
service: ${{ fromJSON(needs.matrix.outputs.services) }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -507,17 +416,10 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Docker Image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
|
||||
- name: Load and Start Appwrite
|
||||
timeout-minutes: 5
|
||||
@@ -533,30 +435,30 @@ jobs:
|
||||
- name: Wait for Open Runtimes
|
||||
timeout-minutes: 3
|
||||
run: |
|
||||
while ! docker compose logs openruntimes-executor | grep -q "Executor is ready."; do
|
||||
while ! docker logs exc1 | grep -q "Executor is ready."; do
|
||||
echo "Waiting for Executor to come online"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Run tests
|
||||
uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3
|
||||
timeout-minutes: 15
|
||||
uses: itznotabug/php-retry@60547503cb2126eddaa082d0999e99cfca2b3856 # v4
|
||||
with:
|
||||
max_attempts: 2
|
||||
max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }}
|
||||
retry_wait_seconds: 60
|
||||
timeout_minutes: ${{ matrix.timeout_minutes || 20 }}
|
||||
timeout_minutes: ${{ matrix.service.timeout }}
|
||||
job_id: ${{ job.check_run_id }}
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
test_dir: tests/e2e/Services/${{ matrix.service }}
|
||||
test_dir: tests/e2e/Services/${{ matrix.service.name }}
|
||||
command: |
|
||||
SERVICE_PATH="/usr/src/code/tests/e2e/Services/${{ matrix.service }}"
|
||||
SERVICE_PATH="/usr/src/code/tests/e2e/Services/${{ matrix.service.name }}"
|
||||
|
||||
# Services that rely on sequential test method execution (shared static state)
|
||||
FUNCTIONAL_FLAG="--functional"
|
||||
case "${{ matrix.service }}" in
|
||||
Databases|TablesDB|Functions|Realtime|GraphQL|ProjectWebhooks) FUNCTIONAL_FLAG="" ;;
|
||||
esac
|
||||
FUNCTIONAL_FLAG=""
|
||||
if [ "${{ matrix.service.functional }}" = "true" ]; then
|
||||
FUNCTIONAL_FLAG="--functional"
|
||||
fi
|
||||
|
||||
PARATEST_PROCESSES="${{ matrix.paratest_processes }}"
|
||||
PARATEST_PROCESSES="${{ matrix.service.processes }}"
|
||||
if [ -z "$PARATEST_PROCESSES" ]; then
|
||||
PARATEST_PROCESSES="$(nproc)"
|
||||
fi
|
||||
@@ -565,7 +467,7 @@ jobs:
|
||||
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
|
||||
-e _TESTS_OAUTH2_GITHUB_CLIENT_ID="${{ secrets.TESTS_OAUTH2_GITHUB_CLIENT_ID }}" \
|
||||
-e _TESTS_OAUTH2_GITHUB_CLIENT_SECRET="${{ secrets.TESTS_OAUTH2_GITHUB_CLIENT_SECRET }}" \
|
||||
appwrite vendor/bin/paratest --processes "$PARATEST_PROCESSES" $FUNCTIONAL_FLAG "$SERVICE_PATH" --exclude-group abuseEnabled --exclude-group screenshots --log-junit tests/e2e/Services/${{ matrix.service }}/junit.xml
|
||||
appwrite vendor/bin/paratest --processes "$PARATEST_PROCESSES" $FUNCTIONAL_FLAG "$SERVICE_PATH" --exclude-group abuseEnabled --exclude-group screenshots --log-junit tests/e2e/Services/${{ matrix.service.name }}/junit.xml
|
||||
|
||||
- name: Failure Logs
|
||||
if: failure()
|
||||
@@ -575,7 +477,7 @@ jobs:
|
||||
|
||||
e2e_abuse:
|
||||
name: Tests / E2E / Abuse (${{ matrix.mode }})
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache
|
||||
needs: [build, matrix]
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -597,17 +499,10 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Docker Image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
|
||||
- name: Load and Start Appwrite
|
||||
timeout-minutes: 5
|
||||
@@ -621,9 +516,10 @@ jobs:
|
||||
docker compose up -d --quiet-pull --wait
|
||||
|
||||
- name: Run tests
|
||||
uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3
|
||||
timeout-minutes: 15
|
||||
uses: itznotabug/php-retry@60547503cb2126eddaa082d0999e99cfca2b3856 # v4
|
||||
with:
|
||||
max_attempts: 2
|
||||
max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }}
|
||||
retry_wait_seconds: 60
|
||||
timeout_minutes: 15
|
||||
job_id: ${{ job.check_run_id }}
|
||||
@@ -642,7 +538,7 @@ jobs:
|
||||
|
||||
e2e_screenshots:
|
||||
name: Tests / E2E / Screenshots (${{ matrix.mode }})
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache
|
||||
needs: [build, matrix]
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -662,17 +558,10 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Docker Image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
|
||||
- name: Load and Start Appwrite
|
||||
timeout-minutes: 5
|
||||
@@ -687,15 +576,16 @@ jobs:
|
||||
- name: Wait for Open Runtimes
|
||||
timeout-minutes: 3
|
||||
run: |
|
||||
while ! docker compose logs openruntimes-executor | grep -q "Executor is ready."; do
|
||||
while ! docker logs exc1 | grep -q "Executor is ready."; do
|
||||
echo "Waiting for Executor to come online"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Run tests
|
||||
uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3
|
||||
timeout-minutes: 15
|
||||
uses: itznotabug/php-retry@60547503cb2126eddaa082d0999e99cfca2b3856 # v4
|
||||
with:
|
||||
max_attempts: 2
|
||||
max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }}
|
||||
retry_wait_seconds: 60
|
||||
timeout_minutes: 15
|
||||
job_id: ${{ job.check_run_id }}
|
||||
@@ -714,8 +604,8 @@ jobs:
|
||||
|
||||
benchmark:
|
||||
name: Benchmark
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request' || github.event_name == 'push'
|
||||
runs-on: runs-on=${{ github.run_id }}/runner=4cpu-linux-x64/volume=120g/spot=false/extras=otel+ecr-cache
|
||||
needs: build
|
||||
permissions:
|
||||
actions: read
|
||||
@@ -735,18 +625,11 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Pull Appwrite image
|
||||
run: |
|
||||
docker pull ${{ env.REGISTRY_IMAGE }}:${{ github.sha }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker tag ${{ env.REGISTRY_IMAGE }}:${{ github.sha }} ${{ env.IMAGE }}:after
|
||||
docker pull ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}
|
||||
docker tag ${{ env.RUNS_ON_ECR_CACHE }}:${{ env.IMAGE }}-${{ github.sha }} ${{ env.IMAGE }}:after
|
||||
|
||||
- name: Setup k6
|
||||
uses: grafana/setup-k6-action@db07bd9765aac508ef18982e52ab937fe633a065 # v1.2.1
|
||||
@@ -756,9 +639,11 @@ jobs:
|
||||
- name: Prepare benchmark before
|
||||
id: benchmark_before_prepare
|
||||
continue-on-error: true
|
||||
env:
|
||||
BENCHMARK_BEFORE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
|
||||
run: |
|
||||
git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
|
||||
git worktree add --detach /tmp/appwrite-benchmark-before ${{ github.event.pull_request.base.sha }}
|
||||
git fetch --depth=1 origin "${BENCHMARK_BEFORE_SHA}"
|
||||
git worktree add --detach /tmp/appwrite-benchmark-before "${BENCHMARK_BEFORE_SHA}"
|
||||
docker build \
|
||||
--cache-from ${{ env.IMAGE }}:after \
|
||||
--target development \
|
||||
@@ -880,8 +765,8 @@ jobs:
|
||||
if: always()
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
BENCHMARK_BASE_REF: ${{ github.event.pull_request.base.ref }}
|
||||
BENCHMARK_HEAD_REF: ${{ github.event.pull_request.head.ref }}
|
||||
BENCHMARK_BASE_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || github.event.before }}
|
||||
BENCHMARK_HEAD_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.ref || github.sha }}
|
||||
with:
|
||||
script: |
|
||||
const comment = require('./.github/workflows/benchmark-comment.js');
|
||||
|
||||
@@ -15,6 +15,8 @@ Self-hosted Backend-as-a-Service platform. Hybrid monolithic-microservice archit
|
||||
| `composer lint <file>` | Check formatting of a file |
|
||||
| `composer analyze` | Static analysis (PHPStan level 3) |
|
||||
| `composer check` | Same as `analyze` |
|
||||
| `composer refactor:check` | Rector dry-run over `tests/` (CI "Refactor" check) |
|
||||
| `composer refactor` | Apply Rector fixes |
|
||||
|
||||
## Stack
|
||||
|
||||
@@ -117,7 +119,7 @@ Common injections: `$response`, `$request`, `$dbForProject`, `$dbForPlatform`, `
|
||||
|
||||
## Tracing with Utopia Span
|
||||
|
||||
In handlers, only call `Span::add($key, $value)`. **Never** call `Span::init`, `Span::error`, or `Span::finish` -- lifecycle is owned by the entry-point harness (`app/http.php`, `app/worker.php`, `app/realtime.php`, `Bus::dispatch`). For selective export, filter in the sampler in `app/init/span.php`.
|
||||
In handlers, only call `Span::add($key, $value)`. **Never** call `Span::init`, `setError`, or `Span::finish` -- lifecycle is owned by the entry-point harness (`app/http.php`, `app/worker.php`, `app/realtime.php`, `Bus::dispatch`). For selective export, filter in the sampler in `app/init/span.php`.
|
||||
|
||||
Keys are `snake_case` with dots only for child relationships: `project.id` (id of project), `storage.bucket.id`. No dot otherwise: `inbound_bytes`, not `inbound.bytes`. No camelCase, no bare top-level keys (`function.id`, not `functionId`).
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ RUN composer install --ignore-platform-reqs --optimize-autoloader \
|
||||
--no-plugins --no-scripts --prefer-dist \
|
||||
`if [ "$TESTING" != "true" ]; then echo "--no-dev"; fi`
|
||||
|
||||
FROM appwrite/base:1.4.1 AS base
|
||||
FROM appwrite/base:1.4.3 AS base
|
||||
|
||||
LABEL maintainer="team@appwrite.io"
|
||||
|
||||
|
||||
@@ -603,6 +603,13 @@ return [
|
||||
'lengths' => [Database::LENGTH_KEY],
|
||||
'orders' => [Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_type_expire'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['type', 'expire'],
|
||||
'lengths' => [],
|
||||
'orders' => [Database::ORDER_ASC, Database::ORDER_ASC],
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ $console = [
|
||||
'disposableEmails' => false,
|
||||
'canonicalEmails' => false,
|
||||
'freeEmails' => false,
|
||||
'corporateEmails' => false,
|
||||
'invalidateSessions' => true
|
||||
],
|
||||
'authWhitelistEmails' => (!empty(System::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', System::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [],
|
||||
|
||||
@@ -241,6 +241,11 @@ return [
|
||||
'description' => 'This email address must already be in its canonical form. Please remove aliases, tags, or provider-specific variations and try again.',
|
||||
'code' => 400,
|
||||
],
|
||||
Exception::USER_EMAIL_NOT_CORPORATE => [
|
||||
'name' => Exception::USER_EMAIL_NOT_CORPORATE,
|
||||
'description' => 'Only corporate email addresses are allowed. Please use a work email address and try again.',
|
||||
'code' => 400,
|
||||
],
|
||||
Exception::USER_PASSWORD_MISMATCH => [
|
||||
'name' => Exception::USER_PASSWORD_MISMATCH,
|
||||
'description' => 'Passwords do not match. Please check the password and confirm password.',
|
||||
|
||||
@@ -281,6 +281,20 @@ return [
|
||||
'icon' => '',
|
||||
'platforms' => ['client', 'server', 'console'],
|
||||
],
|
||||
'organization' => [
|
||||
'key' => 'organization',
|
||||
'name' => 'Organization',
|
||||
'subtitle' => 'The Organization service allows you to manage organization-level projects.',
|
||||
'description' => '',
|
||||
'controller' => '', // Uses modules
|
||||
'sdk' => true,
|
||||
'docs' => true,
|
||||
'docsUrl' => '',
|
||||
'tests' => false,
|
||||
'optional' => false,
|
||||
'icon' => '',
|
||||
'platforms' => ['server', 'console'],
|
||||
],
|
||||
'migrations' => [
|
||||
'key' => 'migrations',
|
||||
'name' => 'Migrations',
|
||||
|
||||
@@ -29,6 +29,7 @@ use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\MethodType;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\SDK\Specification\Validator\PasswordFormat;
|
||||
use Appwrite\Template\Template;
|
||||
use Appwrite\URL\URL as URLParser;
|
||||
use Appwrite\Usage\Context;
|
||||
@@ -257,7 +258,7 @@ Http::post('/v1/account')
|
||||
->label('abuse-limit', 10)
|
||||
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForProject'])
|
||||
->param('email', '', new EmailValidator(), 'User email.')
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordFormat(new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING)), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
|
||||
->inject('request')
|
||||
->inject('response')
|
||||
@@ -350,6 +351,10 @@ Http::post('/v1/account')
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
try {
|
||||
$userId = $userId == 'unique()' ? ID::unique() : $userId;
|
||||
$user->setAttributes([
|
||||
@@ -1698,6 +1703,10 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
|
||||
$failureRedirect(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
$failureRedirect(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
try {
|
||||
$userId = ID::unique();
|
||||
$user->setAttributes([
|
||||
@@ -1839,6 +1848,10 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
|
||||
$failureRedirect(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
$failureRedirect(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$user->setAttribute('email', $email);
|
||||
$user->setAttribute('emailCanonical', $emailMetadata['emailCanonical']);
|
||||
$user->setAttribute('emailIsCanonical', $emailMetadata['emailIsCanonical']);
|
||||
@@ -2197,6 +2210,10 @@ Http::post('/v1/account/tokens/magic-url')
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$user->setAttributes([
|
||||
'$id' => $userId,
|
||||
'$permissions' => [
|
||||
@@ -2388,6 +2405,7 @@ Http::post('/v1/account/tokens/magic-url')
|
||||
project: $project,
|
||||
recipient: $email,
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_MAGIC_URL,
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
smtp: $smtpConfig,
|
||||
@@ -2517,6 +2535,10 @@ Http::post('/v1/account/tokens/email')
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$user->setAttributes([
|
||||
'$id' => $userId,
|
||||
'$permissions' => [
|
||||
@@ -2730,6 +2752,7 @@ Http::post('/v1/account/tokens/email')
|
||||
project: $project,
|
||||
recipient: $email,
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_OTP,
|
||||
bodyTemplate: $bodyTemplate,
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
@@ -3273,8 +3296,8 @@ Http::patch('/v1/account/password')
|
||||
contentType: ContentType::JSON
|
||||
))
|
||||
->label('abuse-limit', 10)
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('oldPassword', '', new Text(256, 0), 'Current user password. Max length: 256 chars.', true)
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordFormat(new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING)), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('oldPassword', '', new PasswordFormat(new Text(256, 0)), 'Current user password. Max length: 256 chars.', true)
|
||||
->inject('response')
|
||||
->inject('user')
|
||||
->inject('project')
|
||||
@@ -3438,6 +3461,10 @@ Http::patch('/v1/account/email')
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !$emailMetadata['emailIsCorporate']) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$user
|
||||
->setAttribute('email', $email)
|
||||
->setAttribute('emailVerification', false) // After this user needs to confirm mail again
|
||||
@@ -3843,6 +3870,7 @@ Http::post('/v1/account/recovery')
|
||||
recipient: $profile->getAttribute('email', ''),
|
||||
name: $profile->getAttribute('name', ''),
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_RECOVERY,
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
smtp: $smtpConfig,
|
||||
@@ -3890,7 +3918,7 @@ Http::put('/v1/account/recovery')
|
||||
->label('abuse-key', 'url:{url},userId:{param-userId}')
|
||||
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
|
||||
->param('secret', '', new Text(256), 'Valid reset token.')
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordFormat(new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING)), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->inject('response')
|
||||
->inject('user')
|
||||
->inject('dbForProject')
|
||||
@@ -4197,6 +4225,7 @@ Http::post('/v1/account/verifications/email')
|
||||
recipient: $user->getAttribute('email'),
|
||||
name: $user->getAttribute('name') ?? '',
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_VERIFICATION,
|
||||
bodyTemplate: $bodyTemplate,
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
|
||||
@@ -122,11 +122,11 @@ Http::post('/v1/graphql/mutation')
|
||||
->action(function (Request $request, Response $response, GQLSchema $schema, Adapter $promiseAdapter) {
|
||||
$query = $request->getParams();
|
||||
|
||||
if ($request->getHeader('x-sdk-graphql') == 'true') {
|
||||
if ($request->getHeaderLine('x-sdk-graphql') == 'true') {
|
||||
$query = $query['query'];
|
||||
}
|
||||
|
||||
$type = $request->getHeader('content-type');
|
||||
$type = $request->getHeaderLine('content-type');
|
||||
|
||||
if (\str_starts_with($type, 'application/graphql')) {
|
||||
$query = parseGraphql($request);
|
||||
@@ -173,11 +173,11 @@ Http::post('/v1/graphql')
|
||||
->action(function (Request $request, Response $response, GQLSchema $schema, Adapter $promiseAdapter) {
|
||||
$query = $request->getParams();
|
||||
|
||||
if ($request->getHeader('x-sdk-graphql') == 'true') {
|
||||
if ($request->getHeaderLine('x-sdk-graphql') == 'true') {
|
||||
$query = $query['query'];
|
||||
}
|
||||
|
||||
$type = $request->getHeader('content-type');
|
||||
$type = $request->getHeaderLine('content-type');
|
||||
|
||||
if (\str_starts_with($type, 'application/graphql')) {
|
||||
$query = parseGraphql($request);
|
||||
|
||||
@@ -17,6 +17,7 @@ use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\SDK\Specification\Validator\PasswordFormat;
|
||||
use Appwrite\Utopia\Database\Validator\CompoundUID;
|
||||
use Appwrite\Utopia\Database\Validator\CustomId;
|
||||
use Appwrite\Utopia\Database\Validator\Queries\Messages;
|
||||
@@ -458,7 +459,7 @@ Http::post('/v1/messaging/providers/smtp')
|
||||
->param('host', '', new Text(0), 'SMTP hosts. Either a single hostname or multiple semicolon-delimited hostnames. You can also specify a different port for each host such as `smtp1.example.com:25;smtp2.example.com`. You can also specify encryption type, for example: `tls://smtp1.example.com:587;ssl://smtp2.example.com:465"`. Hosts will be tried in order.')
|
||||
->param('port', 587, new Range(1, 65535), 'The default SMTP server port.', true)
|
||||
->param('username', '', new Text(0), 'Authentication username.', true)
|
||||
->param('password', '', new Text(0), 'Authentication password.', true)
|
||||
->param('password', '', new PasswordFormat(new Text(0)), 'Authentication password.', true)
|
||||
->param('encryption', '', new WhiteList(['none', 'ssl', 'tls']), 'Encryption type. Can be omitted, \'ssl\', or \'tls\'', true, enum: new Enum(name: 'SmtpEncryption'))
|
||||
->param('autoTLS', true, new Boolean(), 'Enable SMTP AutoTLS feature.', true)
|
||||
->param('mailer', '', new Text(0), 'The value to use for the X-Mailer header.', true)
|
||||
@@ -1809,7 +1810,7 @@ Http::patch('/v1/messaging/providers/smtp/:providerId')
|
||||
->param('host', '', new Text(0), 'SMTP hosts. Either a single hostname or multiple semicolon-delimited hostnames. You can also specify a different port for each host such as `smtp1.example.com:25;smtp2.example.com`. You can also specify encryption type, for example: `tls://smtp1.example.com:587;ssl://smtp2.example.com:465"`. Hosts will be tried in order.', true)
|
||||
->param('port', null, new Nullable(new Range(1, 65535)), 'SMTP port.', true)
|
||||
->param('username', '', new Text(0), 'Authentication username.', true)
|
||||
->param('password', '', new Text(0), 'Authentication password.', true)
|
||||
->param('password', '', new PasswordFormat(new Text(0)), 'Authentication password.', true)
|
||||
->param('encryption', '', new WhiteList(['none', 'ssl', 'tls']), 'Encryption type. Can be \'ssl\' or \'tls\'', true, enum: new Enum(name: 'SmtpEncryption'))
|
||||
->param('autoTLS', null, new Nullable(new Boolean()), 'Enable SMTP AutoTLS feature.', true)
|
||||
->param('mailer', '', new Text(0), 'The value to use for the X-Mailer header.', true)
|
||||
|
||||
@@ -38,27 +38,31 @@ Http::patch('/v1/projects/:projectId/oauth2')
|
||||
->inject('dbForPlatform')
|
||||
->action(function (string $projectId, string $provider, ?string $appId, ?string $secret, ?bool $enabled, Response $response, Database $dbForPlatform) {
|
||||
|
||||
$project = $dbForPlatform->getDocument('projects', $projectId);
|
||||
$project = $dbForPlatform->withTransaction(function () use ($dbForPlatform, $projectId, $provider, $appId, $secret, $enabled) {
|
||||
$project = $dbForPlatform->getDocument('projects', $projectId, forUpdate: true);
|
||||
|
||||
if ($project->isEmpty()) {
|
||||
throw new Exception(Exception::PROJECT_NOT_FOUND);
|
||||
}
|
||||
if ($project->isEmpty()) {
|
||||
throw new Exception(Exception::PROJECT_NOT_FOUND);
|
||||
}
|
||||
|
||||
$providers = $project->getAttribute('oAuthProviders', []);
|
||||
$providers = $project->getAttribute('oAuthProviders', []);
|
||||
|
||||
if ($appId !== null) {
|
||||
$providers[$provider . 'Appid'] = $appId;
|
||||
}
|
||||
if ($appId !== null) {
|
||||
$providers[$provider . 'Appid'] = $appId;
|
||||
}
|
||||
|
||||
if ($secret !== null) {
|
||||
$providers[$provider . 'Secret'] = $secret;
|
||||
}
|
||||
if ($secret !== null) {
|
||||
$providers[$provider . 'Secret'] = $secret;
|
||||
}
|
||||
|
||||
if ($enabled !== null) {
|
||||
$providers[$provider . 'Enabled'] = $enabled;
|
||||
}
|
||||
if ($enabled !== null) {
|
||||
$providers[$provider . 'Enabled'] = $enabled;
|
||||
}
|
||||
|
||||
$project = $dbForPlatform->updateDocument('projects', $project->getId(), $project->setAttribute('oAuthProviders', $providers));
|
||||
return $dbForPlatform->updateDocument('projects', $project->getId(), new Document([
|
||||
'oAuthProviders' => $providers,
|
||||
]));
|
||||
});
|
||||
|
||||
$response->dynamic($project, Response::MODEL_PROJECT);
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\SDK\Specification\Validator\PasswordFormat;
|
||||
use Appwrite\Utopia\Database\Validator\CustomId;
|
||||
use Appwrite\Utopia\Database\Validator\Queries\Identities;
|
||||
use Appwrite\Utopia\Database\Validator\Queries\Memberships;
|
||||
@@ -148,6 +149,10 @@ function createUser(Hash $hash, string $userId, ?string $email, ?string $passwor
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !($emailMetadata['emailIsCorporate'] ?? true)) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$hashedPassword = null;
|
||||
|
||||
$isHashed = !$hash instanceof Plaintext;
|
||||
@@ -283,7 +288,7 @@ Http::post('/v1/users')
|
||||
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForProject'])
|
||||
->param('email', null, new Nullable(new EmailValidator()), 'User email.', true)
|
||||
->param('phone', null, new Nullable(new Phone()), 'Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'Plain text user password. Must be at least 8 chars.', true, ['project', 'passwordsDictionary'])
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordFormat(new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING)), 'Plain text user password. Must be at least 8 chars.', true, ['project', 'passwordsDictionary'])
|
||||
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
|
||||
->inject('response')
|
||||
->inject('project')
|
||||
@@ -1434,7 +1439,7 @@ Http::patch('/v1/users/:userId/password')
|
||||
]
|
||||
))
|
||||
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? [], allowEmpty: true), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false, allowEmpty: true)], Validator::TYPE_STRING), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordFormat(new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? [], allowEmpty: true), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false, allowEmpty: true)], Validator::TYPE_STRING)), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
|
||||
->inject('response')
|
||||
->inject('project')
|
||||
->inject('dbForProject')
|
||||
@@ -1612,6 +1617,10 @@ Http::patch('/v1/users/:userId/email')
|
||||
throw new Exception(Exception::USER_EMAIL_FREE);
|
||||
}
|
||||
|
||||
if ((($project->getId() === 'console') || ($plan['supportsCorporateEmailValidation'] ?? false)) && ($project->getAttribute('auths', [])['corporateEmails'] ?? false) && !($emailMetadata['emailIsCorporate'] ?? true)) {
|
||||
throw new Exception(Exception::USER_EMAIL_NOT_CORPORATE);
|
||||
}
|
||||
|
||||
$user
|
||||
->setAttribute('email', $email)
|
||||
->setAttribute('emailVerification', false)
|
||||
|
||||
+15
-10
@@ -14,6 +14,7 @@ use Appwrite\Event\Publisher\Delete as DeletePublisher;
|
||||
use Appwrite\Extend\Exception as AppwriteException;
|
||||
use Appwrite\Network\Cors;
|
||||
use Appwrite\Platform\Appwrite;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Transformation\Adapter\Preview;
|
||||
@@ -293,7 +294,12 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S
|
||||
$body = $swooleRequest->getContent() ?: '';
|
||||
$method = $swooleRequest->server['request_method'];
|
||||
|
||||
$requestHeaders = $request->getHeaders();
|
||||
// getHeaders() follows PSR-7 and returns each header as a list of values;
|
||||
// collapse to single-line strings for the function/site header map below.
|
||||
$requestHeaders = \array_map(
|
||||
static fn (array $values) => \implode(', ', $values),
|
||||
$request->getHeaders()
|
||||
);
|
||||
|
||||
if ($resource->isEmpty() || !$resource->getAttribute('enabled')) {
|
||||
if ($type === 'function') {
|
||||
@@ -803,7 +809,7 @@ Http::init()
|
||||
->inject('request')
|
||||
->action(function (Document $project, Request $request) {
|
||||
if ($project->getId() === 'console') {
|
||||
$message = empty($request->getHeader('x-appwrite-project')) ?
|
||||
$message = empty($request->getHeaderLine('x-appwrite-project')) ?
|
||||
'No Appwrite project was specified. Please specify your project ID when initializing your Appwrite SDK.' :
|
||||
'This endpoint is not available for the console project. The Appwrite Console is a reserved project ID and cannot be used with the Appwrite SDKs and APIs. Please check if your project ID is correct.';
|
||||
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, $message);
|
||||
@@ -861,7 +867,7 @@ Http::init()
|
||||
return;
|
||||
}
|
||||
|
||||
$requestFormat = $request->getHeader('x-appwrite-response-format', System::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
|
||||
$requestFormat = $request->getHeaderLine('x-appwrite-response-format', System::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
|
||||
if ($requestFormat) {
|
||||
if (version_compare($requestFormat, '1.4.0', '<')) {
|
||||
$request->addFilter(new RequestV16());
|
||||
@@ -899,7 +905,7 @@ Http::init()
|
||||
}
|
||||
}
|
||||
|
||||
$localeParam = (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''));
|
||||
$localeParam = (string) $request->getParam('locale', $request->getHeaderLine('x-appwrite-locale', ''));
|
||||
if (\in_array($localeParam, $localeCodes)) {
|
||||
$locale->setDefault($localeParam);
|
||||
}
|
||||
@@ -919,7 +925,7 @@ Http::init()
|
||||
/*
|
||||
* Response format
|
||||
*/
|
||||
$responseFormat = $request->getHeader('x-appwrite-response-format', System::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
|
||||
$responseFormat = $request->getHeaderLine('x-appwrite-response-format', System::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
|
||||
if ($responseFormat) {
|
||||
if (version_compare($responseFormat, '1.9.5', '<')) {
|
||||
$response->addFilter(new ResponseV26());
|
||||
@@ -1006,7 +1012,7 @@ Http::init()
|
||||
|
||||
// Application level CSRF protection
|
||||
$origin = $request->getOrigin();
|
||||
if (empty($origin) || !$devKey->isEmpty() || !empty($request->getHeader('x-appwrite-key'))) {
|
||||
if (empty($origin) || !$devKey->isEmpty() || !empty($request->getHeaderLine('x-appwrite-key'))) {
|
||||
return;
|
||||
}
|
||||
$route = $request->getRoute();
|
||||
@@ -1198,7 +1204,7 @@ Http::error()
|
||||
$line = $error->getLine();
|
||||
$trace = $error->getTrace();
|
||||
|
||||
Span::error($error);
|
||||
Span::current()?->setError($error);
|
||||
|
||||
switch ($class) {
|
||||
case Utopia\Http\Exception::class:
|
||||
@@ -1315,7 +1321,7 @@ Http::error()
|
||||
}
|
||||
|
||||
$log->addTag('hostname', $request->getHostname());
|
||||
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')));
|
||||
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeaderLine('x-appwrite-locale', '')));
|
||||
|
||||
$log->addExtra('file', $error->getFile());
|
||||
$log->addExtra('line', $error->getLine());
|
||||
@@ -1657,11 +1663,10 @@ Http::get('/v1/ping')
|
||||
namespace: 'ping',
|
||||
group: null,
|
||||
name: 'get',
|
||||
hide: true,
|
||||
description: <<<EOT
|
||||
Send a ping to project as part of onboarding.
|
||||
EOT,
|
||||
auth: [],
|
||||
auth: [AuthType::ADMIN, AuthType::KEY, AuthType::JWT, AuthType::SESSION],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -46,7 +46,7 @@ Http::get('/v1/mock/tests/locale')
|
||||
->inject('request')
|
||||
->inject('response')
|
||||
->action(function (Locale $locale, array $localeCodes, Request $request, Response $response) {
|
||||
$localeParam = (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''));
|
||||
$localeParam = (string) $request->getParam('locale', $request->getHeaderLine('x-appwrite-locale', ''));
|
||||
if (\in_array($localeParam, $localeCodes)) {
|
||||
$locale->setDefault($localeParam);
|
||||
}
|
||||
|
||||
@@ -201,19 +201,19 @@ Http::init()
|
||||
if (! empty($apiKey->getProjectId())) {
|
||||
$dbKey = $project->find(
|
||||
key: 'secret',
|
||||
find: $request->getHeader('x-appwrite-key', ''),
|
||||
find: $request->getHeaderLine('x-appwrite-key', ''),
|
||||
subject: 'keys'
|
||||
);
|
||||
} elseif (! empty($apiKey->getUserId())) {
|
||||
$dbKey = $user->find(
|
||||
key: 'secret',
|
||||
find: $request->getHeader('x-appwrite-key', ''),
|
||||
find: $request->getHeaderLine('x-appwrite-key', ''),
|
||||
subject: 'keys'
|
||||
);
|
||||
} elseif (! empty($apiKey->getTeamId())) {
|
||||
$dbKey = $team->find(
|
||||
key: 'secret',
|
||||
find: $request->getHeader('x-appwrite-key', ''),
|
||||
find: $request->getHeaderLine('x-appwrite-key', ''),
|
||||
subject: 'keys'
|
||||
);
|
||||
}
|
||||
@@ -231,7 +231,7 @@ Http::init()
|
||||
}
|
||||
|
||||
$sdkValidator = new WhiteList($servers, true);
|
||||
$sdk = $request->getHeader('x-sdk-name', 'UNKNOWN');
|
||||
$sdk = $request->getHeaderLine('x-sdk-name', 'UNKNOWN');
|
||||
|
||||
if ($sdk !== 'UNKNOWN' && $sdkValidator->isValid($sdk)) {
|
||||
$sdks = $dbKey->getAttribute('sdks', []);
|
||||
|
||||
+10
-9
@@ -270,8 +270,8 @@ function createDatabase(Container $resources, string $resourceKey, string $dbNam
|
||||
'$id' => ID::custom($index['$id']),
|
||||
'type' => $index['type'],
|
||||
'attributes' => $index['attributes'],
|
||||
'lengths' => $index['lengths'],
|
||||
'orders' => $index['orders'],
|
||||
'lengths' => $index['lengths'] ?? [],
|
||||
'orders' => $index['orders'] ?? [],
|
||||
]), $collection['indexes']);
|
||||
|
||||
$database->createCollection($key, $attributes, $indexes);
|
||||
@@ -353,8 +353,8 @@ $http->on(Constant::EVENT_START, function ($http) use ($payloadSize, $totalWorke
|
||||
'$id' => ID::custom($index['$id']),
|
||||
'type' => $index['type'],
|
||||
'attributes' => $index['attributes'],
|
||||
'lengths' => $index['lengths'],
|
||||
'orders' => $index['orders'],
|
||||
'lengths' => $index['lengths'] ?? [],
|
||||
'orders' => $index['orders'] ?? [],
|
||||
]), $files['indexes']);
|
||||
|
||||
$dbForPlatform->createCollection('bucket_' . $bucket->getSequence(), $attributes, $indexes);
|
||||
@@ -399,8 +399,8 @@ $http->on(Constant::EVENT_START, function ($http) use ($payloadSize, $totalWorke
|
||||
'$id' => ID::custom($index['$id']),
|
||||
'type' => $index['type'],
|
||||
'attributes' => $index['attributes'],
|
||||
'lengths' => $index['lengths'],
|
||||
'orders' => $index['orders'],
|
||||
'lengths' => $index['lengths'] ?? [],
|
||||
'orders' => $index['orders'] ?? [],
|
||||
]), $files['indexes']);
|
||||
|
||||
$authorization->skip(fn () => $dbForPlatform->createCollection('bucket_' . $bucket->getSequence(), $attributes, $indexes));
|
||||
@@ -529,6 +529,7 @@ $swoole->onRequest(function ($utopiaRequest, $utopiaResponse) use ($files, $swoo
|
||||
$app->setCompression(System::getEnv('_APP_COMPRESSION_ENABLED', 'enabled') === 'enabled');
|
||||
$app->setCompressionMinSize(intval(System::getEnv('_APP_COMPRESSION_MIN_SIZE_BYTES', '1024'))); // 1KB
|
||||
|
||||
$error = null;
|
||||
try {
|
||||
$authorization = $app->context()->get('authorization');
|
||||
|
||||
@@ -542,7 +543,7 @@ $swoole->onRequest(function ($utopiaRequest, $utopiaResponse) use ($files, $swoo
|
||||
$route = $app->match($request)?->route;
|
||||
Span::add('http.path', $route?->getPath() ?? 'unknown');
|
||||
} catch (\Throwable $th) {
|
||||
Span::error($th);
|
||||
$error = $th;
|
||||
|
||||
$version = System::getEnv('_APP_VERSION', 'UNKNOWN');
|
||||
|
||||
@@ -577,7 +578,7 @@ $swoole->onRequest(function ($utopiaRequest, $utopiaResponse) use ($files, $swoo
|
||||
$log->addTag('code', $th->getCode());
|
||||
// $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant
|
||||
$log->addTag('hostname', $request->getHostname());
|
||||
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')));
|
||||
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeaderLine('x-appwrite-locale', '')));
|
||||
|
||||
$log->addExtra('file', $th->getFile());
|
||||
$log->addExtra('line', $th->getLine());
|
||||
@@ -631,7 +632,7 @@ $swoole->onRequest(function ($utopiaRequest, $utopiaResponse) use ($files, $swoo
|
||||
$swooleResponse->end(\json_encode($output));
|
||||
} finally {
|
||||
Span::add('http.response.code', $response->getStatusCode());
|
||||
Span::current()?->finish();
|
||||
Span::current()?->finish(error: $error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -271,6 +271,17 @@ const FUNCTION_ALLOWLIST_HEADERS_RESPONSE = ['content-type', 'content-length'];
|
||||
const MESSAGE_TYPE_EMAIL = 'email';
|
||||
const MESSAGE_TYPE_SMS = 'sms';
|
||||
const MESSAGE_TYPE_PUSH = 'push';
|
||||
const MAIL_TEMPLATE_CERTIFICATE_FAILED = 'certificate-failed';
|
||||
const MAIL_TEMPLATE_DATA_EXPORT = 'data-export';
|
||||
const MAIL_TEMPLATE_INVITATION = 'invitation';
|
||||
const MAIL_TEMPLATE_MAGIC_URL = 'magic-url';
|
||||
const MAIL_TEMPLATE_MFA_CHALLENGE = 'mfa-challenge';
|
||||
const MAIL_TEMPLATE_OTP = 'otp';
|
||||
const MAIL_TEMPLATE_RECOVERY = 'recovery';
|
||||
const MAIL_TEMPLATE_SESSION_ALERT = 'session-alert';
|
||||
const MAIL_TEMPLATE_SMTP_TEST = 'smtp-test';
|
||||
const MAIL_TEMPLATE_VERIFICATION = 'verification';
|
||||
const MAIL_TEMPLATE_WEBHOOK_FAILED = 'webhook-failed';
|
||||
// API key types
|
||||
const API_KEY_STANDARD = 'standard';
|
||||
const API_KEY_EPHEMERAL = 'ephemeral';
|
||||
|
||||
@@ -231,6 +231,7 @@ Database::addFilter(
|
||||
return $database->getAuthorization()->skip(fn () => $database
|
||||
->find('authenticators', [
|
||||
Query::equal('userInternalId', [$document->getSequence()]),
|
||||
Query::orderDesc('$createdAt'),
|
||||
Query::limit(APP_LIMIT_SUBQUERY),
|
||||
]));
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ use Utopia\Validator\WhiteList;
|
||||
*/
|
||||
return function (Container $container): void {
|
||||
$getProjectId = static function (Request $request): string {
|
||||
$projectId = $request->getHeader('x-appwrite-project', '');
|
||||
$projectId = $request->getHeaderLine('x-appwrite-project', '');
|
||||
|
||||
if (!empty($projectId)) {
|
||||
return $projectId;
|
||||
@@ -36,7 +36,7 @@ return function (Container $container): void {
|
||||
};
|
||||
|
||||
$getMode = static function (Request $request, Document $project) use ($getProjectId): string {
|
||||
$mode = $request->getParam('mode', $request->getHeader('x-appwrite-mode', APP_MODE_DEFAULT));
|
||||
$mode = $request->getParam('mode', $request->getHeaderLine('x-appwrite-mode', APP_MODE_DEFAULT));
|
||||
$projectId = $getProjectId($request);
|
||||
|
||||
if (!empty($projectId) && $project->getId() !== $projectId) {
|
||||
@@ -113,7 +113,7 @@ return function (Container $container): void {
|
||||
};
|
||||
|
||||
$findDevKey = static function (Request $request, Document $project, array $servers, Authorization $authorization) use ($getDbForPlatform): Document {
|
||||
$devKey = $request->getHeader('x-appwrite-dev-key', $request->getParam('devKey', ''));
|
||||
$devKey = $request->getHeaderLine('x-appwrite-dev-key', $request->getParam('devKey', ''));
|
||||
$key = $project->find('secret', $devKey, 'devKeys');
|
||||
|
||||
if (!$key) {
|
||||
@@ -137,7 +137,7 @@ return function (Container $container): void {
|
||||
}
|
||||
|
||||
$sdkValidator = new WhiteList($servers, true);
|
||||
$sdk = \strtolower($request->getHeader('x-sdk-name', 'UNKNOWN'));
|
||||
$sdk = \strtolower($request->getHeaderLine('x-sdk-name', 'UNKNOWN'));
|
||||
|
||||
if ($sdk !== 'unknown' && $sdkValidator->isValid($sdk)) {
|
||||
$sdks = $key->getAttribute('sdks', []);
|
||||
@@ -233,7 +233,7 @@ return function (Container $container): void {
|
||||
);
|
||||
|
||||
if (empty($store->getProperty('id', '')) && empty($store->getProperty('secret', ''))) {
|
||||
$sessionHeader = $request->getHeader('x-appwrite-session', '');
|
||||
$sessionHeader = $request->getHeaderLine('x-appwrite-session', '');
|
||||
|
||||
if (!empty($sessionHeader)) {
|
||||
$store->decode($sessionHeader);
|
||||
@@ -241,7 +241,7 @@ return function (Container $container): void {
|
||||
}
|
||||
|
||||
if (empty($store->getProperty('id', '')) && empty($store->getProperty('secret', ''))) {
|
||||
$fallback = \json_decode($request->getHeader('x-fallback-cookies', ''), true);
|
||||
$fallback = \json_decode($request->getHeaderLine('x-fallback-cookies', ''), true);
|
||||
$store->decode((\is_array($fallback) && isset($fallback[$store->getKey()])) ? $fallback[$store->getKey()] : '');
|
||||
}
|
||||
|
||||
@@ -271,7 +271,7 @@ return function (Container $container): void {
|
||||
$user = new User([]);
|
||||
}
|
||||
|
||||
$authJWT = $request->getHeader('x-appwrite-jwt', '');
|
||||
$authJWT = $request->getHeaderLine('x-appwrite-jwt', '');
|
||||
if (!empty($authJWT) && !$project->isEmpty()) {
|
||||
if (!$user->isEmpty()) {
|
||||
throw new Exception(Exception::USER_JWT_AND_COOKIE_SET);
|
||||
@@ -300,8 +300,8 @@ return function (Container $container): void {
|
||||
}
|
||||
}
|
||||
|
||||
$accountKey = $request->getHeader('x-appwrite-key', '');
|
||||
$accountKeyUserId = $request->getHeader('x-appwrite-user', '');
|
||||
$accountKey = $request->getHeaderLine('x-appwrite-key', '');
|
||||
$accountKeyUserId = $request->getHeaderLine('x-appwrite-user', '');
|
||||
|
||||
if (!empty($accountKeyUserId) && !empty($accountKey)) {
|
||||
if (!$user->isEmpty()) {
|
||||
@@ -329,9 +329,9 @@ return function (Container $container): void {
|
||||
|
||||
// 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->getHeader('x-appwrite-impersonate-user-id', (string)$request->getParam('impersonateUserId', ''));
|
||||
$impersonateEmail = $request->getHeader('x-appwrite-impersonate-user-email', (string)$request->getParam('impersonateEmail', ''));
|
||||
$impersonatePhone = $request->getHeader('x-appwrite-impersonate-user-phone', (string)$request->getParam('impersonatePhone', ''));
|
||||
$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;
|
||||
|
||||
+16
-19
@@ -6,7 +6,6 @@ use Appwrite\Hooks\Hooks;
|
||||
use Appwrite\PubSub\Adapter\Redis as PubSub;
|
||||
use Appwrite\URL\URL as AppwriteURL;
|
||||
use MaxMind\Db\Reader;
|
||||
use Swoole\Database\PDOProxy;
|
||||
use Utopia\Cache\Adapter\Redis as RedisCache;
|
||||
use Utopia\Config\Config;
|
||||
use Utopia\Console;
|
||||
@@ -291,15 +290,14 @@ $register->set('pools', function () {
|
||||
$resource = match ($dsnScheme) {
|
||||
'mysql',
|
||||
'mariadb' => function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
|
||||
return new PDOProxy(function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
|
||||
return new PDO("mysql:host={$dsnHost};port={$dsnPort};dbname={$dsnDatabase};charset=utf8mb4", $dsnUser, $dsnPass, [
|
||||
\PDO::ATTR_TIMEOUT => 3, // Seconds
|
||||
\PDO::ATTR_PERSISTENT => false,
|
||||
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
|
||||
\PDO::ATTR_EMULATE_PREPARES => true,
|
||||
\PDO::ATTR_STRINGIFY_FETCHES => true
|
||||
]);
|
||||
});
|
||||
return new PDO("mysql:host={$dsnHost};port={$dsnPort};dbname={$dsnDatabase};charset=utf8mb4", $dsnUser, $dsnPass, [
|
||||
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
||||
\PDO::ATTR_TIMEOUT => 3, // Seconds
|
||||
\PDO::ATTR_PERSISTENT => false,
|
||||
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
|
||||
\PDO::ATTR_EMULATE_PREPARES => true,
|
||||
\PDO::ATTR_STRINGIFY_FETCHES => true
|
||||
]);
|
||||
},
|
||||
'mongodb' => function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
|
||||
try {
|
||||
@@ -312,15 +310,14 @@ $register->set('pools', function () {
|
||||
}
|
||||
},
|
||||
'postgresql' => function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
|
||||
return new PDOProxy(function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
|
||||
return new PDO("pgsql:host={$dsnHost};port={$dsnPort};dbname={$dsnDatabase};connect_timeout=3", $dsnUser, $dsnPass, array(
|
||||
\PDO::ATTR_TIMEOUT => 3, // Seconds
|
||||
\PDO::ATTR_PERSISTENT => false,
|
||||
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
|
||||
\PDO::ATTR_EMULATE_PREPARES => true,
|
||||
\PDO::ATTR_STRINGIFY_FETCHES => true
|
||||
));
|
||||
});
|
||||
return new PDO("pgsql:host={$dsnHost};port={$dsnPort};dbname={$dsnDatabase};connect_timeout=3", $dsnUser, $dsnPass, array(
|
||||
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
||||
\PDO::ATTR_TIMEOUT => 3, // Seconds
|
||||
\PDO::ATTR_PERSISTENT => false,
|
||||
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
|
||||
\PDO::ATTR_EMULATE_PREPARES => true,
|
||||
\PDO::ATTR_STRINGIFY_FETCHES => true
|
||||
));
|
||||
},
|
||||
default => function () use ($dsnHost, $dsnPort, $dsnPass) {
|
||||
$redis = new \Redis();
|
||||
|
||||
@@ -387,7 +387,7 @@ return function (Container $context): void {
|
||||
|
||||
// Get session from header for SSR clients
|
||||
if (empty($store->getProperty('id', '')) && empty($store->getProperty('secret', ''))) {
|
||||
$sessionHeader = $request->getHeader('x-appwrite-session', '');
|
||||
$sessionHeader = $request->getHeaderLine('x-appwrite-session', '');
|
||||
|
||||
if (! empty($sessionHeader)) {
|
||||
$store->decode($sessionHeader);
|
||||
@@ -399,7 +399,7 @@ return function (Container $context): void {
|
||||
|
||||
if (empty($store->getProperty('id', '')) && empty($store->getProperty('secret', ''))) {
|
||||
$response->addHeader('X-Debug-Fallback', 'true');
|
||||
$fallback = $request->getHeader('x-fallback-cookies', '');
|
||||
$fallback = $request->getHeaderLine('x-fallback-cookies', '');
|
||||
$fallback = \json_decode($fallback, true);
|
||||
$store->decode(((is_array($fallback) && isset($fallback[$store->getKey()])) ? $fallback[$store->getKey()] : ''));
|
||||
}
|
||||
@@ -432,7 +432,7 @@ return function (Container $context): void {
|
||||
$user = new User([]);
|
||||
}
|
||||
|
||||
$authJWT = $request->getHeader('x-appwrite-jwt', '');
|
||||
$authJWT = $request->getHeaderLine('x-appwrite-jwt', '');
|
||||
if (! empty($authJWT) && ! $project->isEmpty()) { // JWT authentication
|
||||
if (! $user->isEmpty()) {
|
||||
throw new Exception(Exception::USER_JWT_AND_COOKIE_SET);
|
||||
@@ -462,8 +462,8 @@ return function (Container $context): void {
|
||||
}
|
||||
|
||||
// Account based on account API key
|
||||
$accountKey = $request->getHeader('x-appwrite-key', '');
|
||||
$accountKeyUserId = $request->getHeader('x-appwrite-user', '');
|
||||
$accountKey = $request->getHeaderLine('x-appwrite-key', '');
|
||||
$accountKeyUserId = $request->getHeaderLine('x-appwrite-user', '');
|
||||
if (! empty($accountKeyUserId) && ! empty($accountKey)) {
|
||||
if (! $user->isEmpty()) {
|
||||
throw new Exception(Exception::USER_API_KEY_AND_SESSION_SET);
|
||||
@@ -491,9 +491,9 @@ 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->getHeader('x-appwrite-impersonate-user-id', (string)$request->getParam('impersonateUserId', ''));
|
||||
$impersonateEmail = $request->getHeader('x-appwrite-impersonate-user-email', (string)$request->getParam('impersonateEmail', ''));
|
||||
$impersonatePhone = $request->getHeader('x-appwrite-impersonate-user-phone', (string)$request->getParam('impersonatePhone', ''));
|
||||
$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;
|
||||
@@ -525,10 +525,10 @@ return function (Container $context): void {
|
||||
/** @var Appwrite\Utopia\Request $request */
|
||||
/** @var Utopia\Database\Database $dbForPlatform */
|
||||
/** @var Utopia\Database\Document $console */
|
||||
$projectId = $request->getParam('project', $request->getHeader('x-appwrite-project', ''));
|
||||
$projectId = $request->getParam('project', $request->getHeaderLine('x-appwrite-project', ''));
|
||||
// Realtime channel "project" can send project=Query array
|
||||
if (! \is_string($projectId)) {
|
||||
$projectId = $request->getHeader('x-appwrite-project', '');
|
||||
$projectId = $request->getHeaderLine('x-appwrite-project', '');
|
||||
}
|
||||
|
||||
// Backwards compatibility for new services, originally project resources
|
||||
@@ -920,9 +920,9 @@ return function (Container $context): void {
|
||||
* - 'default' => Requests for Client and Server Side
|
||||
* - 'admin' => Request from the Console on non-console projects
|
||||
*/
|
||||
$mode = $request->getParam('mode', $request->getHeader('x-appwrite-mode', APP_MODE_DEFAULT));
|
||||
$mode = $request->getParam('mode', $request->getHeaderLine('x-appwrite-mode', APP_MODE_DEFAULT));
|
||||
|
||||
$projectId = $request->getParam('project', $request->getHeader('x-appwrite-project', ''));
|
||||
$projectId = $request->getParam('project', $request->getHeaderLine('x-appwrite-project', ''));
|
||||
if (!empty($projectId) && $project->getId() !== $projectId) {
|
||||
$mode = APP_MODE_ADMIN;
|
||||
}
|
||||
@@ -932,7 +932,7 @@ return function (Container $context): void {
|
||||
|
||||
$context->set('requestTimestamp', function ($request) {
|
||||
// TODO: Move this to the Request class itself
|
||||
$timestampHeader = $request->getHeader('x-appwrite-timestamp');
|
||||
$timestampHeader = $request->getHeaderLine('x-appwrite-timestamp');
|
||||
$requestTimestamp = null;
|
||||
if (! empty($timestampHeader)) {
|
||||
try {
|
||||
@@ -946,7 +946,7 @@ return function (Container $context): void {
|
||||
}, ['request']);
|
||||
|
||||
$context->set('devKey', function (Request $request, Document $project, array $servers, Database $dbForPlatform, Authorization $authorization) {
|
||||
$devKey = $request->getHeader('x-appwrite-dev-key', $request->getParam('devKey', ''));
|
||||
$devKey = $request->getHeaderLine('x-appwrite-dev-key', $request->getParam('devKey', ''));
|
||||
|
||||
// Check if given key match project's development keys
|
||||
$key = $project->find('secret', $devKey, 'devKeys');
|
||||
@@ -972,7 +972,7 @@ return function (Container $context): void {
|
||||
|
||||
// add sdk to key
|
||||
$sdkValidator = new WhiteList($servers, true);
|
||||
$sdk = \strtolower($request->getHeader('x-sdk-name', 'UNKNOWN'));
|
||||
$sdk = \strtolower($request->getHeaderLine('x-sdk-name', 'UNKNOWN'));
|
||||
|
||||
if ($sdk !== 'unknown' && $sdkValidator->isValid($sdk)) {
|
||||
$sdks = $key->getAttribute('sdks', []);
|
||||
@@ -1001,7 +1001,7 @@ return function (Container $context): void {
|
||||
} else {
|
||||
$route = $utopia->match($request)?->route;
|
||||
$path = ! empty($route) ? $route->getPath() : $request->getURI();
|
||||
$orgHeader = $request->getHeader('x-appwrite-organization', '');
|
||||
$orgHeader = $request->getHeaderLine('x-appwrite-organization', '');
|
||||
if (str_starts_with($path, '/v1/projects/:projectId')) {
|
||||
$uri = $request->getURI();
|
||||
$pid = explode('/', $uri)[3];
|
||||
@@ -1047,7 +1047,7 @@ return function (Container $context): void {
|
||||
}
|
||||
|
||||
if ($allowed) {
|
||||
$host = $request->getQuery('appwrite-hostname', $request->getHeader('x-appwrite-hostname', '')) ?? '';
|
||||
$host = $request->getQuery('appwrite-hostname', $request->getHeaderLine('x-appwrite-hostname', '')) ?? '';
|
||||
if (! empty($host)) {
|
||||
return $host;
|
||||
}
|
||||
@@ -1057,7 +1057,7 @@ return function (Container $context): void {
|
||||
}, ['request', 'apiKey']);
|
||||
|
||||
$context->set('apiKey', function (Request $request, Document $project, Document $team, Document $user): ?Key {
|
||||
$key = $request->getHeader('x-appwrite-key');
|
||||
$key = $request->getHeaderLine('x-appwrite-key');
|
||||
|
||||
if (empty($key)) {
|
||||
return null;
|
||||
@@ -1065,9 +1065,9 @@ return function (Container $context): void {
|
||||
|
||||
$key = Key::decode($project, $team, $user, $key);
|
||||
|
||||
$userHeader = $request->getHeader('x-appwrite-user');
|
||||
$organizationHeader = $request->getHeader('x-appwrite-organization');
|
||||
$projectHeader = $request->getHeader('x-appwrite-project');
|
||||
$userHeader = $request->getHeaderLine('x-appwrite-user');
|
||||
$organizationHeader = $request->getHeaderLine('x-appwrite-organization');
|
||||
$projectHeader = $request->getHeaderLine('x-appwrite-project');
|
||||
|
||||
if (! empty($key->getProjectId())) {
|
||||
if (empty($projectHeader) || $projectHeader !== $key->getProjectId()) {
|
||||
@@ -1108,7 +1108,11 @@ return function (Container $context): void {
|
||||
return new Document([]);
|
||||
}
|
||||
|
||||
$token = $authorization->skip(fn () => $dbForProject->getDocument('resourceTokens', $tokenId));
|
||||
try {
|
||||
$token = $authorization->skip(fn () => $dbForProject->getDocument('resourceTokens', $tokenId));
|
||||
} catch (\Utopia\Database\Exception\NotFound) {
|
||||
return new Document([]);
|
||||
}
|
||||
|
||||
if ($token->isEmpty()) {
|
||||
return new Document([]);
|
||||
@@ -1170,7 +1174,7 @@ return function (Container $context): void {
|
||||
['host' => \gethostname(), 'project' => $project->getId()]
|
||||
);
|
||||
|
||||
$timeout = \intval($request->getHeader('x-appwrite-timeout'));
|
||||
$timeout = \intval($request->getHeaderLine('x-appwrite-timeout'));
|
||||
if (!empty($timeout) && Http::isDevelopment()) {
|
||||
$database->setTimeout($timeout);
|
||||
}
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ $traceProjectId = System::getEnv('_APP_TRACE_PROJECT_ID', '');
|
||||
$traceFunctionId = System::getEnv('_APP_TRACE_FUNCTION_ID', '');
|
||||
$traceEnabled = $traceProjectId !== '' || $traceFunctionId !== '';
|
||||
|
||||
Span::addExporter(new Exporter\Pretty(), function (Span $span) use ($traceEnabled, $traceProjectId, $traceFunctionId): bool {
|
||||
Span::setExporters(new Exporter\Pretty(sampler: function (Span $span) use ($traceEnabled, $traceProjectId, $traceFunctionId): bool {
|
||||
if (\str_starts_with($span->getAction(), 'listener.')) {
|
||||
return $span->getError() !== null;
|
||||
}
|
||||
@@ -29,4 +29,4 @@ Span::addExporter(new Exporter\Pretty(), function (Span $span) use ($traceEnable
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}));
|
||||
+51
-24
@@ -710,8 +710,15 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Restore authorization after subscribe
|
||||
if ($authorization !== null) {
|
||||
// meta can be empty as well as the channels are not required query param to connect
|
||||
// channels and queries can be sent via message later on
|
||||
// so if meta is empty we are not subscribing above to the projectId
|
||||
if (!isset($realtime->connections[$connection])) {
|
||||
$realtime->subscribe($projectId, $connection, '', $roles, [], [], $userId);
|
||||
}
|
||||
if ($authorization !== null && isset($realtime->connections[$connection])) {
|
||||
$realtime->connections[$connection]['authorization'] = $authorization;
|
||||
}
|
||||
|
||||
@@ -866,6 +873,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
Span::add('realtime.origin', $request->getOrigin());
|
||||
}
|
||||
|
||||
$error = null;
|
||||
try {
|
||||
/** @var Document $project */
|
||||
$project = $connectionContainer->get('project');
|
||||
@@ -935,7 +943,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
$channels = Realtime::convertChannels($request->getQuery('channels', []), $user->getId());
|
||||
$channelCount = \count($channels);
|
||||
|
||||
$updateStats = static function (string $projectId, ?string $teamId, string $payloadJson) use ($register, $stats): void {
|
||||
$updateStats = static function (string $projectId, ?string $teamId) use ($register, $stats): void {
|
||||
$register->get('telemetry.connectionCounter')->add(1);
|
||||
$register->get('telemetry.workerClientCounter')->add(1, $register->get('telemetry.workerAttributes'));
|
||||
$register->get('telemetry.connectionCreatedCounter')->add(1);
|
||||
@@ -949,7 +957,6 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
|
||||
triggerStats([
|
||||
METRIC_REALTIME_CONNECTIONS => 1,
|
||||
METRIC_REALTIME_OUTBOUND => \strlen($payloadJson),
|
||||
], $projectId);
|
||||
};
|
||||
|
||||
@@ -970,9 +977,12 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
|
||||
$realtime->subscribe($project->getId(), $connection, '', $roles, [], [], $user->getId());
|
||||
$realtime->connections[$connection]['authorization'] = $authorization;
|
||||
$updateStats($project->getId(), $project->getAttribute('teamId'));
|
||||
$server->send([$connection], $connectedPayloadJson);
|
||||
$outboundBytes += \strlen($connectedPayloadJson);
|
||||
$updateStats($project->getId(), $project->getAttribute('teamId'), $connectedPayloadJson);
|
||||
triggerStats([
|
||||
METRIC_REALTIME_OUTBOUND => \strlen($connectedPayloadJson),
|
||||
], $project->getId());
|
||||
$subscriptionMode = 'message';
|
||||
$success = true;
|
||||
return;
|
||||
@@ -990,6 +1000,8 @@ $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);
|
||||
|
||||
$mapping = [];
|
||||
foreach ($subscriptions as $index => $subscription) {
|
||||
$subscriptionId = ID::unique();
|
||||
@@ -1006,31 +1018,33 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
|
||||
$mapping[$index] = $subscriptionId;
|
||||
}
|
||||
|
||||
$realtime->connections[$connection]['authorization'] = $authorization;
|
||||
$updateStats($project->getId(), $project->getAttribute('teamId'));
|
||||
|
||||
$subscriptionCount = \count($subscriptions);
|
||||
if (!empty($subscriptions)) {
|
||||
$register->get('telemetry.workerSubscriptionCounter')->add(\count($subscriptions), $register->get('telemetry.workerAttributes'));
|
||||
}
|
||||
|
||||
$realtime->connections[$connection]['authorization'] = $authorization;
|
||||
|
||||
$user = empty($user->getId()) ? null : $response->output($user, Response::MODEL_ACCOUNT);
|
||||
|
||||
$connectedPayloadJson = json_encode([
|
||||
'type' => 'connected',
|
||||
'data' => [
|
||||
'channels' => $names,
|
||||
'subscriptions' => $mapping,
|
||||
'user' => $user
|
||||
'user' => $sanitizedUser
|
||||
]
|
||||
]);
|
||||
|
||||
$server->send([$connection], $connectedPayloadJson);
|
||||
$outboundBytes += \strlen($connectedPayloadJson);
|
||||
$updateStats($project->getId(), $project->getAttribute('teamId'), $connectedPayloadJson);
|
||||
triggerStats([
|
||||
METRIC_REALTIME_OUTBOUND => \strlen($connectedPayloadJson),
|
||||
], $project->getId());
|
||||
$success = true;
|
||||
|
||||
} catch (Throwable $th) {
|
||||
Span::error($th);
|
||||
$error = $th;
|
||||
|
||||
// Convert known Utopia DB exceptions to AppwriteException so isPublishable()
|
||||
// suppresses expected client errors (permission denied, query timeout) from Sentry.
|
||||
@@ -1088,7 +1102,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
|
||||
if (!empty($logUser?->getId())) {
|
||||
Span::add('user.id', $logUser->getId());
|
||||
}
|
||||
Span::current()?->finish();
|
||||
Span::current()?->finish(error: $error);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1107,6 +1121,7 @@ $server->onMessage(function (int $connection, string $message) use ($container,
|
||||
Span::add('realtime.inbound_bytes', $rawSize);
|
||||
Span::add('realtime.container.id', $containerId);
|
||||
|
||||
$error = null;
|
||||
try {
|
||||
$response = new Response(new SwooleResponse());
|
||||
|
||||
@@ -1230,13 +1245,16 @@ $server->onMessage(function (int $connection, string $message) use ($container,
|
||||
$outboundBytes += $bytes;
|
||||
|
||||
if ($project !== null && !$project->isEmpty()) {
|
||||
triggerStats([METRIC_REALTIME_OUTBOUND => $bytes], $project->getId());
|
||||
triggerStats([
|
||||
METRIC_REALTIME_OUTBOUND => $bytes,
|
||||
METRIC_REALTIME_CONNECTIONS_MESSAGES_SENT => 1,
|
||||
], $project->getId());
|
||||
}
|
||||
}
|
||||
|
||||
$success = true;
|
||||
} catch (Throwable $th) {
|
||||
Span::error($th);
|
||||
$error = $th;
|
||||
|
||||
// Convert known Utopia DB exceptions to AppwriteException so isPublishable()
|
||||
// suppresses expected client errors (permission denied, query timeout) from Sentry.
|
||||
@@ -1282,7 +1300,7 @@ $server->onMessage(function (int $connection, string $message) use ($container,
|
||||
Span::add('project.id', $project?->getId() ?? $projectId);
|
||||
Span::add('user.id', $realtime->connections[$connection]['userId'] ?? null);
|
||||
Span::add('realtime.message_type', $messageType);
|
||||
Span::current()?->finish();
|
||||
Span::current()?->finish(error: $error);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1302,20 +1320,27 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register, $
|
||||
|
||||
try {
|
||||
if (array_key_exists($connection, $realtime->connections)) {
|
||||
$stats->decr($realtime->connections[$connection]['projectId'], 'connectionsTotal');
|
||||
// These decrements are symmetric with the increments in updateStats (onOpen),
|
||||
// which run when the connection enters $realtime->connections — the same gate as the
|
||||
// array_key_exists check above. The connectionsTotal stat is keyed by project, so it's
|
||||
// additionally guarded: a connection can exist without a stored projectId (e.g. only an
|
||||
// authorization entry left after an orphaning re-subscribe).
|
||||
$register->get('telemetry.connectionCounter')->add(-1);
|
||||
$register->get('telemetry.workerClientCounter')->add(-1, $register->get('telemetry.workerAttributes'));
|
||||
if (!empty($projectId)) {
|
||||
$stats->decr($projectId, 'connectionsTotal');
|
||||
}
|
||||
$subscriptionsBeforeClose = \count($realtime->getSubscriptionMetadata($connection));
|
||||
if ($subscriptionsBeforeClose > 0) {
|
||||
$register->get('telemetry.workerSubscriptionCounter')->add(-$subscriptionsBeforeClose, $register->get('telemetry.workerAttributes'));
|
||||
}
|
||||
|
||||
$projectId = $realtime->connections[$connection]['projectId'];
|
||||
/** @var array<string, Document> $presencesById */
|
||||
$presencesById = $realtime->connections[$connection]['presences'] ?? [];
|
||||
|
||||
if (
|
||||
!empty($presencesById)
|
||||
&& !empty($projectId)
|
||||
&& $projectId !== 'console'
|
||||
) {
|
||||
go(function () use ($presencesById, $projectId, $userId, $container, $presenceState): void {
|
||||
@@ -1369,7 +1394,7 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register, $
|
||||
);
|
||||
$presenceState->triggerUsage($publisherForUsage, $project, -$deletionCount);
|
||||
} catch (Throwable $th) {
|
||||
Span::error($th);
|
||||
Span::current()?->setError($th);
|
||||
logError($th, 'realtimeOnClosePresenceDeletion', tags: [
|
||||
'projectId' => $projectId,
|
||||
'presences' => \count($presences)
|
||||
@@ -1396,7 +1421,7 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register, $
|
||||
}
|
||||
}
|
||||
} catch (Throwable $th) {
|
||||
Span::error($th);
|
||||
Span::current()?->setError($th);
|
||||
logError($th, 'realtimeOnClosePresenceCleanup', tags: [
|
||||
'projectId' => $projectId,
|
||||
]);
|
||||
@@ -1406,22 +1431,24 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register, $
|
||||
});
|
||||
}
|
||||
|
||||
triggerStats([
|
||||
METRIC_REALTIME_CONNECTIONS => -1,
|
||||
], $projectId);
|
||||
if (!empty($projectId)) {
|
||||
triggerStats([
|
||||
METRIC_REALTIME_CONNECTIONS => -1,
|
||||
], $projectId);
|
||||
}
|
||||
}
|
||||
$success = true;
|
||||
} catch (\Throwable $th) {
|
||||
// Log only; do not rethrow. If we let this bubble, Swoole dumps full coroutine
|
||||
// backtraces and unsubscribe() below would never run (connection cleanup would fail).
|
||||
Console::error('Realtime onClose error: ' . $th->getMessage());
|
||||
Span::error($th);
|
||||
Span::current()?->setError($th);
|
||||
} finally {
|
||||
try {
|
||||
$realtime->unsubscribe($connection);
|
||||
} catch (\Throwable $th) {
|
||||
Console::error('Realtime onClose unsubscribe error: ' . $th->getMessage());
|
||||
Span::error($th);
|
||||
Span::current()?->setError($th);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -12,6 +12,7 @@ $version = $this->getParam('version', '');
|
||||
$organization = $this->getParam('organization', '');
|
||||
$image = $this->getParam('image', '');
|
||||
$enableAssistant = $this->getParam('enableAssistant', false);
|
||||
$executorImages = $this->getParam('executorImages', '');
|
||||
$dbService = $this->getParam('database', 'mongodb');
|
||||
$allowedDbServices = ['mariadb', 'mongodb'];
|
||||
if (!\in_array($dbService, $allowedDbServices, true)) {
|
||||
@@ -983,15 +984,14 @@ $hostPath = rtrim($this->getParam('hostPath', ''), '/');
|
||||
- appwrite
|
||||
|
||||
openruntimes-executor:
|
||||
container_name: openruntimes-executor
|
||||
container_name: exc1
|
||||
hostname: exc1
|
||||
<<: *x-logging
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGINT
|
||||
image: openruntimes/executor:0.11.4
|
||||
image: openruntimes/executor:0.25.1
|
||||
networks:
|
||||
- appwrite
|
||||
- runtimes
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- appwrite-builds:/storage/builds:rw
|
||||
@@ -1001,6 +1001,9 @@ $hostPath = rtrim($this->getParam('hostPath', ''), '/');
|
||||
# It's not possible to share mount file between 2 containers without host mount (copying is too slow)
|
||||
- /tmp:/tmp:rw
|
||||
environment:
|
||||
- OPR_EXECUTOR_CONNECTION_STORAGE=local://localhost
|
||||
- OPR_EXECUTOR_CONNECTION_BUILD_CACHE_STORAGE=
|
||||
- OPR_EXECUTOR_IMAGES=<?php echo $executorImages; ?>
|
||||
- OPR_EXECUTOR_INACTIVE_TRESHOLD=$_APP_COMPUTE_INACTIVE_THRESHOLD
|
||||
- OPR_EXECUTOR_MAINTENANCE_INTERVAL=$_APP_COMPUTE_MAINTENANCE_INTERVAL
|
||||
- OPR_EXECUTOR_NETWORK=$_APP_COMPUTE_RUNTIMES_NETWORK
|
||||
@@ -1209,3 +1212,4 @@ volumes:
|
||||
appwrite-sites:
|
||||
appwrite-builds:
|
||||
appwrite-config:
|
||||
openruntimes-node-modules-cache:
|
||||
+1
-1
@@ -118,7 +118,7 @@ $worker
|
||||
->action(function (Throwable $error, ?Logger $logger, Log $log, Document $project, Authorization $authorization) use ($queueName) {
|
||||
$version = System::getEnv('_APP_VERSION', 'UNKNOWN');
|
||||
|
||||
Span::error($error);
|
||||
Span::current()?->setError($error);
|
||||
|
||||
if ($logger) {
|
||||
$log->setNamespace('appwrite-worker');
|
||||
|
||||
+12
-12
@@ -53,21 +53,21 @@
|
||||
"ext-sockets": "*",
|
||||
"appwrite/php-runtimes": "0.20.*",
|
||||
"appwrite/php-clamav": "2.0.*",
|
||||
"utopia-php/abuse": "1.3.*",
|
||||
"utopia-php/abuse": "1.4.*",
|
||||
"utopia-php/agents": "2.*",
|
||||
"utopia-php/analytics": "0.15.*",
|
||||
"utopia-php/audit": "^2.4",
|
||||
"utopia-php/auth": "0.5.*",
|
||||
"utopia-php/audit": "2.6.*",
|
||||
"utopia-php/auth": "^0.7",
|
||||
"utopia-php/cache": "^3.0",
|
||||
"utopia-php/cli": "0.23.*",
|
||||
"utopia-php/cli": "^0.24",
|
||||
"utopia-php/compression": "0.1.*",
|
||||
"utopia-php/config": "1.*",
|
||||
"utopia-php/console": "0.1.*",
|
||||
"utopia-php/database": "5.*",
|
||||
"utopia-php/database": "6.0.*",
|
||||
"utopia-php/detector": "0.2.*",
|
||||
"utopia-php/domains": "^2.2",
|
||||
"utopia-php/emails": "0.7.*",
|
||||
"utopia-php/dns": "1.7.*",
|
||||
"utopia-php/dns": "^1.8",
|
||||
"utopia-php/dsn": "0.2.1",
|
||||
"utopia-php/http": "^2.0@RC",
|
||||
"utopia-php/fetch": "^1.1",
|
||||
@@ -76,13 +76,13 @@
|
||||
"utopia-php/locale": "0.8.*",
|
||||
"utopia-php/lock": "0.2.*",
|
||||
"utopia-php/logger": "0.8.*",
|
||||
"utopia-php/messaging": "1.0.*",
|
||||
"utopia-php/migration": "1.*",
|
||||
"utopia-php/platform": "1.0.0-rc5",
|
||||
"utopia-php/messaging": "^1.2",
|
||||
"utopia-php/migration": "1.14.*",
|
||||
"utopia-php/platform": "^1.0@RC",
|
||||
"utopia-php/pools": "1.*",
|
||||
"utopia-php/span": "1.1.*",
|
||||
"utopia-php/span": "3.0.*",
|
||||
"utopia-php/preloader": "0.2.*",
|
||||
"utopia-php/queue": "0.20.*",
|
||||
"utopia-php/queue": "^0.21",
|
||||
"utopia-php/servers": "0.4.*",
|
||||
"utopia-php/registry": "0.5.*",
|
||||
"utopia-php/storage": "2.*",
|
||||
@@ -102,7 +102,7 @@
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-fileinfo": "*",
|
||||
"appwrite/sdk-generator": "*",
|
||||
"appwrite/sdk-generator": "^2.0",
|
||||
"brianium/paratest": "7.*",
|
||||
"phpunit/phpunit": "12.*",
|
||||
"swoole/ide-helper": "6.*",
|
||||
|
||||
Generated
+190
-224
File diff suppressed because it is too large.
Load diff
+6
-3
@@ -387,7 +387,7 @@ services:
|
||||
environment:
|
||||
- _APP_ENV
|
||||
- _APP_WORKERS_NUM=1
|
||||
- _APP_WORKER_MAX_COROUTINES=1
|
||||
- _APP_WORKER_MAX_COROUTINES=8
|
||||
- _APP_WORKER_PER_CORE
|
||||
- _APP_POOL_ADAPTER
|
||||
- _APP_OPENSSL_KEY_V1
|
||||
@@ -1246,11 +1246,11 @@ services:
|
||||
- appwrite
|
||||
|
||||
openruntimes-executor:
|
||||
container_name: openruntimes-executor
|
||||
container_name: exc1
|
||||
hostname: exc1
|
||||
<<: *x-logging
|
||||
stop_signal: SIGINT
|
||||
image: openruntimes/executor:0.11.4
|
||||
image: openruntimes/executor:0.25.1
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- appwrite
|
||||
@@ -1264,6 +1264,8 @@ services:
|
||||
# It's not possible to share mount file between 2 containers without host mount (copying is too slow)
|
||||
- /tmp:/tmp:rw
|
||||
environment:
|
||||
- OPR_EXECUTOR_CONNECTION_STORAGE=local://localhost
|
||||
- OPR_EXECUTOR_CONNECTION_BUILD_CACHE_STORAGE=
|
||||
- OPR_EXECUTOR_IMAGE_PULL=enabled
|
||||
- OPR_EXECUTOR_INACTIVE_TRESHOLD=$_APP_COMPUTE_INACTIVE_THRESHOLD
|
||||
- OPR_EXECUTOR_MAINTENANCE_INTERVAL=$_APP_COMPUTE_MAINTENANCE_INTERVAL
|
||||
@@ -1526,3 +1528,4 @@ volumes:
|
||||
appwrite-builds:
|
||||
appwrite-config:
|
||||
appwrite-models:
|
||||
openruntimes-node-modules-cache:
|
||||
@@ -143,6 +143,7 @@ class Mails extends Listener
|
||||
project: $project,
|
||||
recipient: $event->user['email'],
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_SESSION_ALERT,
|
||||
bodyTemplate: __DIR__ . '/../../../../app/config/locale/templates/' . $smtpBaseTemplate . '.tpl',
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Event\Message;
|
||||
|
||||
use Utopia\Database\Document;
|
||||
|
||||
final class Executions extends Base
|
||||
{
|
||||
/**
|
||||
* @param array<Document> $executions
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Document $project,
|
||||
public readonly array $executions,
|
||||
) {
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'project' => $this->project->getArrayCopy(),
|
||||
'executions' => \array_map(
|
||||
fn (Document $execution) => $execution->getArrayCopy(),
|
||||
$this->executions
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): static
|
||||
{
|
||||
return new self(
|
||||
project: new Document($data['project'] ?? []),
|
||||
executions: \array_map(
|
||||
fn (array $execution) => new Document($execution),
|
||||
$data['executions'] ?? []
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ final class Mail extends Base
|
||||
public readonly string $recipient = '',
|
||||
public readonly string $name = '',
|
||||
public readonly string $subject = '',
|
||||
public readonly string $template = '',
|
||||
public readonly string $bodyTemplate = '',
|
||||
public readonly string $body = '',
|
||||
public readonly string $preview = '',
|
||||
@@ -33,6 +34,7 @@ final class Mail extends Base
|
||||
'recipient' => $this->recipient,
|
||||
'name' => $this->name,
|
||||
'subject' => $this->subject,
|
||||
'template' => $this->template,
|
||||
'bodyTemplate' => $this->bodyTemplate,
|
||||
'body' => $this->body,
|
||||
'preview' => $this->preview,
|
||||
@@ -52,6 +54,7 @@ final class Mail extends Base
|
||||
recipient: $data['recipient'] ?? '',
|
||||
name: $data['name'] ?? '',
|
||||
subject: $data['subject'] ?? '',
|
||||
template: $data['template'] ?? '',
|
||||
bodyTemplate: $data['bodyTemplate'] ?? '',
|
||||
body: $data['body'] ?? '',
|
||||
preview: $data['preview'] ?? '',
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Appwrite\Event\Publisher;
|
||||
|
||||
use Appwrite\Event\Message\Execution as ExecutionMessage;
|
||||
use Appwrite\Event\Message\Executions as ExecutionsMessage;
|
||||
use Utopia\Queue\Publisher;
|
||||
use Utopia\Queue\Queue;
|
||||
|
||||
@@ -15,7 +16,7 @@ readonly class Execution extends Base
|
||||
parent::__construct($publisher);
|
||||
}
|
||||
|
||||
public function enqueue(ExecutionMessage $message): string|bool
|
||||
public function enqueue(ExecutionMessage|ExecutionsMessage $message): string|bool
|
||||
{
|
||||
return $this->publish($this->queue, $message);
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ class Exception extends \Exception
|
||||
public const string USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists';
|
||||
public const string USER_EMAIL_DISPOSABLE = 'user_email_disposable';
|
||||
public const string USER_EMAIL_FREE = 'user_email_free';
|
||||
public const string USER_EMAIL_NOT_CORPORATE = 'user_email_not_corporate';
|
||||
public const string USER_EMAIL_NOT_CANONICAL = 'user_email_not_canonical';
|
||||
public const string USER_PASSWORD_MISMATCH = 'user_password_mismatch';
|
||||
public const string USER_SESSION_NOT_FOUND = 'user_session_not_found';
|
||||
|
||||
@@ -40,8 +40,9 @@ class Resolvers
|
||||
);
|
||||
}
|
||||
|
||||
// Response headers follow PSR-7: keys are lowercased and values are lists.
|
||||
$headers = $from->getHeaders();
|
||||
$fallbackCookies = $headers['X-Fallback-Cookies'] ?? null;
|
||||
$fallbackCookies = $headers['x-fallback-cookies'] ?? null;
|
||||
if ($fallbackCookies === null) {
|
||||
return;
|
||||
}
|
||||
@@ -347,7 +348,7 @@ class Resolvers
|
||||
$request->addHeader('x-appwrite-source', 'graphql');
|
||||
|
||||
// Drop json content type so post args are used directly.
|
||||
if (\str_starts_with($request->getHeader('content-type'), 'application/json')) {
|
||||
if (\str_starts_with($request->getHeaderLine('content-type'), 'application/json')) {
|
||||
$request->removeHeader('content-type');
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,15 @@ class V24 extends Migration
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'tokens':
|
||||
try {
|
||||
$this->createIndexFromCollection($this->dbForProject, $id, '_key_type_expire');
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create index \"_key_type_expire\" from {$id}: {$th->getMessage()}");
|
||||
}
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'databases':
|
||||
if ($collectionType === 'projects') {
|
||||
try {
|
||||
|
||||
@@ -42,7 +42,14 @@ class Install extends Action
|
||||
->param('accountPassword', '', new Password(allowEmpty: true), 'Account password', true)
|
||||
->param('database', '', new WhiteList(['mongodb', 'mariadb', 'postgresql']), 'Database adapter', true)
|
||||
->param('installId', '', new Text(64, 0), 'Installation ID', true)
|
||||
->param('retryStep', null, new Nullable(new WhiteList([Server::STEP_DOCKER_COMPOSE, Server::STEP_ENV_VARS, Server::STEP_DOCKER_CONTAINERS], true)), 'Retry from step', true)
|
||||
->param('retryStep', null, new Nullable(new WhiteList([
|
||||
Server::STEP_CONFIG_FILES,
|
||||
Server::STEP_DOCKER_COMPOSE,
|
||||
Server::STEP_ENV_VARS,
|
||||
Server::STEP_DOCKER_CONTAINERS,
|
||||
Server::STEP_ACCOUNT_SETUP,
|
||||
Server::STEP_MIGRATION,
|
||||
], true)), 'Retry from step', true)
|
||||
->param('migrate', false, new \Utopia\Validator\Boolean(true), 'Run database migration after upgrade', true)
|
||||
->inject('request')
|
||||
->inject('response')
|
||||
@@ -73,7 +80,7 @@ class Install extends Action
|
||||
Config $config,
|
||||
array $paths
|
||||
): void {
|
||||
$acceptHeader = $request->getHeader('accept');
|
||||
$acceptHeader = $request->getHeaderLine('accept');
|
||||
$wantsStream = stripos($acceptHeader, 'text/event-stream') !== false;
|
||||
|
||||
if ($wantsStream) {
|
||||
|
||||
@@ -69,17 +69,33 @@ class Reset extends Action
|
||||
$isLocal = $config->isLocal();
|
||||
$composeFileName = $isLocal ? 'docker-compose.web-installer.yml' : 'docker-compose.yml';
|
||||
$envFileName = $isLocal ? '.env.web-installer' : '.env';
|
||||
$path = $isLocal ? '/usr/src/code' : '/usr/src/code/appwrite';
|
||||
$path = $isLocal ? $config->getHostPath() : '/usr/src/code/appwrite';
|
||||
|
||||
if ($path === null || $path === '') {
|
||||
return 'Missing host path for local installer reset';
|
||||
}
|
||||
|
||||
$composeFile = $path . '/' . $composeFileName;
|
||||
$envFile = $path . '/' . $envFileName;
|
||||
|
||||
if (file_exists($composeFile)) {
|
||||
$command = array_map(escapeshellarg(...), [
|
||||
$command = [
|
||||
'docker', 'compose',
|
||||
'-f', $composeFile,
|
||||
];
|
||||
if (file_exists($envFile)) {
|
||||
$command[] = '--env-file';
|
||||
$command[] = $envFile;
|
||||
}
|
||||
$command = array_map(escapeshellarg(...), [
|
||||
...$command,
|
||||
'-f',
|
||||
$composeFile,
|
||||
...($isLocal ? ['--project-name', 'appwrite'] : []),
|
||||
'--project-directory', $path,
|
||||
'down', '-v', '--remove-orphans',
|
||||
'--project-directory',
|
||||
$path,
|
||||
'down',
|
||||
'-v',
|
||||
'--remove-orphans',
|
||||
]);
|
||||
|
||||
$output = [];
|
||||
@@ -92,7 +108,6 @@ class Reset extends Action
|
||||
@unlink($composeFile);
|
||||
}
|
||||
|
||||
$envFile = $path . '/' . $envFileName;
|
||||
if (file_exists($envFile)) {
|
||||
@unlink($envFile);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ class Validate extends Action
|
||||
public static function validateCsrf(Request $request): bool
|
||||
{
|
||||
$cookie = $request->getCookie(Server::CSRF_COOKIE);
|
||||
$header = $request->getHeader('x-appwrite-installer-csrf');
|
||||
$header = $request->getHeaderLine('x-appwrite-installer-csrf');
|
||||
|
||||
return $cookie !== '' && $header !== '' && hash_equals($cookie, $header);
|
||||
}
|
||||
|
||||
@@ -114,7 +114,6 @@ class Server
|
||||
}
|
||||
|
||||
if (isset($opts['docker'])) {
|
||||
$this->printInstallerUrl($host, $port);
|
||||
$this->startDockerInstaller($opts);
|
||||
}
|
||||
|
||||
@@ -365,9 +364,13 @@ class Server
|
||||
'-i',
|
||||
'--rm',
|
||||
'--name', $container,
|
||||
'--label', 'com.docker.compose.project=appwrite-installer',
|
||||
'--label', 'com.docker.compose.service=appwrite-installer',
|
||||
'--add-host', 'host.docker.internal:host-gateway',
|
||||
'-p', "127.0.0.1:$port:" . self::INSTALLER_WEB_PORT,
|
||||
'--volume', '/var/run/docker.sock:/var/run/docker.sock',
|
||||
'--volume', "$volumePath:/usr/src/code:rw",
|
||||
'--volume', "$volumePath:$volumePath:rw",
|
||||
];
|
||||
$args[] = '-e';
|
||||
$args[] = 'APPWRITE_INSTALLER_CONFIG=' . $configJson;
|
||||
|
||||
@@ -336,6 +336,7 @@ class Create extends Action
|
||||
project: $project,
|
||||
recipient: $user->getAttribute('email'),
|
||||
subject: $subject,
|
||||
template: MAIL_TEMPLATE_MFA_CHALLENGE,
|
||||
bodyTemplate: $bodyTemplate,
|
||||
body: $body,
|
||||
preview: $preview,
|
||||
|
||||
@@ -42,6 +42,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-browser.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -42,6 +42,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-credit-card.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -54,6 +54,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-favicon.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -42,6 +42,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-flag.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -45,6 +45,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-image.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -44,6 +44,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-initials.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -42,6 +42,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-qr.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -57,6 +57,7 @@ class Get extends Action
|
||||
description: '/docs/references/avatars/get-screenshot.md',
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
|
||||
@@ -139,18 +139,6 @@ class Base extends Action
|
||||
'activate' => $activate,
|
||||
]));
|
||||
|
||||
$function = $function
|
||||
->setAttribute('latestDeploymentId', $deployment->getId())
|
||||
->setAttribute('latestDeploymentInternalId', $deployment->getSequence())
|
||||
->setAttribute('latestDeploymentCreatedAt', $deployment->getCreatedAt())
|
||||
->setAttribute('latestDeploymentStatus', $deployment->getAttribute('status', ''));
|
||||
$dbForProject->updateDocument('functions', $function->getId(), new Document([
|
||||
'latestDeploymentId' => $deployment->getId(),
|
||||
'latestDeploymentInternalId' => $deployment->getSequence(),
|
||||
'latestDeploymentCreatedAt' => $deployment->getCreatedAt(),
|
||||
'latestDeploymentStatus' => $deployment->getAttribute('status', ''),
|
||||
]));
|
||||
|
||||
$publisherForBuilds->enqueue(new BuildMessage(
|
||||
project: $project,
|
||||
resource: $function,
|
||||
@@ -253,18 +241,6 @@ class Base extends Action
|
||||
'activate' => $activate,
|
||||
]));
|
||||
|
||||
$site = $site
|
||||
->setAttribute('latestDeploymentId', $deployment->getId())
|
||||
->setAttribute('latestDeploymentInternalId', $deployment->getSequence())
|
||||
->setAttribute('latestDeploymentCreatedAt', $deployment->getCreatedAt())
|
||||
->setAttribute('latestDeploymentStatus', $deployment->getAttribute('status', ''));
|
||||
$dbForProject->updateDocument('sites', $site->getId(), new Document([
|
||||
'latestDeploymentId' => $deployment->getId(),
|
||||
'latestDeploymentInternalId' => $deployment->getSequence(),
|
||||
'latestDeploymentCreatedAt' => $deployment->getCreatedAt(),
|
||||
'latestDeploymentStatus' => $deployment->getAttribute('status', ''),
|
||||
]));
|
||||
|
||||
$sitesDomain = $platform['sitesDomain'];
|
||||
$domain = ID::unique() . "." . $sitesDomain;
|
||||
|
||||
|
||||
@@ -21,6 +21,41 @@ class Action extends AppwriteAction
|
||||
return $this->context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Database types this path may operate on. Single source of truth shared by
|
||||
* the list filter ({@see getDatabaseTypeQueryFilters()}) and the by-id guard
|
||||
* ({@see isDatabaseTypeMismatch()}) so they cannot diverge.
|
||||
*
|
||||
* TablesDB is the compatibility successor to the legacy databases API, so it
|
||||
* also serves legacy-typed databases; the other product APIs are scoped to
|
||||
* their own type. Every database carries a non-null `type` (set on create
|
||||
* and backfilled to 'legacy' by migration V23), so null is not represented.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
protected function getAllowedDatabaseTypes(): array
|
||||
{
|
||||
return match ($this->getDatabaseType()) {
|
||||
DATABASE_TYPE_TABLESDB => [DATABASE_TYPE_TABLESDB, DATABASE_TYPE_LEGACY],
|
||||
default => [$this->getDatabaseType()],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A database resolved by id on a product-DB path must be one of the path's
|
||||
* allowed types; otherwise it is treated as not-found rather than proceeding
|
||||
* to a type-mismatched backend operation that surfaces as an opaque 500. The
|
||||
* legacy /v1/databases API is intentionally not type-guarded.
|
||||
*/
|
||||
protected function isDatabaseTypeMismatch(Document $database): bool
|
||||
{
|
||||
if ($this->getDatabaseType() === DATABASE_TYPE_LEGACY) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !in_array($database->getAttribute('type', ''), $this->getAllowedDatabaseTypes(), true);
|
||||
}
|
||||
|
||||
public function setHttpPath(string $path): self
|
||||
{
|
||||
if (\str_contains($path, '/tablesdb')) {
|
||||
|
||||
+8
-6
@@ -6,6 +6,7 @@ use Appwrite\Event\Event;
|
||||
use Appwrite\Event\Message\Database as DatabaseMessage;
|
||||
use Appwrite\Event\Publisher\Database as DatabasePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Action as DatabasesAction;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
use Throwable;
|
||||
@@ -21,10 +22,9 @@ use Utopia\Database\Helpers\ID;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\Database\Validator\Structure;
|
||||
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Platform\Action as UtopiaAction;
|
||||
use Utopia\Validator\Range;
|
||||
|
||||
abstract class Action extends UtopiaAction
|
||||
abstract class Action extends DatabasesAction
|
||||
{
|
||||
/**
|
||||
* @var string The current context (either 'column' or 'attribute')
|
||||
@@ -36,12 +36,14 @@ abstract class Action extends UtopiaAction
|
||||
*/
|
||||
abstract protected function getResponseModel(): string|array;
|
||||
|
||||
public function setHttpPath(string $path): UtopiaAction
|
||||
public function setHttpPath(string $path): DatabasesAction
|
||||
{
|
||||
if (\str_contains($path, '/tablesdb')) {
|
||||
$this->context = COLUMNS;
|
||||
}
|
||||
return parent::setHttpPath($path);
|
||||
parent::setHttpPath($path);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -333,7 +335,7 @@ abstract class Action extends UtopiaAction
|
||||
|
||||
$db = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($db->isEmpty()) {
|
||||
if ($db->isEmpty() || $this->isDatabaseTypeMismatch($db)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
@@ -495,7 +497,7 @@ abstract class Action extends UtopiaAction
|
||||
{
|
||||
$db = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($db->isEmpty()) {
|
||||
if ($db->isEmpty() || $this->isDatabaseTypeMismatch($db)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -76,7 +76,7 @@ class Delete extends Action
|
||||
public function action(string $databaseId, string $collectionId, string $key, UtopiaResponse $response, Database $dbForProject, DatabasePublisher $publisherForDatabase, Event $queueForEvents, Authorization $authorization): void
|
||||
{
|
||||
$db = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($db->isEmpty()) {
|
||||
if ($db->isEmpty() || $this->isDatabaseTypeMismatch($db)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ class Get extends Action
|
||||
public function action(string $databaseId, string $collectionId, string $key, UtopiaResponse $response, Database $dbForProject, Authorization $authorization): void
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -7,6 +7,7 @@ use Appwrite\Event\Publisher\Database as DatabasePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -57,6 +58,10 @@ class Create extends Action
|
||||
model: $this->getResponseModel()
|
||||
)
|
||||
],
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createLongtextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -6,6 +6,7 @@ use Appwrite\Event\Event;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -55,6 +56,10 @@ class Update extends Action
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.updateLongtextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -7,6 +7,7 @@ use Appwrite\Event\Publisher\Database as DatabasePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -57,6 +58,10 @@ class Create extends Action
|
||||
model: $this->getResponseModel()
|
||||
)
|
||||
],
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createMediumtextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -6,6 +6,7 @@ use Appwrite\Event\Event;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -55,6 +56,10 @@ class Update extends Action
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.updateMediumtextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ class Create extends Action
|
||||
$twoWayKey ??= $collectionId;
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -7,6 +7,7 @@ use Appwrite\Event\Publisher\Database as DatabasePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -57,6 +58,10 @@ class Create extends Action
|
||||
model: $this->getResponseModel()
|
||||
)
|
||||
],
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createTextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -6,6 +6,7 @@ use Appwrite\Event\Event;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -55,6 +56,10 @@ class Update extends Action
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.updateTextColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -7,6 +7,7 @@ use Appwrite\Event\Publisher\Database as DatabasePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -59,6 +60,10 @@ class Create extends Action
|
||||
model: $this->getResponseModel()
|
||||
)
|
||||
],
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createVarcharColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+5
@@ -6,6 +6,7 @@ use Appwrite\Event\Event;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Attributes\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -57,6 +58,10 @@ class Update extends Action
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.updateVarcharColumn',
|
||||
),
|
||||
))
|
||||
->param('databaseId', '', new UID(), 'Database ID.')
|
||||
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ class XList extends Action
|
||||
public function action(string $databaseId, string $collectionId, array $queries, bool $includeTotal, UtopiaResponse $response, Database $dbForProject, Authorization $authorization): void
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ class Create extends Action
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
@@ -103,6 +103,15 @@ class Create extends Action
|
||||
// Map aggregate permissions into the multiple permissions they represent.
|
||||
$permissions = Permission::aggregate($permissions) ?? [];
|
||||
|
||||
// Resolve the data-plane database BEFORE writing the metadata row. For a
|
||||
// dedicated product database this throws while provisioning (no DSN yet);
|
||||
// writing the row first would leave an orphaned collection with no backing
|
||||
// collection, which lists fine but fails every document operation.
|
||||
/**
|
||||
* @var Database $dbForDatabases
|
||||
*/
|
||||
$dbForDatabases = $getDatabasesDB($database);
|
||||
|
||||
try {
|
||||
$collection = $dbForProject->createDocument('database_' . $database->getSequence(), new Document([
|
||||
'$id' => $collectionId,
|
||||
@@ -122,11 +131,6 @@ class Create extends Action
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @var Database $dbForDatabases
|
||||
*/
|
||||
$dbForDatabases = $getDatabasesDB($database);
|
||||
|
||||
$collectionKey = 'database_' . $database->getSequence() . '_collection_' . $collection->getSequence();
|
||||
$databaseKey = 'database_' . $database->getSequence();
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ class Delete extends Action
|
||||
public function action(string $databaseId, string $collectionId, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, DatabasePublisher $publisherForDatabase, Event $queueForEvents, Authorization $authorization): void
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ class Decrement extends Action
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ class Increment extends Action
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ class Delete extends Action
|
||||
public function action(string $databaseId, string $collectionId, array $queries, ?string $transactionId, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Context $usage, Event $queueForEvents, Event $queueForRealtime, FunctionPublisher $publisherForFunctions, Event $queueForWebhooks, array $plan, EventProcessor $eventProcessor): void
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ class Update extends Action
|
||||
}
|
||||
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ class Upsert extends Action
|
||||
public function action(string $databaseId, string $collectionId, array $documents, ?string $transactionId, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Context $usage, Event $queueForEvents, Event $queueForRealtime, FunctionPublisher $publisherForFunctions, Event $queueForWebhooks, array $plan, EventProcessor $eventProcessor): void
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -209,7 +209,7 @@ class Create extends Action
|
||||
}
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -110,7 +110,7 @@ class Delete extends Action
|
||||
$isAPIKey = $user->isKey($authorization->getRoles());
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -82,7 +82,7 @@ class Get extends Action
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ class XList extends Action
|
||||
public function action(string $databaseId, string $collectionId, string $documentId, array $queries, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Locale $locale, Reader $geodb, Authorization $authorization, Audit $audit): void
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ class Update extends Action
|
||||
$isAPIKey = $user->isKey($authorization->getRoles());
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ class Upsert extends Action
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ class XList extends Action
|
||||
$isPrivilegedUser = $user->isPrivileged($authorization->getRoles());
|
||||
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ class Get extends Action
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+6
-4
@@ -3,9 +3,9 @@
|
||||
namespace Appwrite\Platform\Modules\Databases\Http\Databases\Collections\Indexes;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Utopia\Platform\Action as UtopiaAction;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Action as DatabasesAction;
|
||||
|
||||
abstract class Action extends UtopiaAction
|
||||
abstract class Action extends DatabasesAction
|
||||
{
|
||||
/**
|
||||
* The current API context (either 'columnIndex' or 'index').
|
||||
@@ -17,12 +17,14 @@ abstract class Action extends UtopiaAction
|
||||
*/
|
||||
abstract protected function getResponseModel(): string;
|
||||
|
||||
public function setHttpPath(string $path): UtopiaAction
|
||||
public function setHttpPath(string $path): DatabasesAction
|
||||
{
|
||||
if (\str_contains($path, '/tablesdb')) {
|
||||
$this->context = COLUMN_INDEX;
|
||||
}
|
||||
return parent::setHttpPath($path);
|
||||
parent::setHttpPath($path);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ class Create extends Action
|
||||
{
|
||||
$db = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($db->isEmpty()) {
|
||||
if ($db->isEmpty() || $this->isDatabaseTypeMismatch($db)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ class Delete extends Action
|
||||
{
|
||||
$db = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($db->isEmpty()) {
|
||||
if ($db->isEmpty() || $this->isDatabaseTypeMismatch($db)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
$collection = $dbForProject->getDocument('database_' . $db->getSequence(), $collectionId);
|
||||
|
||||
@@ -67,7 +67,7 @@ class Get extends Action
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
$collection = $dbForProject->getDocument('database_' . $database->getSequence(), $collectionId);
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ class XList extends Action
|
||||
/** @var Document $database */
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ class XList extends Action
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ class Update extends Action
|
||||
public function action(string $databaseId, string $collectionId, ?string $name, ?array $permissions, bool $documentSecurity, bool $enabled, bool $purge, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Event $queueForEvents, Authorization $authorization): void
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ class XList extends Action
|
||||
{
|
||||
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -199,6 +199,24 @@ class Create extends Action
|
||||
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
$this->createMetadataCollection($dbForProject, $database);
|
||||
|
||||
$queueForEvents->setParam('databaseId', $database->getId());
|
||||
|
||||
$response
|
||||
->setStatusCode(SwooleResponse::STATUS_CODE_CREATED)
|
||||
->dynamic($database, UtopiaResponse::MODEL_DATABASE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the per-database metadata collection (`database_{internalId}`) that holds
|
||||
* the database's collection definitions. Extracted so product overrides that
|
||||
* provision a backend asynchronously (e.g. documentsdb, vectorsdb) can initialise
|
||||
* the metadata exactly like a standard database create instead of leaving it
|
||||
* uninitialised, which makes the first collection create fail.
|
||||
*/
|
||||
protected function createMetadataCollection(Database $dbForProject, Document $database): void
|
||||
{
|
||||
$collections = $this->getDatabaseCollection();
|
||||
if (empty($collections)) {
|
||||
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The "collections" collection is not configured.');
|
||||
@@ -217,19 +235,11 @@ class Create extends Action
|
||||
try {
|
||||
$dbForProject->createCollection('database_' . $database->getSequence(), $attributes, $indexes);
|
||||
} catch (DuplicateException) {
|
||||
throw new Exception(Exception::DATABASE_ALREADY_EXISTS, params: [$databaseId]);
|
||||
throw new Exception(Exception::DATABASE_ALREADY_EXISTS, params: [$database->getId()]);
|
||||
} catch (IndexException $e) {
|
||||
throw new Exception(Exception::INDEX_INVALID);
|
||||
} catch (LimitException) {
|
||||
// TODO: @Jake, how do we handle this collection/table?
|
||||
// there's no context awareness at this level on what the api is.
|
||||
throw new Exception(Exception::COLLECTION_LIMIT_EXCEEDED, params: [$databaseId]);
|
||||
throw new Exception(Exception::COLLECTION_LIMIT_EXCEEDED, params: [$database->getId()]);
|
||||
}
|
||||
|
||||
$queueForEvents->setParam('databaseId', $database->getId());
|
||||
|
||||
$response
|
||||
->setStatusCode(SwooleResponse::STATUS_CODE_CREATED)
|
||||
->dynamic($database, UtopiaResponse::MODEL_DATABASE);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Platform\Action;
|
||||
|
||||
class Delete extends Action
|
||||
{
|
||||
@@ -68,7 +67,7 @@ class Delete extends Action
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Platform\Action;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
@@ -60,7 +59,7 @@ class Get extends Action
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Appwrite\Platform\Modules\Databases\Http\Databases\Logs;
|
||||
|
||||
use Appwrite\Detector\Detector;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
@@ -23,7 +24,6 @@ use Utopia\Database\Validator\Query\Offset;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Locale\Locale;
|
||||
use Utopia\Platform\Action;
|
||||
|
||||
class XList extends Action
|
||||
{
|
||||
@@ -75,7 +75,7 @@ class XList extends Action
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Appwrite\Platform\Modules\Databases\Http\Databases\Transactions;
|
||||
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -49,7 +50,11 @@ class Create extends Action
|
||||
model: UtopiaResponse::MODEL_TRANSACTION,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createTransaction',
|
||||
)
|
||||
))
|
||||
->param('ttl', APP_DATABASE_TXN_TTL_DEFAULT, new Range(min: APP_DATABASE_TXN_TTL_MIN, max: APP_DATABASE_TXN_TTL_MAX), 'Seconds before the transaction expires.', true)
|
||||
->inject('response')
|
||||
|
||||
@@ -7,6 +7,7 @@ use Appwrite\Event\Publisher\Delete as DeletePublisher;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -48,7 +49,11 @@ class Delete extends Action
|
||||
model: UtopiaResponse::MODEL_NONE,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::NONE
|
||||
contentType: ContentType::NONE,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.deleteTransaction',
|
||||
)
|
||||
))
|
||||
->param('transactionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Transaction ID.', false, ['dbForProject'])
|
||||
->inject('response')
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Appwrite\Platform\Modules\Databases\Http\Databases\Transactions;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
@@ -45,7 +46,11 @@ class Get extends Action
|
||||
model: UtopiaResponse::MODEL_TRANSACTION,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.getTransaction',
|
||||
)
|
||||
))
|
||||
->param('transactionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Transaction ID.', false, ['dbForProject'])
|
||||
->inject('response')
|
||||
|
||||
+7
-2
@@ -7,6 +7,7 @@ use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Transactions\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Database\Documents\User;
|
||||
@@ -56,7 +57,11 @@ class Create extends Action
|
||||
model: UtopiaResponse::MODEL_TRANSACTION,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.createOperations',
|
||||
)
|
||||
))
|
||||
->param('transactionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Transaction ID.', false, ['dbForProject'])
|
||||
->param('operations', [], new ArrayList(new Operation(type: 'legacy')), 'Array of staged operations.', true)
|
||||
@@ -117,7 +122,7 @@ class Create extends Action
|
||||
}
|
||||
|
||||
$database = $databases[$operation['databaseId']] ??= $authorization->skip(fn () => $dbForProject->getDocument('databases', $operation['databaseId']));
|
||||
if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database) || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$operation['databaseId']]);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ use Appwrite\Extend\Exception;
|
||||
use Appwrite\Functions\EventProcessor;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Usage\Context;
|
||||
@@ -65,7 +66,11 @@ class Update extends Action
|
||||
model: UtopiaResponse::MODEL_TRANSACTION,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.updateTransaction',
|
||||
)
|
||||
))
|
||||
->param('transactionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Transaction ID.', false, ['dbForProject'])
|
||||
->param('commit', false, new Boolean(), 'Commit transaction?', true)
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Appwrite\Platform\Modules\Databases\Http\Databases\Transactions;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Database\Validator\Queries\Transactions;
|
||||
@@ -48,7 +49,11 @@ class XList extends Action
|
||||
model: UtopiaResponse::MODEL_TRANSACTION_LIST,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
contentType: ContentType::JSON,
|
||||
deprecated: new Deprecated(
|
||||
since: '1.8.0',
|
||||
replaceWith: 'tablesDB.listTransactions',
|
||||
)
|
||||
))
|
||||
->param('queries', [], new Transactions(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries).', true)
|
||||
->inject('response')
|
||||
|
||||
@@ -13,7 +13,6 @@ use Appwrite\Utopia\Response as UtopiaResponse;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Validator\Boolean;
|
||||
use Utopia\Validator\Text;
|
||||
|
||||
@@ -69,7 +68,7 @@ class Update extends Action
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace Appwrite\Platform\Modules\Databases\Http\Databases\Usage;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\Platform\Modules\Databases\Http\Databases\Action as DatabasesAction;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Deprecated;
|
||||
@@ -20,7 +20,7 @@ use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
|
||||
use Utopia\Platform\Enum;
|
||||
use Utopia\Validator\WhiteList;
|
||||
|
||||
class Get extends Action
|
||||
class Get extends DatabasesAction
|
||||
{
|
||||
public static function getName(): string
|
||||
{
|
||||
@@ -29,7 +29,7 @@ class Get extends Action
|
||||
|
||||
protected $databaseType = DATABASE_TYPE_LEGACY;
|
||||
|
||||
public function setHttpPath(string $path): Action
|
||||
public function setHttpPath(string $path): DatabasesAction
|
||||
{
|
||||
$this->databaseType = match (true) {
|
||||
str_contains($path, '/documentsdb') => DATABASE_TYPE_DOCUMENTSDB,
|
||||
@@ -114,7 +114,7 @@ class Get extends Action
|
||||
{
|
||||
$database = $dbForProject->getDocument('databases', $databaseId);
|
||||
|
||||
if ($database->isEmpty()) {
|
||||
if ($database->isEmpty() || $this->isDatabaseTypeMismatch($database)) {
|
||||
throw new Exception(Exception::DATABASE_NOT_FOUND, params: [$databaseId]);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user