Compare commits

...
Author SHA1 Message Date
Darshan 94c511f39a lint. 2026-03-05 14:03:30 +05:30
Darshan 7d72fd77e5 fix: test. 2026-03-05 13:58:42 +05:30
Darshan 7477b43653 fix: correct tag. 2026-03-05 13:38:14 +05:30
Darshan 569505c54d readd: local source mounts. 2026-03-05 13:21:49 +05:30
DarshanandGitHub e0d2db0c24 Merge pull request #11458 from appwrite/simplify-dev-merge 2026-03-05 13:13:43 +05:30
Darshan dc66be4b2c Merge branch 'feat-installer' into 'simplify-dev'. 2026-03-05 13:12:15 +05:30
Jake Barnby 321528cac0 (refactor): Use Composer autoloading, Installer Platform class, and Utopia param validation 2026-03-04 22:58:55 +13:00
Jake Barnby 00d10e62b5 (feat): Add AppDomain validator for installer input 2026-03-04 22:58:48 +13:00
Jake Barnby cd5f3c3eb3 (chore): Bump base Docker image to 1.0.1 2026-03-04 22:58:43 +13:00
Jake BarnbyandClaude Opus 4.6 34dd5006bb fix: update installer ModuleTest for new Shutdown action
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:04:06 +13:00
Jake Barnby 3cc2375b15 Merge remote-tracking branch 'origin/1.8.x' into feat-installer 2026-03-03 20:57:13 +13:00
Jake Barnby 5ee58dcc81 (fix): Fix installer progress step transitions and redirect handling 2026-03-03 19:47:37 +13:00
Jake Barnby 1dfee199c0 (fix): Fix installer health check, network connect, and shutdown flow 2026-03-03 19:47:29 +13:00
HemachandarandGitHub 598c71fb11 Move VCS events APIs to Modules (#11403)
* Move VCS events APIs to Modules

* trait

* lint

* fix external flow

* fix overriden vars

* feedback
2026-03-03 00:15:09 +05:30
Chirag AggarwalandGitHub 40fc4edb25 Merge pull request #11433 from appwrite/update-sdk-diff-check
chore: improve sdk diff check
2026-03-02 23:43:50 +05:30
Chirag Aggarwal feedd0eb4a improve prompt 2026-03-02 23:30:47 +05:30
Chirag Aggarwal f41c19ed3e improve prompt 2026-03-02 23:26:48 +05:30
Chirag Aggarwal 94bd9661b3 change 2026-03-02 23:24:48 +05:30
Chirag Aggarwal e31843be4b change 2026-03-02 23:20:29 +05:30
Chirag Aggarwal e7424e70aa chore: improve sdk diff check 2026-03-02 23:14:08 +05:30
Jake Barnby 4fda4d4ac3 Fix host access 2026-03-03 00:46:51 +13:00
Jake Barnby 9c7cef2971 Fix pg 18 path 2026-03-03 00:46:38 +13:00
Jake Barnby 029cd695dd Use custom image 2026-03-03 00:46:25 +13:00
Jake BarnbyandGitHub 5dadb9a998 Merge pull request #11430 from appwrite/realtime-tablesdb-prefix 2026-03-02 23:52:02 +13:00
HemachandarandGitHub 164c372b21 Per-project permissions for installations (#11423)
* Per-project permissions for installations

* lint
2026-03-02 16:10:58 +05:30
HemachandarandGitHub cb260fa3d8 Add authorized field to VCS repository model (#11420)
* Add authorized field to VCS repository model

* use new API
2026-03-02 15:48:08 +05:30
ArnabChatterjee20k 05a2f56945 updated tests 2026-03-02 14:27:54 +05:30
Jake Barnby 349bc63618 Trap ctrl+c on start 2026-03-02 21:53:08 +13:00
ArnabChatterjee20k 82a5d138e0 refactor: enhance event handling by ensuring unique events and improving channel merging in Realtime adapter 2026-03-02 14:22:44 +05:30
Jake Barnby dcfc33c65d (chore): Update lock 2026-03-02 21:50:30 +13:00
Jake Barnby 4c76ddc2a3 (fix): Fix installer Swoole migration and database selection 2026-03-02 21:50:25 +13:00
ArnabChatterjee20k 3d4f37c482 refactor: improve channel handling for Realtime events and update tests for TablesDB compatibility 2026-03-02 14:12:13 +05:30
Jake BarnbyandGitHub b03ad6d523 Merge pull request #11392 from appwrite/migration-resource-enum-fix 2026-03-02 20:09:05 +13:00
Jake Barnby f540df50b1 Merge remote-tracking branch 'origin/1.8.x' into feat-installer 2026-03-02 18:40:37 +13:00
Jake Barnby adda327509 Update lock 2026-03-02 18:40:19 +13:00
Prem Palanisamy 5c2b1be581 chore: update sdk-generator to 1.11.3 2026-02-27 09:04:18 +00:00
Prem Palanisamy b3b2fe3ba2 Merge remote-tracking branch 'origin/1.8.x' into migration-resource-enum-fix 2026-02-27 09:01:31 +00:00
Jake BarnbyandGitHub 9667ec2434 Merge pull request #11414 from appwrite/fix-realtime-regions 2026-02-27 08:10:01 +00:00
Jake BarnbyandGitHub 1790f56d99 Merge branch '1.8.x' into feat-installer 2026-02-27 06:07:56 +00:00
Jake BarnbyandGitHub 3c4c78d086 Merge branch '1.8.x' into fix-realtime-regions 2026-02-27 06:07:06 +00:00
Jake BarnbyandGitHub 98aab7b34d Merge pull request #11421 from appwrite/realtime-log-improve 2026-02-27 05:55:13 +00:00
Prem Palanisamy 81e828a200 use named arguments and elvis operator for realtime error logging 2026-02-26 15:45:46 +00:00
Prem Palanisamy 218d25ba1b improve realtime error logging with project, user, and auth context 2026-02-26 15:45:46 +00:00
Eldad A. FuxandGitHub 908a74f69d Merge pull request #11413 from appwrite/fix-users-optional-name-error
Fix users optional name error
2026-02-26 16:23:03 +01:00
Jake BarnbyandClaude Opus 4.6 18d7b12dff fix: capture readExistingCompose result and document shadowed param in Upgrade
- Store readExistingCompose() return value in $data before using it
  (previously $data was undefined on line 60)
- Add comment documenting that CLI database param is intentionally
  overridden by detection from existing configuration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 02:56:55 +13:00
Jake BarnbyandClaude Opus 4.6 118199fd4b fix: revert name/email hashing in analytics payload
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 02:54:06 +13:00
Jake BarnbyandGitHub 8368a28ff5 Merge pull request #10832 from appwrite/cached-documents-list 2026-02-26 12:55:05 +00:00
Jake BarnbyandGitHub abe21d51cb Merge pull request #11418 from appwrite/copilot/sub-pr-11414-again 2026-02-26 12:54:03 +00:00
copilot-swe-agent[bot]andabnegate 339ecc418d test: remove testConnectionFailureRegionMismatch and mock PATCH route
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-26 12:46:47 +00:00
Jake BarnbyandClaude Opus 4.6 7a27cf4ac7 fix: address review feedback for installer PR
- Initialize $isUpgrade=false in Install.php action() to prevent undefined variable
- Assign $this->lockedDatabase in Upgrade.php before calling parent::action()
- Remove stack trace exposure from buildErrorDetails() in Http Install action
- Suppress raw exception messages for 500+ errors in Error handler
- Remove sessionSecret from progress details to prevent credential leak
- Hash name/email in analytics payload to avoid sending raw PII
- Validate and default dbService in compose.phtml to prevent invalid output
- Fix host normalization in progress.js redirect URL builder
- Release global lock on early return for existing installation conflict
- Consolidate duplicate database host/port assignment blocks
- Add @runInSeparateProcess to testRouteRegistration to prevent global state leak

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 01:44:46 +13:00
copilot-swe-agent[bot]andabnegate 5ff7e2af24 fix: revert regions.php, add mock PATCH route for project region in tests
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-26 12:31:05 +00:00
Jake Barnby f8d8997ae3 Update installer 2026-02-27 01:29:38 +13:00
copilot-swe-agent[bot]andabnegate 9aa47c267d test: add region mismatch failure test and fra region to config
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-26 12:14:23 +00:00
Prem Palanisamy 12dca64b60 Merge remote-tracking branch 'origin/1.8.x' into migration-resource-enum-fix 2026-02-26 12:04:16 +00:00
copilot-swe-agent[bot]andabnegate 952f48c72a fix: use AppwriteException, fix console region, add region check test
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-26 11:55:15 +00:00
copilot-swe-agent[bot] 4e80f7eb9a Initial plan 2026-02-26 11:35:32 +00:00
Jake BarnbyandGitHub 9db037722c Merge pull request #11416 from appwrite/copilot/sub-pr-11414 2026-02-26 11:33:44 +00:00
eldadfux ded05ebea2 Merge remote-tracking branch 'origin/1.8.x' into fix-users-optional-name-error 2026-02-26 12:09:12 +01:00
Eldad A. FuxandGitHub a71f3555ae Merge pull request #11412 from appwrite/fix-better-error-for-functions
Fix better error for functions
2026-02-26 12:07:31 +01:00
copilot-swe-agent[bot]andabnegate 4500349fda fix: use 'default' fallback for _APP_REGION in realtime.php
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-26 11:00:09 +00:00
copilot-swe-agent[bot] 611495ec28 Initial plan 2026-02-26 10:50:52 +00:00
Jake Barnby 347436d370 Add region check 2026-02-26 23:37:26 +13:00
Jake BarnbyandGitHub dd925e335b Merge pull request #11411 from appwrite/bump-pools 2026-02-26 10:35:46 +00:00
Chirag AggarwalandGitHub 0e8b5f1d04 Merge pull request #11400 from appwrite/fix-execution-timeout-status
fix: show timed-out executions as failed across API endpoints
2026-02-26 15:43:00 +05:30
Jake BarnbyandClaude Opus 4.6 8dfaf4a9a9 fix: remove unused collectionUpdatedAt from cache key
The schema hash already captures all collection changes, making the
$updatedAt field redundant (and unreliable since Utopia preserves it).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 23:12:38 +13:00
Jake BarnbyandClaude Opus 4.6 d5b2f97252 fix: use md5 hash of attributes/indexes instead of counts in cache key
Counts alone miss delete/re-add scenarios where the count stays the same
but the schema is different. MD5 of the full attribute and index arrays
captures any schema change.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 23:07:24 +13:00
Jake Barnby a7046dbe3c (fix): Replace tab characters with spaces in tests.yml workflow 2026-02-26 22:43:23 +13:00
eldadfux 47a81d165e Fix for user name to accept null and cast as string 2026-02-26 10:30:41 +01:00
eldadfux d7c8b9d43a Better error message when a function fail instead of general_unknown 2026-02-26 10:24:46 +01:00
Jake Barnby 5f58e1da90 (fix): Fix syntax error and lint issues in Upgrade.php 2026-02-26 22:13:46 +13:00
Jake Barnby 7f29baec77 (style): Fix indentation and import ordering lint errors 2026-02-26 22:02:49 +13:00
ArnabChatterjee20k 7562946434 bump pools 2026-02-26 14:29:31 +05:30
Jake Barnby bc992f15fc (chore): Update composer.lock to match composer.json 2026-02-26 21:56:38 +13:00
Jake Barnby 904f94659f (docs): Update web installer docs for Swoole architecture 2026-02-26 21:42:48 +13:00
Jake Barnby 8892e4f30e (test): Add unit tests for installer module, state, and config 2026-02-26 21:42:42 +13:00
Jake Barnby 41948cb337 (refactor): Replace HttpHandler with Utopia Platform module/action pattern and Swoole HTTP server 2026-02-26 21:42:37 +13:00
Jake BarnbyandClaude Opus 4.6 4d19a5e855 fix: include attribute and index counts in document list cache key
The collection $updatedAt is preserved by Utopia Database's updateDocument()
when the value is already set, so it doesn't change when attributes/indexes
are created. Include attribute and index counts in the cache key to ensure
schema changes properly invalidate the document list cache.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 21:10:57 +13:00
Jake BarnbyandClaude Opus 4.6 1c85789a6e fix: scope cache tests to setup document IDs to avoid count mismatch
The testListDocumentsWithCache and testListDocumentsCacheBustedByAttributeChange
tests were failing because testCreateDocument (which runs earlier) adds 3 more
documents to the same movies collection, resulting in 6 docs instead of expected 3.
Additionally, the cache bust test was getting a cache 'hit' instead of 'miss' on
its first request due to sharing the same cache key as the previous test.

Fix by filtering all cache test queries to the 3 known setup document IDs, and
using distinct select/order queries in each test to avoid cache key collisions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 20:34:46 +13:00
HemachandarandGitHub a76a42d2dc Change validation order in delete memberships API (#11410) 2026-02-26 12:25:28 +05:30
eldadfux 79d219bf50 fix cache duplication 2026-02-26 07:50:51 +01:00
eldadfux 9b2143a2a5 Fixed cache duplication 2026-02-26 07:44:35 +01:00
Jake BarnbyandClaude Opus 4.6 b174a50b2a fix: address coderabbit review comments
- Fix indentation alignment in cache hit detection condition
- Add total count assertions for cached and non-cached responses in test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 19:00:25 +13:00
Jake Barnby 26dac3a410 Merge remote-tracking branch 'origin/1.8.x' into feat-installer
# Conflicts:
#	.gitignore
#	composer.lock
#	tests/e2e/Services/Databases/DatabasesBase.php
2026-02-26 18:51:23 +13:00
Jake Barnby 3ecb4ee4e2 Sync 1.8.x 2026-02-26 18:50:29 +13:00
HemachandarandGitHub 76965252d8 Move teams API to Modules (#11358)
* Move teams API to Modules

* lint

* Move team prefs & logs API to Modules (#11359)

* Move team prefs & logs API to Modules

* format

* missin desc

* Move team memberships API to Modules (#11362)

* Move team memberships API to Modules

* fix config dir

* Cloud parity

* params

* Cloud conflicts

* refactor

* prop

* refactor

* set teamId

* feedback

* feedback 2

* fix url-encoding
2026-02-26 11:18:29 +05:30
Jake Barnby 3e0ee30428 Add tests for collection bust 2026-02-26 18:31:52 +13:00
Jake Barnby 0e7c50ef71 Include collection update time in key 2026-02-26 18:26:30 +13:00
Jake Barnby b8ee9fbe2c Update lock 2026-02-26 17:11:51 +13:00
Jake Barnby d49dea9790 Merge remote-tracking branch 'origin/1.8.x' into cached-documents-list
# Conflicts:
#	composer.lock
#	tests/e2e/Services/Databases/DatabasesBase.php
2026-02-26 17:02:33 +13:00
Chirag Aggarwal 8891890601 fix: show timed-out executions as failed across API endpoints
Executions that time out can remain stuck in waiting or processing status
in the database. This mirrors the frontend workaround from console#2788
across the relevant API endpoints for both functions and sites.

Changes:
- GET execution/log: override status to failed in response if elapsed time
  since creation exceeds the resource timeout
- LIST executions/logs: same in-response override; when caller filters by
  failed, expands DB query with OR to also fetch waiting/processing entries
  created before the timeout threshold so they appear in results; skips
  in-response override when caller explicitly requests a non-failed status
  to avoid contradicting the filter
- DELETE execution: allows deletion of timed-out executions that are still
  stored as waiting/processing by treating them as failed for the status guard

All changes are in-memory only — the database records are not modified.
Includes a note to remove once a proper DB-level fix is applied.
2026-02-26 09:22:33 +05:30
Jake BarnbyandGitHub 0272a7f337 Merge pull request #11404 from appwrite/realtime-channels-tablesdb-fix 2026-02-26 03:43:50 +00:00
Jake BarnbyandGitHub 52d5ae50d9 Merge pull request #11405 from appwrite/patch-text-types-return 2026-02-26 03:33:52 +00:00
premtsd-codeandGitHub db85004b12 Merge branch '1.8.x' into migration-resource-enum-fix 2026-02-25 23:16:52 +00:00
eldadfux b7e4f78c56 fix 2026-02-26 00:00:10 +01:00
eldadfux 159da8ba31 Fix 500 errors where we don't report duplication properly 2026-02-25 23:58:22 +01:00
HemachandarandGitHub cfddef3706 Upgrade utopia-php/vcs (#11401)
* Upgrade `utopia-php/vcs`

* fix

* bump
2026-02-25 19:54:04 +05:30
ArnabChatterjee20k ca8d613614 updated test 2026-02-25 19:46:09 +05:30
ArnabChatterjee20k 8c579cf88d updated string filtering in the filters 2026-02-25 19:29:03 +05:30
ArnabChatterjee20k a57d970840 Add support for tablesdb in event generation and realtime channels 2026-02-25 18:58:33 +05:30
Prem Palanisamy 88ce622e4a chore: update utopia-php/migration to 1.6.2 2026-02-25 12:06:12 +00:00
premtsd-codeandGitHub c041e57b8f Merge branch '1.8.x' into migration-resource-enum-fix 2026-02-25 11:57:48 +00:00
Atharva DeosthaleandGitHub 5d6e43e01b Merge pull request #11371 from appwrite/add-cursor-plugin 2026-02-25 17:11:20 +05:30
Prem Palanisamy 4a0f00f7db chore: update utopia-migration to 134efdc 2026-02-25 11:35:07 +00:00
premtsd-codeandGitHub de21cab22a Merge branch '1.8.x' into migration-resource-enum-fix 2026-02-25 10:28:28 +00:00
Prem Palanisamy f8929e1f2e fix: use utopia-migration dev branch with deployment download fixes 2026-02-25 10:25:05 +00:00
Atharva Deosthale c1e2d4593d Merge remote-tracking branch 'origin/1.8.x' into add-cursor-plugin
# Conflicts:
#	composer.lock
2026-02-25 15:41:05 +05:30
Jake BarnbyandGitHub 32ef15f89a Merge pull request #11398 from appwrite/fix-cast 2026-02-25 09:58:35 +00:00
Jake Barnby 7dc50b43dc Fix method 2026-02-25 22:20:52 +13:00
Jake Barnby a43e94990b Lint 2026-02-25 21:49:31 +13:00
Jake Barnby c91252d94c Switch types 2026-02-25 21:42:28 +13:00
Damodar LohaniandGitHub b4a32c8265 Merge pull request #11397 from appwrite/revert-11387-feat-update-project-usage
Revert "Fix: add missing sites bandwidth to project usage"
2026-02-25 13:35:55 +05:45
Jake Barnby 62d03199b6 Force ID as int 2026-02-25 20:44:44 +13:00
Damodar LohaniandGitHub 244606ff1d Revert "Fix: add missing sites bandwidth to project usage" 2026-02-25 12:56:05 +05:45
Prem Palanisamy 754ddbef3c fix: remove deployment from MigrationReport model 2026-02-25 06:47:08 +00:00
Prem Palanisamy ed93b77faa fix: remove strict WhiteList for Appwrite migration endpoints 2026-02-25 06:44:42 +00:00
Prem Palanisamy 5a6cfdbe4c fix: revert composer to 1.8.x and remove child resource counts from MigrationReport 2026-02-25 06:42:46 +00:00
Atharva Deosthale 9ee6304513 format 2026-02-25 10:35:32 +05:30
Atharva Deosthale ff4e756958 Merge remote-tracking branch 'origin/1.8.x' into add-cursor-plugin
# Conflicts:
#	composer.lock
#	src/Appwrite/Platform/Tasks/SDKs.php
2026-02-25 10:32:51 +05:30
Atharva Deosthale 19df20de61 composer 2026-02-25 10:18:37 +05:30
Prem Palanisamy 6b90d00cc2 fix: update utopia-migration lock to include strtolower removal 2026-02-25 00:24:16 +00:00
Prem Palanisamy 3ba5e12f89 fix: add deployment and environmentVariable to MigrationReport model 2026-02-24 23:19:21 +00:00
Prem Palanisamy dc441c3973 fix: enable strict mode for Appwrite migration resource WhiteList 2026-02-24 22:44:57 +00:00
Prem Palanisamy 9745df4d37 fix: update utopia-migration to camelCase resource types 2026-02-24 22:30:32 +00:00
Prem Palanisamy 715adf62ca fix: update utopia-migration to snake_case resource types 2026-02-24 15:54:42 +00:00
Prem Palanisamy 90ab70dfc6 fix: use dev branch of utopia-php/migration for site camelCase fix 2026-02-24 15:54:42 +00:00
Prem Palanisamy b0c5185ebd feat: add site migration 2026-02-24 15:54:42 +00:00
Prem Palanisamy d58873ef14 added site migration E2E test 2026-02-24 15:54:42 +00:00
Prem Palanisamy 105c885c3f added site migration 2026-02-24 15:54:42 +00:00
Prem Palanisamy ad625029e8 feat: add migration resource enums to SDK specification 2026-02-24 15:54:42 +00:00
Eldad A. FuxandGitHub ac0aa81629 Merge pull request #11378 from appwrite/fix-missing-email-warning
OAuth provider handling fix
2026-02-24 14:36:09 +01:00
Eldad A. FuxandGitHub 0c83fa40e4 Merge pull request #11380 from appwrite/feat-fix-email-key
Feat fix for missing null safety on console redirects
2026-02-24 14:35:50 +01:00
Eldad A. FuxandGitHub f832b96e3b Merge pull request #11384 from appwrite/fix-proper-error-namespace-and-method
Update composer.lock and enhance error logging in HTTP requests
2026-02-24 14:30:47 +01:00
eldadfux 2b5307715a Merge remote 1.8.x
Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	composer.lock
2026-02-24 14:25:56 +01:00
Jake BarnbyandGitHub aa7dfd0bd1 Merge pull request #11312 from appwrite/feat-mongodb 2026-02-24 09:32:22 +00:00
Jake Barnby aeaa184aec Use auth roles 2026-02-24 22:12:20 +13:00
Jake BarnbyandGitHub 9dd707cd1b Merge branch '1.8.x' into cached-documents-list 2026-02-24 09:04:32 +00:00
Jake BarnbyandClaude Opus 4.6 8dfc4abfe0 fix: cache DatabasesStringTypesTest setup before waiting
Same cache-before-wait pattern as DatabasesBase to prevent
cascading 409 failures when attribute polling times out.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 20:47:56 +13:00
Damodar LohaniandGitHub b3f7256156 Merge pull request #11387 from appwrite/feat-update-project-usage
Fix: add missing sites bandwidth to project usage
2026-02-24 12:51:39 +05:45
Jake BarnbyandClaude Opus 4.6 3b3177722b fix: cache setup data before waiting to prevent 409 on retry
When setupAttributes() or setupIndexes() timed out during
waitForAllAttributes/waitForAllIndexes, the cache was never populated.
Subsequent test methods calling setup again would find empty cache,
reuse the same collection IDs (from collection cache), and attempt to
re-create existing attributes/indexes, resulting in 409 Conflict errors.

Fix: populate the static cache immediately after successful creation
(202 assertions), before the wait calls. This ensures retries skip
creation and go straight to waiting.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 20:06:20 +13:00
Damodar Lohani 2898d57243 Fix: Add missing sites bandwidth in the project usage 2026-02-24 06:26:52 +00:00
Jake BarnbyandClaude Opus 4.6 3306a03e8e chore: add 5-minute retry wait to reduce CI resource contention
With 120+ jobs starting simultaneously, transient failures are common
due to resource contention. Adding retry_wait_seconds: 300 to all
php-retry action usages gives the CI environment time to settle
before retrying failed tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 19:07:42 +13:00
Jake BarnbyandClaude Opus 4.6 e1791e17c3 fix: increase attribute/index polling timeouts to 240s for shared mode CI
Shared tables mode experiences significant worker queue contention during
parallel test execution. 120s was insufficient for attribute processing
in Shared V1 mode and occasionally for PostgreSQL under load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 17:50:46 +13:00
Jake BarnbyandClaude Opus 4.6 e69c1ddc7f fix: add executor readiness check to Site Screenshots CI jobs
The Site Screenshots CI jobs were missing the "Wait for Open Runtimes"
step that other E2E test jobs have, causing deployments to fail with
"Failed to connect to exc1 port 80" when the executor wasn't ready yet.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 17:37:15 +13:00
Jake BarnbyandClaude Opus 4.6 9a97694a19 fix: resolve flaky E2E tests for realtime, avatars, migrations, and GraphQL
- Realtime: Use getLastEmailByAddress with userId probe instead of getLastEmail
  to prevent email race conditions in parallel execution; add status assertions
  on verification/recovery PUT responses for clearer failure diagnostics
- Avatars: Wrap external URL image fetches in assertEventually to retry
  transient network failures from appwrite.io
- Migrations: Increase performMigrationSync timeout from 10s to 60s
- GraphQL: Increase attribute polling timeouts from 60s to 120s with 500ms
  intervals to accommodate PostgreSQL under CI load

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 16:51:22 +13:00
Jake BarnbyandClaude Opus 4.6 7df86a3838 fix: cast attribute defaults after queue deserialization and improve test robustness
- Fix float/int/bool attribute creation failures caused by type loss
  during queue serialization in the Databases worker
- Rework session limit test to retry session creation for cache
  propagation in shared mode
- Increase GraphQL attribute polling timeouts from 30s to 60s
- Increase SchemaPolling waitForAllAttributes timeout to 180s
- Increase Realtime WebSocket client timeout from 30s to 45s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 16:02:23 +13:00
Jake BarnbyandClaude Opus 4.6 07dc088e4e fix: improve E2E test probes and enable function webhook events
- Fix testPasswordRecoveryUrlParams: use URL-based probes instead of
  userId-based probes to distinguish between test cases that share the
  same user
- Enable functions.* webhook events in ProjectCustom for function
  webhook tests that were silently passing by matching stale events
- Fix setupTeamMembership: add email address probe to getLastEmail to
  prevent picking up wrong invitation email
- Fix getLastEmail multi-email race: assert count inside assertEventually
  when requesting multiple emails

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 15:15:59 +13:00
Jake BarnbyandClaude Opus 4.6 5cb36a0a3a fix: resolve E2E test race conditions in parallel execution
- Add probe callback support to getLastEmail(), getLastEmailByAddress(),
  and getLastRequest() to filter results by content before accepting
- Fix variable name typo in TeamsCustomClientTest ($email vs $lastEmail)
- Add event probes to all 56 webhook test getLastRequest() calls to
  filter by specific event pattern (resource ID + action)
- Add email probes to Account OTP/recovery/magic-url tests to wait for
  the correct email (security phrase, Password Reset subject, etc.)
- Add email probes to Projects tests for recovery email URL matching
- Increase FunctionsSchedule future time from 1min to 2min to avoid
  timing issues when seconds are zeroed

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 14:43:15 +13:00
Jake Barnby 811a759a8f Update lock 2026-02-24 14:14:14 +13:00
Jake Barnby 1c457c3a80 Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2026-02-24 14:07:14 +13:00
Jake Barnby 1cb7c4b3f6 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	.gitignore
#	composer.lock
#	tests/e2e/Services/Teams/TeamsCustomClientTest.php
2026-02-24 14:06:57 +13:00
Jake Barnby bada1a7c05 Timing updates 2026-02-24 14:00:07 +13:00
Luke B. SilverandGitHub 850b35d73c Merge pull request #11385 from appwrite/fix/missing-span-import
hotfix/ incorrect span import
2026-02-23 23:35:55 +00:00
eldadfux fb8a1057af Update composer.lock 2026-02-23 19:47:22 +01:00
eldadfux ae4c02221f Merge remote 1.8.x
Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	composer.lock
2026-02-23 19:46:48 +01:00
eldadfux 3b1b7bd611 Update composer.lock and enhance error logging in HTTP requests
- Updated versions for several dependencies in composer.lock, including utopia-php/database (5.3.3), utopia-php/detector (0.2.4), utopia-php/dns (1.6.5), utopia-php/framework (0.33.40), utopia-php/queue (0.15.6), and utopia-php/storage (1.0.1).
- Improved error logging in app/http.php and app/controllers/general.php to handle null routes gracefully, ensuring that the HTTP method and request URI are logged correctly even when the route is not defined.
2026-02-23 19:35:52 +01:00
Jake BarnbyandGitHub e92b80b3cb Merge branch '1.8.x' into feat-mongodb 2026-02-24 02:53:40 +13:00
Jake BarnbyandClaude Opus 4.6 95c67ea155 fix: resolve merge conflict markers in composer.lock
The merge of 1.8.x into feat-mongodb left unresolved conflict markers
in composer.lock, breaking all CI checks. Resolved in favor of
feat-mongodb values (minimum-stability: dev, prefer-stable: true)
to match composer.json.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 22:17:55 +13:00
Jake BarnbyandGitHub 0019f01492 Merge branch '1.8.x' into feat-mongodb 2026-02-23 21:21:26 +13:00
eldadfux 9cabe15219 Fix for console redirect warning 2026-02-22 20:38:42 +01:00
eldadfux addba2cdb7 Refactor OAuth provider checks in account controller
Updated the handling of OAuth provider configurations to ensure that defaults are set when parameters are missing. This change improves error handling by checking for null values and ensuring class existence before proceeding with OAuth operations.
2026-02-22 11:42:12 +01:00
Jake BarnbyandClaude Opus 4.6 f2759cb65a fix: remove file caching, disable --functional for Databases/Functions/Realtime
Services that depend on shared static state between test methods
(Databases, Functions, Realtime) now run without --functional flag,
so test methods execute sequentially within each class while classes
still run in parallel. All other services keep --functional mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 03:44:28 +13:00
Jake BarnbyandClaude Opus 4.6 32c84ae869 fix: retry on TCP connection errors in callWithAuthRetry for Functions tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 03:29:31 +13:00
Jake BarnbyandClaude Opus 4.6 48698f40ba fix: add polling and delay for testSSRLogs logging config propagation
After setting logging=false, the site runtime may not immediately pick up
the config change. Add a 5s delay and poll for the NEW log entry (filtering
out the old one by $id) to avoid picking up stale log entries with content.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 03:12:44 +13:00
Jake BarnbyandClaude Opus 4.6 8d18a33072 fix: call ensureSharedProject() in all setup methods, not just setupDatabase
When setupAttributes/setupIndexes/etc hit the file cache, they return
immediately without calling setupDatabase(), so ensureSharedProject()
was never called. This left self::$project empty, causing getProject()
to create a new project that didn't match the cached database IDs (404s).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 03:11:50 +13:00
Jake BarnbyandClaude Opus 4.6 a0b8437f08 fix: scope file caching to Database tests only, revert for non-Database tests
The previous file caching approach cached getRoot(), getUser(), getProject(),
and getConsoleVariables() globally. This caused all test methods in a class
to share the same project, breaking non-Database tests that expect isolated
state (Account 401s, Storage 500s, Users 404s, etc.).

Now file caching is only applied in Database/Transaction test setup chains:
- ensureSharedProject() in DatabasesBase, TransactionsBase, TransactionPermissionsBase
  creates and file-caches both the project AND user so all methods share
  consistent project + user state (needed for collection permissions)
- Non-Database tests (Account, Storage, Users, etc.) create their own
  isolated projects per-process as before

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 02:46:56 +13:00
Jake BarnbyandClaude Opus 4.6 3ea1e8e59f fix: add file-based cross-process caching for ParaTest --functional mode
With --functional mode, each test method runs in its own process so
static caches are empty. This causes every method to recreate projects,
databases, collections, attributes, and indexes - flooding the serial
database worker queue and causing attribute polling timeouts.

File-based caching with file locks ensures resources are created once
per test class, then shared across all method processes. This restores
--functional mode and dramatically reduces worker queue load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 01:47:20 +13:00
Chirag Aggarwal 7737139f23 composer 2026-02-20 17:59:33 +05:30
Atharva Deosthale a803bafbb8 feat: add cursor-plugin SDK support 2026-02-20 17:54:50 +05:30
Jake BarnbyandClaude Opus 4.6 8be633a140 fix: remove --functional from paratest to use class-level parallelism
With --functional mode, every test method gets its own process with no
static cache sharing. This causes each method to independently create
databases, collections, and attributes, flooding the serial database
worker queue. Without --functional, each test class shares static caches
between methods, dramatically reducing schema operation count.

Also reverts _APP_WORKERS_NUM change since worker must remain serial.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 00:38:39 +13:00
Jake BarnbyandClaude Opus 4.6 31f4260908 fix: increase database worker count and test resilience for parallel execution
Parallel test execution via ParaTest creates more queue load than a single
database worker can handle, causing attributes to get stuck at 'processing'.
Increase _APP_WORKERS_NUM to 4 to match parallelism, increase WebSocket
timeout from 15s to 30s, and add retry logic for proxy requests in Sites tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 00:16:40 +13:00
Jake BarnbyandClaude Opus 4.6 818c89fe23 fix: increase site deployment build and activation polling timeouts
Build timeout: 120s → 240s
Activation timeout: 60s → 120s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 22:37:41 +13:00
Jake BarnbyandClaude Opus 4.6 58bf529183 fix: make testGetAccountLogs flexible for 1 or 2 audit logs
The user.create audit may or may not be present depending on async
audit processing timing. Accept either count and adjust offset/limit
assertions accordingly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 21:28:09 +13:00
Jake BarnbyandClaude Opus 4.6 abdceb831a fix: resolve E2E test failures for screenshots, account logs, risky tests, and deployment timeouts
- Accept 404 alongside 200 for screenshot tests with custom headers/permissions (browser service CI limitation)
- Fix testGetAccountLogs to expect 1 log (session.create only, user.create audit not triggered for self-service)
- Move getSupportForOperators() check before any assertions in testOperators/testBulkOperators (PHPUnit 12 risky test fix)
- Increase deployment build/activation polling timeout from 240s to 360s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 20:43:51 +13:00
Jake BarnbyandClaude Opus 4.6 b976454416 fix: add early failure detection and increase polling timeouts
Throw Critical exception when attribute/index/deployment status is
'failed' to fail tests immediately instead of waiting 15-20 minutes.
Increase default schema polling timeouts from 15 to 20 minutes for
CI stability under parallel load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 19:51:59 +13:00
Jake BarnbyandClaude Opus 4.6 b7d503e8e9 fix: resolve MariaDB spatial attribute and index creation failures
- Replace findOne()->isEmpty() with count() > 0 in spatial check to avoid
  potential false positives when checking for existing data in empty collections
- Use waitForAllAttributes instead of waitForAttribute before spatial index
  creation to ensure the collection document cache is refreshed
- Add response assertions for attribute creation in testSpatialPolygonAttributes
  to fail fast instead of timing out for 15 minutes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 18:53:50 +13:00
Jake BarnbyandClaude Opus 4.6 168f9828bc fix: make activate param optional in site deployments
The activate param in Deployments/Create was missing the optional flag,
making it required unlike the VCS and Template deployment endpoints.
This caused 400 errors for multipart/form-data requests where the param
was present but treated as missing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 17:40:31 +13:00
Jake BarnbyandClaude Opus 4.6 89f0f227d6 fix: resolve CI failures in database, functions, and realtime tests
- Increase SchemaPolling default timeouts from 8min to 15min for
  waitForAttribute, waitForAttributes, waitForAttributeCount, and
  waitForIndex to match waitForAllAttributes/waitForAllIndexes. Under
  parallel test load the database worker gets backlogged, causing
  attributes to stay in 'processing' state longer than 8 minutes.
- Add isEmpty check in Functions Delete before updating schedules to
  prevent 500 errors when the schedule document is missing (consistent
  with other modules like Executions/Delete).
- Add retry logic to cleanupFunction in FunctionsBase for transient
  MongoDB transaction abort errors during function deletion.
- Increase Realtime attribute/index polling timeouts from 2min to 15min
  to handle worker backlog under CI load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 17:22:51 +13:00
Jake BarnbyandClaude Opus 4.6 0b7c8865f5 fix: increase E2E test timeout from 30 to 40 minutes
Database tests (PostgreSQL, Shared V1, Shared V2) consistently take
31-32 minutes, just exceeding the 30-minute timeout. Increase to 40
minutes for all E2E service tests to prevent false timeout failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 04:19:44 +13:00
Jake BarnbyandClaude Opus 4.6 a952dad8d3 fix: add missing Role import and convert @group to PHP 8 attributes
- Add missing `use Utopia\Database\Helpers\Role` import in ProjectsBase.php
  (fixes "Class Role not found" fatal error)
- Convert @group ciIgnore docblock annotations to #[Group('ciIgnore')]
  PHP 8 attributes (PHPUnit 12 no longer supports docblock annotations)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 03:26:15 +13:00
Jake BarnbyandClaude Opus 4.6 2a535a2adc fix: exclude ciIgnore tests from CI and increase Realtime polling timeouts
- Add --exclude-group ciIgnore to paratest commands in tests.yml
  (the @group ciIgnore annotation was defined but never excluded)
- Increase attribute/index polling timeouts in RealtimeConsoleClientTest
  from 15s to 120s for Shared V2 stability

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 03:10:56 +13:00
Jake BarnbyandClaude Opus 4.6 b645721e14 fix: resolve CI failures from 1.8.x merge
- Remove unused WhiteList import in teams.php (linter fix)
- Add missing $teamId and $newTeam params to setupProject() in ProjectsBase.php (fixes 401 errors in all Projects tests)
- Filter execution logs by requestPath in testSSRLogs to avoid picking up screenshot worker executions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 02:46:23 +13:00
Jake BarnbyandGitHub 8a6ddeef30 Merge branch '1.8.x' into feat-mongodb 2026-02-20 01:33:02 +13:00
Jake BarnbyandClaude Opus 4.6 8a391e2e27 fix: mark transactionId as required param in transaction endpoints
Path parameters should not be optional. This caused SDK TypeScript
build failures where transactionId was typed as string | undefined.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 00:36:41 +13:00
Jake BarnbyandClaude Opus 4.6 c2e4ddc177 fix: bump utopia-php/database to 5.3.2
Includes fix for empty orderAsc() attribute mapping in MongoDB adapter
that caused subQueryVariables filter to hang and crash the service.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 16:05:47 +13:00
Jake BarnbyandClaude Opus 4.6 ce0b7ab455 fix: increase function deployment build timeout to 4 minutes
FunctionsBase deployment polling was only 100 seconds, insufficient
under CI load when build workers are busy. Increased to 240 seconds
for both deployment readiness and activation checks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 06:10:18 +13:00
Jake BarnbyandClaude Opus 4.6 c1cb7bdc8e fix: increase schema polling timeouts to 15 minutes
Spatial attribute creation under parallel CI load consistently exceeds
10 minutes. Increased both waitForAllAttributes and waitForAllIndexes
from 10/8 minutes to 15 minutes to accommodate heavy parallel load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 05:12:09 +13:00
Jake BarnbyandClaude Opus 4.6 54505c0600 fix: increase polling timeouts for CI stability
Spatial attribute creation under parallel MariaDB load and function
deployment builds under MongoDB can exceed previous limits. Increased
SchemaPolling timeout from 8 to 10 minutes and GraphQL function build
timeout from 2 to 4 minutes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 04:21:49 +13:00
Jake BarnbyandClaude Opus 4.6 e26bac1e6e fix: resolve merge conflicts in projects.php template endpoints
Merge from 1.8.x left 6 unresolved conflicts in SMS/email template
endpoints. Resolved by keeping both the dynamic UID validator from
feat-mongodb and the strict WhiteList comparison from 1.8.x.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 03:41:36 +13:00
Jake BarnbyandClaude Opus 4.6 f8e29c6b38 fix: prevent testTimeout from deleting shared database
testTimeout was using setupDatabase() to get the shared database, creating
a collection within it, then deleting the entire database at cleanup. This
destroyed the shared Movies/Actors/Books collections, causing testNotSearch
and other tests relying on the shared database to fail with 404.

Fix: only delete the test collection, not the shared database. Also add
waitForAttribute to prevent intermittent failures from attribute not being
available when inserting documents.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 02:37:06 +13:00
Jake BarnbyandGitHub 3bf594ecae Merge branch '1.8.x' into feat-mongodb 2026-02-18 12:09:43 +00:00
Jake BarnbyandClaude Opus 4.6 fa972093f4 fix: front-load fulltext search infrastructure into cached setup chain
Move the Books collection, attributes, and fulltext index creation into
the shared setupCollection/setupAttributes/setupIndexes cache chain so
they are processed early when the worker queue is less loaded. This
eliminates testNotSearch creating redundant infrastructure from scratch
at test time when the queue is overwhelmed with 830+ parallel tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 23:26:03 +13:00
Jake BarnbyandClaude Opus 4.6 ddb392caf7 fix: increase SchemaPolling default timeouts from 4min to 8min
MariaDB attribute/index processing consistently times out under parallel
test load in CI with different tests failing each run. Increase all default
polling timeouts from 240s to 480s to handle worst-case MariaDB load.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 23:18:56 +13:00
Jake BarnbyandClaude Opus 4.6 dca375624c fix: add missing 202 assertions before schema polling waits
- Fix testSpatialDistanceInMeter: move assertEquals(202) BEFORE waitForIndex
  (was after, causing misleading 4-minute timeout on creation failure)
- Add 202 assertions to testSpatialAttributesMixedCollection attribute creation
- Add 202 assertion to testConcurrentTransactionConflicts attribute creation
- Add 202 assertion to fulltext search index creation
- Add 202 assertion to shared collection attribute creation

These ensure tests fail fast with clear errors if schema creation returns
an error, instead of pointlessly polling for 4 minutes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 22:58:05 +13:00
Jake Barnby 3e0febca92 Revert "fix: increase SchemaPolling default timeouts from 4min to 6min"
This reverts commit 2a4c33be11.
2026-02-18 22:49:31 +13:00
Jake BarnbyandClaude Opus 4.6 2a4c33be11 fix: increase SchemaPolling default timeouts from 4min to 6min
MariaDB attribute/index processing consistently times out under parallel
test load in CI. Increase all default polling timeouts from 240s to 360s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 22:39:07 +13:00
Jake BarnbyandClaude Opus 4.6 6582ec8e67 fix: register TYPE_ID in GraphQL Mapper and fix Schedules tests for ParaTest
- Add 'id' => Type::string() to GraphQL Mapper Registry defaults to handle
  Model::TYPE_ID used by Document and Row models ($sequence field)
- Refactor SchedulesConsoleClientTest to use static-cached setup helpers
  instead of @depends annotations, which don't work in ParaTest --functional mode

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 21:59:33 +13:00
Jake Barnby 2c5806d1e7 Revert "fix: revert accidentally committed working tree changes"
This reverts commit a3503f4124.

# Conflicts:
#	composer.lock
2026-02-18 21:45:54 +13:00
Jake Barnby 43f7c99039 Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2026-02-18 21:44:48 +13:00
Jake Barnby c584a72496 Update lock 2026-02-18 21:44:32 +13:00
Jake BarnbyandGitHub ce64011551 Merge branch '1.8.x' into feat-mongodb 2026-02-18 08:42:56 +00:00
Jake BarnbyandClaude Opus 4.6 a3503f4124 fix: revert accidentally committed working tree changes
Reverts composer.lock (database 5.3.0→5.2.1), Model.php TYPE_ID,
Document.php/Row.php $sequence type changes, and OpenAPI/Swagger
id type additions that were unintentionally included in dd1a3d82.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 20:58:54 +13:00
Jake BarnbyandClaude Opus 4.6 0d1a6e07b4 fix: use relative path for --log-junit so retry action can find JUnit XML
The retry action couldn't extract the container name from docker compose
exec commands to copy the JUnit XML. Using a relative path works because
CWD inside the container is /usr/src/code and the volume mount
./tests:/usr/src/code/tests makes the file accessible at the same
relative path on both container and host.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 20:30:48 +13:00
Jake BarnbyandClaude Opus 4.6 dd1a3d8222 fix: adjust testCreateIndexes index count for MongoDB maxIndexLength=1024
MongoDB's maxIndexLength (1024) allows the 512+512 index to succeed,
resulting in 5 indexes instead of 4. Use conditional count and
assertContains for position-independent key checks.

Verified: 830/830 Database tests pass locally on MongoDB with paratest.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 19:59:20 +13:00
Jake BarnbyandClaude Opus 4.6 93bc3871df fix: MongoDB test compatibility and enable JUnit XML for paratest retry
- testCreateIndexes: conditionally check index length based on adapter's maxIndexLength (MongoDB 1024 vs SQL 768)
- testConcurrentTransactionConflicts: accept both 409 and 500 since MongoDB adapter doesn't map write conflicts to ConflictException
- testEnforceCollectionPermissions: add error body to assertion for debugging
- Enable --log-junit for paratest in both project and shared mode CI jobs so itznotabug/php-retry@v3 can identify and selectively retry failing tests

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 19:09:01 +13:00
Jake BarnbyandClaude Opus 4.6 ca01ec7b6b fix: increase SchemaPolling default timeout to 240s for CI stability
120s was insufficient for attribute processing under parallel CI load,
causing spurious timeout failures in spatial, transaction, and attribute tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 16:28:24 +13:00
Jake BarnbyandClaude Opus 4.6 d6d12d818c fix: use getContainerIdResponseKey() instead of hardcoded $collectionId in upsert test
TablesDB uses $tableId not $collectionId in data payloads.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 16:03:46 +13:00
Jake BarnbyandClaude Opus 4.6 442a8d86d6 fix: use getRecordResource() instead of hardcoded 'documents' in testUpsertDocument
TablesDB uses 'rows' not 'documents' for the list records response key.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:44:41 +13:00
Jake BarnbyandClaude Opus 4.6 84c40cea41 fix: resolve testCreateAttributes, testUpsertDocument, and SchemaPolling timeouts
- Fix testCreateAttributes: use $actorsAttr instead of undefined $actors variable,
  and use $this->getSchemaResource() instead of hardcoded 'attributes' for TablesDB compat
- Fix testUpsertDocument: add missing 'data' => $upsertData in PUT request body
- Increase SchemaPolling default timeout from 60s to 120s for CI stability with
  spatial attributes under parallel load

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:25:45 +13:00
Jake BarnbyandClaude Opus 4.6 9796c46975 fix: misplaced assertion in testUpdateAttributeEnum and reduce timeouts
- Move maxLength/assertStringContainsString from testUpdateAttributeEnum
  back to testPatchAttribute where $attribute is defined
- Fix remaining $data['moviesId'] -> $moviesId in testCreateAttributes
- Reduce WebSocket timeout from 30s to 15s for faster failure detection
- Reduce Realtime helper assertEventually from 30s to 15s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:07:05 +13:00
Jake BarnbyandClaude Opus 4.6 ae4e79518b fix: remaining testCreateAttributes undefined variable references
- Change $data['moviesId'] to $moviesId at integers2 attribute creation
- Change $data['actorsId'] to $actorsId at relationship assertion

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:59:25 +13:00
Jake BarnbyandClaude Opus 4.6 2c1919140f fix: resolve additional test failures from CI results
DatabasesBase:
- testCreateAttributes: use local $moviesId/$actorsId instead of $data['...']
- testValidateOperators: add missing setupOneToManyRelationship() call
- testSelectQueries: add missing setupOneToManyRelationship() call
- testUniqueIndexDuplicate: define missing $serverHeaders variable
- testListDocuments: change return type from array to void (no callers)

RealtimeConsoleClientTest:
- testAttributesCollectionsAPI: create database/collection before opening
  WebSocket to prevent their events from interfering with attribute events
- testAttributesTablesAPI: same restructuring for TablesDB variant

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:42:41 +13:00
Jake BarnbyandClaude Opus 4.6 acad17f3b8 fix: resolve test failures and reduce excessive timeouts
- DatabasesBase: fix 5 merge corruption issues (missing integers2 attr,
  undefined vars, wrong assertion, wrong setup method)
- WebhooksBase: increase deployment build timeout from 10s to 120s
- RealtimeBase: reduce WebSocket timeout 120s→30s, fix deprecated nullable
- RealtimeConsoleClientTest: reduce assertEventually 120s→30s
- SchemaPolling: reduce all default timeouts 600s→60s
- SitesBase: reduce build timeout 300s→120s, activation 200s→60s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:23:42 +13:00
Jake BarnbyandClaude Opus 4.6 a70e94a67b fix: resolve merge corruption in tests.yml workflow
The e2e_service_test job's command block had corrupted shell syntax from
a bad merge - orphaned elif/else without matching if, and duplicate
if-elif blocks for DB adapter env vars. The set-db-env step already sets
these via GITHUB_ENV, making the inline exports redundant.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 13:41:08 +13:00
Jake Barnby ec9cb430af CI 2026-02-18 13:34:50 +13:00
Jake BarnbyandClaude Opus 4.6 9e628072eb fix: resolve additional merge corruptions in test files
- DatabasesBase.php: fix array indentation for 'library' key inside 'data' array
- SitesBase.php: fix corrupted while-loop/assertEventually merge in
  activation check
- DatabasesStringTypesTest.php: remove return $data from void methods,
  convert @depends chain to use setupDatabaseAndCollection()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 04:11:37 +13:00
Jake BarnbyandClaude Opus 4.6 6c29f4e285 fix: resolve merge corruptions in DatabasesBase.php from feat-db-tests merge
- Replace all hardcoded Legacy-style URLs with API-agnostic helpers
  (getContainerUrl, getSchemaUrl, getRecordUrl, getIndexUrl)
- Replace hardcoded param keys (collectionId, documentSecurity,
  relatedCollectionId, attributes) with helper methods
- Replace hardcoded response keys ($collectionId, relatedCollection)
  with getContainerIdResponseKey() and getRelatedResourceKey()
- Fix structural merge corruptions where code from different methods
  got interleaved (testCreateAttributes, testCreateIndexes,
  testGetDocumentWithQueries, testOperators, testUniqueIndexDuplicate)
- Remove orphaned code fragments and stale return statements
- Fix void methods incorrectly returning $data
- Add proper setup calls in relationship test methods
- Update composer.lock to match composer.json

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 03:55:39 +13:00
Jake Barnby 64a368ba3d Merge remote-tracking branch 'origin/feat-db-tests' into feat-mongodb
# Conflicts:
#	.github/workflows/tests.yml
#	src/Appwrite/Utopia/Response.php
#	src/Appwrite/Utopia/Response/Model/AttributeList.php
#	tests/e2e/Client.php
#	tests/e2e/Scopes/ProjectCustom.php
#	tests/e2e/Services/Databases/DatabasesBase.php
#	tests/e2e/Services/Databases/Legacy/DatabasesCustomClientTest.php
#	tests/e2e/Services/Databases/Legacy/DatabasesCustomServerTest.php
#	tests/e2e/Services/Databases/Legacy/DatabasesStringTypesTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomClientTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomServerTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesStringTypesTest.php
#	tests/e2e/Services/Databases/Transactions/TransactionsBase.php
#	tests/e2e/Services/GraphQL/Legacy/DatabaseServerTest.php
#	tests/e2e/Services/GraphQL/TablesDB/DatabaseServerTest.php
#	tests/e2e/Services/Messaging/MessagingBase.php
#	tests/e2e/Services/Sites/SitesBase.php
#	tests/e2e/Services/Sites/SitesCustomServerTest.php
2026-02-18 03:27:23 +13:00
Jake Barnby 10d21bbed6 Cycle lock 2026-02-18 00:45:30 +13:00
Jake Barnby 4529786cc1 Update lock 2026-02-17 23:09:06 +13:00
Jake BarnbyandGitHub 51af714ea8 Merge branch '1.8.x' into feat-mongodb 2026-02-17 08:38:34 +00:00
Jake Barnby f262b46580 Update lock 2026-02-17 19:07:04 +13:00
Jake Barnby 459a5617d6 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2026-02-17 16:32:46 +13:00
Jake BarnbyandGitHub 1740ce59c0 Merge branch '1.8.x' into feat-mongodb 2026-02-16 13:16:45 +00:00
Jake BarnbyandClaude Opus 4.6 bf68bb2f71 fix: resolve MongoDB-specific E2E test failures and $sequence type bug
- Fix $sequence always cast to string (was incorrectly cast to int for numeric values) in Document.php and Row.php
- Add supportForMultipleFulltextIndexes, supportForAttributeResizing, supportForSchemas console variables for MongoDB adapter
- Fix testCreateIndexes to use getSupportForMultipleFulltextIndexes() instead of getSupportForRelationships() for fulltext index error branching
- Fix testAttributeRowWidthLimit/testColumnRowWidthLimit to skip on databases without schema support (MongoDB)
- Fix testAttributeUpdateStringResize/testColumnUpdateStringResize to skip on databases without attribute resizing support (MongoDB)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 01:43:28 +13:00
Jake BarnbyandGitHub 436ced3f1f Merge branch '1.8.x' into feat-mongodb 2026-02-16 09:13:34 +00:00
Jake Barnby b025ad0e8c Update lock 2026-02-14 18:33:29 +13:00
Jake Barnby 82dada5732 Cast if num 2026-02-14 18:04:28 +13:00
Jake BarnbyandGitHub caafe2678b Merge branch '1.8.x' into feat-mongodb 2026-02-14 04:50:00 +00:00
Jake BarnbyandClaude Opus 4.6 ab19a73b33 fix: adjust messaging scheduledAt timings for CI reliability
Set initial schedule to 20s and reschedule to 10s to balance between:
- Not being picked up by scheduler before reschedule (3-4s interval)
- Providing enough margin (6s) after scheduledAt for processing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 02:00:09 +13:00
Jake BarnbyandClaude Opus 4.6 ecf0b4a1dd fix: change $sequence to string type to support MongoDB UUID7 values
The Document and Row response models were casting $sequence to (int),
which destroyed UUID7 values on MongoDB. On MongoDB, $sequence is the
internal _id field which is a UUID7 string, not an auto-increment integer.
The (int) cast converted UUID7 values like "019c56a9-df6d-73fa-8d48-..."
to 19, making $sequence queries fail validation with 400.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:29:38 +13:00
Jake BarnbyandClaude Opus 4.6 7708f13ebd fix: revert database package, add debug output for $sequence query failures
- Revert utopia-php/database to 5.1.2 (the Sequence validator fix
  incorrectly assumed $sequence is always integer, but on MongoDB
  internal collections it uses UUID7)
- Revert Base.php change
- Add detailed error messages to testGetDocumentWithQueries and
  testGetRowWithQueries to capture actual $sequence values and API
  error responses for debugging
- Keep Messaging scheduledAt fix (30s initial, 15s rescheduled)
- Keep Functions auth retry improvement (10 retries with project refresh)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:09:31 +13:00
Jake BarnbyandClaude Opus 4.6 f7ba5e39b7 fix: update Sequence validator, fix messaging race condition, improve auth retry
- Update utopia-php/database to fix Sequence validator rejecting integer
  $sequence values on MongoDB (VAR_UUID7) adapters
- Fix Base.php Filter constructor passing APP_DATABASE_QUERY_MAX_VALUES
  as $idAttributeType instead of the correct Database::VAR_INTEGER
- Fix Messaging testUpdateScheduledAt race condition by increasing
  initial scheduledAt from 3s to 30s so scheduler doesn't fire before
  the PATCH update processes
- Improve Functions callWithAuthRetry to refresh project credentials
  after 4 consecutive 401 failures and increase max retries to 10

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:54:39 +13:00
Jake BarnbyandClaude Opus 4.6 5cf272b21a fix: add $sequence to SELECT query in testGetDocumentWithQueries
The SELECT query didn't include $sequence, so accessing
$response['body']['$sequence'] returned null. The subsequent
Query::equal('$sequence', [null.'']) produced an empty string
which is invalid for the integer $sequence field, causing 400.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 22:02:09 +13:00
Jake BarnbyandClaude Opus 4.6 991af09fdf fix: improve auth retry resilience for MongoDB CI stability
- Increase callWithAuthRetry from 5 to 8 retries with capped delay (50s total)
- Increase ProjectCustom retries from 3 to 5 with 1s delays
- Fix swapped assertEquals parameters in FunctionsBase for clearer errors

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 21:46:24 +13:00
Jake BarnbyandGitHub b7ce686d73 Merge branch '1.8.x' into feat-mongodb 2026-02-13 07:18:26 +00:00
Jake BarnbyandClaude Opus 4.6 5df786b5ad fix: add retry logic for 401 errors and explicit site deployment activation
- Add retry logic with delays for transient 401 auth errors during project
  setup in ProjectCustom::getProject() (cherry-pick from feat-db-tests)
- Replace 10-minute activation polling in SitesBase with 30-second auto-activation
  wait followed by explicit PATCH /sites/:siteId/deployment fallback to prevent
  test suite timeouts when the build worker is slow to auto-activate

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 20:05:49 +13:00
Jake Barnby 57e7f57056 Revert "Revert removals"
This reverts commit 005a3f4775.
2026-02-13 18:00:10 +13:00
Jake Barnby 005a3f4775 Revert removals 2026-02-13 17:52:50 +13:00
Jake Barnby b41678d57a Merge remote-tracking branch 'origin/feat-mongodb' into feat-installer
# Conflicts:
#	.github/workflows/tests.yml
#	Dockerfile
#	app/views/install/compose.phtml
#	composer.lock
#	mongo-entrypoint.sh
#	src/Appwrite/Platform/Tasks/Install.php
#	src/Appwrite/Platform/Tasks/Upgrade.php
#	tests/e2e/Client.php
#	tests/e2e/Services/Databases/DatabasesBase.php
#	tests/e2e/Services/Databases/Legacy/DatabasesCustomClientTest.php
#	tests/e2e/Services/Databases/Legacy/DatabasesCustomServerTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomClientTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomServerTest.php
#	tests/e2e/Services/Databases/Transactions/TransactionsBase.php
#	tests/e2e/Services/GraphQL/Legacy/DatabaseServerTest.php
#	tests/e2e/Services/GraphQL/TablesDB/DatabaseServerTest.php
#	tests/e2e/Services/Projects/ProjectsConsoleClientTest.php
#	tests/e2e/Services/Teams/TeamsCustomClientTest.php
2026-02-13 17:09:42 +13:00
Jake BarnbyandGitHub 75ac4e4447 Merge branch '1.8.x' into feat-db-tests 2026-02-13 04:00:43 +00:00
Jake Barnby dbf3b52d4c Update lock 2026-02-13 16:12:43 +13:00
Jake BarnbyandGitHub 9c40d0c6f8 Merge pull request #11317 from appwrite/copilot/sub-pr-11312 2026-02-13 03:02:25 +00:00
Jake BarnbyandGitHub 2b536078bb Merge branch '1.8.x' into feat-mongodb 2026-02-13 02:19:37 +00:00
copilot-swe-agent[bot]andabnegate 3d58ed10dc Use explicit empty strings for environment variables
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-13 02:06:37 +00:00
copilot-swe-agent[bot]andabnegate 0a79370e1c Use GitHub Actions env config instead of sed commands
Co-authored-by: abnegate <5857008+abnegate@users.noreply.github.com>
2026-02-13 02:05:30 +00:00
copilot-swe-agent[bot] 2ee38ff45d Initial plan 2026-02-13 02:01:54 +00:00
Jake Barnby 3b8ab19fa0 Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2026-02-13 14:42:47 +13:00
Jake Barnby af7862bbbd Remove invalid patch 2026-02-13 14:42:37 +13:00
Jake BarnbyandGitHub 1dcee3edbf Fxx variables 2026-02-13 01:40:37 +00:00
Jake BarnbyandGitHub 1274d56234 Update src/Appwrite/Auth/OAuth2/Mock.php 2026-02-13 14:34:31 +13:00
Jake BarnbyandGitHub c8db0c6dcc Apply suggestions from code review 2026-02-13 14:34:02 +13:00
Jake BarnbyandClaude Opus 4.6 52606f352c fix: handle 401 in assertEventually and increase curl timeout to 30s
- setupDeployment's assertEventually callbacks now handle 401 responses
  gracefully instead of crashing with "Undefined array key"
- Increase Client curl timeout from 15s to 30s for slow CI runners
  (testDeleteScheduledExecution and testGetScreenshotWithPermissions
  were hitting the 15s limit)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 10:37:07 +13:00
Jake BarnbyandClaude Opus 4.6 37b857903a fix: add callWithAuthRetry to FunctionsBase for transient 401s
Extract retry logic into a reusable callWithAuthRetry helper with
exponential backoff (5 retries, 2/4/6/8s delays). Apply to both
setupFunction and setupDeployment.

Previous fix only retried setupFunction, but 401 can hit any API call.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 10:07:26 +13:00
Jake BarnbyandClaude Opus 4.6 efb523dab4 fix: add retry logic to setupFunction for flaky 401 auth errors
All 15 FunctionsCustomServerTest failures originate from setupFunction()
getting a transient 401 when the API key lookup fails under CI load.
Retry up to 3 times with a 2s delay on 401 responses.

Remove the per-method #[Retry] on testScopes since the root fix is now
in setupFunction.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 09:53:14 +13:00
Jake BarnbyandClaude Opus 4.6 aa369dc371 fix: increase Sites activation timeout to 600s and add retry to testScopes
MongoDB CI builds take longer to process the deployment queue, causing
testSiteDomainReclaiming to timeout at 400s. Increase to 600s.

testScopes has an intermittent 401 auth failure - add #[Retry(count: 3)]
for resilience.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 09:16:27 +13:00
Jake BarnbyandClaude Opus 4.6 a13b9c0a88 fix: Increase Sites deployment activation timeouts and fix race condition
- Increase activation timeout in SitesBase setupDeployment from 200s to 400s
- Add assertEventually for deploymentId check in testCreateDeployment to handle
  the race condition where build worker sets deployment status to 'ready' before
  setting site.deploymentId
- Increase build ready timeouts from 50s to 300s in testCreateDeployment

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 08:37:14 +13:00
Jake BarnbyandClaude Opus 4.6 8b822cd97c fix: Add missing _APP_DB_ADAPTER env var to worker-executions, worker-screenshots, and task-interval
The default for _APP_DB_ADAPTER was changed from 'mariadb' to 'mongodb' in
registers.php. Services without this env var default to the MongoDB adapter,
causing MariaDB/PostgreSQL function executions to get stuck in 'waiting'
status because the worker-executions service cannot connect to the database.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 07:53:16 +13:00
Jake BarnbyandClaude Opus 4.6 f0e6105ba0 fix: Use Docker Compose profiles to isolate database containers in CI
- Add profiles to database services (mariadb, mongodb, postgresql) so only
  the needed database starts per CI job, freeing resources for the executor
- Increase Sites deployment activation timeouts from 50-100s to 200s for
  MongoDB compatibility
- Increase SSR logs polling timeout from 30s to 120s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 07:27:21 +13:00
Jake BarnbyandClaude Opus 4.6 25a9aa1805 fix: Fix Sites test SSR logs timing and PostgreSQL search stop word
- Add polling for SSR execution logs instead of immediate access
- Change testListSites framework from 'other' to 'analog' because
  PostgreSQL treats 'other' as a fulltext stop word

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 06:36:51 +13:00
Jake BarnbyandClaude Opus 4.6 6f56c9c2ee fix: Gate spatial index null tests on adapter capability
PostgreSQL supports spatial indexes on nullable columns and required
spatial attributes on existing data, unlike MariaDB. Expose
supportForSpatialIndexNull console variable and condition test
assertions accordingly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 06:22:53 +13:00
Jake BarnbyandClaude Opus 4.6 e3a39499f2 fix: Patch PostgreSQL boolean type mismatch in batch inserts
The SQL adapter's createDocuments() unconditionally casts boolean values to
integers (line 2518 in SQL.php), but PostgreSQL rejects int values for native
BOOLEAN columns. The single-document path already has an instanceof check to
preserve booleans for Postgres, but createDocuments() was missed.

This patch applies the same fix via a PHP script run during Docker build.
Fixes 26 test failures across PostgreSQL Legacy, TablesDB, and GraphQL suites.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 05:44:58 +13:00
Jake BarnbyandClaude Opus 4.6 e3c58a8c05 fix: Correct test capability gates and GraphQL dependencies
- Change spatial test gates from getSupportForRelationships() to
  getSupportForSpatials() in both Legacy and TablesDB DatabasesBase
- Add both relationship AND spatial gates for spatial relationship tests
- Add missing @depends for float, email, and datetime attributes/columns
  in GraphQL Server tests to ensure schema is complete before document/row
  creation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 05:06:48 +13:00
Jake BarnbyandClaude Opus 4.6 74b4c44bde fix: Gate relationship test on adapter support in TablesDB
MongoDB doesn't support relationships, so testInvalidRelationshipDocumentId
returns 400 instead of 202. Skip the test when the adapter lacks support.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 04:59:00 +13:00
Jake BarnbyandClaude Opus 4.6 9b2dd958b5 fix: Use correct capability check for partial fulltext search in Users test
PostgreSQL's ts_vector/ts_query doesn't support partial word matching
(searching "man" won't find "manchester"), unlike MariaDB's LIKE-based
search. The test used getSupportForRelationships() as a proxy for this
capability, which was wrong for PostgreSQL (supports relationships but
not partial fulltext search).

Add supportForFulltextWildcard to console variables endpoint and use
it in the Users test instead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 04:56:39 +13:00
Jake BarnbyandClaude Opus 4.6 b952bf7978 fix: Use custom PostgreSQL image with required extensions (PostGIS, pgvector)
The Postgres adapter in utopia-php/database requires PostGIS, pgvector,
and pg_trgm extensions. The plain postgres:18 image lacked these, causing
"collation utf8_ci_ai does not exist" errors (CREATE EXTENSION failed
before the collation could be created).

Switch to postgres:17 with a custom Dockerfile that installs the required
extensions, matching the approach used by utopia-php/database's own tests.
Also reverts the volume mount to /var/lib/postgresql/data (correct for v17).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 04:25:35 +13:00
Jake BarnbyandClaude Opus 4.6 490b9f844f fix: Update PostgreSQL volume mount for postgres:18 compatibility
PostgreSQL 18+ stores data in major-version-specific subdirectories under
/var/lib/postgresql instead of directly in /var/lib/postgresql/data. The
old mount path caused the container to crash immediately on startup with
a migration error, which was the actual root cause of all PostgreSQL CI
failures (the container was dead so Docker DNS couldn't resolve its name).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 04:14:45 +13:00
Jake BarnbyandClaude Opus 4.6 eaff193055 fix: Resolve PostgreSQL DNS failure by routing through Docker's embedded DNS
The appwrite container's `dns: 172.16.238.100` (CoreDNS) bypassed Docker's
embedded DNS, preventing resolution of service names like `postgresql`.
CoreDNS only handles custom test domains and forwards unknown queries to
Cloudflare, which can't resolve Docker service names.

Fix: Add 127.0.0.11 (Docker embedded DNS) as primary resolver and configure
CoreDNS to forward unknown queries to Docker DNS with Cloudflare as fallback.
Bind CoreDNS to its static IP to avoid port conflict with Docker's DNS proxy.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 04:02:31 +13:00
Jake BarnbyandClaude Opus 4.6 61e69027a3 debug: Include error message in database connection retry log
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 03:34:22 +13:00
Jake BarnbyandClaude Opus 4.6 fc893e1c7e fix: Add connect_timeout to PostgreSQL DSN and add server logs to CI
PDO ATTR_TIMEOUT does not control connection timeout for the pgsql driver.
Without connect_timeout in the DSN, the PDO constructor blocks indefinitely
if PostgreSQL isn't ready, which blocks the Swoole master process event loop
(since coroutine hooks are not enabled in http.php) and prevents all HTTP
request dispatching.

Also add appwrite server logs to CI failure output for debugging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 03:17:48 +13:00
Jake BarnbyandClaude Opus 4.6 9b5695a21b fix: Use simple list form for worker-executions depends_on
Docker Compose doesn't support variable interpolation in depends_on map
keys (expanded form with condition). Use simple list form like all other
services.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 02:53:32 +13:00
Jake BarnbyandClaude Opus 4.6 c9aa80473d fix: Correct import ordering for WhiteList in teams controller
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 02:47:45 +13:00
Jake BarnbyandClaude Opus 4.6 462ce71512 fix: Replace hardcoded mariadb dependencies with dynamic DB host in docker-compose
Four services (worker-screenshots, worker-executions, task-maintenance,
task-interval) had hardcoded `depends_on: mariadb` instead of using
`${_APP_DB_HOST:-mongodb}` like all other services. This caused ALL
PostgreSQL E2E tests to fail because those services couldn't start.

Also fix Storage test assertion that incorrectly used
getSupportForRelationships() as proxy for max UID length - the UID
validator always limits to 36 chars regardless of adapter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 02:44:49 +13:00
Jake BarnbyandClaude Opus 4.6 0e6fa7f300 fix: Add missing WhiteList import in teams controller
The WhiteList validator was used at lines 486 and 1090 but never imported,
causing a "Class not found" error and 500 response instead of proper validation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 02:36:29 +13:00
Jake BarnbyandGitHub cee77d0564 Merge branch '1.8.x' into feat-mongodb 2026-02-12 12:42:54 +00:00
Jake BarnbyandClaude Opus 4.6 2869d057f9 fix: Populate console variables with actual database adapter capabilities
The console variables endpoint was using model defaults (all true) for
supportForRelationships, supportForOperators, supportForSpatials, and
maxIndexLength instead of reading from the actual database adapter.
This caused tests to run unsupported operations on MongoDB.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 01:41:03 +13:00
Jake BarnbyandClaude Opus 4.6 f13f80b2a3 fix: Handle unlimited attribute limit for MongoDB in subQueryAttributes filter
MongoDB adapter returns 0 from getLimitForAttributes() meaning unlimited,
but Query::limit(0) fails validation since minimum valid limit is 1.
Fall back to APP_LIMIT_SUBQUERY (1000) when adapter reports unlimited.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 00:55:05 +13:00
Jake Barnby ccb8b9eb6f Revert "fix: Set MariaDB adapter for non-adapter-specific CI tests"
This reverts commit 17d9a72922.
2026-02-13 00:35:56 +13:00
Jake BarnbyandClaude Opus 4.6 17d9a72922 fix: Set MariaDB adapter for non-adapter-specific CI tests
The .env defaults were changed to mongodb, but tests that don't
explicitly set a DB adapter (general, shared mode, abuse, screenshots)
were implicitly using the default. These tests need MariaDB since
shared tables mode is not supported with MongoDB yet.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 00:34:38 +13:00
Jake BarnbyandClaude Opus 4.6 d3e6c48a59 fix: Add missing Authorization parameter to Columns XList action
The TablesDB Columns XList::action() method was missing the
Authorization $authorization parameter that exists in the parent
Attributes XList class, causing a PHP fatal error that prevented
the appwrite service from starting.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 23:57:51 +13:00
Jake Barnby 638778413d Fix workflows 2026-02-12 23:44:45 +13:00
Jake Barnby 6a005c06b1 Format 2026-02-12 23:40:51 +13:00
Jake Barnby 5590f0bcd0 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	.env
#	.github/workflows/tests.yml
#	app/controllers/api/projects.php
#	app/controllers/api/teams.php
#	app/init/registers.php
#	app/views/install/compose.phtml
#	composer.json
#	composer.lock
#	docker-compose.yml
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Create.php
#	src/Appwrite/Platform/Tasks/Install.php
#	src/Appwrite/Platform/Tasks/Upgrade.php
#	tests/e2e/Services/Databases/Legacy/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2026-02-12 23:35:21 +13:00
Jake BarnbyandGitHub 408f65bf64 Merge branch '1.8.x' into feat-db-tests 2026-02-12 09:14:57 +00:00
Jake BarnbyandClaude Opus 4.6 aa8324f7b9 fix: increase Proxy deployment activation timeout to 5 minutes
Under heavy parallel CI load, VCS deployments take longer to build
and activate. Increased from 200s to 300s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 19:25:08 +13:00
Jake BarnbyandClaude Opus 4.6 6efb20f44c fix: increase all schema polling default timeouts to 10 minutes
Under parallel CI load with MariaDB, attribute processing frequently
exceeds the previous 5-minute default timeout. Increased all polling
defaults (waitForAttribute, waitForAttributes, waitForAttributeCount,
waitForAllAttributes, waitForIndex, waitForAllIndexes) to 10 minutes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:50:32 +13:00
Jake BarnbyandClaude Opus 4.6 663b75bc03 fix: increase waitForAllAttributes timeout for movies collection setup
The 'integers' attribute was getting stuck in 'processing' status under
MariaDB parallel CI load, exceeding the default 5-minute timeout.
Increased to 10 minutes, matching the spatial test timeout.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:36:36 +13:00
Jake BarnbyandClaude Opus 4.6 006867617b Fix parallel test assertions and graceful runtime cleanup
- Fix testListProjectKey: use dynamic key counts instead of hardcoded 5
  (parallel workers don't share state from testCreateProjectKey)
- Fix testGetProjectKey: expect 'Key Test' from setupProjectWithKey(),
  not 'Key Custom' from a previously-dependent test
- Handle 404 in Executor::deleteRuntime() (runtime already gone)
- Make cancel deployment cleanup best-effort (status already updated)
- Apply same fix to Sites cancel endpoint

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:23:55 +13:00
Jake BarnbyandClaude Opus 4.6 fa7ebbffa8 Fix void return in testListProjectKey and increase spatial test timeout
- Remove `return $data` from testListProjectKey() which is declared void,
  causing fatal PHP error that crashed Projects and Abuse test suites
- Increase waitForAllAttributes timeout to 10min for spatial column test
  to handle MariaDB slowness under parallel CI load

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:12:54 +13:00
Jake Barnby d2e77aa5cd Fix indents 2026-02-12 16:35:36 +13:00
Jake Barnby 7d5f6c9bf3 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	.github/workflows/tests.yml
#	composer.lock
#	tests/e2e/Services/Projects/ProjectsConsoleClientTest.php
#	tests/e2e/Services/Teams/TeamsCustomClientTest.php
2026-02-12 12:34:42 +13:00
Jake BarnbyandGitHub 00525a5a02 Merge branch '1.8.x' into feat-db-tests 2026-02-09 22:58:10 +00:00
Darshan ccd43c9c2a add: timeout back with correct fix. 2026-02-09 15:54:06 +05:30
Darshan fa6e8b8158 add: timeout back. 2026-02-09 15:41:45 +05:30
Darshan 96d94c9452 update: cleanup on redirects. 2026-02-09 14:57:37 +05:30
Darshan 6454ef55ad fix: router bug for in network connection. 2026-02-09 14:47:47 +05:30
Darshan d502320a94 update: simpler dev testing. 2026-02-09 14:47:26 +05:30
Jake BarnbyandClaude Opus 4.6 39b6aad959 fix: Use 'columns' instead of 'attributes' for TablesDB index creation
The TablesDB index creation API requires 'columns' parameter, not
'attributes' (which is the collections API parameter). This caused
testDeleteIndexTablesAPI to always fail because the index was never
actually created.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 22:11:18 +13:00
Jake BarnbyandClaude Opus 4.6 7bfae7c2c3 fix: Add diagnostic assertions to Realtime test helpers
Add response status checks on all creation calls (database, table,
column, index) to catch silent failures early and provide diagnostic
info instead of mysterious 404s during polling.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 21:26:16 +13:00
Jake BarnbyandClaude Opus 4.6 4412be13f0 fix: Increase Proxy deployment activation timeout from 100s to 200s
Same issue as Sites - under CI parallel load the deployment builds
successfully but activation propagation takes longer than 100s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 21:03:56 +13:00
Jake BarnbyandClaude Opus 4.6 b597fb9956 fix: Replace sleep(5) with proper polling and increase timeouts in Realtime tests
The Realtime test helpers used fragile sleep(5) for attribute/index
creation and had short polling timeouts (30s/60s) that fail under CI
parallel load. Replaced with assertEventually polling and increased
all timeouts to 120s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 20:42:15 +13:00
Jake BarnbyandClaude Opus 4.6 6a1fa1d608 fix: Increase schema polling timeouts from 3min to 5min for CI stability
Under parallel load in CI, attribute/index workers can take longer than
3 minutes to process. Increase all polling timeouts to 5 minutes to
reduce flaky failures from worker queue congestion.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:54:01 +13:00
Jake BarnbyandClaude Opus 4.6 2a41fc6f23 fix: Move server-side check before setupCollection in testConsoleProject
Prevents risky test warning where setupCollection makes assertions
before expectNotToPerformAssertions is called for server-side tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:15:35 +13:00
Jake BarnbyandClaude Opus 4.6 a55a784f07 fix: Use fresh magic URL token in testCreateSessionWithMagicUrl
The cached token from setupMagicUrl may have been consumed by
setupMagicUrlSession in a previous test method in the same process,
causing a 401 when the test tries to create a session with it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 18:20:36 +13:00
Jake BarnbyandClaude Opus 4.6 64d6efd098 fix: Add missing attribute types to Collection/AttributeList models and fix parallel test issues
- Add MODEL_ATTRIBUTE_VARCHAR/TEXT/MEDIUMTEXT/LONGTEXT to Collection and
  AttributeList models, fixing TypeError in Response::hasModel() that
  caused 4974 server crashes when serializing collections with new
  string attribute types
- Initialize $ruleType to null in Response::output() to prevent
  undefined variable when no model condition matches
- Isolate testUniqueIndexDuplicate with its own collection to prevent
  duplicate title interference from parallel tests in the same process
- Add retry mechanism to phone session creation for OTP token issues
- Increase GraphQL function build timeout from 30s to 120s
- Increase Sites deployment activation timeout from 100s to 200s
- Relax GraphQL bulk update row count assertion for parallel safety

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 17:53:21 +13:00
Jake BarnbyandClaude Opus 4.6 b3eecac6f9 fix: Add error details to assertions and handle 409 in relationship setup
- Add response body to assertion messages for debugging 400/409 errors
- Re-add 409 handling for relationship creation (race condition in parallel mode)
- Use explicit fullName: null instead of empty data for null person documents

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 16:56:08 +13:00
Jake BarnbyandClaude Opus 4.6 d617f89642 fix: Fix parallel test failures across Databases, GraphQL, Realtime, and Account
- DatabasesBase: Wait for twoWayKey attribute on library collection in
  setupOneToManyRelationship; use server API key headers for document creation
- DatabasesStringTypesTest: Add delays between attribute creation batches to
  avoid overwhelming the database worker
- SchemaPolling: Improve waitForAllAttributes error messaging
- GraphQL UsersTest: Use fresh user in testDeleteUserSession to avoid
  session conflicts
- Realtime: Increase WebSocket timeout to 120s and index polling to 60s
- Account: Add better error reporting for phone session creation failures

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 16:08:55 +13:00
Jake BarnbyandClaude Opus 4.6 e319feb1d4 fix: Fix relationship twoWayKey, hardcoded IDs, and datetime format issues
- Set explicit twoWayKey in testOneToOneRelationship to avoid auto-generated ID
- Replace hardcoded person10/library10/11 IDs with ID::unique() in setupOneToManyRelationship
- Fix remaining datetime format comparison in testUpdateScheduledAt
- Use assertStringContainsString for Projects mock numbers excess items test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 15:28:38 +13:00
Jake BarnbyandClaude Opus 4.6 1b9d0ca1c6 fix: Fix remaining parallel-safety issues from CI iteration 2
- Fix DB relationship tests: use ID::unique() for person/library collections
- Fix DB StringTypesTest: use waitForAllAttributes instead of sleep(3)
- Fix DB permissions tests: update expected counts for parallel mode
- Fix Account OAuth tests: clean up shared mock OAuth email before use
- Fix Account phone tests: ensure phone auth enabled, unique phone numbers
- Fix Messaging: compare datetime via timestamps, accept processing state
- Fix GraphQL testGetColumn: call setupStringColumn instead of setupTable
- Fix Projects: update mock numbers error message assertion

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 14:55:41 +13:00
Jake BarnbyandClaude Opus 4.6 161e4e53d4 fix: Address remaining parallel-safety failures across all test suites
- Fix Legacy DatabasesStringTypesTest with project-keyed setup cache
- Fix Account OTP test with unique email, phone session re-login
- Fix GraphQL setup methods with sleep, 409 handling, missing columns
- Fix Databases list/pagination tests with document ID filtering
- Fix Permissions tests with assertGreaterThanOrEqual for counts
- Fix Messaging scheduled tests to not depend on scheduler timing
- Increase Realtime WebSocket timeout to 60s and assertEventually to 30s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 14:20:42 +13:00
Jake BarnbyandClaude Opus 4.6 2da4211f69 fix: Make E2E tests parallel-safe for functional mode
- Fix missing return statement in DatabasesBase::testListDocuments
- Rewrite DatabasesStringTypesTest with project-keyed setup cache
- Use assertGreaterThanOrEqual in Functions testListDeployments
- Clean up OIDC provider after Account OAuth2 test
- Key all GraphQL static caches by project ID with unique IDs
- Replace sleep() with assertEventually in Realtime tests
- Increase Messaging scheduled message timeout to 180s
- Increase Sites deployment timeouts to 120s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 13:25:19 +13:00
Jake BarnbyandClaude Opus 4.5 c5ec632709 fix: Make Functions execution tests parallel-safe
- testListExecutions: Don't assume position in results list
- Use assertContains with array_column instead of position[0]

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:59:51 +13:00
Jake BarnbyandClaude Opus 4.5 870ccc9a1b fix: Fix webhook tests for parallel mode
- testDeleteUser: User is created with status=true, so assert that
- testUpdateUserStatus: Use probe to find correct webhook event

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:58:53 +13:00
Jake BarnbyandClaude Opus 4.5 0737ba1329 fix: Make more tests parallel-safe for functional mode
- Account: Use unique emails/phone numbers to avoid collisions
- Functions: Use flexible assertions for counts and search results
- GraphQL: Add better error handling and use unique IDs
- Projects: Use assertGreaterThanOrEqual for list counts
- Webhooks: Use probe to find specific delete webhook event

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:48:55 +13:00
Jake BarnbyandClaude Opus 4.5 627def5993 fix: Make Functions testListDeployments parallel-safe
- Use foreach loop to check all deployments instead of hardcoded indices
- Fix offset test to not assume exactly 1 function exists

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:25:10 +13:00
Jake BarnbyandClaude Opus 4.5 6e103393b8 fix: Fix undefined $data variables in Webhooks tests
- testCreateAttributes: Use $actorsId instead of undefined $data['actorsId']
- testCreateColumns: Use $actorsId instead of undefined $data['actorsId']
- testCreateAccountSession: Add assertion for account creation success

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:23:44 +13:00
Jake BarnbyandClaude Opus 4.5 a4cca146d3 fix: Remove undefined $totalUsers and use parallel-safe assertions
The testListUsers function was using $totalUsers which was removed when
the test was refactored for parallel execution. Now uses $minUsers and
flexible assertions instead of position-based assertions.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:22:14 +13:00
Jake BarnbyandClaude Opus 4.5 e605848541 perf: Enable --functional mode for true method-level parallelism
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:19:38 +13:00
Jake BarnbyandClaude Opus 4.5 9f9d195daf fix: Add retry logic and defensive checks for Teams owner downgrade test
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:16:41 +13:00
Jake BarnbyandClaude Opus 4.5 a79f33a3a1 fix: Remove incorrect json_decode in setupUser
The client body is already decoded as array, not JSON string.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:13:23 +13:00
Jake BarnbyandClaude Opus 4.5 6be719c9d4 fix: Add retry logic for 401 errors in ProjectCustom::getProject
Under high parallel load, authentication can transiently fail with 401.
Add retry logic with delays to handle these transient failures.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:07:00 +13:00
Jake BarnbyandClaude Opus 4.5 ce200d20d4 fix: Make webhook account tests self-sufficient
Update account name before testing to ensure webhook data has
expected 'New Name' value, regardless of test execution order.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:59:58 +13:00
Jake BarnbyandClaude Opus 4.5 8627251ae4 fix: Make testDeleteStorageBucket self-sufficient
Update bucket name before deleting to ensure webhook data has
expected name, regardless of whether testUpdateStorageBucket ran.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:59:16 +13:00
Jake BarnbyandClaude Opus 4.5 1f17dca7c9 fix: Handle 409 conflicts in GraphQL TablesDB tests
- setupDatabase() now fetches existing database on conflict
- setupTable() now fetches existing tables on conflict
- Enables parallel test execution with fixed resource IDs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:56:45 +13:00
Jake BarnbyandClaude Opus 4.5 0e828f3fcc fix: Handle 409 conflicts in GraphQL Legacy tests
- setupDatabase() now fetches existing database on conflict
- setupCollections() now fetches existing collections on conflict
- Enables parallel test execution with fixed resource IDs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:55:59 +13:00
Jake BarnbyandClaude Opus 4.5 d4020686f2 fix: Make testListUsers parallel-safe
- Use assertGreaterThanOrEqual instead of exact count
- Find users by ID instead of assuming position
- Document expected minimum user count for isolated execution

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:53:42 +13:00
Jake BarnbyandClaude Opus 4.5 de8915b416 fix: Make testListBucket self-sufficient for parallel execution
Create bucket1 within testListBucket instead of relying on
testCreateBucket running first. Accept 409 if bucket already exists.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:47:29 +13:00
Jake BarnbyandClaude Opus 4.5 fd8e8fc736 fix: Make Storage cursorAfter test parallel-safe
Use assertGreaterThanOrEqual and find bucket by ID instead of
assuming exact count and position after cursor query.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:42:43 +13:00
Jake BarnbyandClaude Opus 4.5 07c9a274b1 fix: Use assertGreaterThanOrEqual for fileSecurity bucket count
In parallel execution, there may be more buckets with fileSecurity=true

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:36:21 +13:00
Jake BarnbyandClaude Opus 4.5 40ed0da8b3 fix: Fix testUpdateAccountNameSearch for parallel execution
Use assertGreaterThanOrEqual and find user by ID instead of assuming position

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:27:47 +13:00
Jake BarnbyandClaude Opus 4.5 a2ae55dcbe fix: Improve parallel test isolation for Account, Storage, Messaging
- Account: Add createFreshAccountWithSession() for predictable session/log counts
- Account: Update testGetAccountSessions and testGetAccountLogs to use fresh accounts
- Storage: Fix testListBucket to find bucket by ID instead of assuming first position
- Messaging: Fix testListSubscribers to find subscriber by ID instead of assuming first position

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 20:24:28 +13:00
Jake BarnbyandClaude Opus 4.5 3b025fa12a fix: Make testCreateAttributes and testCreateIndexes parallel-safe
These tests were creating resources directly in the shared collections,
which conflicts with setupAttributes() and setupIndexes() when tests
run in parallel. Now each test creates its own dedicated collection
to avoid conflicts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 18:50:36 +13:00
Jake BarnbyandClaude Opus 4.5 945eb43558 fix: Use more entropy for email generation in parallel tests
Adding process ID and random bytes to uniqid() to avoid email
collisions when running tests in parallel with functional mode.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 18:00:27 +13:00
Jake BarnbyandClaude Opus 4.5 62e0598008 fix: Remove more invalid returns from void test methods
Removed return statements from testManyToOneRelationship and
testManyToManyRelationship which were declared as void. These
cause PHP fatal errors in PHP 8.4+.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 17:46:42 +13:00
Jake BarnbyandClaude Opus 4.5 fd0a4a0e88 fix: Remove invalid return from void testUpdateDocument method
The testUpdateDocument method was declared as void but returned [].
This causes a PHP fatal error in PHP 8.4.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 17:36:20 +13:00
Jake BarnbyandClaude Opus 4.5 2a4ef06355 fix: Make Sites tests parallel-safe for --functional mode
Add search filters to isolate test data in testListSites to prevent
count assertions from failing when other test methods create sites
during parallel execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 17:24:57 +13:00
Jake BarnbyandClaude Opus 4.5 2d160747ca perf: Remove @depends from Migrations, Projects, and Tokens tests
Added helper methods with static caching for independent test execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 12:13:54 +13:00
Jake BarnbyandClaude Opus 4.5 2a3e2d8be5 perf: Remove @depends from all GraphQL tests
Added helper methods with static caching for:
- Legacy/DatabaseClientTest.php
- Legacy/DatabaseServerTest.php
- TablesDB/DatabaseClientTest.php
- TablesDB/DatabaseServerTest.php

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 12:01:31 +13:00
Jake BarnbyandClaude Opus 4.5 e976617869 perf: Remove @depends from Databases permissions and partial GraphQL tests
- Added setupDatabase() helper with caching to all permission test files
- Removed @depends from LegacyPermissionsMemberTest, LegacyPermissionsTeamTest
- Removed @depends from TablesDBPermissionsMemberTest, TablesDBPermissionsTeamTest
- Partial GraphQL test updates from agents

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 11:56:58 +13:00
Jake BarnbyandClaude Opus 4.5 f624646480 perf: Remove @depends from Account, Functions, Storage, Users, VCS, Messaging tests
Added helper methods with static caching to enable parallel test execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 11:54:14 +13:00
Jake BarnbyandClaude Opus 4.5 f5f60ab85b perf: Remove @depends from Database Transactions tests
Enables parallel test execution for Transactions tests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:47:23 +13:00
Jake BarnbyandClaude Opus 4.5 b1257cc40a perf: Remove @depends from Webhooks and Teams tests
Enables --functional mode for parallel test execution by:
- Adding helper methods for independent test setup
- Removing all #[Depends] annotations
- Using static caching for shared resources

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:47:12 +13:00
Jake BarnbyandClaude Opus 4.5 02240fd14f fix: Correct TablesDB API paths in Realtime test helpers
- Use /databases endpoint instead of /tablesdb for database creation
- Use /columns/string instead of /attributes/string for table columns
- Fix testAttributesCollectionsAPI return type from array to void

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:46:59 +13:00
Jake Barnby 24f8275f52 Revert "fix: run Databases and FunctionsSchedule tests sequentially"
This reverts commit 8dadcfeebe.
2026-02-06 04:36:55 +13:00
Jake BarnbyandClaude Opus 4.5 2e9c1b4745 fix: Remove @depends chains from Realtime tests for parallel execution
- Add helper methods createCollectionWithAttribute(), createTableWithAttribute(),
  createCollectionWithIndex(), createTableWithIndex() to RealtimeConsoleClientTest
- Add createTeam() helper to RealtimeCustomClientTest
- Replace all @depends annotations with direct helper method calls
- Enable tests to run in parallel with --functional flag

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:28:12 +13:00
Jake BarnbyandClaude Opus 4.5 8dadcfeebe fix: run Databases and FunctionsSchedule tests sequentially
Parallel test execution with paratest overwhelms the single databases
worker when many tests create attributes simultaneously. Run these
specific services sequentially with PHPUnit to ensure the worker
can keep up with attribute processing jobs.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:15:56 +13:00
Jake BarnbyandClaude Opus 4.5 2c5dee0fdd fix: resolve test failures in Databases, Functions, Messaging, Storage
- Fix typo CLient -> Client in DatabasesBase.php:4568
- Fix typo CLient -> Client in StorageCustomClientTest.php:428
- Fix cleanupFunction() call with extra parameter in FunctionsScheduleTest.php:175
- Increase message scheduling test timeouts from 30s to 180s for CI stability

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 04:03:40 +13:00
Jake BarnbyandClaude Opus 4.5 4631a2a75f Revert test changes (back to original state)
The --functional flag cannot be used because tests rely on static
properties to share state between test methods (e.g., $databaseId
set in testCreateDatabase is used by testCreateTable). With --functional,
each test method runs in a separate process so these properties are not
initialized.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 03:42:32 +13:00
Jake BarnbyandClaude Opus 4.5 1ef96627d3 fix: scale databases worker to handle parallel test load
The root cause of flaky attribute processing tests is that a single
appwrite-worker-databases container cannot keep up with attribute
creation jobs when tests run in parallel via paratest.

This fix:
- Scales the databases worker to 4 instances during E2E service tests
- Reverts timeout increases that masked the underlying issue

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 03:04:22 +13:00
Jake BarnbyandClaude Opus 4.5 fb2dc89041 fix: increase SchemaPolling timeout to 10 minutes for CI stability
Increase all default timeouts in SchemaPolling trait from 5 minutes to
10 minutes. With tests running in parallel via paratest, the attribute
processing worker can become backlogged under heavy CI load, requiring
longer wait times for attributes to transition from 'processing' to
'available' status.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 02:59:38 +13:00
Jake BarnbyandClaude Opus 4.5 262425fdb6 fix: increase SchemaPolling timeout to 5 minutes for CI stability
Increase all default timeouts in SchemaPolling trait from 3 minutes to
5 minutes to handle slower attribute processing when running tests in
parallel under heavy CI load.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 02:41:55 +13:00
Jake Barnby c8d2cc090e Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	tests/e2e/Services/Databases/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2026-02-06 01:29:44 +13:00
Jake BarnbyandClaude Opus 4.5 3ea4810d3a fix: increase SchemaPolling default timeout to 3 minutes for CI
Increase all default timeouts in SchemaPolling trait from 2 minutes to
3 minutes to handle slower attribute processing in CI environments.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:57:36 +13:00
Jake BarnbyandClaude Opus 4.5 20f7af49b1 fix: increase FunctionsSchedule test timeout for CI stability
Remove explicit sleep and increase assertEventually timeout from 60s to
180s to account for slower deployment and scheduling in CI. Also use
assertGreaterThanOrEqual to handle cases where multiple executions
may have run.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:45:30 +13:00
Jake BarnbyandClaude Opus 4.5 a9b55f4c74 fix: improve test stability for CI failures
- Skip FunctionsCustomServerTest::testCreateFunctionAndDeploymentFromTemplateCommit when GitHub API is rate-limited or unavailable
- Increase waitForAllAttributes timeout to 3 minutes for testBulkDeleteMatchingUpdatedDocuments to handle slow attribute processing in CI

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:31:26 +13:00
Jake BarnbyandGitHub 4a2e3b7b22 Merge branch '1.8.x' into feat-db-tests 2026-02-05 03:12:24 +00:00
Jake BarnbyandClaude Opus 4.5 6850d7ae9e fix: add sleep for async attribute deletion verification
Attribute deletion is asynchronous - add sleep to wait for deletion
to complete before verifying the attribute no longer exists.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 02:01:01 +13:00
Jake BarnbyandClaude Opus 4.5 45a3793cc0 fix: correct expected default values and attribute name in tests
- Update expected default values to match the actual defaults (update
  tests are skipped, so original defaults apply)
- Fix varchar_max -> varchar_min (varchar_max was never created)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 01:48:36 +13:00
Jake BarnbyandClaude Opus 4.5 2e061e2f2b fix: make testCreatePhoneVerification self-contained
Remove @depends annotation and set up phone number within the test
to ensure it works with PHPUnit 12 and paratest parallel execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 01:33:01 +13:00
Jake BarnbyandClaude Opus 4.5 6f6ea94a19 fix: make testUpdateWithExistingRelationships self-contained
Remove @depends annotation and create a new database within the test
to fix compatibility with PHPUnit 12 and paratest parallel execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 01:30:52 +13:00
Darshan 850bd81511 fix: local image tagging. 2026-02-04 17:54:26 +05:30
Jake BarnbyandClaude Opus 4.5 0aff01793b fix: remove @depends annotations from DatabasesStringTypesTest
Replace @depends annotations with static property assertions to fix
compatibility issues with PHPUnit 12 and paratest parallel execution.

Tests now use self::$databaseId and self::$collectionId/self::$tableId
directly instead of passing data between dependent tests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 01:18:16 +13:00
Jake Barnby e70739a3c0 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	Dockerfile
#	app/controllers/api/account.php
#	app/controllers/api/avatars.php
#	app/controllers/api/console.php
#	app/controllers/api/projects.php
#	app/controllers/api/storage.php
#	app/controllers/api/teams.php
#	app/http.php
#	app/init/database/filters.php
#	app/init/registers.php
#	app/init/resources.php
#	app/views/install/compose.phtml
#	composer.json
#	composer.lock
#	docker-compose.yml
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Update.php
#	src/Appwrite/Platform/Modules/Functions/Http/Deployments/XList.php
#	src/Appwrite/Platform/Tasks/Install.php
#	tests/e2e/Services/Projects/ProjectsConsoleClientTest.php
2026-02-05 01:01:03 +13:00
Jake BarnbyandClaude Opus 4.5 f34983f056 fix: update composer image to 2.x for PHP 8.3+ compatibility
PHPUnit 12 requires PHP 8.3+ and uses PHP enums like
CodeCoverageInitializationStatus. The old composer:2.0 image used
PHP 8.0.6 which doesn't support enums, causing autoloader issues.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 00:41:50 +13:00
Jake Barnby 97be6e2cf4 Merge branch 'feat-installer' of github.com:appwrite/appwrite into feat-installer 2026-02-05 00:31:10 +13:00
Jake Barnby 1df76ed975 Merge remote-tracking branch 'origin/1.8.x' into feat-installer
# Conflicts:
#	Dockerfile
#	app/views/install/compose.phtml
#	composer.lock
#	src/Appwrite/Platform/Tasks/Install.php
2026-02-05 00:29:29 +13:00
Jake Barnby 4933cdda10 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests 2026-02-05 00:16:15 +13:00
Jake Barnby b704378bf1 Revert platform downgrade 2026-02-05 00:16:08 +13:00
Jake BarnbyandGitHub 2278a423f5 Merge pull request #11175 from appwrite/new-install-ui
Add web installer
2026-02-04 11:15:20 +00:00
Jake Barnby cfa4c0876b Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.lock
#	src/Appwrite/Messaging/Adapter/Realtime.php
2026-02-04 23:47:08 +13:00
Jake Barnby 936adce15b Update phpunit 2026-02-04 23:45:46 +13:00
Jake BarnbyandClaude Opus 4.5 0a492fb1e2 fix: pin utopia-php/platform to 0.7.14 for framework compatibility
Platform 0.7.15 introduced a breaking change that requires Utopia\Http
instead of Utopia\App, but framework 0.33.x still uses Utopia\App.
This pins platform to 0.7.14 which is compatible with the current
framework version.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 23:30:23 +13:00
Darshan 282b3c74ec fix: local install path. 2026-02-04 15:49:05 +05:30
Darshan 180276bd9d remove: mock stuff.
fix: layout regression.
2026-02-04 15:48:37 +05:30
Darshan abab48c1b9 remove: mock stuff. 2026-02-04 14:48:42 +05:30
Jake Barnby cdcee01015 Update lock 2026-02-04 19:53:28 +13:00
Jake Barnby d4694ff8af Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.json
#	composer.lock
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
#	tests/e2e/Services/Projects/ProjectsConsoleClientTest.php
#	tests/e2e/Services/Realtime/RealtimeCustomClientTest.php
2026-02-04 19:49:09 +13:00
Darshan 587f9965a2 misc. 2026-02-03 14:37:29 +05:30
Darshan bdad14e83a fix: gradient. 2026-02-03 14:32:24 +05:30
Darshan 92e94e365f update: send to existing analyics endpoint. 2026-02-03 13:54:20 +05:30
Darshan 35918465f8 update: address comments, remove name field and auto-derive. 2026-02-02 19:00:54 +05:30
Darshan 42e52fcaa6 revert: handle fallbacks on growth. 2026-01-30 12:11:39 +05:30
Darshan ba29e66292 add: fallbacks. 2026-01-30 12:09:09 +05:30
Darshan d8cc3202c6 add: tracking on installations. 2026-01-30 11:44:00 +05:30
Darshan 02ce669993 update: design changes on creds step. 2026-01-30 11:08:26 +05:30
Darshan a2a24ee367 update: behavioural hotfix. 2026-01-26 19:27:22 +05:30
Darshan 5e0f163f1f fix: tests. 2026-01-26 19:25:08 +05:30
Darshan c9a6a0f0aa add: deps. 2026-01-26 18:57:50 +05:30
Darshan f5681f1167 fix: bun availability on CI. 2026-01-26 18:44:55 +05:30
Darshan 0e4d514007 update: docs. 2026-01-26 18:41:44 +05:30
Darshan c39d8ad591 fix: tests. 2026-01-26 18:31:16 +05:30
Darshan f59796e290 update: use helpers. 2026-01-26 18:06:36 +05:30
Darshan cff11cae5a update: use more constants. 2026-01-26 18:00:45 +05:30
Darshan aa3047f338 update: use constants for regexes. 2026-01-26 17:48:08 +05:30
Darshan e17b8cec38 update: consistent naming pattern. 2026-01-26 17:40:19 +05:30
Darshan fc2ee0c32a update: inline args. 2026-01-26 17:35:13 +05:30
Darshan 5690eb1dc5 update: filter checks. 2026-01-26 17:26:18 +05:30
Darshan fbba7166ae update: send mock/default values from backend.
update: update task callback.
2026-01-26 17:22:02 +05:30
Darshan 289c3e233e update: misc fixes. 2026-01-26 17:14:31 +05:30
Darshan 6345802b1a update: use helper method. 2026-01-26 17:06:52 +05:30
Darshan 7fb654e3a4 misc: updates, cleanups. 2026-01-26 16:10:51 +05:30
Darshan 8b9051751a update: password validation.
misc: updates, cleanups.
2026-01-26 15:26:56 +05:30
Darshan 335c3f363c fix: ci. 2026-01-25 18:07:42 +05:30
Darshan 6dac2ce253 improve: animations like imagine.
fix: password eye button not showing again.
2026-01-25 18:01:58 +05:30
Darshan f34e40e1e4 add: ci tests. 2026-01-25 17:12:55 +05:30
Darshan fe74760177 update: screenshot tests. 2026-01-25 17:06:10 +05:30
Darshan 2d5e64a21e update: screenshot tests. 2026-01-25 15:42:09 +05:30
Darshan b503965e8c update: tests. 2026-01-25 15:20:09 +05:30
Darshan a9da80687f remove: unneeded check. 2026-01-25 11:33:24 +05:30
Darshan d4dd6cf634 add: completion marker. 2026-01-25 11:33:05 +05:30
Darshan 85d2e08dc5 update: installer doc. 2026-01-25 10:51:09 +05:30
Darshan 0eda9e6315 add: account creation.
feat: mocking options.
2026-01-24 20:09:56 +05:30
Darshan eb8abcfe63 fix: empty input considered as invalid.
fix: referencing wrong file in upgrade task.
2026-01-24 16:35:14 +05:30
Darshan 80a5c24840 bump: gitignore. 2026-01-24 16:32:01 +05:30
Darshan 5144b1ce88 update: splits.
fix: broken SSE.
fix: upgrade flow not working.
feat: csrf tokens for better security.
fix: local testing mode with wrong paths.
feat: csrf validations pre-post hook plus proper permissions handling on files.
feat: js modules for better handling of js operations on web installer frontend ui.
2026-01-24 16:30:51 +05:30
Darshan 3d86f67acb update: move server handling to a new file.
update: tooltip things.
remove: unused var.
2026-01-22 19:52:46 +05:30
Darshan 58440e70ac misc. 2026-01-22 18:12:41 +05:30
Darshan dd16ead898 update: new installer ui. 2026-01-22 17:28:23 +05:30
Jake Barnby bdb8bc081f Add doc 2026-01-21 18:09:46 +13:00
Jake BarnbyandGitHub 9f0ca2bc53 Update src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php 2026-01-20 20:42:36 +13:00
Jake BarnbyandGitHub 605cf0c985 Update src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php 2026-01-20 18:21:14 +13:00
shimon 7e1838dda6 typo 2026-01-19 14:02:14 +02:00
shimon 2016e9bc2f Update XList parameters: remove 'cache' and adjust 'ttl' default value to 0, reflecting changes in caching logic across tests. 2026-01-19 13:14:26 +02:00
Jake BarnbyandGitHub afe800197b Update .github/workflows/tests.yml 2026-01-19 23:39:53 +13:00
Jake Barnby 8335e43eaa Merge branch '1.8.x' into feat-db-tests 2026-01-19 18:34:35 +13:00
shimon b3d1410ca9 Refactor XList parameters: rename 'total' to 'includeTotal' for clarity and update related logic in action method to maintain functionality. 2026-01-18 14:27:57 +02:00
shimon a2d56a47cd merge with 1.8x 2026-01-18 11:13:45 +02:00
shimon 316bbfe43d Merge branch '1.8.x', commit '3b5351afb6473e559c945846f0bf7e928b636d83' of github.com:appwrite/appwrite into cached-documents-list
# Conflicts:
#	composer.lock
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
2026-01-18 11:13:08 +02:00
Jake Barnby a425c460c2 CI 2026-01-17 01:25:50 +13:00
Jake Barnby 9331ae1cbb CI 2026-01-17 01:02:25 +13:00
Jake Barnby 0cc3db6095 Fix flaky test timing issues
- Increase SchemaPolling default timeout from 60s to 120s
- Replace hardcoded sleep() with assertEventually() for message status polling in Messaging tests
2026-01-16 22:57:05 +13:00
Jake Barnby 36c4228de6 Remove debug code 2026-01-16 22:31:35 +13:00
Jake Barnby 34810ca5bb Debug: dump response body on failure 2026-01-16 21:44:28 +13:00
Jake Barnby 392619284e Fix perms tests 2026-01-16 21:09:46 +13:00
Jake Barnby 2dae0ece5d Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests 2026-01-16 20:50:00 +13:00
Jake BarnbyandClaude Opus 4.5 63b3365ce9 Fix PHPUnit 11 migration test issues
- Add missing @depends testCreateDatabase to testUpdateWithExistingRelationships in DatabasesBase.php
- Fix data provider keys in LegacyPermissionsMemberTest and TablesDBPermissionsMemberTest to match parameter names (any->anyCount, users->usersCount, doconly->docOnlyCount)
- Convert provideCustomExecutions data provider to positional arrays to avoid PHPUnit 11 named argument conflicts with @depends
- Restore @depends testUpdateAccountPhone for testCreatePhoneVerification in GraphQL AccountTest

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 18:59:53 +13:00
Jake BarnbyandClaude Opus 4.5 4adc4f65ad Add missing PHPUnit #[Depends] to GraphQL Functions tests
Fixed missing #[Depends] attributes:
- FunctionsClientTest: 4 methods (testCreateDeployment, testCreateExecution,
  testGetExecutions, testGetExecution)
- FunctionsServerTest: 11 methods (all test methods with parameters)
- Legacy/DatabaseServerTest: Fixed testCreateIndex dependency
  (was depending on void-returning testUpdateURLAttribute)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 18:28:38 +13:00
Jake BarnbyandClaude Opus 4.5 7498c330eb Add missing PHPUnit #[Depends] to Functions, Messaging, Webhooks tests
Fixed missing #[Depends] attributes:
- FunctionsCustomServerTest: testCancelDeploymentBuild → testCreateDeployment
- MessagingBase: testDeleteMessage → testSendEmail
- WebhooksBase: testDeleteDocument → testUpdateDocument, testDeleteRow → testUpdateRow
- WebhooksCustomClientTest: testUpdateAccountName → testDeleteAccountSessions

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 18:18:55 +13:00
Jake BarnbyandClaude Opus 4.5 1d03af22e4 Add missing PHPUnit #[Depends] attributes to GraphQL tests
PHPUnit 11 requires explicit #[Depends] attributes. The migration removed
@depends annotations but didn't add all corresponding #[Depends] attributes.

Fixed in:
- GraphQL/Legacy/DatabaseClientTest: 5 methods
- GraphQL/StorageClientTest: 7 methods
- GraphQL/StorageServerTest: 10 methods
- GraphQL/TeamsServerTest: 3 methods
- GraphQL/TeamsClientTest: 2 methods
- GraphQL/TablesDB/DatabaseServerTest: ~40 methods
- GraphQL/TablesDB/DatabaseClientTest: 5 methods

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 18:10:30 +13:00
Jake BarnbyandClaude Opus 4.5 7d6ac8f7a2 Add missing PHPUnit #[Depends] attributes
PHPUnit 11 requires explicit #[Depends] attributes instead of the old
@depends annotations. Several test methods were missing these attributes,
causing "Too few arguments" errors when PHPUnit tried to run the tests.

Fixed in:
- AccountCustomClientTest: testUpdateAccountPassword, testUpdateAccountRecovery, testCreateSession
- GraphQL/Legacy/DatabaseServerTest: Added 36 missing #[Depends] attributes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 17:51:31 +13:00
Jake BarnbyandClaude Opus 4.5 c5c2c44755 Fix PHPUnit --exclude-group deprecation warning
PHPUnit 11+ warns when using comma-separated values with --exclude-group.
This warning causes the tests to return exit code 1 despite all tests passing.

Fix by using separate --exclude-group flags for each group.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 17:33:51 +13:00
Jake Barnby 46f3fadc5d Fix hooks 2026-01-15 17:21:05 +13:00
Jake Barnby 714b8d7ea6 Migrate to PHPUnit 11 2026-01-15 16:14:53 +13:00
Jake Barnby 84f9485049 Fix tests 2026-01-15 14:04:39 +13:00
Jake Barnby d7a6a7b5d8 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.lock
#	tests/e2e/Services/Databases/Legacy/Permissions/DatabasesPermissionsGuestTest.php
#	tests/e2e/Services/Databases/TablesDB/Permissions/DatabasesPermissionsGuestTest.php
2026-01-15 12:43:26 +13:00
Jake Barnby feab8a26e5 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.lock
#	tests/e2e/Services/Databases/Legacy/Permissions/DatabasesPermissionsGuestTest.php
#	tests/e2e/Services/Databases/TablesDB/Permissions/DatabasesPermissionsGuestTest.php
2026-01-14 19:59:36 +13:00
Jake Barnby 962626a4fb Update lock 2026-01-14 01:56:02 +13:00
Jake Barnby 0f953e4a52 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.lock
2026-01-14 01:33:22 +13:00
Jake Barnby bb09abc087 Update CTA check 2026-01-14 01:23:48 +13:00
Jake Barnby 0b27d92509 Update lock 2026-01-13 22:09:05 +13:00
Jake Barnby 5153617f04 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests
# Conflicts:
#	composer.lock
#	tests/e2e/Services/Databases/Legacy/Permissions/DatabasesPermissionsGuestTest.php
#	tests/e2e/Services/Databases/TablesDB/Permissions/DatabasesPermissionsGuestTest.php
2026-01-13 22:04:36 +13:00
Jake Barnby a34fa1ceb6 Fix abuse 2026-01-13 22:01:22 +13:00
Jake Barnby cd21140572 Fix request fetching 2026-01-13 22:01:16 +13:00
Jake Barnby 8eb09a98fe Fix otp user 2026-01-11 02:49:28 +13:00
Jake Barnby 879a599bed Fix parallel cases 2026-01-11 02:33:20 +13:00
Jake Barnby 1a22c281f5 Parallelise 2026-01-10 21:25:06 +13:00
Jake Barnby f797ae3ac6 Remove sleeps 2026-01-10 14:53:29 +13:00
Jake Barnby 658308a447 Merge remote-tracking branch 'origin/1.8.x' into feat-db-tests 2026-01-10 03:21:38 +13:00
Jake Barnby 9498a8ba5d Consolidate, remove depends, add fixtures 2026-01-10 03:21:31 +13:00
Shimon NewmanandGitHub 3b5351afb6 Merge branch '1.8.x' into cached-documents-list 2026-01-06 13:03:18 +02:00
shimon ecc4052bdc Clarify TTL parameter description in XList class for cached responses to enhance documentation accuracy. 2026-01-06 12:58:58 +02:00
shimon fc84012977 Inject user dependency into XList class for enhanced functionality and improved caching accuracy. 2026-01-06 12:56:18 +02:00
shimon c882afbd2c Enhance XList class by injecting user dependency and updating cache key format to include user ID for improved caching accuracy. 2026-01-06 12:52:36 +02:00
Jake Barnby 29dd4e23e2 Update console 2025-12-17 18:36:30 +13:00
Jake Barnby 58470bfa7f Update upgrade/install flows 2025-12-17 18:36:23 +13:00
Jake Barnby 4fb43c6e69 Fix install flow 2025-12-17 16:14:20 +13:00
Jake Barnby c5dadc787d Block operator tests 2025-12-11 00:23:46 +13:00
Jake Barnby 587a0facf7 Fix teams test 2025-12-10 22:33:30 +13:00
Jake Barnby a8cf0a6176 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	app/controllers/api/teams.php
#	app/init/resources.php
#	composer.lock
#	tests/e2e/Services/Databases/Legacy/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2025-12-10 20:12:27 +13:00
shimon 305697a5d3 Update composer dependencies and refactor cache handling in XList class for improved performance 2025-12-09 11:29:09 +02:00
shimon d954681132 matcing documents xlist params order 2025-12-08 15:41:13 +02:00
shimon 872345366a linter 2025-12-08 13:43:05 +02:00
shimon 5b1aec0f0b Enhance XList functionality by adding cache and TTL parameters for improved query performance and response management. 2025-12-08 13:34:09 +02:00
shimon 98d063132c composer.lock 2025-12-08 09:57:49 +02:00
shimon fcb3699e99 Merge branch 'refactor-auth-single-instance' of github.com:appwrite/appwrite into cached-documents-list
# Conflicts:
#	composer.json
#	composer.lock
2025-12-08 09:56:48 +02:00
shimon 39658a7ee1 fixing comments 2025-12-08 09:55:15 +02:00
Jake Barnby cbf0cc842d Add web installer 2025-12-02 23:33:21 +13:00
Jake Barnby 2139a4d742 Format 2025-11-26 23:49:21 +13:00
Jake Barnby b9ca0e5dc2 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2025-11-26 22:50:15 +13:00
Jake Barnby cdb331a704 Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2025-11-26 22:49:50 +13:00
Jake Barnby 092f623373 Fix tests 2025-11-26 22:49:39 +13:00
Jake BarnbyandGitHub bd124aad2a Merge branch '1.8.x' into feat-mongodb 2025-11-25 08:26:00 +00:00
Jake Barnby 2776925540 Tests via console features 2025-11-25 21:11:01 +13:00
shimon 6213df9fb3 Update composer.lock for sdk-generator version 1.5.8 and adjust caching TTL in XList to 30 seconds; modify related tests for consistency in cache behavior. 2025-11-23 12:46:16 +02:00
Jake Barnby 188f8f3ecd Fix missing param 2025-11-20 20:20:58 +13:00
Jake Barnby e12d463fe0 Fix merge 2025-11-20 19:13:14 +13:00
Jake Barnby d8d970e03e Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	app/controllers/api/account.php
#	app/controllers/api/messaging.php
#	app/controllers/api/projects.php
#	app/controllers/api/storage.php
#	app/controllers/api/teams.php
#	app/controllers/api/users.php
#	composer.lock
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Datetime/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Email/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Float/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/IP/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Integer/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Line/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Point/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Polygon/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Relationship/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/String/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/URL/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Get.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Boolean/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Datetime/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Email/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Enum/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Float/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/IP/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Integer/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Line/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Point/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Polygon/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/Relationship/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/String/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Columns/URL/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Delete.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Bulk/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Decrement.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Column/Increment.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Get.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Upsert.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/XList.php
#	src/Appwrite/Platform/Modules/Functions/Http/Deployments/Create.php
#	src/Appwrite/Platform/Modules/Sites/Http/Deployments/Create.php
#	src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Buckets/Files/Create.php
#	src/Appwrite/Platform/Modules/Tokens/Http/Tokens/Update.php
2025-11-20 17:46:19 +13:00
shimon 30df7a43d5 Refactor caching logic in XList to use JSON encoding for query serialization and update cache header keys to lowercase in tests 2025-11-18 20:11:02 +02:00
shimon 8fc9fdb7dc cached documents list 2025-11-18 16:37:52 +02:00
shimon 77905e241f cached documents list 2025-11-18 16:26:56 +02:00
Jake Barnby 1e1df1ce2d Fix skips 2025-10-24 00:06:58 +13:00
Jake Barnby bae759957c Fix graphql test 2025-10-23 23:57:11 +13:00
Jake Barnby 9aba82630a Fix console test 2025-10-23 23:57:00 +13:00
Jake Barnby 3f473f2790 Fix checks 2025-10-23 23:40:27 +13:00
Jake Barnby b79439a730 Default to mariadb for existing installs 2025-10-23 23:02:41 +13:00
Jake Barnby 861684883f Add DB adapter console var 2025-10-23 23:02:29 +13:00
Jake Barnby 337503ed47 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	composer.lock
2025-10-23 17:15:57 +13:00
Jake Barnby 71f52025ec Review fixes 2025-10-22 00:30:00 +13:00
Jake Barnby 505181d749 Update lock 2025-10-21 18:45:27 +13:00
Jake Barnby b12e006014 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	app/init/resources.php
#	composer.lock
2025-10-21 18:43:41 +13:00
Jake Barnby 1e60a01a69 Use db length for project ID 2025-10-21 15:31:46 +13:00
Jake Barnby f1c7af0426 Fix wrong db for UID max length check 2025-10-21 15:04:08 +13:00
Jake Barnby c3d4cf947e Fix unit test 2025-10-21 14:24:32 +13:00
Jake Barnby 0d35af8cfa Fix tests 2025-10-21 14:24:26 +13:00
Jake Barnby 390d1560f4 Fix tests 2025-10-21 14:16:59 +13:00
Jake Barnby 94bf1f6ee0 Add missing imports 2025-10-21 14:15:45 +13:00
Jake Barnby 2870419e1b Update lock 2025-10-21 14:10:32 +13:00
Jake Barnby f9b0455794 Revert "Fix optionality"
This reverts commit 994de06457.

# Conflicts:
#	app/controllers/api/messaging.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Boolean/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Transactions/Update.php
2025-10-21 13:05:54 +13:00
Jake Barnby 6a7b8f0726 Add injection max length on txn 2025-10-21 13:03:24 +13:00
Jake Barnby 994de06457 Fix optionality 2025-10-21 12:36:13 +13:00
Jake Barnby ad9e6afd86 Fix sync 2025-10-21 03:18:29 +13:00
Jake Barnby 3a8e2b080d Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	app/init/resources.php
#	composer.json
#	composer.lock
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Indexes/Create.php
#	tests/e2e/Services/Databases/Legacy/DatabasesBase.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2025-10-21 03:16:21 +13:00
Jake BarnbyGitHubcoderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1f743dfe8c Update src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Attributes/Enum/Create.php
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-10-14 22:23:38 +13:00
Jake Barnby a4093067ac Update database 2025-10-14 21:06:32 +13:00
Jake Barnby 72868ed7aa Fix async index delete 2025-10-14 19:39:49 +13:00
Jake Barnby f328a68ec1 Update db for decode fix 2025-10-14 19:39:40 +13:00
Jake Barnby 754537f34b Update lock 2025-10-14 18:16:48 +13:00
Jake Barnby bc4326414b Retry loop on create databases 2025-10-14 18:12:09 +13:00
Jake Barnby 3e7f865f0a Update lock 2025-10-14 17:13:05 +13:00
Jake Barnby e956ad58a9 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	composer.lock
2025-10-14 16:42:40 +13:00
Jake Barnby ddec873f72 Update database 2025-10-14 16:39:44 +13:00
Jake Barnby f78f08bff9 Transaction support 2025-10-13 18:23:43 +13:00
Jake Barnby 38b04566b6 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php
#	src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Delete.php
2025-10-09 17:36:22 +13:00
Jake Barnby c89af1201a Fix tests 2025-10-09 16:37:17 +13:00
Jake Barnby 9f85ca83b4 Fix roles param 2025-10-09 14:33:05 +13:00
Jake Barnby d5d09061e9 Fix index validator params 2025-10-09 13:46:14 +13:00
Jake Barnby 143be8239f Fix inject 2025-10-09 00:41:25 +13:00
Jake Barnby da519046dd Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2025-10-08 00:05:05 +13:00
Jake Barnby 0c5573ab05 Fix list wrapping UID injections 2025-10-08 00:04:52 +13:00
Jake BarnbyandGitHub fa60f03536 Merge branch '1.8.x' into feat-mongodb 2025-10-07 18:52:28 +13:00
Jake Barnby 28392647e0 Pass adapter max ID length to validator 2025-10-07 18:52:05 +13:00
Jake Barnby 4b0eddcc84 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	composer.json
#	composer.lock
2025-10-07 18:16:02 +13:00
Jake Barnby 94e40c0127 Update database 2025-10-04 10:15:13 +13:00
Jake Barnby 498235a2ef Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2025-10-03 23:19:33 +13:00
Jake Barnby 52c9671157 Update deps 2025-10-03 23:19:09 +13:00
Jake Barnby 61a1efd0fe Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2025-10-02 19:25:56 +13:00
Jake Barnby faf837e389 Update db for index validation fix 2025-10-02 15:29:27 +13:00
Jake Barnby 3ecd7e6a95 Fix fts create on array 2025-10-01 22:02:41 +13:00
Jake Barnby 36782650c6 Revert "Add CI debug"
This reverts commit 2d3dea84e3.
2025-10-01 21:36:03 +13:00
Jake Barnby 2f6bc9115f Fix workflows init 2025-10-01 21:35:55 +13:00
Jake Barnby 2d3dea84e3 Add CI debug 2025-10-01 21:10:26 +13:00
Jake Barnby b12f4008eb Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	composer.lock
2025-10-01 20:13:48 +13:00
Jake Barnby 408bca400b Fix spatial tests 2025-10-01 19:33:11 +13:00
Jake Barnby 6bacec52c5 Fix storage test 2025-10-01 17:11:02 +13:00
Jake Barnby 9d70b5cab2 Fix domain test 2025-10-01 17:09:07 +13:00
Jake Barnby d9baf5b628 Fix sites error 2025-10-01 12:31:07 +13:00
Jake Barnby 9e837c2eb9 Fix storage error 2025-10-01 12:31:02 +13:00
Jake Barnby f3460db369 Fix fulltext error 2025-10-01 12:30:48 +13:00
Jake Barnby b57839402f Update DB 2025-10-01 02:14:51 +13:00
Jake Barnby 763158fe81 Fix usage tests 2025-10-01 01:30:18 +13:00
Jake Barnby 766c3293d2 Fix index text checks 2025-10-01 00:47:07 +13:00
Jake Barnby 1226c0834c Fix upsert 2025-10-01 00:13:09 +13:00
Jake Barnby f0983cd9ff Remove mounts 2025-10-01 00:03:07 +13:00
Jake Barnby daeb721995 Fix tests 2025-09-30 23:44:26 +13:00
Jake Barnby 0555a27656 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2025-09-30 22:58:38 +13:00
Jake Barnby da3284ce84 Update deps 2025-09-30 22:58:29 +13:00
Jake Barnby 53f8a3a78b Update DB 2025-09-29 19:39:51 +13:00
Jake Barnby aa77253b14 Fix OSV 2025-09-26 22:17:01 +12:00
Jake Barnby 78c5743e75 Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb
# Conflicts:
#	composer.lock
2025-09-26 22:14:40 +12:00
Jake Barnby 156a944b54 Merge remote-tracking branch 'origin/feat-mongodb-index-validation' into feat-mongodb 2025-09-26 22:05:31 +12:00
Jake Barnby b07fd5afe6 Merge remote-tracking branch 'origin/feat-mongodb-pulls' into feat-mongodb 2025-09-26 22:05:24 +12:00
shimon b828621feb Update composer dependencies and enhance index validation in database module 2025-09-21 19:14:40 +03:00
shimon 3edc055c9d Skip spatial column tests for MongoDB support in DatabasesBase trait 2025-09-21 16:02:36 +03:00
shimon ceda513083 Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb-pulls
# Conflicts:
#	composer.lock
#	src/Appwrite/Platform/Workers/StatsUsage.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2025-09-21 15:55:11 +03:00
Shimon NewmanandGitHub 2d47b88246 Merge pull request #10527 from appwrite/feat-mongodb-pulls
Feat mongodb pulls
2025-09-21 15:46:15 +03:00
shimon b88e74095b Merge remote-tracking branch 'origin/feat-mongodb-pulls' into feat-mongodb-pulls
# Conflicts:
#	composer.json
2025-09-21 15:44:41 +03:00
shimon 4d85c5ca4f composer 2025-09-21 15:42:44 +03:00
shimon c89e649d05 composer 2025-09-21 15:38:35 +03:00
shimon d9bdf01cee db lib ver 2025-09-21 15:30:09 +03:00
shimon 54e3a4b25d db lib ver 2025-09-21 15:27:41 +03:00
shimon b1e55702c8 Refactor MongoDB test cases for improved readability and consistency. Adjust whitespace in conditional statements and remove redundant test methods related to spatial columns. Add new tests for spatial distance queries and update existing tests to ensure proper functionality. 2025-09-16 19:14:09 +03:00
shimon f16eba2f9f Update PHPUnit configuration to stop on failure set to false, and clean up whitespace in multiple files for consistency. Adjust comments and ensure proper formatting in test cases and API handling. 2025-09-16 19:13:38 +03:00
shimon 7c0bd1da88 uncomment inversion tests 2025-09-16 17:51:29 +03:00
shimon cc87de8934 Merge branch 'feat-mongodb-pulls' of github.com:appwrite/appwrite into feat-mongodb-pulls
# Conflicts:
#	composer.lock
2025-09-16 17:43:47 +03:00
shimon 5f8dc9998c Refactor database document handling by replacing createOrUpdateDocuments with upsertDocuments in multiple classes. Clean up common.php by removing commented-out index definitions and ensuring proper indexing for MongoDB compatibility. Update UsageTest to correct API endpoint paths for database operations. 2025-09-16 17:39:41 +03:00
shimon cc7778ceea database lib check 2025-09-16 11:10:06 +03:00
shimon f5fc099d87 Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb-pulls
# Conflicts:
#	composer.lock
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2025-09-16 10:26:43 +03:00
shimon 89d06d00c0 Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb-pulls
# Conflicts:
#	.github/workflows/tests.yml
#	composer.lock
#	tests/e2e/Services/Databases/TablesDB/DatabasesBase.php
2025-09-11 16:54:49 +03:00
shimon 882cd8c83e Merge remote-tracking branch 'origin/feat-mongodb-pulls' into feat-mongodb-pulls
# Conflicts:
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomClientTest.php
2025-09-11 16:43:39 +03:00
shimon 80cc6a0bb3 DatabasesCustomClientTest.php 2025-09-11 16:42:33 +03:00
shimon fc4ad175dd Update composer.json and composer.lock to reflect new versioning for utopia-php/database and other dependencies. Adjusted package versions for brick/math, open-telemetry/api, and symfony components. Added symfony/polyfill-php83 for compatibility with PHP 8.3 features. Minor formatting changes in MigrationsBase.php for code clarity. 2025-09-11 16:38:41 +03:00
shimon a0def8edf8 Updates 2025-08-31 17:57:58 +03:00
shimon bdb8204910 Refactor database attribute tests to streamline size validation and add support for additional integer index. Updated size constraints for 'description' and 'tagline' attributes, and introduced a new 'integers2' attribute to accommodate MongoDB limitations. Adjusted assertions to reflect these changes. 2025-08-27 16:32:13 +03:00
shimon 1274614d18 Update composer.json and composer.lock to reflect new versioning for utopia-php/database and other dependencies. Adjusted Docker configuration to set the database adapter to MariaDB. 2025-08-27 13:55:48 +03:00
shimon 4f937ac549 Update composer.json and composer.lock to reflect changes in utopia-php/database versioning, including the removal of the 'with-uuid7' suffix. Updated dependencies for composer/semver, symfony/polyfill packages, and phpunit/phpunit to their latest versions for improved compatibility and performance. 2025-08-27 10:28:17 +03:00
shimon 6910d669de Update composer.json to correct utopia-php/database version reference and modify test to use the correct endpoint for MongoDB operations. 2025-08-27 10:25:23 +03:00
shimon 4fb680350a Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb-pulls
# Conflicts:
#	Dockerfile
#	composer.json
#	composer.lock
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomClientTest.php
#	tests/e2e/Services/Databases/TablesDB/DatabasesCustomServerTest.php
2025-08-26 14:20:47 +03:00
Shimon NewmanandGitHub ff35dc6114 Merge pull request #10375 from appwrite/feat-mongodb-pulls
Feat mongodb pulls
2025-08-26 13:53:42 +03:00
shimon 38433b9ac1 Remove unnecessary var_dump statement from ProjectsConsoleClientTest for improved code clarity and consistency. 2025-08-26 13:52:05 +03:00
shimon b98be4756c Update composer.json and composer.lock to reflect changes in utopia-php/database versioning and dependencies. Adjusted MongoDB-related test conditions for improved compatibility and clarity. Removed unnecessary var_dump statements in account.php and enhanced logging in various test files for better debugging. 2025-08-26 13:48:01 +03:00
shimon ff8418ffb9 Update composer.lock to reflect new references and timestamps for dependencies, including updates for utopia-php/database and phpunit/phpunit. Removed duplicate entries and unnecessary lines for improved clarity. 2025-08-12 18:01:38 +03:00
shimon e151425b95 Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb-pulls 2025-08-12 17:54:55 +03:00
shimon b9f4815c3a Remove unnecessary var_dump statements from api.php and enhance logging in MessagingConsoleClientTest for improved clarity and debugging. This aligns with recent efforts to clean up debugging output across the codebase. 2025-08-12 17:47:11 +03:00
shimon c4fb7ecbc1 Refactor and clean up debugging output across multiple files, including mock.php, account.php, and OAuth2 classes. Removed unnecessary var_dump statements for improved code clarity and consistency. Updated MongoDB condition checks in test cases to ensure case-insensitive comparisons. 2025-08-12 15:20:30 +03:00
shimon 24b7c95514 Merge branch 'feat-mongodb' of github.com:appwrite/appwrite into feat-mongodb 2025-08-11 22:07:11 +03:00
shimon 870125ed84 Refactor MongoDB condition checks in DatabasesCustomClientTest and UsersBase. Improved formatting for consistency and clarity in test assertions, particularly for MongoDB-related tests. 2025-08-11 22:07:05 +03:00
shimon e1475619ba Refactor debugging output across various files, including http.php, mock.php, and OAuth2 classes. Adjusted var_dump statements for improved traceability and consistency. Updated test assertions in ProjectsConsoleClientTest and UsersBase to enhance clarity and functionality. 2025-08-11 22:05:18 +03:00
Matej Bačo ba058a89a3 Merge branch '1.8.x' into feat-mongodb 2025-08-11 13:22:27 +02:00
shimon 236fab4658 Update composer configuration for minimum stability and prefer stable packages. Adjust utopia-php/database version alias and update phpunit and sebastian packages to latest versions. Add debugging output in http.php and uncomment OAuth2 conversion test in AccountCustomClientTest for improved functionality. 2025-08-11 11:56:38 +03:00
shimon 6cfd6d9ac9 Remove debugging var_dump statements from projects API and enhance error handling in XList class. Update test cases to comment out a specific OAuth2 conversion test for clarity. 2025-08-11 11:28:11 +03:00
shimon da706378ea Enhance debugging output in OAuth2 mock endpoints and update MongoDB version in tests. Added var_dump statements for better traceability during OAuth2 flows and adjusted test assertions for user search functionality. 2025-08-11 11:27:45 +03:00
shimon 40e36e23dd Merge remote-tracking branch 'origin/1.8.x' into feat-mongodb 2025-08-10 18:16:03 +03:00
shimon 603980759a composer.lock 2025-08-06 15:49:05 +03:00
shimon d63a218bd8 Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb
# Conflicts:
#	composer.json
#	composer.lock
2025-08-06 15:48:19 +03:00
shimon def3628205 feat: rename tables to grids and update documentation 2025-08-06 15:37:59 +03:00
shimon 779fb7bd20 Update composer dependencies and Docker Compose configuration for MongoDB integration. Change database alias in composer.json, update package versions in composer.lock, and adjust volume mappings in Docker Compose to include MongoDB source directories. Refactor application code to set tenant to null for database connections. 2025-08-06 15:07:04 +03:00
shimon ea1aef1d70 composer.lock 2025-08-03 18:40:45 +03:00
shimon b1cc203eba composer 2025-08-03 18:38:38 +03:00
shimon b3e1a3415a Merge branch '1.8.x' of github.com:appwrite/appwrite into feat-mongodb
# Conflicts:
#	app/init/resources.php
#	composer.json
#	composer.lock
2025-08-03 18:33:27 +03:00
shimon d48248c9a2 Refactor Docker Compose and application code for MongoDB integration. Remove health check configuration and simplify service dependencies in Docker Compose. Update error logging in application to include context for MongoDB connection issues. 2025-08-03 18:13:16 +03:00
shimon eafca0c431 Add support for multiple database adapters in GitHub Actions workflow, including MARIADB and MONGODB. Set environment variables based on selected adapter for testing. 2025-07-31 18:22:42 +03:00
shimon a92bdfaed0 Update Docker Compose to clarify MongoDB readiness check comment, addressing implications of template substitution limitations. 2025-07-31 17:49:04 +03:00
shimon 46965135a4 Update Docker Compose and application configuration to support MongoDB as the primary database, replacing all instances of MariaDB. Introduce a new environment variable for database selection and adjust database schemes in the application initialization. 2025-07-31 17:17:08 +03:00
shimon 33c5ac83b2 Enhance Docker Compose configuration for MongoDB, add health checks, and update user creation logic in mongo-init.js. Improve database connection handling and fix conditional checks in application code. 2025-07-31 12:47:12 +03:00
shimon 57c08a41f1 Update environment configuration to support MongoDB, enhance Docker Compose for MongoDB integration, and improve database connection handling in the application. 2025-07-29 23:08:00 +03:00
shimon 36e7452f78 Update environment variables, Dockerfile version, and enhance MongoDB connection handling in the application. Add console document creation logic and improve code formatting for better readability. 2025-07-28 17:34:11 +03:00
shimon 469801b862 Update database configuration to use MongoDB, add MongoDB and Mongo Express services to Docker Compose, and adjust related code for MongoDB integration. 2025-07-27 20:38:49 +03:00
477 changed files with 40232 additions and 47229 deletions
+4 -3
View File
@@ -39,9 +39,10 @@ _APP_REDIS_HOST=redis
_APP_REDIS_PORT=6379
_APP_REDIS_PASS=
_APP_REDIS_USER=
_APP_DB_ADAPTER=mariadb
_APP_DB_HOST=mariadb
_APP_DB_PORT=3306
COMPOSE_PROFILES=mongodb
_APP_DB_ADAPTER=mongodb
_APP_DB_HOST=mongodb
_APP_DB_PORT=27017
_APP_DB_SCHEMA=appwrite
_APP_DB_USER=user
_APP_DB_PASS=password
+139 -77
View File
@@ -98,16 +98,14 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose up -d
sleep 10
- name: Logs
run: docker compose logs appwrite
- name: Doctor
run: docker compose exec -T appwrite doctor
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Environment Variables
run: docker compose exec -T appwrite vars
@@ -115,8 +113,9 @@ jobs:
- name: Run Unit Tests
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/unit
@@ -144,11 +143,15 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose up -d
sleep 10
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Wait for Open Runtimes
timeout-minutes: 3
run: |
@@ -160,8 +163,9 @@ jobs:
- name: Run General Tests
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/General
@@ -173,10 +177,8 @@ jobs:
- name: Failure Logs
if: failure()
run: |
echo "=== Appwrite Worker Builds Logs ==="
docker compose logs appwrite-worker-builds
echo "=== OpenRuntimes Executor Logs ==="
docker compose logs openruntimes-executor
echo "=== Appwrite Logs ==="
docker compose logs
e2e_service_test:
name: E2E Service Test
@@ -190,15 +192,14 @@ jobs:
matrix:
db_adapter: [
MARIADB,
POSTGRESQL
POSTGRESQL,
MONGODB
]
service: [
Account,
Avatars,
Console,
Databases/Legacy,
Databases/TablesDB,
Databases,
Functions,
FunctionsSchedule,
GraphQL,
@@ -228,12 +229,37 @@ jobs:
path: /tmp/${{ env.IMAGE }}.tar
fail-on-cache-miss: true
- name: Set DB Adapter environment
id: set-db-env
run: |
DB_ADAPTER_LOWER=$(echo "${{ matrix.db_adapter }}" | tr 'A-Z' 'a-z')
echo "COMPOSE_PROFILES=${DB_ADAPTER_LOWER}" >> $GITHUB_ENV
if [ "${{ matrix.db_adapter }}" = "MARIADB" ]; then
echo "_APP_DB_ADAPTER=mariadb" >> $GITHUB_ENV
echo "_APP_DB_HOST=mariadb" >> $GITHUB_ENV
echo "_APP_DB_PORT=3306" >> $GITHUB_ENV
elif [ "${{ matrix.db_adapter }}" = "MONGODB" ]; then
echo "_APP_DB_ADAPTER=mongodb" >> $GITHUB_ENV
echo "_APP_DB_HOST=mongodb" >> $GITHUB_ENV
echo "_APP_DB_PORT=27017" >> $GITHUB_ENV
elif [ "${{ matrix.db_adapter }}" = "POSTGRESQL" ]; then
echo "_APP_DB_ADAPTER=postgresql" >> $GITHUB_ENV
echo "_APP_DB_HOST=postgresql" >> $GITHUB_ENV
echo "_APP_DB_PORT=5432" >> $GITHUB_ENV
fi
- name: Load and Start Appwrite
timeout-minutes: 3
env:
_APP_BROWSER_HOST: http://invalid-browser/v1
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
sed -i 's|^_APP_BROWSER_HOST=.*|_APP_BROWSER_HOST=http://invalid-browser/v1|' .env
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Wait for Open Runtimes
timeout-minutes: 3
@@ -246,50 +272,38 @@ jobs:
- name: Run ${{ matrix.service }} tests with Project table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 20
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/${{ matrix.service }}
command: |
echo "Using project tables"
SERVICE_PATH="/usr/src/code/tests/e2e/Services/${{ matrix.service }}"
export _APP_DATABASE_SHARED_TABLES=
export _APP_DATABASE_SHARED_TABLES_V1=
# Set DB Adapter Specific ENV Vars using if-elif
if [ "${{ matrix.db_adapter }}" = "MARIADB" ]; then
export _APP_DB_ADAPTER=mariadb
export _APP_DB_HOST=mariadb
export _APP_DB_PORT=3306
export _APP_DB_SCHEMA=appwrite
elif [ "${{ matrix.db_adapter }}" = "POSTGRESQL" ]; then
export _APP_DB_ADAPTER=postgresql
export _APP_DB_HOST=postgresql
export _APP_DB_PORT=5432
export _APP_DB_SCHEMA=appwrite
else
echo "Unknown DB adapter: ${{ matrix.db_adapter }}"
exit 1
fi
# Services that rely on sequential test method execution (shared static state)
FUNCTIONAL_FLAG="--functional"
case "${{ matrix.service }}" in
Databases|Functions|Realtime) FUNCTIONAL_FLAG="" ;;
esac
echo "Running with paratest (parallel) for: ${{ matrix.service }} ${FUNCTIONAL_FLAG:+(functional)}"
docker compose exec -T \
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_DB_ADAPTER \
-e _APP_DB_HOST \
-e _APP_DB_PORT \
-e _APP_DB_SCHEMA \
-e _APP_DATABASE_SHARED_TABLES="" \
-e _APP_DATABASE_SHARED_TABLES_V1="" \
-e _APP_DB_ADAPTER="${{ env._APP_DB_ADAPTER }}" \
-e _APP_DB_HOST="${{ env._APP_DB_HOST }}" \
-e _APP_DB_PORT="${{ env._APP_DB_PORT }}" \
-e _APP_DB_SCHEMA=appwrite \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/${{ matrix.service }} --debug --exclude-group abuseEnabled,screenshots
appwrite vendor/bin/paratest --processes $(nproc) $FUNCTIONAL_FLAG "$SERVICE_PATH" --exclude-group abuseEnabled --exclude-group screenshots --exclude-group ciIgnore --log-junit tests/e2e/Services/${{ matrix.service }}/junit.xml
- name: Failure Logs
if: failure()
run: |
echo "=== Appwrite Worker Builds Logs ==="
docker compose logs appwrite-worker-builds
echo "=== OpenRuntimes Executor Logs ==="
docker compose logs openruntimes-executor
echo "=== Appwrite Logs ==="
docker compose logs
e2e_shared_mode_test:
name: E2E Shared Mode Service Test
@@ -307,8 +321,7 @@ jobs:
Account,
Avatars,
Console,
Databases/Legacy,
Databases/TablesDB,
Databases,
Functions,
FunctionsSchedule,
GraphQL,
@@ -344,10 +357,14 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Wait for Open Runtimes
timeout-minutes: 3
@@ -360,8 +377,9 @@ jobs:
- name: Run ${{ matrix.service }} tests with ${{ matrix.tables-mode }} table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 20
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/${{ matrix.service }}
@@ -375,12 +393,20 @@ jobs:
export _APP_DATABASE_SHARED_TABLES=database_db_main
export _APP_DATABASE_SHARED_TABLES_V1=
fi
SERVICE_PATH="/usr/src/code/tests/e2e/Services/${{ matrix.service }}"
# Services that rely on sequential test method execution (shared static state)
FUNCTIONAL_FLAG="--functional"
case "${{ matrix.service }}" in
Databases|Functions|Realtime) FUNCTIONAL_FLAG="" ;;
esac
docker compose exec -T \
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/${{ matrix.service }} --debug --exclude-group abuseEnabled,screenshots
appwrite vendor/bin/paratest --processes $(nproc) $FUNCTIONAL_FLAG "$SERVICE_PATH" --exclude-group abuseEnabled --exclude-group screenshots --exclude-group ciIgnore --log-junit tests/e2e/Services/${{ matrix.service }}/junit.xml
- name: Failure Logs
if: failure()
@@ -409,17 +435,22 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
sed -i 's/_APP_OPTIONS_ABUSE=disabled/_APP_OPTIONS_ABUSE=enabled/' .env
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Run Projects tests in dedicated table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/Projects
@@ -432,7 +463,7 @@ jobs:
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/Projects --debug --group=abuseEnabled
appwrite vendor/bin/paratest --processes $(nproc) /usr/src/code/tests/e2e/Services/Projects --group abuseEnabled
- name: Failure Logs
if: failure()
@@ -469,17 +500,22 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
sed -i 's/_APP_OPTIONS_ABUSE=disabled/_APP_OPTIONS_ABUSE=enabled/' .env
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Run Projects tests in ${{ matrix.tables-mode }} table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/Projects
@@ -498,7 +534,7 @@ jobs:
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/Projects --debug --group=abuseEnabled
appwrite vendor/bin/paratest --processes $(nproc) /usr/src/code/tests/e2e/Services/Projects --group abuseEnabled
- name: Failure Logs
if: failure()
@@ -527,17 +563,30 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
sed -i 's/_APP_OPTIONS_ABUSE=disabled/_APP_OPTIONS_ABUSE=enabled/' .env
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Wait for Open Runtimes
timeout-minutes: 3
run: |
while ! docker compose logs openruntimes-executor | grep -q "Executor is ready."; do
echo "Waiting for Executor to come online"
sleep 1
done
- name: Run Site tests with browser connected in dedicated table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/Sites
@@ -551,7 +600,7 @@ jobs:
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/Sites --debug --group=screenshots
appwrite vendor/bin/paratest --processes $(nproc) /usr/src/code/tests/e2e/Services/Sites --group screenshots
- name: Failure Logs
if: failure()
@@ -588,17 +637,30 @@ jobs:
fail-on-cache-miss: true
- name: Load and Start Appwrite
timeout-minutes: 3
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
sed -i 's/_APP_OPTIONS_ABUSE=disabled/_APP_OPTIONS_ABUSE=enabled/' .env
docker compose up -d
sleep 30
until docker compose exec -T appwrite doctor > /dev/null 2>&1; do
echo "Waiting for Appwrite to be ready..."
sleep 2
done
- name: Wait for Open Runtimes
timeout-minutes: 3
run: |
while ! docker compose logs openruntimes-executor | grep -q "Executor is ready."; do
echo "Waiting for Executor to come online"
sleep 1
done
- name: Run Site tests with browser connected in ${{ matrix.tables-mode }} table mode
uses: itznotabug/php-retry@v3
with:
max_attempts: 3
timeout_minutes: 30
max_attempts: 2
retry_wait_seconds: 300
timeout_minutes: 15
job_id: ${{ job.check_run_id }}
github_token: ${{ secrets.GITHUB_TOKEN }}
test_dir: tests/e2e/Services/Sites
@@ -618,7 +680,7 @@ jobs:
-e _APP_DATABASE_SHARED_TABLES \
-e _APP_DATABASE_SHARED_TABLES_V1 \
-e _APP_E2E_RESPONSE_FORMAT="${{ github.event.inputs.response_format }}" \
appwrite test /usr/src/code/tests/e2e/Services/Sites --debug --group=screenshots
appwrite vendor/bin/paratest --processes $(nproc) /usr/src/code/tests/e2e/Services/Sites --group screenshots
- name: Failure Logs
if: failure()
+13 -1
View File
@@ -19,4 +19,16 @@ Makefile
appwrite.config.json
/.zed/
/app/config/specs/
/docs/examples/
/docs/examples/
.phpunit.cache
playwright-report
test-results
docker-compose.web-installer.yml
.env.web-installer
docker-compose.web-installer.yml.**.backup
# local installer output dir
appwrite/
# screenshots
tests/playwright/screenshots
+6 -2
View File
@@ -1,4 +1,4 @@
FROM composer:2.0 AS composer
FROM composer:2 AS composer
ARG TESTING=false
ENV TESTING=$TESTING
@@ -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.0.0 AS base
FROM appwrite/base:1.0.1 AS base
LABEL maintainer="team@appwrite.io"
@@ -37,6 +37,9 @@ COPY ./app /usr/src/code/app
COPY ./public /usr/src/code/public
COPY ./bin /usr/local/bin
COPY ./src /usr/src/code/src
COPY ./dev /usr/src/code/dev
COPY ./mongo-init.js /usr/src/code/mongo-init.js
COPY ./mongo-entrypoint.sh /usr/src/code/mongo-entrypoint.sh
# Set Volumes
RUN mkdir -p /storage/uploads && \
@@ -117,5 +120,6 @@ RUN if [ "$DEBUG" = "true" ]; then \
fi
EXPOSE 80
EXPOSE 8080
CMD [ "php", "app/http.php" ]
+1 -21
View File
@@ -1617,13 +1617,6 @@ return [
],
],
'indexes' => [
[
'$id' => ID::custom('_fulltext_name'),
'type' => Database::INDEX_FULLTEXT,
'attributes' => ['name'],
'lengths' => [],
'orders' => [],
],
[
'$id' => ID::custom('_key_search'),
'type' => Database::INDEX_FULLTEXT,
@@ -1853,13 +1846,6 @@ return [
'lengths' => [],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_name'),
'type' => Database::INDEX_FULLTEXT,
'attributes' => ['name'],
'lengths' => [],
'orders' => [Database::ORDER_ASC],
],
[
'$id' => ID::custom('_key_type'),
'type' => Database::INDEX_KEY,
@@ -2127,14 +2113,8 @@ return [
'filters' => ['topicSearch'],
],
],
'indexes' => [
[
'$id' => ID::custom('_key_name'),
'type' => Database::INDEX_FULLTEXT,
'attributes' => ['name'],
'lengths' => [],
'orders' => [],
],
[
'$id' => ID::custom('_key_search'),
'type' => Database::INDEX_FULLTEXT,
+1 -1
View File
@@ -26,7 +26,7 @@ $console = [
'hostname' => 'localhost',
], // Current host is added on app init
],
'region' => 'fra',
'region' => System::getEnv('_APP_REGION', 'default'),
'legalName' => '',
'legalCountry' => '',
'legalState' => '',
+15
View File
@@ -139,6 +139,11 @@ return [
'description' => 'There was an error processing your request. Please check the inputs and try again.',
'code' => 400,
],
Exception::GENERAL_FEATURE_UNSUPPORTED => [
'name' => Exception::GENERAL_FEATURE_UNSUPPORTED,
'description' => 'This feature is not supported with your current configuration.',
'code' => 400,
],
/** User Errors */
Exception::USER_COUNT_EXCEEDED => [
@@ -625,6 +630,11 @@ return [
'description' => 'Site with the requested ID could not be found.',
'code' => 404,
],
Exception::SITE_ALREADY_EXISTS => [
'name' => Exception::SITE_ALREADY_EXISTS,
'description' => 'Site with the requested ID already exists. Try again with a different ID or use ID.unique() to generate a unique ID.',
'code' => 409,
],
Exception::SITE_TEMPLATE_NOT_FOUND => [
'name' => Exception::SITE_TEMPLATE_NOT_FOUND,
'description' => 'Site Template with the requested ID could not be found.',
@@ -1286,6 +1296,11 @@ return [
'description' => 'Message with the requested ID could not be found.',
'code' => 404,
],
Exception::MESSAGE_ALREADY_EXISTS => [
'name' => Exception::MESSAGE_ALREADY_EXISTS,
'description' => 'Message with the requested ID already exists. Try again with a different ID or use ID.unique() to generate a unique ID.',
'code' => 409,
],
Exception::MESSAGE_MISSING_TARGET => [
'name' => Exception::MESSAGE_MISSING_TARGET,
'description' => 'Message with the requested ID has no recipients (topics or users or targets).',
+19
View File
@@ -289,6 +289,25 @@ return [
'repoBranch' => 'main',
'changelog' => \realpath(__DIR__ . '/../../docs/sdks/agent-skills/CHANGELOG.md'),
],
[
'key' => 'cursor-plugin',
'name' => 'CursorPlugin',
'version' => '0.1.0',
'url' => 'https://github.com/appwrite/cursor-plugin.git',
'enabled' => true,
'beta' => false,
'dev' => false,
'hidden' => false,
'family' => APP_SDK_PLATFORM_CONSOLE,
'prism' => 'cursor-plugin',
'source' => \realpath(__DIR__ . '/../sdks/console-cursor-plugin'),
'gitUrl' => 'git@github.com:appwrite/cursor-plugin.git',
'gitRepoName' => 'cursor-plugin',
'gitUserName' => 'appwrite',
'gitBranch' => 'dev',
'repoBranch' => 'main',
'changelog' => \realpath(__DIR__ . '/../../docs/sdks/cursor-plugin/CHANGELOG.md'),
],
],
],
+2 -2
View File
@@ -160,7 +160,7 @@ return [
'name' => 'Teams',
'subtitle' => 'The Teams service allows you to group users of your project and to enable them to share read and write access to your project resources',
'description' => '/docs/services/teams.md',
'controller' => 'api/teams.php',
'controller' => '', // Uses modules
'sdk' => true,
'docs' => true,
'docsUrl' => 'https://appwrite.io/docs/client/teams',
@@ -188,7 +188,7 @@ return [
'name' => 'VCS',
'subtitle' => 'The VCS service allows you to interact with providers like GitHub, GitLab etc.',
'description' => '',
'controller' => 'api/vcs.php',
'controller' => '', // Uses modules
'sdk' => false,
'docs' => false,
'docsUrl' => '',
+69 -69
View File
@@ -358,15 +358,6 @@ return [
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_ADAPTER',
'description' => 'Which database adapter to use. Must be one of: mariadb, postgresql.',
'introduction' => '1.6.0',
'default' => 'mariadb',
'required' => true,
'question' => 'Choose your database (mariadb|postgresql)',
'filter' => ''
],
[
'name' => '_APP_TRUSTED_HEADERS',
'description' => 'This option allows you to set the list of trusted headers, the value is a commaseparated list of HTTP header names, evaluated left-to-right for the first valid IP. Header names are treated case-insensitively.',
@@ -378,6 +369,75 @@ return [
]
],
],
[
'category' => 'Database',
'description' => 'Appwrite uses a database for storing user and meta data. You can choose between MariaDB, MongoDB or PostgreSQL.',
'variables' => [
[
'name' => '_APP_DB_ADAPTER',
'description' => 'Which database to use. Must be one of: MariaDB, MongoDB, or PostgreSQL',
'introduction' => '1.9.0',
'default' => 'mongodb',
'required' => true,
'question' => 'Choose your database (mariadb|mongodb|postgresql)',
'filter' => ''
],
[
'name' => '_APP_DB_HOST',
'description' => 'Database server host name address. Default value is: \'mongodb\'.',
'introduction' => '',
'default' => 'mongodb',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_PORT',
'description' => 'Database server TCP port. Default value is: \'27017\'.',
'introduction' => '',
'default' => '27017',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_SCHEMA',
'description' => 'Database server database schema. Default value is: \'appwrite\'.',
'introduction' => '',
'default' => 'appwrite',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_USER',
'description' => 'Database server user name. Default value is: \'user\'.',
'introduction' => '',
'default' => 'user',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_PASS',
'description' => 'Database server user password. Default value is: \'password\'.',
'introduction' => '',
'default' => 'password',
'required' => false,
'question' => '',
'filter' => 'password'
],
[
'name' => '_APP_DB_ROOT_PASS',
'description' => 'Database server root password. Default value is: \'rootsecretpassword\'.',
'introduction' => '',
'default' => 'rootsecretpassword',
'required' => false,
'question' => '',
'filter' => 'password'
],
],
],
[
'category' => 'Redis',
'description' => 'Appwrite uses a Redis server for managing cache, queues and scheduled tasks. The Redis env vars are used to allow Appwrite server to connect to the Redis container.',
@@ -420,66 +480,6 @@ return [
],
],
],
[
'category' => 'MariaDB',
'description' => 'Appwrite is using a MariaDB server for managing persistent database data. The MariaDB env vars are used to allow Appwrite server to connect to the MariaDB container.',
'variables' => [
[
'name' => '_APP_DB_HOST',
'description' => 'MariaDB server host name address. Default value is: \'mariadb\'.',
'introduction' => '',
'default' => 'mariadb',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_PORT',
'description' => 'MariaDB server TCP port. Default value is: \'3306\'.',
'introduction' => '',
'default' => '3306',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_SCHEMA',
'description' => 'MariaDB server database schema. Default value is: \'appwrite\'.',
'introduction' => '',
'default' => 'appwrite',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_USER',
'description' => 'MariaDB server user name. Default value is: \'user\'.',
'introduction' => '',
'default' => 'user',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_DB_PASS',
'description' => 'MariaDB server user password. Default value is: \'password\'.',
'introduction' => '',
'default' => 'password',
'required' => false,
'question' => '',
'filter' => 'password'
],
[
'name' => '_APP_DB_ROOT_PASS',
'description' => 'MariaDB server root password. Default value is: \'rootsecretpassword\'.',
'introduction' => '',
'default' => 'rootsecretpassword',
'required' => false,
'question' => '',
'filter' => 'password'
],
],
],
[
'category' => 'InfluxDB',
'description' => 'Deprecated since 1.4.8.',
+36 -32
View File
@@ -367,7 +367,7 @@ Http::post('/v1/account')
contentType: ContentType::JSON
))
->label('abuse-limit', 10)
->param('userId', '', new CustomId(), '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.')
->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 PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), '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)
@@ -728,7 +728,7 @@ Http::get('/v1/account/sessions/:sessionId')
],
contentType: ContentType::JSON
))
->param('sessionId', '', new UID(), 'Session ID. Use the string \'current\' to get the current device session.')
->param('sessionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Session ID. Use the string \'current\' to get the current device session.', false, ['dbForProject'])
->inject('response')
->inject('user')
->inject('locale')
@@ -780,7 +780,7 @@ Http::delete('/v1/account/sessions/:sessionId')
contentType: ContentType::NONE
))
->label('abuse-limit', 100)
->param('sessionId', '', new UID(), 'Session ID. Use the string \'current\' to delete the current device session.')
->param('sessionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Session ID. Use the string \'current\' to delete the current device session.', false, ['dbForProject'])
->inject('requestTimestamp')
->inject('request')
->inject('response')
@@ -868,7 +868,7 @@ Http::patch('/v1/account/sessions/:sessionId')
contentType: ContentType::JSON
))
->label('abuse-limit', 10)
->param('sessionId', '', new UID(), 'Session ID. Use the string \'current\' to update the current device session.')
->param('sessionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Session ID. Use the string \'current\' to update the current device session.', false, ['dbForProject'])
->inject('response')
->inject('user')
->inject('dbForProject')
@@ -902,13 +902,13 @@ Http::patch('/v1/account/sessions/:sessionId')
// Refresh OAuth access token
$provider = $session->getAttribute('provider', '');
$refreshToken = $session->getAttribute('providerRefreshToken', '');
$oAuthProviders = Config::getParam('oAuthProviders');
$className = $oAuthProviders[$provider]['class'];
if (!\class_exists($className)) {
$oAuthProviders = Config::getParam('oAuthProviders') ?? [];
$className = $oAuthProviders[$provider]['class'] ?? null;
if (!empty($provider) && ($className === null || !\class_exists($className))) {
throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);
}
if (!empty($provider) && \class_exists($className)) {
if (!empty($provider) && $className !== null && \class_exists($className)) {
$appId = $project->getAttribute('oAuthProviders', [])[$provider . 'Appid'] ?? '';
$appSecret = $project->getAttribute('oAuthProviders', [])[$provider . 'Secret'] ?? '{}';
@@ -1262,7 +1262,7 @@ Http::post('/v1/account/sessions/token')
->label('abuse-limit', 10)
->label('abuse-key', 'ip:{ip},userId:{param-userId}')
->label('abuse-reset', [201])
->param('userId', '', new CustomId(), '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.')
->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('secret', '', new Text(256), 'Secret of a token generated by login methods. For example, the `createMagicURLToken` or `createPhoneToken` methods.')
->inject('request')
->inject('response')
@@ -1340,9 +1340,9 @@ Http::get('/v1/account/sessions/oauth2/:provider')
throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please configure the provider app ID and app secret key from your ' . APP_NAME . ' console to continue.');
}
$oAuthProviders = Config::getParam('oAuthProviders');
$className = $oAuthProviders[$provider]['class'];
if (!\class_exists($className)) {
$oAuthProviders = Config::getParam('oAuthProviders') ?? [];
$className = $oAuthProviders[$provider]['class'] ?? null;
if ($className === null || !\class_exists($className)) {
throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);
}
@@ -1485,19 +1485,20 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
} elseif ($protocol === 'http' && $port !== '80') {
$callbackBase .= ':' . $port;
}
$callback = $callbackBase . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project->getId();
$defaultState = ['success' => $project->getAttribute('url', ''), 'failure' => ''];
$appId = $project->getAttribute('oAuthProviders', [])[$provider . 'Appid'] ?? '';
$appSecret = $project->getAttribute('oAuthProviders', [])[$provider . 'Secret'] ?? '{}';
$providerEnabled = $project->getAttribute('oAuthProviders', [])[$provider . 'Enabled'] ?? false;
$oAuthProviders = Config::getParam('oAuthProviders');
$className = $oAuthProviders[$provider]['class'];
if (!\class_exists($className)) {
$oAuthProviders = Config::getParam('oAuthProviders') ?? [];
$className = $oAuthProviders[$provider]['class'] ?? null;
if ($className === null || !\class_exists($className)) {
throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);
}
$providers = Config::getParam('oAuthProviders');
$providers = Config::getParam('oAuthProviders') ?? [];
$providerName = $providers[$provider]['name'] ?? '';
/** @var Appwrite\Auth\OAuth2 $oauth2 */
@@ -1547,6 +1548,7 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
if (!empty($state['failure'])) {
$failure = URLParser::parse($state['failure']);
}
$failureRedirect = (function (string $type, ?string $message = null, ?int $code = null) use ($failure, $response) {
$exception = new Exception($type, $message, $code);
if (!empty($failure)) {
@@ -1592,7 +1594,9 @@ Http::get('/v1/account/sessions/oauth2/:provider/redirect')
$accessToken = $oauth2->getAccessToken($code);
$refreshToken = $oauth2->getRefreshToken($code);
$accessTokenExpiry = $oauth2->getAccessTokenExpiry($code);
} catch (OAuth2Exception $ex) {
$failureRedirect(
$ex->getType(),
'Failed to obtain access token. The ' . $providerName . ' OAuth2 provider returned an error: ' . $ex->getMessage(),
@@ -2031,9 +2035,9 @@ Http::get('/v1/account/tokens/oauth2/:provider')
throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please configure the provider app ID and app secret key from your ' . APP_NAME . ' console to continue.');
}
$oAuthProviders = Config::getParam('oAuthProviders');
$className = $oAuthProviders[$provider]['class'];
if (!\class_exists($className)) {
$oAuthProviders = Config::getParam('oAuthProviders') ?? [];
$className = $oAuthProviders[$provider]['class'] ?? null;
if ($className === null || !\class_exists($className)) {
throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);
}
@@ -2092,7 +2096,7 @@ Http::post('/v1/account/tokens/magic-url')
))
->label('abuse-limit', 60)
->label('abuse-key', ['url:{url},email:{param-email}', 'url:{url},ip:{ip}'])
->param('userId', '', new CustomId(), 'Unique 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. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.')
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Unique 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. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.', false, ['dbForProject'])
->param('email', '', new EmailValidator(), 'User email.')
->param('url', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['redirectValidator'])
->param('phrase', false, new Boolean(), 'Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.', true)
@@ -2372,7 +2376,7 @@ Http::post('/v1/account/tokens/email')
))
->label('abuse-limit', 10)
->label('abuse-key', ['url:{url},email:{param-email}', 'url:{url},ip:{ip}'])
->param('userId', '', new CustomId(), '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. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.')
->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. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored.', false, ['dbForProject'])
->param('email', '', new EmailValidator(), 'User email.')
->param('phrase', false, new Boolean(), 'Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.', true)
->inject('request')
@@ -2679,7 +2683,7 @@ Http::put('/v1/account/sessions/magic-url')
->label('abuse-limit', 10)
->label('abuse-key', 'ip:{ip},userId:{param-userId}')
->label('abuse-reset', [201])
->param('userId', '', new CustomId(), '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.')
->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('secret', '', new Text(256), 'Valid verification token.')
->inject('request')
->inject('response')
@@ -2728,7 +2732,7 @@ Http::put('/v1/account/sessions/phone')
))
->label('abuse-limit', 10)
->label('abuse-key', 'ip:{ip},userId:{param-userId}')
->param('userId', '', new CustomId(), '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.')
->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('secret', '', new Text(256), 'Valid verification token.')
->inject('request')
->inject('response')
@@ -2771,7 +2775,7 @@ Http::post('/v1/account/tokens/phone')
))
->label('abuse-limit', 10)
->label('abuse-key', ['url:{url},phone:{param-phone}', 'url:{url},ip:{ip}'])
->param('userId', '', new CustomId(), 'Unique 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. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored.')
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Unique 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. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored.', false, ['dbForProject'])
->param('phone', '', new Phone(), 'Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.')
->inject('request')
->inject('response')
@@ -3748,7 +3752,7 @@ Http::put('/v1/account/recovery')
))
->label('abuse-limit', 10)
->label('abuse-key', 'url:{url},userId:{param-userId}')
->param('userId', '', new UID(), 'User ID.')
->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 PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
->inject('response')
@@ -4098,7 +4102,7 @@ Http::put('/v1/account/verifications/email')
])
->label('abuse-limit', 10)
->label('abuse-key', 'url:{url},userId:{param-userId}')
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('secret', '', new Text(256), 'Valid verification token.')
->inject('response')
->inject('user')
@@ -4314,7 +4318,7 @@ Http::put('/v1/account/verifications/phone')
))
->label('abuse-limit', 10)
->label('abuse-key', 'userId:{param-userId}')
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('secret', '', new Text(256), 'Valid verification token.')
->inject('response')
->inject('user')
@@ -4379,9 +4383,9 @@ Http::post('/v1/account/targets/push')
],
contentType: ContentType::JSON
))
->param('targetId', '', new CustomId(), 'Target 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.')
->param('targetId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Target 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('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->param('providerId', '', new UID(), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true)
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true, ['dbForProject'])
->inject('queueForEvents')
->inject('user')
->inject('request')
@@ -4463,7 +4467,7 @@ Http::put('/v1/account/targets/:targetId/push')
],
contentType: ContentType::JSON
))
->param('targetId', '', new UID(), 'Target ID.')
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID.', false, ['dbForProject'])
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->inject('queueForEvents')
->inject('user')
@@ -4529,7 +4533,7 @@ Http::delete('/v1/account/targets/:targetId/push')
],
contentType: ContentType::NONE
))
->param('targetId', '', new UID(), 'Target ID.')
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('queueForDeletes')
->inject('user')
@@ -4651,7 +4655,7 @@ Http::delete('/v1/account/identities/:identityId')
],
contentType: ContentType::NONE
))
->param('identityId', '', new UID(), 'Identity ID.')
->param('identityId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Identity ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
+93 -78
View File
@@ -78,7 +78,7 @@ Http::post('/v1/messaging/providers/mailgun')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('apiKey', '', new Text(0), 'Mailgun API Key.', true)
->param('domain', '', new Text(0), 'Mailgun Domain.', true)
@@ -172,7 +172,7 @@ Http::post('/v1/messaging/providers/sendgrid')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('apiKey', '', new Text(0), 'Sendgrid API key.', true)
->param('fromName', '', new Text(128, 0), 'Sender Name.', true)
@@ -254,7 +254,7 @@ Http::post('/v1/messaging/providers/resend')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('apiKey', '', new Text(0), 'Resend API key.', true)
->param('fromName', '', new Text(128, 0), 'Sender Name.', true)
@@ -356,7 +356,7 @@ Http::post('/v1/messaging/providers/smtp')
]
)
])
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->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)
@@ -451,7 +451,7 @@ Http::post('/v1/messaging/providers/msg91')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('templateId', '', new Text(0), 'Msg91 template ID', true)
->param('senderId', '', new Text(0), 'Msg91 sender ID.', true)
@@ -534,7 +534,7 @@ Http::post('/v1/messaging/providers/telesign')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('from', '', new Phone(), 'Sender Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
->param('customerId', '', new Text(0), 'Telesign customer ID.', true)
@@ -618,7 +618,7 @@ Http::post('/v1/messaging/providers/textmagic')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('from', '', new Phone(), 'Sender Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
->param('username', '', new Text(0), 'Textmagic username.', true)
@@ -702,7 +702,7 @@ Http::post('/v1/messaging/providers/twilio')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('from', '', new Phone(), 'Sender Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
->param('accountSid', '', new Text(0), 'Twilio account secret ID.', true)
@@ -786,7 +786,7 @@ Http::post('/v1/messaging/providers/vonage')
)
]
))
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('from', '', new Phone(), 'Sender Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
->param('apiKey', '', new Text(0), 'Vonage API key.', true)
@@ -890,7 +890,7 @@ Http::post('/v1/messaging/providers/fcm')
]
)
])
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('serviceAccountJSON', null, new Nullable(new JSON()), 'FCM service account JSON.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
@@ -980,7 +980,7 @@ Http::post('/v1/messaging/providers/apns')
]
)
])
->param('providerId', '', new CustomId(), 'Provider 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.')
->param('providerId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Provider 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('name', '', new Text(128), 'Provider name.')
->param('authKey', '', new Text(0), 'APNS authentication key.', true)
->param('authKeyId', '', new Text(0), 'APNS authentication key ID.', true)
@@ -1135,7 +1135,7 @@ Http::get('/v1/messaging/providers/:providerId/logs')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -1231,7 +1231,7 @@ Http::get('/v1/messaging/providers/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->inject('dbForProject')
->inject('response')
->action(function (string $providerId, Database $dbForProject, Response $response) {
@@ -1265,7 +1265,7 @@ Http::patch('/v1/messaging/providers/mailgun/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('apiKey', '', new Text(0), 'Mailgun API Key.', true)
->param('domain', '', new Text(0), 'Mailgun Domain.', true)
@@ -1378,7 +1378,7 @@ Http::patch('/v1/messaging/providers/sendgrid/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('apiKey', '', new Text(0), 'Sendgrid API key.', true)
@@ -1476,7 +1476,7 @@ Http::patch('/v1/messaging/providers/resend/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('apiKey', '', new Text(0), 'Resend API key.', true)
@@ -1594,7 +1594,7 @@ Http::patch('/v1/messaging/providers/smtp/:providerId')
]
)
])
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->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)
@@ -1723,7 +1723,7 @@ Http::patch('/v1/messaging/providers/msg91/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('templateId', '', new Text(0), 'Msg91 template ID.', true)
@@ -1810,7 +1810,7 @@ Http::patch('/v1/messaging/providers/telesign/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('customerId', '', new Text(0), 'Telesign customer ID.', true)
@@ -1899,7 +1899,7 @@ Http::patch('/v1/messaging/providers/textmagic/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('username', '', new Text(0), 'Textmagic username.', true)
@@ -1988,7 +1988,7 @@ Http::patch('/v1/messaging/providers/twilio/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('accountSid', '', new Text(0), 'Twilio account secret ID.', true)
@@ -2077,7 +2077,7 @@ Http::patch('/v1/messaging/providers/vonage/:providerId')
)
]
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('apiKey', '', new Text(0), 'Vonage API key.', true)
@@ -2186,7 +2186,7 @@ Http::patch('/v1/messaging/providers/fcm/:providerId')
]
)
])
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('serviceAccountJSON', null, new Nullable(new JSON()), 'FCM service account JSON.', true)
@@ -2282,7 +2282,7 @@ Http::patch('/v1/messaging/providers/apns/:providerId')
]
)
])
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Provider name.', true)
->param('enabled', null, new Nullable(new Boolean()), 'Set as enabled.', true)
->param('authKey', '', new Text(0), 'APNS authentication key.', true)
@@ -2385,7 +2385,7 @@ Http::delete('/v1/messaging/providers/:providerId')
],
contentType: ContentType::NONE
))
->param('providerId', '', new UID(), 'Provider ID.')
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('dbForProject')
->inject('response')
@@ -2427,7 +2427,7 @@ Http::post('/v1/messaging/topics')
)
]
))
->param('topicId', '', new CustomId(), 'Topic ID. Choose a custom Topic ID or a new Topic ID.')
->param('topicId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID. Choose a custom Topic ID or a new Topic ID.', false, ['dbForProject'])
->param('name', '', new Text(128), 'Topic Name.')
->param('subscribe', [Role::users()], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of role strings with subscribe permission. By default all users are granted with any subscribe permission. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.', true)
->inject('queueForEvents')
@@ -2539,7 +2539,7 @@ Http::get('/v1/messaging/topics/:topicId/logs')
)
]
))
->param('topicId', '', new UID(), 'Topic ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID.', false, ['dbForProject'])
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -2636,7 +2636,7 @@ Http::get('/v1/messaging/topics/:topicId')
)
]
))
->param('topicId', '', new UID(), 'Topic ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID.', false, ['dbForProject'])
->inject('dbForProject')
->inject('response')
->action(function (string $topicId, Database $dbForProject, Response $response) {
@@ -2671,7 +2671,7 @@ Http::patch('/v1/messaging/topics/:topicId')
)
]
))
->param('topicId', '', new UID(), 'Topic ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID.', false, ['dbForProject'])
->param('name', null, new Nullable(new Text(128)), 'Topic Name.', true)
->param('subscribe', null, new Nullable(new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE)), 'An array of role strings with subscribe permission. By default all users are granted with any subscribe permission. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.', true)
->inject('queueForEvents')
@@ -2723,7 +2723,7 @@ Http::delete('/v1/messaging/topics/:topicId')
],
contentType: ContentType::NONE
))
->param('topicId', '', new UID(), 'Topic ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('dbForProject')
->inject('queueForDeletes')
@@ -2770,9 +2770,9 @@ Http::post('/v1/messaging/topics/:topicId/subscribers')
)
]
))
->param('subscriberId', '', new CustomId(), 'Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID.')
->param('topicId', '', new UID(), 'Topic ID. The topic ID to subscribe to.')
->param('targetId', '', new UID(), 'Target ID. The target ID to link to the specified Topic ID.')
->param('subscriberId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID.', false, ['dbForProject'])
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID. The topic ID to subscribe to.', false, ['dbForProject'])
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID. The target ID to link to the specified Topic ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('dbForProject')
->inject('authorization')
@@ -2868,8 +2868,8 @@ Http::get('/v1/messaging/topics/:topicId/subscribers')
)
]
))
->param('topicId', '', new UID(), 'Topic ID. The topic ID subscribed to.')
->param('queries', [], new Subscribers(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Providers::ALLOWED_ATTRIBUTES), true)
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID. The topic ID subscribed to.', false, ['dbForProject'])
->param('queries', [], new Subscribers(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Subscribers::ALLOWED_ATTRIBUTES), true)
->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('dbForProject')
@@ -2954,7 +2954,7 @@ Http::get('/v1/messaging/subscribers/:subscriberId/logs')
)
]
))
->param('subscriberId', '', new UID(), 'Subscriber ID.')
->param('subscriberId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Subscriber ID.', false, ['dbForProject'])
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -3051,8 +3051,8 @@ Http::get('/v1/messaging/topics/:topicId/subscribers/:subscriberId')
)
]
))
->param('topicId', '', new UID(), 'Topic ID. The topic ID subscribed to.')
->param('subscriberId', '', new UID(), 'Subscriber ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID. The topic ID subscribed to.', false, ['dbForProject'])
->param('subscriberId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Subscriber ID.', false, ['dbForProject'])
->inject('dbForProject')
->inject('authorization')
->inject('response')
@@ -3102,8 +3102,8 @@ Http::delete('/v1/messaging/topics/:topicId/subscribers/:subscriberId')
],
contentType: ContentType::NONE
))
->param('topicId', '', new UID(), 'Topic ID. The topic ID subscribed to.')
->param('subscriberId', '', new UID(), 'Subscriber ID.')
->param('topicId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Topic ID. The topic ID subscribed to.', false, ['dbForProject'])
->param('subscriberId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Subscriber ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('dbForProject')
->inject('authorization')
@@ -3169,14 +3169,14 @@ Http::post('/v1/messaging/messages/email')
)
]
))
->param('messageId', '', new CustomId(), 'Message 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.')
->param('messageId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Message 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('subject', '', new Text(998), 'Email Subject.')
->param('content', '', new Text(64230), 'Email Content.')
->param('topics', [], new ArrayList(new UID()), 'List of Topic IDs.', true)
->param('users', [], new ArrayList(new UID()), 'List of User IDs.', true)
->param('targets', [], new ArrayList(new UID()), 'List of Targets IDs.', true)
->param('cc', [], new ArrayList(new UID()), 'Array of target IDs to be added as CC.', true)
->param('bcc', [], new ArrayList(new UID()), 'Array of target IDs to be added as BCC.', true)
->param('topics', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of User IDs.', true, ['dbForProject'])
->param('targets', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Targets IDs.', true, ['dbForProject'])
->param('cc', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'Array of target IDs to be added as CC.', true, ['dbForProject'])
->param('bcc', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'Array of target IDs to be added as BCC.', true, ['dbForProject'])
->param('attachments', [], new ArrayList(new CompoundUID()), 'Array of compound ID strings of bucket IDs and file IDs to be attached to the email. They should be formatted as <BUCKET_ID>:<FILE_ID>.', true)
->param('draft', false, new Boolean(), 'Is message a draft', true)
->param('html', false, new Boolean(), 'Is content of type HTML', true)
@@ -3251,7 +3251,7 @@ Http::post('/v1/messaging/messages/email')
}
}
$message = $dbForProject->createDocument('messages', new Document([
$message = new Document([
'$id' => $messageId,
'providerType' => MESSAGE_TYPE_EMAIL,
'topics' => $topics,
@@ -3267,7 +3267,12 @@ Http::post('/v1/messaging/messages/email')
'attachments' => $attachments,
],
'status' => $status,
]));
]);
try {
$message = $dbForProject->createDocument('messages', $message);
} catch (DuplicateException) {
throw new Exception(Exception::MESSAGE_ALREADY_EXISTS);
}
switch ($status) {
case MessageStatus::PROCESSING:
@@ -3348,11 +3353,11 @@ Http::post('/v1/messaging/messages/sms')
]
)
])
->param('messageId', '', new CustomId(), 'Message 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.')
->param('messageId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Message 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('content', '', new Text(64230), 'SMS Content.')
->param('topics', [], new ArrayList(new UID()), 'List of Topic IDs.', true)
->param('users', [], new ArrayList(new UID()), 'List of User IDs.', true)
->param('targets', [], new ArrayList(new UID()), 'List of Targets IDs.', true)
->param('topics', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of User IDs.', true, ['dbForProject'])
->param('targets', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Targets IDs.', true, ['dbForProject'])
->param('draft', false, new Boolean(), 'Is message a draft', true)
->param('scheduledAt', null, new Nullable(new DatetimeValidator(requireDateInFuture: true)), 'Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.', true)
->inject('queueForEvents')
@@ -3400,7 +3405,7 @@ Http::post('/v1/messaging/messages/sms')
}
}
$message = $dbForProject->createDocument('messages', new Document([
$message = new Document([
'$id' => $messageId,
'providerType' => MESSAGE_TYPE_SMS,
'topics' => $topics,
@@ -3410,7 +3415,12 @@ Http::post('/v1/messaging/messages/sms')
'content' => $content,
],
'status' => $status,
]));
]);
try {
$message = $dbForProject->createDocument('messages', $message);
} catch (DuplicateException) {
throw new Exception(Exception::MESSAGE_ALREADY_EXISTS);
}
switch ($status) {
case MessageStatus::PROCESSING:
@@ -3471,12 +3481,12 @@ Http::post('/v1/messaging/messages/push')
)
]
))
->param('messageId', '', new CustomId(), 'Message 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.')
->param('messageId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Message 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('title', '', new Text(256), 'Title for push notification.', true)
->param('body', '', new Text(64230), 'Body for push notification.', true)
->param('topics', [], new ArrayList(new UID()), 'List of Topic IDs.', true)
->param('users', [], new ArrayList(new UID()), 'List of User IDs.', true)
->param('targets', [], new ArrayList(new UID()), 'List of Targets IDs.', true)
->param('topics', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of User IDs.', true, ['dbForProject'])
->param('targets', [], fn (Database $dbForProject) => new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'List of Targets IDs.', true, ['dbForProject'])
->param('data', null, new Nullable(new JSON()), 'Additional key-value pair data for push notification.', true)
->param('action', '', new Text(256), 'Action for push notification.', true)
->param('image', '', new CompoundUID(), 'Image for push notification. Must be a compound bucket ID to file ID of a jpeg, png, or bmp image in Appwrite Storage. It should be formatted as <BUCKET_ID>:<FILE_ID>.', true)
@@ -3620,7 +3630,7 @@ Http::post('/v1/messaging/messages/push')
$pushData['priority'] = $priority;
}
$message = $dbForProject->createDocument('messages', new Document([
$message = new Document([
'$id' => $messageId,
'providerType' => MESSAGE_TYPE_PUSH,
'topics' => $topics,
@@ -3629,7 +3639,12 @@ Http::post('/v1/messaging/messages/push')
'scheduledAt' => $scheduledAt,
'data' => $pushData,
'status' => $status,
]));
]);
try {
$message = $dbForProject->createDocument('messages', $message);
} catch (DuplicateException) {
throw new Exception(Exception::MESSAGE_ALREADY_EXISTS);
}
switch ($status) {
case MessageStatus::PROCESSING:
@@ -3752,7 +3767,7 @@ Http::get('/v1/messaging/messages/:messageId/logs')
)
],
))
->param('messageId', '', new UID(), 'Message ID.')
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -3849,7 +3864,7 @@ Http::get('/v1/messaging/messages/:messageId/targets')
)
],
))
->param('messageId', '', new UID(), 'Message ID.')
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->param('queries', [], new Targets(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Targets::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -3927,7 +3942,7 @@ Http::get('/v1/messaging/messages/:messageId')
)
]
))
->param('messageId', '', new UID(), 'Message ID.')
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->inject('dbForProject')
->inject('response')
->action(function (string $messageId, Database $dbForProject, Response $response) {
@@ -3961,16 +3976,16 @@ Http::patch('/v1/messaging/messages/email/:messageId')
)
]
))
->param('messageId', '', new UID(), 'Message ID.')
->param('topics', null, new Nullable(new ArrayList(new UID())), 'List of Topic IDs.', true)
->param('users', null, new Nullable(new ArrayList(new UID())), 'List of User IDs.', true)
->param('targets', null, new Nullable(new ArrayList(new UID())), 'List of Targets IDs.', true)
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->param('topics', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of User IDs.', true, ['dbForProject'])
->param('targets', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Targets IDs.', true, ['dbForProject'])
->param('subject', null, new Nullable(new Text(998)), 'Email Subject.', true)
->param('content', null, new Nullable(new Text(64230)), 'Email Content.', true)
->param('draft', null, new Nullable(new Boolean()), 'Is message a draft', true)
->param('html', null, new Nullable(new Boolean()), 'Is content of type HTML', true)
->param('cc', null, new Nullable(new ArrayList(new UID())), 'Array of target IDs to be added as CC.', true)
->param('bcc', null, new Nullable(new ArrayList(new UID())), 'Array of target IDs to be added as BCC.', true)
->param('cc', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'Array of target IDs to be added as CC.', true, ['dbForProject'])
->param('bcc', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'Array of target IDs to be added as BCC.', true, ['dbForProject'])
->param('scheduledAt', null, new Nullable(new DatetimeValidator(requireDateInFuture: true)), 'Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.', true)
->param('attachments', null, new Nullable(new ArrayList(new CompoundUID())), 'Array of compound ID strings of bucket IDs and file IDs to be attached to the email. They should be formatted as <BUCKET_ID>:<FILE_ID>.', true)
->inject('queueForEvents')
@@ -4188,10 +4203,10 @@ Http::patch('/v1/messaging/messages/sms/:messageId')
]
)
])
->param('messageId', '', new UID(), 'Message ID.')
->param('topics', null, new Nullable(new ArrayList(new UID())), 'List of Topic IDs.', true)
->param('users', null, new Nullable(new ArrayList(new UID())), 'List of User IDs.', true)
->param('targets', null, new Nullable(new ArrayList(new UID())), 'List of Targets IDs.', true)
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->param('topics', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of User IDs.', true, ['dbForProject'])
->param('targets', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Targets IDs.', true, ['dbForProject'])
->param('content', null, new Nullable(new Text(64230)), 'Email Content.', true)
->param('draft', null, new Nullable(new Boolean()), 'Is message a draft', true)
->param('scheduledAt', null, new Nullable(new DatetimeValidator(requireDateInFuture: true)), 'Scheduled delivery time for message in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future.', true)
@@ -4350,10 +4365,10 @@ Http::patch('/v1/messaging/messages/push/:messageId')
)
]
))
->param('messageId', '', new UID(), 'Message ID.')
->param('topics', null, new Nullable(new ArrayList(new UID())), 'List of Topic IDs.', true)
->param('users', null, new Nullable(new ArrayList(new UID())), 'List of User IDs.', true)
->param('targets', null, new Nullable(new ArrayList(new UID())), 'List of Targets IDs.', true)
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->param('topics', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Topic IDs.', true, ['dbForProject'])
->param('users', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of User IDs.', true, ['dbForProject'])
->param('targets', null, fn (Database $dbForProject) => new Nullable(new ArrayList(new UID($dbForProject->getAdapter()->getMaxUIDLength()))), 'List of Targets IDs.', true, ['dbForProject'])
->param('title', null, new Nullable(new Text(256)), 'Title for push notification.', true)
->param('body', null, new Nullable(new Text(64230)), 'Body for push notification.', true)
->param('data', null, new Nullable(new JSON()), 'Additional Data for push notification.', true)
@@ -4612,7 +4627,7 @@ Http::delete('/v1/messaging/messages/:messageId')
],
contentType: ContentType::NONE
))
->param('messageId', '', new UID(), 'Message ID.')
->param('messageId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Message ID.', false, ['dbForProject'])
->inject('dbForProject')
->inject('dbForPlatform')
->inject('queueForEvents')
+6 -6
View File
@@ -64,7 +64,7 @@ Http::post('/v1/migrations/appwrite')
))
->param('resources', [], new ArrayList(new WhiteList(Appwrite::getSupportedResources())), 'List of resources to migrate')
->param('endpoint', '', new URL(), 'Source Appwrite endpoint')
->param('projectId', '', new UID(), 'Source Project ID')
->param('projectId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Source Project ID', false, ['dbForProject'])
->param('apiKey', '', new Text(512), 'Source API Key')
->inject('response')
->inject('dbForProject')
@@ -335,8 +335,8 @@ Http::post('/v1/migrations/csv/imports')
)
]
))
->param('bucketId', '', new UID(), 'Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).')
->param('fileId', '', new UID(), 'File ID.')
->param('bucketId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket).', false, ['dbForProject'])
->param('fileId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'File ID.', false, ['dbForProject'])
->param('resourceId', null, new CompoundUID(), 'Composite ID in the format {databaseId:collectionId}, identifying a collection within a database.')
->param('internalFile', false, new Boolean(), 'Is the file stored in an internal bucket?', true)
->inject('response')
@@ -678,7 +678,7 @@ Http::get('/v1/migrations/:migrationId')
)
]
))
->param('migrationId', '', new UID(), 'Migration unique ID.')
->param('migrationId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Migration unique ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $migrationId, Response $response, Database $dbForProject) {
@@ -911,7 +911,7 @@ Http::patch('/v1/migrations/:migrationId')
)
]
))
->param('migrationId', '', new UID(), 'Migration unique ID.')
->param('migrationId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Migration unique ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('project')
@@ -965,7 +965,7 @@ Http::delete('/v1/migrations/:migrationId')
],
contentType: ContentType::NONE
))
->param('migrationId', '', new UID(), 'Migration ID.')
->param('migrationId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Migration ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
+3 -3
View File
@@ -496,7 +496,7 @@ Http::get('/v1/project/variables/:variableId')
)
]
))
->param('variableId', '', new UID(), 'Variable unique ID.', false)
->param('variableId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Variable unique ID.', false, ['dbForProject'])
->inject('response')
->inject('project')
->inject('dbForProject')
@@ -526,7 +526,7 @@ Http::put('/v1/project/variables/:variableId')
)
]
))
->param('variableId', '', new UID(), 'Variable unique ID.', false)
->param('variableId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Variable unique ID.', false, ['dbForProject'])
->param('key', null, new Text(255), 'Variable key. Max length: 255 chars.', false)
->param('value', null, new Nullable(new Text(8192, 0)), 'Variable value. Max length: 8192 chars.', true)
->param('secret', null, new Nullable(new Boolean()), 'Secret variables can be updated or deleted, but only projects can read them during build and runtime.', true)
@@ -585,7 +585,7 @@ Http::delete('/v1/project/variables/:variableId')
],
contentType: ContentType::NONE
))
->param('variableId', '', new UID(), 'Variable unique ID.', false)
->param('variableId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Variable unique ID.', false, ['dbForProject'])
->inject('project')
->inject('response')
->inject('dbForProject')
+54 -55
View File
@@ -71,7 +71,7 @@ Http::get('/v1/projects/:projectId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, Response $response, Database $dbForPlatform) {
@@ -102,7 +102,7 @@ Http::patch('/v1/projects/:projectId/service')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('service', '', new WhiteList(array_keys(array_filter(Config::getParam('services'), fn ($element) => $element['optional'])), true), 'Service name.')
->param('status', null, new Boolean(), 'Service status.')
->inject('response')
@@ -140,7 +140,7 @@ Http::patch('/v1/projects/:projectId/service/all')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('status', null, new Boolean(), 'Service status.')
->inject('response')
->inject('dbForPlatform')
@@ -201,7 +201,7 @@ Http::patch('/v1/projects/:projectId/api')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('api', '', new WhiteList(array_keys(Config::getParam('apis')), true), 'API name.')
->param('status', null, new Boolean(), 'API status.')
->inject('response')
@@ -259,7 +259,7 @@ Http::patch('/v1/projects/:projectId/api/all')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('status', null, new Boolean(), 'API status.')
->inject('response')
->inject('dbForPlatform')
@@ -300,7 +300,7 @@ Http::patch('/v1/projects/:projectId/oauth2')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('provider', '', new WhiteList(\array_keys(Config::getParam('oAuthProviders')), true), 'Provider Name')
->param('appId', null, new Nullable(new Text(256)), 'Provider app ID. Max length: 256 chars.', true)
->param('secret', null, new Nullable(new text(512)), 'Provider secret key. Max length: 512 chars.', true)
@@ -351,7 +351,7 @@ Http::patch('/v1/projects/:projectId/auth/session-alerts')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('alerts', false, new Boolean(true), 'Set to true to enable session emails.')
->inject('response')
->inject('dbForPlatform')
@@ -389,7 +389,7 @@ Http::patch('/v1/projects/:projectId/auth/memberships-privacy')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('userName', true, new Boolean(true), 'Set to true to show userName to members of a team.')
->param('userEmail', true, new Boolean(true), 'Set to true to show email to members of a team.')
->param('mfa', true, new Boolean(true), 'Set to true to show mfa to members of a team.')
@@ -431,7 +431,7 @@ Http::patch('/v1/projects/:projectId/auth/limit')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('limit', false, new Range(0, APP_LIMIT_USERS), 'Set the max number of users allowed in this project. Use 0 for unlimited.')
->inject('response')
->inject('dbForPlatform')
@@ -469,7 +469,7 @@ Http::patch('/v1/projects/:projectId/auth/duration')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('duration', 31536000, new Range(0, 31536000), 'Project session length in seconds. Max length: 31536000 seconds.')
->inject('response')
->inject('dbForPlatform')
@@ -507,7 +507,7 @@ Http::patch('/v1/projects/:projectId/auth/:method')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('method', '', new WhiteList(\array_keys(Config::getParam('auth')), true), 'Auth Method. Possible values: ' . implode(',', \array_keys(Config::getParam('auth'))), false)
->param('status', false, new Boolean(true), 'Set the status of this auth method.')
->inject('response')
@@ -548,7 +548,7 @@ Http::patch('/v1/projects/:projectId/auth/password-history')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('limit', 0, new Range(0, APP_LIMIT_USER_PASSWORD_HISTORY), 'Set the max number of passwords to store in user history. User can\'t choose a new password that is already stored in the password history list. Max number of passwords allowed in history is' . APP_LIMIT_USER_PASSWORD_HISTORY . '. Default value is 0')
->inject('response')
->inject('dbForPlatform')
@@ -586,7 +586,7 @@ Http::patch('/v1/projects/:projectId/auth/password-dictionary')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('enabled', false, new Boolean(false), 'Set whether or not to enable checking user\'s password against most commonly used passwords. Default is false.')
->inject('response')
->inject('dbForPlatform')
@@ -624,7 +624,7 @@ Http::patch('/v1/projects/:projectId/auth/personal-data')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('enabled', false, new Boolean(false), 'Set whether or not to check a password for similarity with personal data. Default is false.')
->inject('response')
->inject('dbForPlatform')
@@ -662,7 +662,7 @@ Http::patch('/v1/projects/:projectId/auth/max-sessions')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('limit', false, new Range(1, APP_LIMIT_USER_SESSIONS_MAX), 'Set the max number of users allowed in this project. Value allowed is between 1-' . APP_LIMIT_USER_SESSIONS_MAX . '. Default is ' . APP_LIMIT_USER_SESSIONS_DEFAULT)
->inject('response')
->inject('dbForPlatform')
@@ -700,7 +700,7 @@ Http::patch('/v1/projects/:projectId/auth/mock-numbers')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('numbers', '', new ArrayList(new MockNumber(), 10), 'An array of mock numbers and their corresponding verification codes (OTPs). Each number should be a valid E.164 formatted phone number. Maximum of 10 numbers are allowed.')
->inject('response')
->inject('dbForPlatform')
@@ -749,7 +749,7 @@ Http::delete('/v1/projects/:projectId')
],
contentType: ContentType::NONE
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('user')
->inject('dbForPlatform')
@@ -792,7 +792,7 @@ Http::post('/v1/projects/:projectId/webhooks')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Webhook name. Max length: 128 chars.')
->param('enabled', true, new Boolean(true), 'Enable or disable a webhook.', true)
->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.')
@@ -857,7 +857,7 @@ Http::get('/v1/projects/:projectId/webhooks')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('dbForPlatform')
@@ -897,8 +897,8 @@ Http::get('/v1/projects/:projectId/webhooks/:webhookId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('webhookId', '', new UID(), 'Webhook unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('webhookId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Webhook unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $webhookId, Response $response, Database $dbForPlatform) {
@@ -938,8 +938,8 @@ Http::put('/v1/projects/:projectId/webhooks/:webhookId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('webhookId', '', new UID(), 'Webhook unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('webhookId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Webhook unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Webhook name. Max length: 128 chars.')
->param('enabled', true, new Boolean(true), 'Enable or disable a webhook.', true)
->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.')
@@ -1004,8 +1004,8 @@ Http::patch('/v1/projects/:projectId/webhooks/:webhookId/signature')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('webhookId', '', new UID(), 'Webhook unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('webhookId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Webhook unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $webhookId, Response $response, Database $dbForPlatform) {
@@ -1051,8 +1051,8 @@ Http::delete('/v1/projects/:projectId/webhooks/:webhookId')
],
contentType: ContentType::NONE
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('webhookId', '', new UID(), 'Webhook unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('webhookId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Webhook unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $webhookId, Response $response, Database $dbForPlatform) {
@@ -1098,10 +1098,9 @@ Http::post('/v1/projects/:projectId/keys')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
// TODO: When migrating to Platform API, mark keyId required for consistency
->param('keyId', 'unique()', new CustomId(), 'Key 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.', true)
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('keyId', 'unique()', fn (Database $dbForPlatform) => new CustomId($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key 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.', true, ['dbForPlatform'])->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.')
->param('expire', null, new Nullable(new DatetimeValidator()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
->inject('response')
@@ -1163,7 +1162,7 @@ Http::get('/v1/projects/:projectId/keys')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('queries', [], new Keys(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Keys::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -1236,8 +1235,8 @@ Http::get('/v1/projects/:projectId/keys/:keyId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('keyId', '', new UID(), 'Key unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, Response $response, Database $dbForPlatform) {
@@ -1278,8 +1277,8 @@ Http::put('/v1/projects/:projectId/keys/:keyId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('keyId', '', new UID(), 'Key unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.')
->param('expire', null, new Nullable(new DatetimeValidator()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
@@ -1333,8 +1332,8 @@ Http::delete('/v1/projects/:projectId/keys/:keyId')
],
contentType: ContentType::NONE
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('keyId', '', new UID(), 'Key unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, Response $response, Database $dbForPlatform) {
@@ -1381,7 +1380,7 @@ Http::post('/v1/projects/:projectId/jwts')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('scopes', [], new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'List of scopes allowed for JWT key. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.')
->param('duration', 900, new Range(0, 3600), 'Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds.', true)
->inject('response')
@@ -1425,7 +1424,7 @@ Http::post('/v1/projects/:projectId/platforms')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param(
'type',
null,
@@ -1503,7 +1502,7 @@ Http::get('/v1/projects/:projectId/platforms')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('dbForPlatform')
@@ -1543,8 +1542,8 @@ Http::get('/v1/projects/:projectId/platforms/:platformId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('platformId', '', new UID(), 'Platform unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $platformId, Response $response, Database $dbForPlatform) {
@@ -1584,8 +1583,8 @@ Http::put('/v1/projects/:projectId/platforms/:platformId')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('platformId', '', new UID(), 'Platform unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('key', '', new Text(256), 'Package name for android or bundle ID for iOS. Max length: 256 chars.', true)
->param('store', '', new Text(256), 'App store or Google Play store ID. Max length: 256 chars.', true)
@@ -1641,8 +1640,8 @@ Http::delete('/v1/projects/:projectId/platforms/:platformId')
],
contentType: ContentType::NONE
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('platformId', '', new UID(), 'Platform unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $platformId, Response $response, Database $dbForPlatform) {
@@ -1708,7 +1707,7 @@ Http::patch('/v1/projects/:projectId/smtp')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('enabled', false, new Boolean(), 'Enable custom SMTP service')
->param('senderName', '', new Text(255, 0), 'Name of the email sender', true)
->param('senderEmail', '', new Email(), 'Email of the sender', true)
@@ -1826,7 +1825,7 @@ Http::post('/v1/projects/:projectId/smtp/tests')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('emails', [], new ArrayList(new Email(), 10), 'Array of emails to send test email to. Maximum of 10 emails are allowed.')
->param('senderName', System::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server'), new Text(255, 0), 'Name of the email sender')
->param('senderEmail', System::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), new Email(), 'Email of the sender')
@@ -1921,7 +1920,7 @@ Http::get('/v1/projects/:projectId/templates/sms/:type/:locale')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['sms'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->inject('response')
@@ -1969,7 +1968,7 @@ Http::get('/v1/projects/:projectId/templates/email/:type/:locale')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['email'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->inject('response')
@@ -2088,7 +2087,7 @@ Http::patch('/v1/projects/:projectId/templates/sms/:type/:locale')
]
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['sms'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->param('message', '', new Text(0), 'Template message')
@@ -2135,7 +2134,7 @@ Http::patch('/v1/projects/:projectId/templates/email/:type/:locale')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['email'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->param('subject', '', new Text(255), 'Email Subject')
@@ -2214,7 +2213,7 @@ Http::delete('/v1/projects/:projectId/templates/sms/:type/:locale')
contentType: ContentType::JSON
)
])
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['sms'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->inject('response')
@@ -2265,7 +2264,7 @@ Http::delete('/v1/projects/:projectId/templates/email/:type/:locale')
],
contentType: ContentType::JSON
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('type', '', new WhiteList(Config::getParam('locale-templates')['email'] ?? [], true), 'Template type')
->param('locale', '', fn ($localeCodes) => new WhiteList($localeCodes), 'Template locale', false, ['localeCodes'])
->inject('response')
@@ -2317,7 +2316,7 @@ Http::patch('/v1/projects/:projectId/auth/session-invalidation')
)
]
))
->param('projectId', '', new UID(), 'Project unique ID.')
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('enabled', false, new Boolean(), 'Update authentication session invalidation status. Use this endpoint to enable or disable session invalidation on password change')
->inject('response')
->inject('dbForPlatform')
File diff suppressed because it is too large Load Diff
+58 -57
View File
@@ -73,8 +73,9 @@ use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
/** TODO: Remove function when we move to using utopia/platform */
function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, string $name, Document $project, Database $dbForProject, Hooks $hooks): Document
function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks): Document
{
$name = $name ?? '';
$plaintextPassword = $password;
$passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;
@@ -246,7 +247,7 @@ Http::post('/v1/users')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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 PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'Plain text user password. Must be at least 8 chars.', true, ['project', 'passwordsDictionary'])
@@ -255,7 +256,7 @@ Http::post('/v1/users')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, ?string $email, ?string $phone, ?string $password, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$plaintext = new Plaintext();
$user = createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks);
@@ -283,7 +284,7 @@ Http::post('/v1/users/bcrypt')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using Bcrypt.')
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
@@ -291,7 +292,7 @@ Http::post('/v1/users/bcrypt')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$bcrypt = new Bcrypt();
$bcrypt->setCost(8); // Default cost
@@ -321,7 +322,7 @@ Http::post('/v1/users/md5')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using MD5.')
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
@@ -329,7 +330,7 @@ Http::post('/v1/users/md5')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$md5 = new MD5();
$user = createUser($md5, $userId, $email, $password, null, $name, $project, $dbForProject, $hooks);
@@ -358,7 +359,7 @@ Http::post('/v1/users/argon2')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using Argon2.')
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
@@ -366,7 +367,7 @@ Http::post('/v1/users/argon2')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$argon2 = new Argon2();
$user = createUser($argon2, $userId, $email, $password, null, $name, $project, $dbForProject, $hooks);
@@ -395,7 +396,7 @@ Http::post('/v1/users/sha')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using SHA.')
->param('passwordVersion', '', new WhiteList(['sha1', 'sha224', 'sha256', 'sha384', 'sha512/224', 'sha512/256', 'sha512', 'sha3-224', 'sha3-256', 'sha3-384', 'sha3-512']), "Optional SHA version used to hash password. Allowed values are: 'sha1', 'sha224', 'sha256', 'sha384', 'sha512/224', 'sha512/256', 'sha512', 'sha3-224', 'sha3-256', 'sha3-384', 'sha3-512'", true)
@@ -404,7 +405,7 @@ Http::post('/v1/users/sha')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $passwordVersion, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, string $passwordVersion, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$sha = new Sha();
if (!empty($passwordVersion)) {
$sha->setVersion($passwordVersion);
@@ -436,7 +437,7 @@ Http::post('/v1/users/phpass')
)
]
))
->param('userId', '', new CustomId(), 'User ID. Choose a custom ID or pass the string `ID.unique()`to auto generate it. 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.')
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'User ID. Choose a custom ID or pass the string `ID.unique()`to auto generate it. 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', '', new Password(), 'User password hashed using PHPass.')
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
@@ -444,7 +445,7 @@ Http::post('/v1/users/phpass')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$phpass = new PHPass();
$user = createUser($phpass, $userId, $email, $password, null, $name, $project, $dbForProject, $hooks);
@@ -473,7 +474,7 @@ Http::post('/v1/users/scrypt')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using Scrypt.')
->param('passwordSalt', '', new Text(128), 'Optional salt used to hash password.')
@@ -486,7 +487,7 @@ Http::post('/v1/users/scrypt')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $passwordSalt, int $passwordCpu, int $passwordMemory, int $passwordParallel, int $passwordLength, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, string $passwordSalt, int $passwordCpu, int $passwordMemory, int $passwordParallel, int $passwordLength, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$scrypt = new Scrypt();
$scrypt
->setSalt($passwordSalt)
@@ -521,7 +522,7 @@ Http::post('/v1/users/scrypt-modified')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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', '', new Password(), 'User password hashed using Scrypt Modified.')
->param('passwordSalt', '', new Text(128), 'Salt used to hash password.')
@@ -532,7 +533,7 @@ Http::post('/v1/users/scrypt-modified')
->inject('project')
->inject('dbForProject')
->inject('hooks')
->action(function (string $userId, string $email, string $password, string $passwordSalt, string $passwordSaltSeparator, string $passwordSignerKey, string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
->action(function (string $userId, string $email, string $password, string $passwordSalt, string $passwordSaltSeparator, string $passwordSignerKey, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks) {
$scryptModified = new ScryptModified();
$scryptModified
->setSalt($passwordSalt)
@@ -566,11 +567,11 @@ Http::post('/v1/users/:userId/targets')
)
]
))
->param('targetId', '', new CustomId(), 'Target 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.')
->param('userId', '', new UID(), 'User ID.')
->param('targetId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'Target 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('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('providerType', '', new WhiteList([MESSAGE_TYPE_EMAIL, MESSAGE_TYPE_SMS, MESSAGE_TYPE_PUSH]), 'The target provider type. Can be one of the following: `email`, `sms` or `push`.')
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->param('providerId', '', new UID(), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true)
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true, ['dbForProject'])
->param('name', '', new Text(128), 'Target name. Max length: 128 chars. For example: My Awesome App Galaxy S23.', true)
->inject('queueForEvents')
->inject('response')
@@ -731,7 +732,7 @@ Http::get('/v1/users/:userId')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $userId, Response $response, Database $dbForProject) {
@@ -762,7 +763,7 @@ Http::get('/v1/users/:userId/prefs')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $userId, Response $response, Database $dbForProject) {
@@ -795,8 +796,8 @@ Http::get('/v1/users/:userId/targets/:targetId')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('targetId', '', new UID(), 'Target ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $userId, string $targetId, Response $response, Database $dbForProject) {
@@ -833,7 +834,7 @@ Http::get('/v1/users/:userId/sessions')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('dbForProject')
@@ -877,7 +878,7 @@ Http::get('/v1/users/:userId/memberships')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('queries', [], new Memberships(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Memberships::ALLOWED_ATTRIBUTES), true)
->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
@@ -932,7 +933,7 @@ Http::get('/v1/users/:userId/logs')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -1019,7 +1020,7 @@ Http::get('/v1/users/:userId/targets')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('queries', [], new Targets(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Targets::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
@@ -1147,7 +1148,7 @@ Http::patch('/v1/users/:userId/status')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('status', null, new Boolean(true), 'User Status. To activate the user pass `true` and to block the user pass `false`.')
->inject('response')
->inject('dbForProject')
@@ -1188,7 +1189,7 @@ Http::put('/v1/users/:userId/labels')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('labels', [], new ArrayList(new Text(36, allowList: [...Text::NUMBERS, ...Text::ALPHABET_UPPER, ...Text::ALPHABET_LOWER]), APP_LIMIT_ARRAY_LABELS_SIZE), 'Array of user labels. Replaces the previous labels. Maximum of ' . APP_LIMIT_ARRAY_LABELS_SIZE . ' labels are allowed, each up to 36 alphanumeric characters long.')
->inject('response')
->inject('dbForProject')
@@ -1231,7 +1232,7 @@ Http::patch('/v1/users/:userId/verification/phone')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('phoneVerification', false, new Boolean(), 'User phone verification status.')
->inject('response')
->inject('dbForProject')
@@ -1273,7 +1274,7 @@ Http::patch('/v1/users/:userId/name')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('name', '', new Text(128, 0), 'User name. Max length: 128 chars.')
->inject('response')
->inject('dbForProject')
@@ -1316,7 +1317,7 @@ Http::patch('/v1/users/:userId/password')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false, allowEmpty: true), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
->inject('response')
->inject('project')
@@ -1415,7 +1416,7 @@ Http::patch('/v1/users/:userId/email')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('email', '', new EmailValidator(allowEmpty: true), 'User email.')
->inject('response')
->inject('dbForProject')
@@ -1526,7 +1527,7 @@ Http::patch('/v1/users/:userId/phone')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('number', '', new Phone(allowEmpty: true), 'User phone number.')
->inject('response')
->inject('dbForProject')
@@ -1616,7 +1617,7 @@ Http::patch('/v1/users/:userId/verification')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('emailVerification', false, new Boolean(), 'User email verification status.')
->inject('response')
->inject('dbForProject')
@@ -1654,7 +1655,7 @@ Http::patch('/v1/users/:userId/prefs')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('prefs', '', new Assoc(), 'Prefs key-value JSON object.')
->inject('response')
->inject('dbForProject')
@@ -1695,10 +1696,10 @@ Http::patch('/v1/users/:userId/targets/:targetId')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('targetId', '', new UID(), 'Target ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID.', false, ['dbForProject'])
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)', true)
->param('providerId', '', new UID(), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true)
->param('providerId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true, ['dbForProject'])
->param('name', '', new Text(128), 'Target name. Max length: 128 chars. For example: My Awesome App Galaxy S23.', true)
->inject('queueForEvents')
->inject('response')
@@ -1820,7 +1821,7 @@ Http::patch('/v1/users/:userId/mfa')
]
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('mfa', null, new Boolean(), 'Enable or disable MFA.')
->inject('response')
->inject('dbForProject')
@@ -1880,7 +1881,7 @@ Http::get('/v1/users/:userId/mfa/factors')
]
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $userId, Response $response, Database $dbForProject) {
@@ -1939,7 +1940,7 @@ Http::get('/v1/users/:userId/mfa/recovery-codes')
]
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->action(function (string $userId, Response $response, Database $dbForProject) {
@@ -2004,7 +2005,7 @@ Http::patch('/v1/users/:userId/mfa/recovery-codes')
]
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2077,7 +2078,7 @@ Http::put('/v1/users/:userId/mfa/recovery-codes')
public: false,
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2150,7 +2151,7 @@ Http::delete('/v1/users/:userId/mfa/authenticators/:type')
contentType: ContentType::NONE
)
])
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('type', null, new WhiteList([Type::TOTP]), 'Type of authenticator.')
->inject('response')
->inject('dbForProject')
@@ -2197,7 +2198,7 @@ Http::post('/v1/users/:userId/sessions')
)
]
))
->param('userId', '', new CustomId(), '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.')
->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'])
->inject('request')
->inject('response')
->inject('dbForProject')
@@ -2289,7 +2290,7 @@ Http::post('/v1/users/:userId/tokens')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('length', 6, new Range(4, 128), 'Token length in characters. The default length is 6 characters', true)
->param('expire', TOKEN_EXPIRATION_GENERIC, new Range(60, TOKEN_EXPIRATION_LOGIN_LONG), 'Token expiration period in seconds. The default expiration is 15 minutes.', true)
->inject('request')
@@ -2355,8 +2356,8 @@ Http::delete('/v1/users/:userId/sessions/:sessionId')
],
contentType: ContentType::NONE
))
->param('userId', '', new UID(), 'User ID.')
->param('sessionId', '', new UID(), 'Session ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('sessionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Session ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2406,7 +2407,7 @@ Http::delete('/v1/users/:userId/sessions')
],
contentType: ContentType::NONE
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2456,7 +2457,7 @@ Http::delete('/v1/users/:userId')
],
contentType: ContentType::NONE
))
->param('userId', '', new UID(), 'User ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2508,8 +2509,8 @@ Http::delete('/v1/users/:userId/targets/:targetId')
],
contentType: ContentType::NONE
))
->param('userId', '', new UID(), 'User ID.')
->param('targetId', '', new UID(), 'Target ID.')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('targetId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Target ID.', false, ['dbForProject'])
->inject('queueForEvents')
->inject('queueForDeletes')
->inject('response')
@@ -2566,7 +2567,7 @@ Http::delete('/v1/users/identities/:identityId')
],
contentType: ContentType::NONE,
))
->param('identityId', '', new UID(), 'Identity ID.')
->param('identityId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Identity ID.', false, ['dbForProject'])
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
@@ -2605,8 +2606,8 @@ Http::post('/v1/users/:userId/jwts')
)
]
))
->param('userId', '', new UID(), 'User ID.')
->param('sessionId', '', new UID(), 'Session ID. Use the string \'recent\' to use the most recent session. Defaults to the most recent session.', true)
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('sessionId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'Session ID. Use the string \'recent\' to use the most recent session. Defaults to the most recent session.', true, ['dbForProject'])
->param('duration', 900, new Range(0, 3600), 'Time in seconds before JWT expires. Default duration is 900 seconds, and maximum is 3600 seconds.', true)
->inject('response')
->inject('dbForProject')
-705
View File
@@ -1,705 +0,0 @@
<?php
use Appwrite\Event\Build;
use Appwrite\Extend\Exception;
use Appwrite\Filter\BranchDomain as BranchDomainFilter;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Appwrite\Vcs\Comment;
use Utopia\Console;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Http\Http;
use Utopia\System\System;
use Utopia\Validator\Text;
use Utopia\VCS\Adapter\Git\GitHub;
use Utopia\VCS\Exception\RepositoryNotFound;
$createGitDeployments = function (GitHub $github, string $providerInstallationId, array $repositories, string $providerBranch, string $providerBranchUrl, string $providerRepositoryName, string $providerRepositoryUrl, string $providerRepositoryOwner, string $providerCommitHash, string $providerCommitAuthor, string $providerCommitAuthorUrl, string $providerCommitMessage, string $providerCommitUrl, string $providerPullRequestId, bool $external, Database $dbForPlatform, Authorization $authorization, Build $queueForBuilds, callable $getProjectDB, Request $request, array $platform) {
$errors = [];
foreach ($repositories as $repository) {
try {
$resourceType = $repository->getAttribute('resourceType');
if ($resourceType !== "function" && $resourceType !== "site") {
continue;
}
$projectId = $repository->getAttribute('projectId');
$project = $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $projectId));
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND, 'Repository references non-existent project');
}
$dbForProject = $getProjectDB($project);
$resourceCollection = $resourceType === "function" ? 'functions' : 'sites';
$resourceId = $repository->getAttribute('resourceId');
$resource = $authorization->skip(fn () => $dbForProject->getDocument($resourceCollection, $resourceId));
$resourceInternalId = $resource->getSequence();
$deploymentId = ID::unique();
$repositoryId = $repository->getId();
$repositoryInternalId = $repository->getSequence();
$providerRepositoryId = $repository->getAttribute('providerRepositoryId');
$installationId = $repository->getAttribute('installationId');
$installationInternalId = $repository->getAttribute('installationInternalId');
$productionBranch = $resource->getAttribute('providerBranch');
$activate = false;
if ($providerBranch == $productionBranch && $external === false) {
$activate = true;
}
$owner = $github->getOwnerName($providerInstallationId) ?? '';
try {
$repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';
if (empty($repositoryName)) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
} catch (RepositoryNotFound $e) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
if (empty($repositoryName)) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
$isAuthorized = !$external;
if (!$isAuthorized && !empty($providerPullRequestId)) {
if (\in_array($providerPullRequestId, $repository->getAttribute('providerPullRequestIds', []))) {
$isAuthorized = true;
}
}
$commentStatus = $isAuthorized ? 'waiting' : 'failed';
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https';
$hostname = $platform['consoleHostname'] ?? '';
$authorizeUrl = $protocol . '://' . $hostname . "/console/git/authorize-contributor?projectId={$projectId}&installationId={$installationId}&repositoryId={$repositoryId}&providerPullRequestId={$providerPullRequestId}";
$action = $isAuthorized ? ['type' => 'logs'] : ['type' => 'authorize', 'url' => $authorizeUrl];
$latestCommentId = '';
if (!empty($providerPullRequestId) && $resource->getAttribute('providerSilentMode', false) === false) {
$latestComment = $authorization->skip(fn () => $dbForPlatform->findOne('vcsComments', [
Query::equal('providerRepositoryId', [$providerRepositoryId]),
Query::equal('providerPullRequestId', [$providerPullRequestId]),
Query::orderDesc('$createdAt'),
]));
if (!$latestComment->isEmpty()) {
$latestCommentId = $latestComment->getAttribute('providerCommentId', '');
$retries = 0;
$lockAcquired = false;
while ($retries < 9) {
$retries++;
try {
$dbForPlatform->createDocument('vcsCommentLocks', new Document([
'$id' => $latestCommentId
]));
$lockAcquired = true;
break;
} catch (\Throwable $err) {
if ($retries >= 9) {
Console::warning("Error creating vcs comment lock for " . $latestCommentId . ": " . $err->getMessage());
}
\sleep(1);
}
}
if ($lockAcquired) {
// Wrap in try/finally to ensure lock file gets deleted
try {
$comment = new Comment($platform);
$comment->parseComment($github->getComment($owner, $repositoryName, $latestCommentId));
$comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, '');
$latestCommentId = \strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment()));
} finally {
$authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId));
}
}
} else {
$comment = new Comment($platform);
$comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, '');
$latestCommentId = \strval($github->createComment($owner, $repositoryName, $providerPullRequestId, $comment->generateComment()));
if (!empty($latestCommentId)) {
$teamId = $project->getAttribute('teamId', '');
$latestComment = $authorization->skip(fn () => $dbForPlatform->createDocument('vcsComments', new Document([
'$id' => ID::unique(),
'$permissions' => [
Permission::read(Role::team(ID::custom($teamId))),
Permission::update(Role::team(ID::custom($teamId), 'owner')),
Permission::update(Role::team(ID::custom($teamId), 'developer')),
Permission::delete(Role::team(ID::custom($teamId), 'owner')),
Permission::delete(Role::team(ID::custom($teamId), 'developer')),
],
'installationInternalId' => $installationInternalId,
'installationId' => $installationId,
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'providerRepositoryId' => $providerRepositoryId,
'providerBranch' => $providerBranch,
'providerPullRequestId' => $providerPullRequestId,
'providerCommentId' => $latestCommentId
])));
}
}
} elseif (!empty($providerBranch)) {
$latestComments = $authorization->skip(fn () => $dbForPlatform->find('vcsComments', [
Query::equal('providerRepositoryId', [$providerRepositoryId]),
Query::equal('providerBranch', [$providerBranch]),
Query::orderDesc('$createdAt'),
]));
foreach ($latestComments as $comment) {
$latestCommentId = $comment->getAttribute('providerCommentId', '');
$retries = 0;
$lockAcquired = false;
while ($retries < 9) {
$retries++;
try {
$dbForPlatform->createDocument('vcsCommentLocks', new Document([
'$id' => $latestCommentId
]));
$lockAcquired = true;
break;
} catch (\Throwable $err) {
if ($retries >= 9) {
Console::warning("Error creating vcs comment lock for " . $latestCommentId . ": " . $err->getMessage());
}
\sleep(1);
}
}
if ($lockAcquired) {
// Wrap in try/finally to ensure lock file gets deleted
try {
$comment = new Comment($platform);
$comment->parseComment($github->getComment($owner, $repositoryName, $latestCommentId));
$comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, '');
$latestCommentId = \strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment()));
} finally {
$authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId));
}
}
}
}
if (!$isAuthorized) {
$resourceName = $resource->getAttribute('name');
$projectName = $project->getAttribute('name');
$name = "{$resourceName} ({$projectName})";
$message = 'Authorization required for external contributor.';
$providerRepositoryId = $repository->getAttribute('providerRepositoryId');
try {
$repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';
if (empty($repositoryName)) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
} catch (RepositoryNotFound $e) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
$owner = $github->getOwnerName($providerInstallationId);
$github->updateCommitStatus($repositoryName, $providerCommitHash, $owner, 'failure', $message, $authorizeUrl, $name);
continue;
}
if ($external) {
$pullRequestResponse = $github->getPullRequest($owner, $repositoryName, $providerPullRequestId);
$providerRepositoryName = $pullRequestResponse['head']['repo']['owner']['login'];
$providerRepositoryOwner = $pullRequestResponse['head']['repo']['name'];
}
$commands = [];
if (!empty($resource->getAttribute('installCommand', ''))) {
$commands[] = $resource->getAttribute('installCommand', '');
}
if (!empty($resource->getAttribute('buildCommand', ''))) {
$commands[] = $resource->getAttribute('buildCommand', '');
}
if (!empty($resource->getAttribute('commands', ''))) {
$commands[] = $resource->getAttribute('commands', '');
}
$deployment = $authorization->skip(fn () => $dbForProject->createDocument('deployments', new Document([
'$id' => $deploymentId,
'$permissions' => [
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'resourceId' => $resourceId,
'resourceInternalId' => $resourceInternalId,
'resourceType' => $resourceCollection,
'entrypoint' => $resource->getAttribute('entrypoint', ''),
'buildCommands' => \implode(' && ', $commands),
'startCommand' => $resource->getAttribute('startCommand', ''),
'buildOutput' => $resource->getAttribute('outputDirectory', ''),
'adapter' => $resource->getAttribute('adapter', ''),
'fallbackFile' => $resource->getAttribute('fallbackFile', ''),
'type' => 'vcs',
'installationId' => $installationId,
'installationInternalId' => $installationInternalId,
'providerRepositoryId' => $providerRepositoryId,
'repositoryId' => $repositoryId,
'repositoryInternalId' => $repositoryInternalId,
'providerBranchUrl' => $providerBranchUrl,
'providerRepositoryName' => $providerRepositoryName,
'providerRepositoryOwner' => $providerRepositoryOwner,
'providerRepositoryUrl' => $providerRepositoryUrl,
'providerCommitHash' => $providerCommitHash,
'providerCommitAuthorUrl' => $providerCommitAuthorUrl,
'providerCommitAuthor' => $providerCommitAuthor,
'providerCommitMessage' => mb_strimwidth($providerCommitMessage, 0, 255, '...'),
'providerCommitUrl' => $providerCommitUrl,
'providerCommentId' => \strval($latestCommentId),
'providerBranch' => $providerBranch,
'activate' => $activate,
])));
$resource = $resource
->setAttribute('latestDeploymentId', $deployment->getId())
->setAttribute('latestDeploymentInternalId', $deployment->getSequence())
->setAttribute('latestDeploymentCreatedAt', $deployment->getCreatedAt())
->setAttribute('latestDeploymentStatus', $deployment->getAttribute('status', ''));
$authorization->skip(fn () => $dbForProject->updateDocument($resource->getCollection(), $resource->getId(), $resource));
if ($resource->getCollection() === 'sites') {
$projectId = $project->getId();
// Deployment preview
$sitesDomain = $platform['sitesDomain'];
$domain = ID::unique() . "." . $sitesDomain;
$ruleId = md5($domain);
$previewRuleId = $ruleId;
$authorization->skip(
fn () => $dbForPlatform->createDocument('rules', new Document([
'$id' => $ruleId,
'projectId' => $project->getId(),
'projectInternalId' => $project->getSequence(),
'domain' => $domain,
'type' => 'deployment',
'trigger' => 'deployment',
'deploymentId' => $deployment->getId(),
'deploymentInternalId' => $deployment->getSequence(),
'deploymentResourceType' => 'site',
'deploymentResourceId' => $resourceId,
'deploymentResourceInternalId' => $resourceInternalId,
'deploymentVcsProviderBranch' => $providerBranch,
'status' => 'verified',
'certificateId' => '',
'search' => implode(' ', [$ruleId, $domain]),
'owner' => 'Appwrite',
'region' => $project->getAttribute('region')
]))
);
// VCS branch preview
if (!empty($providerBranch)) {
$domain = (new BranchDomainFilter())->apply([
'branch' => $providerBranch,
'resourceId' => $resource->getId(),
'projectId' => $project->getId(),
'sitesDomain' => $sitesDomain,
]);
$ruleId = md5($domain);
try {
$authorization->skip(
fn () => $dbForPlatform->createDocument('rules', new Document([
'$id' => $ruleId,
'projectId' => $project->getId(),
'projectInternalId' => $project->getSequence(),
'domain' => $domain,
'type' => 'deployment',
'trigger' => 'deployment',
'deploymentId' => $deployment->getId(),
'deploymentInternalId' => $deployment->getSequence(),
'deploymentResourceType' => 'site',
'deploymentResourceId' => $resourceId,
'deploymentResourceInternalId' => $resourceInternalId,
'deploymentVcsProviderBranch' => $providerBranch,
'status' => 'verified',
'certificateId' => '',
'search' => implode(' ', [$ruleId, $domain]),
'owner' => 'Appwrite',
'region' => $project->getAttribute('region')
]))
);
} catch (Duplicate $err) {
// Ignore, rule already exists; will be updated by builds worker
}
}
// VCS commit preview
if (!empty($providerCommitHash)) {
$domain = "commit-" . substr($providerCommitHash, 0, 16) . ".{$sitesDomain}";
$ruleId = md5($domain);
try {
$authorization->skip(
fn () => $dbForPlatform->createDocument('rules', new Document([
'$id' => $ruleId,
'projectId' => $project->getId(),
'projectInternalId' => $project->getSequence(),
'domain' => $domain,
'type' => 'deployment',
'trigger' => 'deployment',
'deploymentId' => $deployment->getId(),
'deploymentInternalId' => $deployment->getSequence(),
'deploymentResourceType' => 'site',
'deploymentResourceId' => $resourceId,
'deploymentResourceInternalId' => $resourceInternalId,
'deploymentVcsProviderBranch' => $providerBranch,
'status' => 'verified',
'certificateId' => '',
'search' => implode(' ', [$ruleId, $domain]),
'owner' => 'Appwrite',
'region' => $project->getAttribute('region')
]))
);
} catch (Duplicate $err) {
// Ignore, rule already exists; will be updated by builds worker
}
}
}
if ($resource->getCollection() === 'sites' && !empty($latestCommentId) && !empty($previewRuleId)) {
$retries = 0;
$lockAcquired = false;
while ($retries < 9) {
$retries++;
try {
$dbForPlatform->createDocument('vcsCommentLocks', new Document([
'$id' => $latestCommentId
]));
$lockAcquired = true;
break;
} catch (\Throwable $err) {
if ($retries >= 9) {
Console::warning("Error creating vcs comment lock for " . $latestCommentId . ": " . $err->getMessage());
}
\sleep(1);
}
}
if ($lockAcquired) {
// Wrap in try/finally to ensure lock file gets deleted
try {
$rule = $authorization->skip(fn () => $dbForPlatform->getDocument('rules', $previewRuleId));
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https';
$previewUrl = !empty($rule) ? ("{$protocol}://" . $rule->getAttribute('domain', '')) : '';
if (!empty($previewUrl)) {
$comment = new Comment($platform);
$comment->parseComment($github->getComment($owner, $repositoryName, $latestCommentId));
$comment->addBuild($project, $resource, $resourceType, $commentStatus, $deploymentId, $action, $previewUrl);
$github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment());
}
} finally {
$authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $latestCommentId));
}
}
}
if (!empty($providerCommitHash) && $resource->getAttribute('providerSilentMode', false) === false) {
$resourceName = $resource->getAttribute('name');
$projectName = $project->getAttribute('name');
$region = $project->getAttribute('region', 'default');
$name = "{$resourceName} ({$projectName})";
$message = 'Starting...';
$providerRepositoryId = $repository->getAttribute('providerRepositoryId');
try {
$repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';
if (empty($repositoryName)) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
} catch (RepositoryNotFound $e) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
$owner = $github->getOwnerName($providerInstallationId);
$providerTargetUrl = $protocol . '://' . $hostname . "/console/project-$region-$projectId/$resourceCollection/$resourceType-$resourceId";
$github->updateCommitStatus($repositoryName, $providerCommitHash, $owner, 'pending', $message, $providerTargetUrl, $name);
}
$queueForBuilds
->setType(BUILD_TYPE_DEPLOYMENT)
->setResource($resource)
->setDeployment($deployment)
->setProject($project); // set the project because it won't be set for git deployments
$queueForBuilds->trigger(); // must trigger here so that we create a build for each function/site
//TODO: Add event?
} catch (Throwable $e) {
$errors[] = $e->getMessage();
}
}
$queueForBuilds->reset(); // prevent shutdown hook from triggering again
if (!empty($errors)) {
throw new Exception(Exception::GENERAL_UNKNOWN, \implode("\n", $errors));
}
};
Http::post('/v1/vcs/github/events')
->desc('Create event')
->groups(['api', 'vcs'])
->label('scope', 'public')
->inject('gitHub')
->inject('request')
->inject('response')
->inject('dbForPlatform')
->inject('authorization')
->inject('getProjectDB')
->inject('queueForBuilds')
->inject('platform')
->action(
function (GitHub $github, Request $request, Response $response, Database $dbForPlatform, Authorization $authorization, callable $getProjectDB, Build $queueForBuilds, array $platform) use ($createGitDeployments) {
$payload = $request->getRawPayload();
$signatureRemote = $request->getHeader('x-hub-signature-256', '');
$signatureLocal = System::getEnv('_APP_VCS_GITHUB_WEBHOOK_SECRET', '');
$valid = empty($signatureRemote) ? true : $github->validateWebhookEvent($payload, $signatureRemote, $signatureLocal);
if (!$valid) {
throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN, "Invalid webhook payload signature. Please make sure the webhook secret has same value in your GitHub app and in the _APP_VCS_GITHUB_WEBHOOK_SECRET environment variable");
}
$event = $request->getHeader('x-github-event', '');
$privateKey = System::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = System::getEnv('_APP_VCS_GITHUB_APP_ID');
$parsedPayload = $github->getEvent($event, $payload);
if ($event == $github::EVENT_PUSH) {
$providerBranchCreated = $parsedPayload["branchCreated"] ?? false;
$providerBranchDeleted = $parsedPayload["branchDeleted"] ?? false;
$providerBranch = $parsedPayload["branch"] ?? '';
$providerBranchUrl = $parsedPayload["branchUrl"] ?? '';
$providerRepositoryId = $parsedPayload["repositoryId"] ?? '';
$providerRepositoryName = $parsedPayload["repositoryName"] ?? '';
$providerInstallationId = $parsedPayload["installationId"] ?? '';
$providerRepositoryUrl = $parsedPayload["repositoryUrl"] ?? '';
$providerCommitHash = $parsedPayload["commitHash"] ?? '';
$providerRepositoryOwner = $parsedPayload["owner"] ?? '';
$providerCommitAuthorName = $parsedPayload["headCommitAuthorName"] ?? '';
$providerCommitAuthorEmail = $parsedPayload["headCommitAuthorEmail"] ?? '';
$providerCommitAuthorUrl = $parsedPayload["authorUrl"] ?? '';
$providerCommitMessage = $parsedPayload["headCommitMessage"] ?? '';
$providerCommitUrl = $parsedPayload["headCommitUrl"] ?? '';
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
//find resourceId from relevant resources table
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
Query::equal('providerRepositoryId', [$providerRepositoryId]),
Query::limit(100),
]));
// create new deployment only on push (not committed by us) and not when branch is created or deleted
if ($providerCommitAuthorEmail !== APP_VCS_GITHUB_EMAIL && !$providerBranchCreated && !$providerBranchDeleted) {
$createGitDeployments($github, $providerInstallationId, $repositories, $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthorName, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, '', false, $dbForPlatform, $authorization, $queueForBuilds, $getProjectDB, $request, $platform);
}
} elseif ($event == $github::EVENT_INSTALLATION) {
if ($parsedPayload["action"] == "deleted") {
// TODO: Use worker for this job instead (update function/site as well)
$providerInstallationId = $parsedPayload["installationId"];
$installations = $dbForPlatform->find('installations', [
Query::equal('providerInstallationId', [$providerInstallationId]),
Query::limit(1000)
]);
foreach ($installations as $installation) {
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
Query::equal('installationInternalId', [$installation->getSequence()]),
Query::limit(1000)
]));
foreach ($repositories as $repository) {
$authorization->skip(fn () => $dbForPlatform->deleteDocument('repositories', $repository->getId()));
}
$authorization->skip(fn () => $dbForPlatform->deleteDocument('installations', $installation->getId()));
}
}
} elseif ($event == $github::EVENT_PULL_REQUEST) {
if ($parsedPayload["action"] == "opened" || $parsedPayload["action"] == "reopened" || $parsedPayload["action"] == "synchronize") {
$providerBranch = $parsedPayload["branch"] ?? '';
$providerBranchUrl = $parsedPayload["branchUrl"] ?? '';
$providerRepositoryId = $parsedPayload["repositoryId"] ?? '';
$providerRepositoryName = $parsedPayload["repositoryName"] ?? '';
$providerInstallationId = $parsedPayload["installationId"] ?? '';
$providerRepositoryUrl = $parsedPayload["repositoryUrl"] ?? '';
$providerPullRequestId = $parsedPayload["pullRequestNumber"] ?? '';
$providerCommitHash = $parsedPayload["commitHash"] ?? '';
$providerRepositoryOwner = $parsedPayload["owner"] ?? '';
$external = $parsedPayload["external"] ?? true;
$providerCommitUrl = $parsedPayload["headCommitUrl"] ?? '';
$providerCommitAuthorUrl = $parsedPayload["authorUrl"] ?? '';
// Ignore sync for non-external. We handle it in push webhook
if (!$external && $parsedPayload["action"] == "synchronize") {
return $response->json($parsedPayload);
}
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$commitDetails = $github->getCommit($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash);
$providerCommitAuthor = $commitDetails["commitAuthor"] ?? '';
$providerCommitMessage = $commitDetails["commitMessage"] ?? '';
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
Query::equal('providerRepositoryId', [$providerRepositoryId]),
Query::orderDesc('$createdAt')
]));
$createGitDeployments($github, $providerInstallationId, $repositories, $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthor, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, $providerPullRequestId, $external, $dbForPlatform, $authorization, $queueForBuilds, $getProjectDB, $request, $platform);
} elseif ($parsedPayload["action"] == "closed") {
// Allowed external contributions cleanup
$providerRepositoryId = $parsedPayload["repositoryId"] ?? '';
$providerPullRequestId = $parsedPayload["pullRequestNumber"] ?? '';
$external = $parsedPayload["external"] ?? true;
if ($external) {
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
Query::equal('providerRepositoryId', [$providerRepositoryId]),
Query::orderDesc('$createdAt')
]));
foreach ($repositories as $repository) {
$providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []);
if (\in_array($providerPullRequestId, $providerPullRequestIds)) {
$providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]);
$repository = $repository->setAttribute('providerPullRequestIds', $providerPullRequestIds);
$repository = $authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), $repository));
}
}
}
}
}
$response->json($parsedPayload);
}
);
Http::patch('/v1/vcs/github/installations/:installationId/repositories/:repositoryId')
->desc('Update external deployment (authorize)')
->groups(['api', 'vcs'])
->label('scope', 'vcs.write')
->label('sdk', new Method(
namespace: 'vcs',
group: 'repositories',
name: 'updateExternalDeployments',
description: '/docs/references/vcs/update-external-deployments.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
]
))
->param('installationId', '', new Text(256), 'Installation Id')
->param('repositoryId', '', new Text(256), 'VCS Repository Id')
->param('providerPullRequestId', '', new Text(256), 'GitHub Pull Request Id')
->inject('gitHub')
->inject('response')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->inject('getProjectDB')
->inject('queueForBuilds')
->inject('platform')
->action(function (string $installationId, string $repositoryId, string $providerPullRequestId, GitHub $github, Request $request, Response $response, Document $project, Database $dbForPlatform, Authorization $authorization, callable $getProjectDB, Build $queueForBuilds, array $platform) use ($createGitDeployments) {
$installation = $dbForPlatform->getDocument('installations', $installationId);
if ($installation->isEmpty()) {
throw new Exception(Exception::INSTALLATION_NOT_FOUND);
}
$repository = $authorization->skip(fn () => $dbForPlatform->findOne('repositories', [
Query::equal('$id', [$repositoryId]),
Query::equal('projectInternalId', [$project->getSequence()])
]));
if ($repository->isEmpty()) {
throw new Exception(Exception::REPOSITORY_NOT_FOUND);
}
if (\in_array($providerPullRequestId, $repository->getAttribute('providerPullRequestIds', []))) {
throw new Exception(Exception::PROVIDER_CONTRIBUTION_CONFLICT);
}
$providerPullRequestIds = \array_unique(\array_merge($repository->getAttribute('providerPullRequestIds', []), [$providerPullRequestId]));
$repository = $repository->setAttribute('providerPullRequestIds', $providerPullRequestIds);
// TODO: Delete from array when PR is closed
$repository = $authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), $repository));
$privateKey = System::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = System::getEnv('_APP_VCS_GITHUB_APP_ID');
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$repositories = [$repository];
$providerRepositoryId = $repository->getAttribute('providerRepositoryId');
$owner = $github->getOwnerName($providerInstallationId);
try {
$repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';
if (empty($repositoryName)) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
} catch (RepositoryNotFound $e) {
throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);
}
$pullRequestResponse = $github->getPullRequest($owner, $repositoryName, $providerPullRequestId);
$providerBranch = \explode(':', $pullRequestResponse['head']['label'])[1] ?? '';
$providerCommitHash = $pullRequestResponse['head']['sha'] ?? '';
$providerBranchUrl = $pullRequestResponse['head']['repo']['html_url'] ?? '';
$providerRepositoryName = $pullRequestResponse['head']['repo']['name'] ?? '';
$providerRepositoryUrl = $pullRequestResponse['head']['repo']['html_url'] ?? '';
$providerRepositoryOwner = $pullRequestResponse['head']['repo']['owner']['login'] ?? '';
$providerCommitAuthor = $pullRequestResponse['head']['user']['login'] ?? '';
$providerCommitAuthorUrl = $pullRequestResponse['head']['user']['html_url'] ?? '';
$providerCommitMessage = $pullRequestResponse['title'] ?? '';
$providerCommitUrl = $pullRequestResponse['html_url'] ?? '';
$createGitDeployments($github, $providerInstallationId, $repositories, $providerBranch, '', '', '', '', $providerCommitHash, '', '', '', '', $providerPullRequestId, true, $dbForPlatform, $authorization, $queueForBuilds, $getProjectDB, $request, $platform);
$response->noContent();
});
+7 -2
View File
@@ -115,7 +115,8 @@ function router(Http $utopia, Database $dbForPlatform, callable $getProjectDB, S
}
}
if (!in_array($host, $platformHostnames)) {
$routerProtectionEnabled = System::getEnv('_APP_OPTIONS_ROUTER_PROTECTION', 'disabled') === 'enabled';
if ($routerProtectionEnabled && !in_array($host, $platformHostnames)) {
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, 'Router protection does not allow accessing Appwrite over this domain. Please add it as custom domain to your project or disable _APP_OPTIONS_ROUTER_PROTECTION environment variable.', view: $errorView);
}
@@ -1352,7 +1353,7 @@ Http::error()
$log->setMessage($error->getMessage());
$log->addTag('database', $dsn->getHost());
$log->addTag('method', $route->getMethod());
$log->addTag('method', $route?->getMethod() ?? $request->getMethod());
$log->addTag('url', $request->getURI());
$log->addTag('verboseType', get_class($error));
$log->addTag('code', $error->getCode());
@@ -1450,10 +1451,14 @@ Http::error()
// don't fail the error handler
}
$sdk = $route?->getLabel("sdk", false);
$action = 'UNKNOWN_NAMESPACE.UNKNOWN.METHOD';
if (!empty($sdk)) {
/** @var \Appwrite\SDK\Method $sdk */
$action = $sdk->getNamespace() . '.' . $sdk->getMethodName();
} elseif ($route === null) {
$path = ltrim(parse_url($request->getURI(), PHP_URL_PATH) ?? '/', '/') ?: 'root';
$action = 'http.' . $request->getMethod() . '.' . $path;
}
$log->setAction($action);
-1
View File
@@ -31,7 +31,6 @@ Http::get('/v1/mock/tests/general/oauth2')
->param('state', '', new Text(1024), 'OAuth2 state.')
->inject('response')
->action(function (string $client_id, string $redirectURI, string $scope, string $state, Response $response) {
$response->redirect($redirectURI . '?' . \http_build_query(['code' => 'abcdef', 'state' => $state]));
});
+16 -8
View File
@@ -27,6 +27,7 @@ use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\Role;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Authorization\Input;
@@ -472,6 +473,7 @@ Http::init()
/*
* Abuse Check
*/
$abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
$timeLimitArray = [];
@@ -507,6 +509,7 @@ Http::init()
$abuse = new Abuse($timeLimit);
$remaining = $timeLimit->remaining();
$limit = $timeLimit->limit();
$time = $timeLimit->time() + $route->getLabel('abuse-time', 3600);
@@ -927,14 +930,19 @@ Http::shutdown()
$accessedAt = $cacheLog->getAttribute('accessedAt', 0);
$now = DateTime::now();
if ($cacheLog->isEmpty()) {
$authorization->skip(fn () => $dbForProject->createDocument('cache', new Document([
'$id' => $key,
'resource' => $resource,
'resourceType' => $resourceType,
'mimeType' => $response->getContentType(),
'accessedAt' => $now,
'signature' => $signature,
])));
try {
$authorization->skip(fn () => $dbForProject->createDocument('cache', new Document([
'$id' => $key,
'resource' => $resource,
'resourceType' => $resourceType,
'mimeType' => $response->getContentType(),
'accessedAt' => $now,
'signature' => $signature,
])));
} catch (DuplicateException) {
// Race condition: another concurrent request already created the cache document
$cacheLog = $authorization->skip(fn () => $dbForProject->getDocument('cache', $key));
}
} elseif (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) {
$cacheLog->setAttribute('accessedAt', $now);
$authorization->skip(fn () => $dbForProject->updateDocument('cache', $cacheLog->getId(), $cacheLog));
+53 -18
View File
@@ -192,8 +192,8 @@ include __DIR__ . '/controllers/general.php';
function createDatabase(Http $app, string $resourceKey, string $dbName, array $collections, mixed $pools, ?callable $extraSetup = null): void
{
$max = 10;
$sleep = 1;
$max = 15;
$sleep = 2;
$attempts = 0;
while (true) {
@@ -203,8 +203,8 @@ function createDatabase(Http $app, string $resourceKey, string $dbName, array $c
/* @var $database Database */
$database = is_callable($resource) ? $resource() : $resource;
break; // exit loop on success
} catch (\Exception $e) {
Console::warning(" └── Database not ready. Retrying connection ({$attempts})...");
} catch (\Throwable $e) {
Console::warning(" └── Database not ready ({$dbName}). Retrying connection ({$attempts}): " . $e->getMessage());
if ($attempts >= $max) {
throw new \Exception(' └── Failed to connect to database: ' . $e->getMessage());
}
@@ -215,11 +215,27 @@ function createDatabase(Http $app, string $resourceKey, string $dbName, array $c
Span::init("database.setup");
Span::add('database.name', $dbName);
// Attempt to create the database
try {
$database->create();
} catch (\Exception $e) {
Span::add('database.exists', true);
$attempts = 0;
while (true) {
try {
$attempts++;
Console::info(" └── Creating database: $dbName...");
$database->create();
break; // exit loop on success
} catch (\Exception $e) {
if ($e instanceof DuplicateException) {
Span::add('database.exists', true);
Console::info(" └── Skip: metadata table already exists");
break;
}
Console::warning(" └── Database create failed. Retrying ({$attempts})...");
if ($attempts >= $max) {
throw new \Exception(' └── Failed to create database: ' . $e->getMessage());
}
\sleep($sleep);
}
}
// Process collections
@@ -406,10 +422,26 @@ $http->on(Constant::EVENT_START, function (Server $http) use ($payloadSize, $tot
->setTenant(null)
->setNamespace(System::getEnv('_APP_DATABASE_SHARED_NAMESPACE', ''));
try {
$dbForProject->create();
} catch (DuplicateException) {
Span::add('database.exists', true);
$max = 15;
$sleep = 2;
$attempts = 0;
while (true) {
try {
$attempts++;
Console::success('[Setup] - Creating project database: ' . $hostname . '...');
$dbForProject->create();
break; // exit loop on success
} catch (DuplicateException) {
Span::add('database.exists', true);
Console::success('[Setup] - Skip: metadata table already exists');
break;
} catch (\Throwable $e) {
Console::warning(" └── Project database create failed. Retrying ({$attempts})...");
if ($attempts >= $max) {
throw new \Exception(' └── Failed to create project database: ' . $e->getMessage());
}
sleep($sleep);
}
}
if ($dbForProject->getCollection(AuditAdapterSQL::COLLECTION)->isEmpty()) {
@@ -528,8 +560,8 @@ $http->on(Constant::EVENT_REQUEST, function (SwooleRequest $swooleRequest, Swool
$log->setType(Log::TYPE_ERROR);
$log->setMessage($th->getMessage());
$log->addTag('method', $route->getMethod());
$log->addTag('url', $route->getPath());
$log->addTag('method', $route?->getMethod() ?? $request->getMethod());
$log->addTag('url', $route?->getPath() ?? $request->getURI());
$log->addTag('verboseType', get_class($th));
$log->addTag('code', $th->getCode());
// $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant
@@ -541,12 +573,15 @@ $http->on(Constant::EVENT_REQUEST, function (SwooleRequest $swooleRequest, Swool
$log->addExtra('trace', $th->getTraceAsString());
$log->addExtra('roles', isset($authorization) ? $authorization->getRoles() : []);
$sdk = $route->getLabel("sdk", false);
$sdk = $route?->getLabel("sdk", false);
$action = 'UNKNOWN_NAMESPACE.UNKNOWN.METHOD';
if (!empty($sdk)) {
/** @var Appwrite\SDK\Method $sdk */
$action = $sdk->getNamespace() . '.' . $sdk->getMethodName();
} elseif ($route === null) {
$path = ltrim(parse_url($request->getURI(), PHP_URL_PATH) ?? '/', '/') ?: 'root';
$action = 'http.' . $request->getMethod() . '.' . $path;
}
$log->setAction($action);
@@ -610,7 +645,7 @@ $http->on(Constant::EVENT_TASK, function () use ($register) {
if ($latestDocument !== null) {
$queries[] = Query::cursorAfter($latestDocument);
}
if ($lastSyncUpdate != null) {
if ($lastSyncUpdate !== null) {
$queries[] = Query::greaterThanEqual('$updatedAt', $lastSyncUpdate);
}
$results = [];
@@ -618,7 +653,7 @@ $http->on(Constant::EVENT_TASK, function () use ($register) {
$authorization = $app->getResource('authorization');
$results = $authorization->skip(fn () => $dbForPlatform->find('rules', $queries));
} catch (Throwable $th) {
Console::error($th->getMessage());
Console::error('rules ' . $th->getMessage());
}
$sum = count($results);
+4
View File
@@ -6,6 +6,7 @@ const APP_NAME = 'Appwrite';
const APP_DOMAIN = 'appwrite.io';
const APP_VIEWS_DIR = __DIR__ . '/../views';
const APP_CE_CONFIG_DIR = __DIR__ . '/../config';
// Email
const APP_EMAIL_TEAM = 'team@localhost.test'; // Default email address
@@ -391,5 +392,8 @@ const COOKIE_NAME_PREVIEW = 'a_jwt_console';
const CACHE_RECONNECT_MAX_RETRIES = 2;
const CACHE_RECONNECT_RETRY_DELAY = 1000;
/* Web installer */
const LOCAL_API_TIMEOUT = 30 * 1000; // 30 seconds
// Project status
const PROJECT_STATUS_ACTIVE = 'active';
+5 -1
View File
@@ -72,7 +72,7 @@ Database::addFilter(
$attributes = $database->getAuthorization()->skip(fn () => $database->find('attributes', [
Query::equal('collectionInternalId', [$document->getSequence()]),
Query::equal('databaseInternalId', [$document->getAttribute('databaseInternalId')]),
Query::limit($database->getLimitForAttributes()),
Query::limit($database->getLimitForAttributes() ?: APP_LIMIT_SUBQUERY),
]));
foreach ($attributes as $attribute) {
@@ -88,6 +88,10 @@ Database::addFilter(
break;
case Database::VAR_STRING:
case Database::VAR_VARCHAR:
case Database::VAR_TEXT:
case Database::VAR_MEDIUMTEXT:
case Database::VAR_LONGTEXT:
$filters = $attribute->getAttribute('filters', []);
$attribute->setAttribute('encrypt', in_array('encrypt', $filters));
break;
+37 -22
View File
@@ -12,6 +12,7 @@ use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Config\Config;
use Utopia\Console;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Adapter\Mongo;
use Utopia\Database\Adapter\MySQL;
use Utopia\Database\Adapter\Postgres;
use Utopia\Database\Adapter\SQL;
@@ -24,6 +25,7 @@ use Utopia\Logger\Adapter\LogOwl;
use Utopia\Logger\Adapter\Raygun;
use Utopia\Logger\Adapter\Sentry;
use Utopia\Logger\Logger;
use Utopia\Mongo\Client as MongoClient;
use Utopia\Pools\Adapter\Stack as StackPool;
use Utopia\Pools\Adapter\Swoole as SwoolePool;
use Utopia\Pools\Group;
@@ -151,13 +153,14 @@ $register->set('pools', function () {
$group = new Group();
$fallbackForDB = 'db_main=' . AppwriteURL::unparse([
'scheme' => System::getEnv('_APP_DB_ADAPTER', 'mariadb'),
'host' => System::getEnv('_APP_DB_HOST', 'mariadb'),
'port' => System::getEnv('_APP_DB_PORT', '3306'),
'scheme' => System::getEnv('_APP_DB_ADAPTER', 'mongodb'),
'host' => System::getEnv('_APP_DB_HOST', 'mongodb'),
'port' => System::getEnv('_APP_DB_PORT', '27017'),
'user' => System::getEnv('_APP_DB_USER', ''),
'pass' => System::getEnv('_APP_DB_PASS', ''),
'path' => System::getEnv('_APP_DB_SCHEMA', ''),
]);
$fallbackForRedis = 'redis_main=' . AppwriteURL::unparse([
'scheme' => 'redis',
'host' => System::getEnv('_APP_REDIS_HOST', 'redis'),
@@ -171,19 +174,19 @@ $register->set('pools', function () {
'type' => 'database',
'dsns' => $fallbackForDB,
'multiple' => false,
'schemes' => ['mariadb', 'mysql','postgresql'],
'schemes' => ['mariadb', 'mongodb', 'mysql', 'postgresql'],
],
'database' => [
'type' => 'database',
'dsns' => $fallbackForDB,
'multiple' => true,
'schemes' => ['mariadb', 'mysql','postgresql'],
'schemes' => ['mariadb', 'mongodb', 'mysql', 'postgresql'],
],
'logs' => [
'type' => 'database',
'dsns' => System::getEnv('_APP_CONNECTIONS_DB_LOGS', $fallbackForDB),
'multiple' => false,
'schemes' => ['mariadb', 'mysql','postgresql'],
'schemes' => ['mariadb', 'mongodb', 'mysql', 'postgresql'],
],
'publisher' => [
'type' => 'publisher',
@@ -263,6 +266,7 @@ $register->set('pools', function () {
*
* Resource assignment to an adapter will happen below.
*/
$resource = match ($dsnScheme) {
'mysql',
'mariadb' => function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {
@@ -276,9 +280,19 @@ $register->set('pools', function () {
]);
});
},
'mongodb' => function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase, $dsn) {
try {
$mongo = new MongoClient($dsnDatabase, $dsnHost, (int)$dsnPort, $dsnUser, $dsnPass, false);
@$mongo->connect();
return $mongo;
} catch (\Throwable $e) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, "MongoDB connection failed: " . $e->getMessage());
}
},
'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}", $dsnUser, $dsnPass, array(
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,
@@ -309,6 +323,7 @@ $register->set('pools', function () {
$adapter = match ($dsn->getScheme()) {
'mariadb' => new MariaDB($resource()),
'mysql' => new MySQL($resource()),
'mongodb' => new Mongo($resource()),
'postgresql' => new Postgres($resource()),
default => null
};
@@ -365,28 +380,28 @@ $register->set('db', function () {
$dbUser = System::getEnv('_APP_DB_USER', '');
$dbPass = System::getEnv('_APP_DB_PASS', '');
$dbSchema = System::getEnv('_APP_DB_SCHEMA', '');
$dbAdapter = System::getEnv('_APP_DB_ADAPTER', 'mariadb');
$dbAdapter = System::getEnv('_APP_DB_ADAPTER', 'mongodb');
$dsn = '';
switch ($dbAdapter) {
case 'postgresql':
$dsn = "pgsql:host={$dbHost};port={$dbPort};dbname={$dbSchema}";
break;
case 'mongodb':
try {
$mongo = new MongoClient($dbSchema, $dbHost, (int)$dbPort, $dbUser, $dbPass, false);
@$mongo->connect();
return $mongo;
} catch (\Throwable $e) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'MongoDB connection failed: ' . $e->getMessage());
}
case 'mysql':
case 'mariadb':
default:
$dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbSchema};charset=utf8mb4";
break;
return new PDO($dsn, $dbUser, $dbPass, SQL::getPDOAttributes());
case 'postgresql':
$dsn = "pgsql:host={$dbHost};port={$dbPort};dbname={$dbSchema};connect_timeout=3";
return new PDO($dsn, $dbUser, $dbPass, SQL::getPDOAttributes());
default:
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Invalid database adapter');
}
return new PDO(
$dsn,
$dbUser,
$dbPass,
SQL::getPDOAttributes()
);
});
$register->set('smtp', function () {
+3 -7
View File
@@ -412,13 +412,7 @@ Http::setResource('user', function (string $mode, Document $project, Document $c
) { // Validate user has valid login token
$user = new User([]);
}
// if (APP_MODE_ADMIN === $mode) {
// if ($user->find('teamInternalId', $project->getAttribute('teamInternalId'), 'memberships')) {
// $authorization->setDefaultStatus(false); // Cancel security segmentation for admin users.
// } else {
// $user = new Document([]);
// }
// }
$authJWT = $request->getHeader('x-appwrite-jwt', '');
if (!empty($authJWT) && !$project->isEmpty()) { // JWT authentication
if (!$user->isEmpty()) {
@@ -1297,6 +1291,8 @@ Http::setResource('team', function (Document $project, Database $dbForPlatform,
}
}
// if teamInternalId is empty, return an empty document
if (empty($teamInternalId)) {
return new Document([]);
}
+69 -41
View File
@@ -248,48 +248,62 @@ $adapter
$server = new Server($adapter);
$logError = function (Throwable $error, string $action) use ($register) {
$logger = $register->get('realtimeLogger');
// Allows overriding
if (!function_exists('logError')) {
function logError(Throwable $error, string $action, array $tags = [], ?Document $project = null, ?Document $user = null, ?Authorization $authorization = null): void
{
global $register;
if ($logger && !$error instanceof Exception) {
$version = System::getEnv('_APP_VERSION', 'UNKNOWN');
$logger = $register->get('realtimeLogger');
$log = new Log();
$log->setNamespace("realtime");
$log->setServer(System::getEnv('_APP_LOGGING_SERVICE_IDENTIFIER', \gethostname()));
$log->setVersion($version);
$log->setType(Log::TYPE_ERROR);
$log->setMessage($error->getMessage());
if ($logger && !$error instanceof Exception) {
$version = System::getEnv('_APP_VERSION', 'UNKNOWN');
$log->addTag('code', $error->getCode());
$log->addTag('verboseType', get_class($error));
$log = new Log();
$log->setNamespace("realtime");
$log->setServer(System::getEnv('_APP_LOGGING_SERVICE_IDENTIFIER', \gethostname()));
$log->setVersion($version);
$log->setType(Log::TYPE_ERROR);
$log->setMessage($error->getMessage());
$log->addExtra('file', $error->getFile());
$log->addExtra('line', $error->getLine());
$log->addExtra('trace', $error->getTraceAsString());
$log->addTag('code', $error->getCode());
$log->addTag('verboseType', get_class($error));
$log->addTag('projectId', $project?->getId() ?: 'n/a');
$log->addTag('userId', $user?->getId() ?: 'n/a');
$log->setAction($action);
foreach ($tags as $key => $value) {
$log->addTag($key, $value ?: 'n/a');
}
$isProduction = System::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
$log->addExtra('file', $error->getFile());
$log->addExtra('line', $error->getLine());
$log->addExtra('trace', $error->getTraceAsString());
$log->addExtra('detailedTrace', $error->getTrace());
$log->addExtra('roles', $authorization?->getRoles() ?? []);
try {
$responseCode = $logger->addLog($log);
Console::info('Error log pushed with status code: ' . $responseCode);
} catch (Throwable $th) {
Console::error('Error pushing log: ' . $th->getMessage());
$log->setAction($action);
$isProduction = System::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
try {
$responseCode = $logger->addLog($log);
Console::info('Error log pushed with status code: ' . $responseCode);
} catch (Throwable $th) {
Console::error('Error pushing log: ' . $th->getMessage());
}
}
Console::error('[Error] Type: ' . get_class($error));
Console::error('[Error] Message: ' . $error->getMessage());
Console::error('[Error] File: ' . $error->getFile());
Console::error('[Error] Line: ' . $error->getLine());
}
}
Console::error('[Error] Type: ' . get_class($error));
Console::error('[Error] Message: ' . $error->getMessage());
Console::error('[Error] File: ' . $error->getFile());
Console::error('[Error] Line: ' . $error->getLine());
};
$server->error(logError(...));
$server->error($logError);
$server->onStart(function () use ($stats, $register, $containerId, &$statsDocument, $logError) {
$server->onStart(function () use ($stats, $register, $containerId, &$statsDocument) {
sleep(5); // wait for the initial database schema to be ready
Console::success('Server started successfully');
@@ -326,7 +340,7 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume
*/
// TODO: Remove this if check once it doesn't cause issues for cloud
if (System::getEnv('_APP_EDITION', 'self-hosted') === 'self-hosted') {
Timer::tick(5000, function () use ($register, $stats, &$statsDocument, $logError) {
Timer::tick(5000, function () use ($register, $stats, &$statsDocument) {
$payload = [];
foreach ($stats as $projectId => $value) {
$payload[$projectId] = $stats->get($projectId, 'connectionsTotal');
@@ -344,13 +358,13 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume
$database->getAuthorization()->skip(fn () => $database->updateDocument('realtime', $statsDocument->getId(), $statsDocument));
} catch (Throwable $th) {
$logError($th, "updateWorkerDocument");
logError($th, "updateWorkerDocument");
}
});
}
});
$server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $realtime, $logError) {
$server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $realtime) {
Console::success('Worker ' . $workerId . ' started successfully');
$telemetry = getTelemetry($workerId);
@@ -362,7 +376,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
$attempts = 0;
$start = time();
Timer::tick(5000, function () use ($server, $register, $realtime, $stats, $logError) {
Timer::tick(5000, function () use ($server, $register, $realtime, $stats) {
/**
* Sending current connections to project channels on the console project every 5 seconds.
*/
@@ -548,7 +562,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
}
});
} catch (Throwable $th) {
$logError($th, "pubSubConnection");
logError($th, "pubSubConnection");
Console::error('Pub/sub error: ' . $th->getMessage());
$attempts++;
@@ -560,7 +574,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
Console::error('Failed to restart pub/sub...');
});
$server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $register, $stats, &$realtime, $logError) {
$server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $register, $stats, &$realtime) {
$app = new Http('UTC');
$request = new Request($request);
$response = new Response(new SwooleResponse());
@@ -571,6 +585,10 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
Http::setResource('request', fn () => $request);
Http::setResource('response', fn () => $response);
$project = null;
$logUser = null;
$authorization = null;
try {
/** @var Document $project */
$project = $app->getResource('project');
@@ -591,8 +609,15 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
throw new AppwriteException(AppwriteException::GENERAL_API_DISABLED);
}
$projectRegion = $project->getAttribute('region', '');
$currentRegion = System::getEnv('_APP_REGION', 'default');
if (!empty($projectRegion) && $projectRegion !== $currentRegion) {
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, 'Project is not accessible in this region. Please make sure you are using the correct endpoint');
}
$timelimit = $app->getResource('timelimit');
$user = $app->getResource('user'); /** @var User $user */
$logUser = $user;
/*
* Abuse Check
@@ -683,11 +708,11 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$stats->incr($project->getId(), 'connections');
$stats->incr($project->getId(), 'connectionsTotal');
} catch (Throwable $th) {
$logError($th, "initServer");
logError($th, 'realtime', project: $project, user: $logUser, authorization: $authorization);
// Handle SQL error code is 'HY000'
$code = $th->getCode();
if (!is_int($code)) {
if (!\is_int($code)) {
$code = 500;
}
@@ -718,7 +743,10 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
}
});
$server->onMessage(function (int $connection, string $message) use ($server, $register, $realtime, $containerId, $logError) {
$server->onMessage(function (int $connection, string $message) use ($server, $register, $realtime, $containerId) {
$project = null;
$authorization = null;
try {
$response = new Response(new SwooleResponse());
$projectId = $realtime->connections[$connection]['projectId'] ?? null;
@@ -844,7 +872,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Message type is not valid.');
}
} catch (Throwable $th) {
$logError($th, "realtimeMessage");
logError($th, 'realtimeMessage', project: $project, authorization: $authorization);
$code = $th->getCode();
if (!is_int($code)) {
$code = 500;
+129 -21
View File
@@ -12,7 +12,12 @@ $version = $this->getParam('version', '');
$organization = $this->getParam('organization', '');
$image = $this->getParam('image', '');
$enableAssistant = $this->getParam('enableAssistant', false);
$dbService = $this->getParam('database');
$dbService = $this->getParam('database', 'mongodb');
$allowedDbServices = ['mariadb', 'mongodb', 'postgresql'];
if (!\in_array($dbService, $allowedDbServices, true)) {
$dbService = 'mongodb';
}
$hostPath = rtrim($this->getParam('hostPath', ''), '/');
?>services:
traefik:
image: traefik:3.6
@@ -62,6 +67,9 @@ $dbService = $this->getParam('database');
- traefik.http.routers.appwrite_api_https.service=appwrite_api
- traefik.http.routers.appwrite_api_https.tls=true
volumes:
<?php if ($version === 'local' && !empty($hostPath)): ?>
- <?php echo $hostPath; ?>:/usr/src/code:rw
<?php endif; ?>
- appwrite-uploads:/storage/uploads:rw
- appwrite-imports:/storage/imports:rw
- appwrite-cache:/storage/cache:rw
@@ -104,6 +112,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -183,7 +192,7 @@ $dbService = $this->getParam('database');
appwrite-console:
<<: *x-logging
container_name: appwrite-console
image: <?php echo $organization; ?>/console:7.5.7
image: <?php echo $organization; ?>/console:7.6.4
restart: unless-stopped
networks:
- appwrite
@@ -237,6 +246,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -256,7 +266,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -265,6 +275,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -283,13 +294,14 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_OPENSSL_KEY_V1
- _APP_EMAIL_SECURITY
- _APP_SYSTEM_SECURITY_EMAIL_ADDRESS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -312,7 +324,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
volumes:
- appwrite-uploads:/storage/uploads:rw
- appwrite-cache:/storage/cache:rw
@@ -328,6 +340,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -376,7 +389,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -385,6 +398,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -403,7 +417,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
volumes:
- appwrite-functions:/storage/functions:rw
- appwrite-sites:/storage/sites:rw
@@ -419,6 +433,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -472,7 +487,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
volumes:
- appwrite-config:/storage/config:rw
- appwrite-certificates:/storage/certificates:rw
@@ -492,6 +507,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -510,7 +526,7 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
- openruntimes-executor
environment:
- _APP_ENV
@@ -522,6 +538,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -557,6 +574,7 @@ $dbService = $this->getParam('database');
- _APP_OPENSSL_KEY_V1
- _APP_SYSTEM_EMAIL_NAME
- _APP_SYSTEM_EMAIL_ADDRESS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -597,6 +615,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -640,7 +659,7 @@ $dbService = $this->getParam('database');
volumes:
- appwrite-imports:/storage/imports:rw
depends_on:
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -656,6 +675,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -692,6 +712,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -717,11 +738,12 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -747,11 +769,12 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -776,11 +799,12 @@ $dbService = $this->getParam('database');
- appwrite
depends_on:
- redis
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -804,7 +828,7 @@ $dbService = $this->getParam('database');
networks:
- appwrite
depends_on:
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
- redis
environment:
- _APP_ENV
@@ -814,6 +838,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -830,7 +855,7 @@ $dbService = $this->getParam('database');
networks:
- appwrite
depends_on:
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
- redis
environment:
- _APP_ENV
@@ -840,6 +865,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -856,7 +882,7 @@ $dbService = $this->getParam('database');
networks:
- appwrite
depends_on:
- <?= $dbService . "\n" ?>
- <?= $dbService . "\n" ?>
- redis
environment:
- _APP_ENV
@@ -866,6 +892,7 @@ $dbService = $this->getParam('database');
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -945,9 +972,7 @@ $dbService = $this->getParam('database');
- OPR_EXECUTOR_STORAGE_WASABI_REGION=$_APP_STORAGE_WASABI_REGION
- OPR_EXECUTOR_STORAGE_WASABI_BUCKET=$_APP_STORAGE_WASABI_BUCKET
<?php if ($dbService === 'mariadb'): ?>
mariadb:
image: mariadb:10.11
container_name: appwrite-mariadb
@@ -964,26 +989,105 @@ $dbService = $this->getParam('database');
- MARIADB_AUTO_UPGRADE=1
command: 'mysqld --innodb-flush-method=fsync'
<?php elseif ($dbService === 'mongodb'): ?>
mongodb:
image: mongo:8.2.5
container_name: appwrite-mongodb
<<: *x-logging
networks:
- appwrite
volumes:
- appwrite-mongodb:/data/db
- appwrite-mongodb-keyfile:/data/keyfile
ports:
- "27017:27017"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=${_APP_DB_ROOT_PASS}
- MONGO_INITDB_DATABASE=${_APP_DB_SCHEMA}
- MONGO_INITDB_USERNAME=${_APP_DB_USER}
- MONGO_INITDB_PASSWORD=${_APP_DB_PASS}
entrypoint:
- /bin/bash
- -c
- |
set -e
KEYFILE_PATH="/data/keyfile/mongo-keyfile"
INIT_FLAG="/data/db/.mongodb_initialized"
# Generate keyfile if it doesn't exist
if [ ! -f "$$KEYFILE_PATH" ]; then
echo "Generating random MongoDB keyfile..."
mkdir -p /data/keyfile
openssl rand -base64 756 > "$$KEYFILE_PATH"
fi
chmod 400 "$$KEYFILE_PATH"
chown mongodb:mongodb "$$KEYFILE_PATH" 2>/dev/null || chown 999:999 "$$KEYFILE_PATH"
# If not initialized, start without auth first to set up replica set and users
if [ ! -f "$$INIT_FLAG" ]; then
echo "First-time initialization: starting MongoDB without auth..."
mongod --replSet rs0 --bind_ip_all --fork --logpath /var/log/mongodb/mongod.log --dbpath /data/db
echo "Waiting for MongoDB to start..."
sleep 5
echo "Initializing replica set..."
mongosh --eval "rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'mongodb:27017'}]})"
echo "Waiting for replica set to initialize..."
sleep 5
echo "Creating root user..."
mongosh admin --eval "db.createUser({user: '$$MONGO_INITDB_ROOT_USERNAME', pwd: '$$MONGO_INITDB_ROOT_PASSWORD', roles: ['root']})"
echo "Creating application user..."
mongosh admin --eval "db.createUser({user: '$$MONGO_INITDB_USERNAME', pwd: '$$MONGO_INITDB_PASSWORD', roles: [{role: 'readWrite', db: '$$MONGO_INITDB_DATABASE'}]})"
echo "Shutting down MongoDB..."
mongod --dbpath /data/db --shutdown
touch "$$INIT_FLAG"
echo "Initialization complete."
fi
echo "Starting MongoDB with authentication..."
exec mongod --replSet rs0 --bind_ip_all --auth --keyFile "$$KEYFILE_PATH"
healthcheck:
test: |
mongosh -u root -p "$$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --quiet --eval "rs.status().ok" | grep -q 1
interval: 10s
timeout: 10s
retries: 10
start_period: 60s
<?php elseif ($dbService === 'postgresql'): ?>
postgresql:
image: postgres:15
image: appwrite/postgres:0.1.0
container_name: appwrite-postgresql
restart: unless-stopped
networks:
- appwrite
volumes:
- appwrite-postgresql:/var/lib/postgresql/data:rw
- appwrite-postgresql:/var/lib/postgresql:rw
environment:
- POSTGRES_DB=${_APP_DB_SCHEMA}
- POSTGRES_USER=${_APP_DB_USER}
- POSTGRES_PASSWORD=${_APP_DB_PASS}
command: "postgres"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${_APP_DB_USER} -d ${_APP_DB_SCHEMA}"]
interval: 10s
timeout: 10s
retries: 10
start_period: 30s
<?php endif; ?>
redis:
image: redis:7.2.4-alpine
image: redis:7.4.7-alpine
container_name: appwrite-redis
<<: *x-logging
restart: unless-stopped
@@ -1019,6 +1123,10 @@ volumes:
appwrite-mariadb:
<?php elseif ($dbService === 'postgresql'): ?>
appwrite-postgresql:
<?php elseif ($dbService === 'mongodb'): ?>
appwrite-mongodb:
appwrite-mongodb-keyfile:
appwrite-mongodb-config:
<?php endif; ?>
appwrite-redis:
appwrite-cache:
+147
View File
@@ -0,0 +1,147 @@
<?php
$isUpgrade = $isUpgrade ?? false;
$lockedDatabase = $lockedDatabase ?? null;
$vars = $vars ?? [];
$defaultHttpPort = $defaultHttpPort ?? '80';
$defaultHttpsPort = $defaultHttpsPort ?? '443';
$defaultAppDomain = $vars['_APP_DOMAIN']['default'] ?? 'localhost';
$defaultAppDomain = ($defaultAppDomain === 'traefik') ? 'localhost' : $defaultAppDomain;
$defaultEmailCertificates = $defaultEmailCertificates ?? '';
$defaultSecretKey = $vars['_APP_OPENSSL_KEY_V1']['default'] ?? '';
$defaultAssistantOpenAIKey = $vars['_APP_ASSISTANT_OPENAI_API_KEY']['default'] ?? '';
$defaultDatabase = $vars['_APP_DB_ADAPTER']['default'] ?? 'mongodb';
$lockedDatabase = $isUpgrade && empty($lockedDatabase) ? $defaultDatabase : $lockedDatabase;
$isLocalInstall = $isLocalInstall ?? false;
$cardStep = min(4, $step);
$stepFile = __DIR__ . "/installer/templates/steps/step-{$cardStep}.phtml";
if (!is_file($stepFile)) {
$stepFile = __DIR__ . "/installer/templates/steps/step-1.phtml";
}
$cssVersion = @filemtime(__DIR__ . '/installer/css/styles.css') ?: time();
$tooltipsVersion = @filemtime(__DIR__ . '/installer/js/tooltips.js') ?: time();
$constantsVersion = @filemtime(__DIR__ . '/installer/js/constants.js') ?: time();
$stepsContextVersion = @filemtime(__DIR__ . '/installer/js/modules/context.js') ?: time();
$stepsStateVersion = @filemtime(__DIR__ . '/installer/js/modules/state.js') ?: time();
$stepsValidationVersion = @filemtime(__DIR__ . '/installer/js/modules/validation.js') ?: time();
$stepsUiVersion = @filemtime(__DIR__ . '/installer/js/modules/ui.js') ?: time();
$stepsToastVersion = @filemtime(__DIR__ . '/installer/js/modules/toast.js') ?: time();
$stepsProgressVersion = @filemtime(__DIR__ . '/installer/js/modules/progress.js') ?: time();
$stepsVersion = @filemtime(__DIR__ . '/installer/js/steps.js') ?: time();
$installerVersion = @filemtime(__DIR__ . '/installer/js/installer.js') ?: time();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $isUpgrade ? 'Appwrite Update' : 'Appwrite Installation'; ?></title>
<meta name="appwrite-installer-csrf" content="<?php echo htmlspecialchars($csrfToken ?? '', ENT_QUOTES); ?>">
<link rel="icon" type="image/svg+xml" href="installer/icons/appwrite-mark.svg">
<link rel="stylesheet" href="installer/css/styles.css?v=<?php echo $cssVersion; ?>">
<script src="installer/js/tooltips.js?v=<?php echo $tooltipsVersion; ?>" defer></script>
<script src="installer/js/constants.js?v=<?php echo $constantsVersion; ?>" defer></script>
<!-- Load context first; other modules depend on InstallerStepsContext. -->
<script src="installer/js/modules/context.js?v=<?php echo $stepsContextVersion; ?>" defer></script>
<script src="installer/js/modules/state.js?v=<?php echo $stepsStateVersion; ?>" defer></script>
<script src="installer/js/modules/validation.js?v=<?php echo $stepsValidationVersion; ?>" defer></script>
<script src="installer/js/modules/ui.js?v=<?php echo $stepsUiVersion; ?>" defer></script>
<script src="installer/js/modules/toast.js?v=<?php echo $stepsToastVersion; ?>" defer></script>
<script src="installer/js/modules/progress.js?v=<?php echo $stepsProgressVersion; ?>" defer></script>
<script src="installer/js/steps.js?v=<?php echo $stepsVersion; ?>" defer></script>
<script src="installer/js/installer.js?v=<?php echo $installerVersion; ?>" defer></script>
</head>
<body
class="installer-page"
data-step="<?php echo $step; ?>"
data-upgrade="<?php echo $isUpgrade ? 'true' : 'false'; ?>"
<?php if (!empty($lockedDatabase)) { ?>
data-locked-database="<?php echo htmlspecialchars((string) $lockedDatabase, ENT_QUOTES, 'UTF-8'); ?>"
<?php } ?>
data-default-http-port="<?php echo htmlspecialchars((string) $defaultHttpPort, ENT_QUOTES, 'UTF-8'); ?>"
data-default-https-port="<?php echo htmlspecialchars((string) $defaultHttpsPort, ENT_QUOTES, 'UTF-8'); ?>"
data-default-app-domain="<?php echo htmlspecialchars((string) $defaultAppDomain, ENT_QUOTES, 'UTF-8'); ?>"
data-default-email-certificates="<?php echo htmlspecialchars((string) $defaultEmailCertificates, ENT_QUOTES, 'UTF-8'); ?>"
data-default-secret-key="<?php echo htmlspecialchars((string) $defaultSecretKey, ENT_QUOTES, 'UTF-8'); ?>"
data-default-assistant-openai-key="<?php echo htmlspecialchars((string) $defaultAssistantOpenAIKey, ENT_QUOTES, 'UTF-8'); ?>"
data-default-database="<?php echo htmlspecialchars((string) $defaultDatabase, ENT_QUOTES, 'UTF-8'); ?>"
<?php if ($isLocalInstall) { ?>
data-dev-mode="true"
<?php } ?>
>
<div class="installer-backdrop" aria-hidden="true">
<span class="installer-gradients">
<span class="installer-blob blob-one">
<?php include __DIR__ . '/installer/icons/install-bg-1.svg'; ?>
</span>
<span class="installer-blob blob-two">
<?php include __DIR__ . '/installer/icons/install-bg-2.svg'; ?>
</span>
</span>
</div>
<main class="installer-main">
<div class="installer-card" data-step="<?php echo $step; ?>">
<div class="installer-step">
<div class="step-panel is-active">
<?php include $stepFile; ?>
</div>
</div>
<div class="action-shell">
<div class="divider"></div>
<div class="action-bar">
<button class="button secondary" type="button" data-action="back">
<span class="button-text typography-text-m-500">Back</span>
</button>
<div class="step-indicators" aria-hidden="true">
<span class="step-indicator" data-step="1">
<span class="indicator-active"><?php include __DIR__ . '/installer/icons/indicator-active.svg'; ?></span>
<span class="indicator-inactive"><?php include __DIR__ . '/installer/icons/indicator-inactive.svg'; ?></span>
</span>
<span class="step-indicator" data-step="2">
<span class="indicator-active"><?php include __DIR__ . '/installer/icons/indicator-active.svg'; ?></span>
<span class="indicator-inactive"><?php include __DIR__ . '/installer/icons/indicator-inactive.svg'; ?></span>
</span>
<span class="step-indicator" data-step="3">
<span class="indicator-active"><?php include __DIR__ . '/installer/icons/indicator-active.svg'; ?></span>
<span class="indicator-inactive"><?php include __DIR__ . '/installer/icons/indicator-inactive.svg'; ?></span>
</span>
<span class="step-indicator" data-step="4">
<span class="indicator-active"><?php include __DIR__ . '/installer/icons/indicator-active.svg'; ?></span>
<span class="indicator-inactive"><?php include __DIR__ . '/installer/icons/indicator-inactive.svg'; ?></span>
</span>
</div>
<button class="button primary" type="button" data-action="next">
<span class="button-text typography-text-m-500">Next</span>
</button>
</div>
</div>
</div>
<div class="install-screen" aria-live="polite">
<div class="install-screen-content">
<?php if ($step === 5) { include __DIR__ . '/installer/templates/steps/step-5.phtml'; } ?>
</div>
</div>
</main>
<footer class="installer-footer">
<div class="appwrite-logo">
<?php include __DIR__ . '/installer/icons/appwrite-logo.svg'; ?>
</div>
</footer>
<template id="field-error-template">
<div class="field-error typography-caption-400 text-error">
<span class="field-error-icon">
<?php include __DIR__ . '/installer/icons/exclamation-circle.svg'; ?>
</span>
<span class="field-error-text"></span>
</div>
</template>
<div id="installer-toast-stack" class="installer-toast-stack" aria-live="polite" aria-atomic="true"></div>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,13 @@
<svg width="131" height="25" viewBox="0 0 131 25" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M38.2643 19.5087C40.4069 19.5087 41.49 18.3947 41.9609 17.6362H42.1728C42.267 18.4421 42.832 19.2006 43.9386 19.2006H46.0341V16.8304H45.4926C45.1159 16.8304 44.9275 16.617 44.9275 16.2852V6.78055H42.1492V8.29751H41.9373C41.3958 7.53903 40.2656 6.47242 38.1937 6.47242C34.8974 6.47242 32.4487 9.2219 32.4487 12.9906C32.4487 16.7593 34.9445 19.5087 38.2643 19.5087ZM38.7588 16.8067C36.8045 16.8067 35.2741 15.3608 35.2741 13.0143C35.2741 10.7151 36.7574 9.15079 38.7352 9.15079C40.6188 9.15079 42.1963 10.5492 42.1963 13.0143C42.1963 15.1238 40.8543 16.8067 38.7588 16.8067Z" fill="#19191D"/>
<path d="M47.6745 24.0166H50.4528V17.6362H50.6647C51.1826 18.3947 52.2893 19.5087 54.4789 19.5087C57.7752 19.5087 60.1768 16.7118 60.1768 12.9906C60.1768 9.2456 57.6104 6.47242 54.2906 6.47242C52.1715 6.47242 51.1356 7.63384 50.6411 8.2738H50.4292V6.78055H47.6745V24.0166ZM53.8903 16.8778C51.9832 16.8778 50.4057 15.4556 50.4057 12.9906C50.4057 10.8811 51.7477 9.10339 53.8432 9.10339C55.7974 9.10339 57.3279 10.644 57.3279 12.9906C57.3279 15.2897 55.8445 16.8778 53.8903 16.8778Z" fill="#19191D"/>
<path d="M61.6104 24.0166H64.3887V17.6362H64.6006C65.1186 18.3947 66.2252 19.5087 68.4149 19.5087C71.7112 19.5087 73.8839 16.7118 73.8839 12.9906C73.8839 9.2456 71.5464 6.47242 68.2265 6.47242C66.1075 6.47242 65.0715 7.63384 64.5771 8.2738H64.3652V6.78055H61.6104V24.0166ZM67.8263 16.8778C65.9191 16.8778 64.3416 15.4556 64.3416 12.9906C64.3416 10.8811 65.6837 9.10339 67.7792 9.10339C69.7334 9.10339 71.2638 10.644 71.2638 12.9906C71.2638 15.2897 69.7805 16.8778 67.8263 16.8778Z" fill="#19191D"/>
<path d="M77.5565 19.489H81.4885L83.7252 9.74733H83.8665L86.1033 19.489H90.0117L93.1415 7.06896H90.3414L88.1046 16.8343H87.8927L85.6559 7.06896H81.9594L79.6991 16.8343H79.4872L77.2739 7.06896H74.3073L77.5565 19.489Z" fill="#19191D"/>
<path d="M94.549 19.489H97.3273V13.3501C97.3273 11.0036 98.4104 9.55771 100.435 9.55771H101.66V6.76083H100.741C99.1638 6.76083 97.963 7.85114 97.4921 8.89405H97.3038V7.06896H94.549V19.489Z" fill="#19191D"/>
<path d="M115.447 19.489H117.613V17.0003H115.47C114.623 17.0003 114.27 16.621 114.27 15.744V9.53401H117.754V7.06896H114.27V3.58472H111.633V7.06896H109.325V9.53401H111.468V15.7677C111.468 18.3987 113.045 19.489 115.447 19.489Z" fill="#19191D"/>
<path d="M125.067 19.5087C127.633 19.5087 129.893 18.2288 130.694 15.6452L128.151 15.029C127.704 16.4037 126.409 17.1148 125.043 17.1148C123.018 17.1148 121.676 15.7875 121.653 13.7016H131V12.9195C131 9.2219 128.716 6.47242 124.949 6.47242C121.629 6.47242 118.78 9.10339 118.78 13.0143C118.78 16.8067 121.3 19.5087 125.067 19.5087ZM121.676 11.6632C121.841 10.17 123.183 8.91377 124.949 8.91377C126.644 8.91377 128.033 9.98037 128.175 11.6632H121.676Z" fill="#19191D"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M108.09 19.489H105.312V9.53401H103.145V7.06896H108.09V19.489Z" fill="#19191D"/>
<path d="M106.494 5.34533C107.507 5.34533 108.26 4.58686 108.26 3.59136C108.26 2.61956 107.507 1.86108 106.494 1.86108C105.482 1.86108 104.729 2.61956 104.729 3.59136C104.729 4.58686 105.482 5.34533 106.494 5.34533Z" fill="#19191D"/>
<path d="M24.2577 16.4436V21.9248H10.6705C6.71194 21.9248 3.25559 19.7204 1.40636 16.4436C1.13754 15.9672 0.90225 15.4674 0.704883 14.9487C0.31744 13.9322 0.0738912 12.8415 0 11.7034V10.2214C0.0160422 9.96781 0.0413207 9.71617 0.0743773 9.46752C0.141949 8.95727 0.244035 8.45799 0.378206 7.97265C1.64748 3.37143 5.77469 0 10.6705 0C15.5662 0 19.693 3.37143 20.9622 7.97265H15.1526C14.1988 6.47279 12.5479 5.4812 10.6705 5.4812C8.79305 5.4812 7.14216 6.47279 6.18839 7.97265C5.89768 8.42859 5.67212 8.93136 5.52434 9.46752C5.39308 9.94289 5.32308 10.4442 5.32308 10.9624C5.32308 12.5335 5.96768 13.9497 7.00119 14.9487C7.95886 15.876 9.25 16.4436 10.6705 16.4436H24.2577Z" fill="#FD366E"/>
<path d="M24.2578 9.46753V14.9487H14.3398C15.3733 13.9497 16.018 12.5335 16.018 10.9624C16.018 10.4442 15.9479 9.9429 15.8167 9.46753H24.2578Z" fill="#FD366E"/>
</svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,4 @@
<svg width="25" height="22" viewBox="0 0 25 22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M24.2577 16.4436V21.9248H10.6705C6.71194 21.9248 3.25559 19.7204 1.40636 16.4436C1.13754 15.9672 0.90225 15.4674 0.704883 14.9487C0.31744 13.9322 0.0738912 12.8415 0 11.7034V10.2214C0.0160422 9.96781 0.0413207 9.71617 0.0743773 9.46752C0.141949 8.95727 0.244035 8.45799 0.378206 7.97265C1.64748 3.37143 5.77469 0 10.6705 0C15.5662 0 19.693 3.37143 20.9622 7.97265H15.1526C14.1988 6.47279 12.5479 5.4812 10.6705 5.4812C8.79305 5.4812 7.14216 6.47279 6.18839 7.97265C5.89768 8.42859 5.67212 8.93136 5.52434 9.46752C5.39308 9.94289 5.32308 10.4442 5.32308 10.9624C5.32308 12.5335 5.96768 13.9497 7.00119 14.9487C7.95886 15.876 9.25 16.4436 10.6705 16.4436H24.2577Z" fill="#FD366E"/>
<path d="M24.2578 9.46753V14.9487H14.3398C15.3733 13.9497 16.018 12.5335 16.018 10.9624C16.018 10.4442 15.9479 9.9429 15.8167 9.46753H24.2578Z" fill="#FD366E"/>
</svg>

After

Width:  |  Height:  |  Size: 980 B

@@ -0,0 +1,3 @@
<svg class="accordion-chevron" data-open="false" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path fill-rule="evenodd" clip-rule="evenodd" d="M5.29289 7.29289C5.68342 6.90237 6.31658 6.90237 6.70711 7.29289L10 10.5858L13.2929 7.29289C13.6834 6.90237 14.3166 6.90237 14.7071 7.29289C15.0976 7.68342 15.0976 8.31658 14.7071 8.70711L10.7071 12.7071C10.3166 13.0976 9.68342 13.0976 9.29289 12.7071L5.29289 8.70711C4.90237 8.31658 4.90237 7.68342 5.29289 7.29289Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 536 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" aria-hidden="true">
<path fill="currentColor" d="M7 9a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2z"/>
<path fill="currentColor" d="M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2V5h8a2 2 0 0 0-2-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 293 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" aria-hidden="true">
<path fill="currentColor" fill-rule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0m-7 4a1 1 0 1 1-2 0 1 1 0 0 1 2 0m-1-9a1 1 0 0 0-1 1v4a1 1 0 1 0 2 0V6a1 1 0 0 0-1-1" clip-rule="evenodd"/>
</svg>

After

Width:  |  Height:  |  Size: 296 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
<path fill="currentColor" fill-rule="evenodd" d="M3.707 2.293a1 1 0 1 0-1.414 1.414l14 14a1 1 0 1 0 1.414-1.414l-1.473-1.473A10 10 0 0 0 19.543 10C18.268 5.943 14.478 3 10 3a9.96 9.96 0 0 0-4.512 1.074zm4.261 4.26 1.514 1.515a2.003 2.003 0 0 1 2.45 2.45l1.515 1.514a4 4 0 0 0-5.478-5.478" clip-rule="evenodd"/>
<path fill="currentColor" d="M12.454 16.697 9.75 13.992a4 4 0 0 1-3.742-3.742L2.335 6.578A10 10 0 0 0 .458 10c1.274 4.057 5.065 7 9.542 7 .847 0 1.67-.105 2.454-.303"/>
</svg>

After

Width:  |  Height:  |  Size: 568 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
<path fill="currentColor" d="M10 12a2 2 0 1 0 0-4 2 2 0 0 0 0 4"/>
<path fill="currentColor" fill-rule="evenodd" d="M.457 10C1.732 5.943 5.522 3 10 3s8.267 2.943 9.542 7c-1.275 4.057-5.065 7-9.542 7-4.478 0-8.268-2.943-9.543-7M14 10a4 4 0 1 1-8 0 4 4 0 0 1 8 0" clip-rule="evenodd"/>
</svg>

After

Width:  |  Height:  |  Size: 372 B

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M5 8C5 6.34315 6.34315 5 8 5C9.65685 5 11 6.34315 11 8C11 9.65685 9.65685 11 8 11C6.34315 11 5 9.65685 5 8Z" fill="#FD366E"/>
</svg>

After

Width:  |  Height:  |  Size: 261 B

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M5 8C5 6.34315 6.34315 5 8 5C9.65685 5 11 6.34315 11 8C11 9.65685 9.65685 11 8 11C6.34315 11 5 9.65685 5 8Z" fill="#D8D8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 261 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" aria-hidden="true">
<path fill="currentColor" fill-rule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0m-7-4a1 1 0 1 1-2 0 1 1 0 0 1 2 0M9 9a1 1 0 1 0 0 2v3a1 1 0 0 0 1 1h1a1 1 0 1 0 0-2v-3a1 1 0 0 0-1-1z" clip-rule="evenodd"/>
</svg>

After

Width:  |  Height:  |  Size: 313 B

@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" width="408" height="353" viewBox="0 0 408 353" fill="none" aria-hidden="true">
<g filter="url(#filter0_f_3091_1065)">
<path d="M216.4 88.698C162.554 64.5014 104.764 118.126 82.6001 147.963C90.6227 156.819 114.663 172.323 146.645 163.495C186.622 152.459 191.109 162.269 229.454 181.887C267.799 201.506 268.207 261.18 291.051 268.537C313.895 275.894 322.054 244.422 324.501 193.74C326.949 143.058 283.709 118.944 216.4 88.698Z" fill="url(#paint0_radial_3091_1065)"/>
</g>
<defs>
<filter id="filter0_f_3091_1065" x="9.91821e-05" y="-2.28882e-05" width="407.2" height="352.2" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="41.3" result="effect1_foregroundBlur_3091_1065"/>
</filter>
<radialGradient id="paint0_radial_3091_1065" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(203.6 176.1) rotate(-90) scale(93.5 121)">
<stop stop-color="#FE9567"/>
<stop offset="1" stop-color="#FE9567" stop-opacity="0"/>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,16 @@
<svg width="569" height="367" viewBox="0 0 569 367" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<g filter="url(#install-bg-2-filter)">
<path d="M136.265 227.973C89.0703 207.713 99.6672 144.647 110.865 115.646C130.119 111.289 176.904 102.33 210.005 101.35C251.382 100.125 288.253 121.773 333.317 135.252C378.381 148.731 466.051 125.449 467.28 160.577C468.509 195.704 412.793 254.522 402.142 242.269C391.49 230.015 319.798 227.973 246.057 254.522C172.316 281.072 195.257 253.297 136.265 227.973Z" fill="url(#install-bg-2-paint)"/>
</g>
<defs>
<filter id="install-bg-2-filter" x="-0.000198364" y="0.0000457764" width="568.6" height="366.6" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="50.65" result="effect1_foregroundBlur_install_bg_2"/>
</filter>
<radialGradient id="install-bg-2-paint" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(284.3 183.3) rotate(-90) scale(82 183)">
<stop stop-color="#FD366E"/>
<stop offset="1" stop-color="#FD366E" stop-opacity="0"/>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<circle class="check-bg" cx="8" cy="8" r="7" fill="var(--fgcolor-neutral-primary)"/>
<path class="check-mark" d="M5 8.2L7.2 10.2L11.2 6.2" fill="none" stroke="var(--fgcolor-on-invert)" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 383 B

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path class="spinner-ring" opacity="0.2" d="M14.4001 7.99998C14.4001 11.5346 11.5347 14.4 8.0001 14.4C4.46548 14.4 1.6001 11.5346 1.6001 7.99998C1.6001 4.46535 4.46548 1.59998 8.0001 1.59998C11.5347 1.59998 14.4001 4.46535 14.4001 7.99998ZM2.8801 7.99998C2.8801 10.8277 5.1724 13.12 8.0001 13.12C10.8278 13.12 13.1201 10.8277 13.1201 7.99998C13.1201 5.17228 10.8278 2.87998 8.0001 2.87998C5.1724 2.87998 2.8801 5.17228 2.8801 7.99998Z" fill="var(--fgcolor-neutral-secondary)"/>
<path class="spinner-arc" d="M4.32921 2.7574C5.15654 2.1781 6.10923 1.80282 7.10939 1.66226C8.10955 1.5217 9.12877 1.61984 10.0837 1.94866C11.0387 2.27748 11.9023 2.82764 12.6039 3.55416C13.3055 4.28069 13.8252 5.16294 14.1204 6.1288C14.4157 7.09465 14.4782 8.11668 14.3029 9.11133C14.1275 10.106 13.7192 11.045 13.1114 11.8516C12.5035 12.6582 11.7134 13.3095 10.8057 13.7523C9.8979 14.195 8.89823 14.4166 7.8884 14.399L7.91074 13.1192C8.71861 13.1333 9.51834 12.956 10.2446 12.6018C10.9708 12.2476 11.6029 11.7266 12.0891 11.0813C12.5754 10.436 12.902 9.68477 13.0423 8.88906C13.1826 8.09334 13.1326 7.27572 12.8964 6.50303C12.6601 5.73035 12.2444 5.02454 11.6831 4.44333C11.1218 3.86211 10.431 3.42198 9.66701 3.15892C8.90304 2.89586 8.08766 2.81735 7.28753 2.9298C6.48741 3.04225 5.72525 3.34247 5.06339 3.80592L4.32921 2.7574Z" fill="var(--fgcolor-neutral-secondary)"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path fill="currentColor" fill-rule="evenodd" d="M5 9V7a5 5 0 1 1 10 0v2a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2m8-2v2H7V7a3 3 0 1 1 6 0" clip-rule="evenodd"/>
</svg>

After

Width:  |  Height:  |  Size: 309 B

@@ -0,0 +1,10 @@
<svg width="34" height="34" viewBox="0 0 34 34" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="0.5" y="0.5" width="33" height="33" rx="8.5" fill="white" stroke="#EDEDF0"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M28.3208 9.43304C27.9548 9.4451 28.0607 9.61 27.2684 9.80574C26.468 10.0028 25.5 9.88216 24.6393 10.2441C22.387 11.188 22.0224 14.8372 19.3397 16.249C17.5807 17.2424 15.7869 17.4703 14.1835 17.973C12.8965 18.4892 12.0961 18.8311 11.1523 19.6448C10.4203 20.2763 10.242 20.889 9.47647 21.6813C8.70022 22.7364 5.75747 21.7993 5 23.1225C5.39952 23.3813 5.6301 23.4523 6.33127 23.3598C6.18647 23.6346 5.26411 23.9966 5.43169 24.4015C5.43169 24.4015 7.66121 24.8077 9.54081 23.6735C10.4176 23.3169 11.2394 22.5621 12.6015 22.3811C14.3658 22.1465 16.354 22.7512 18.487 22.9214C18.046 23.7928 17.5915 24.3077 17.1048 25.0263C16.9547 25.1885 17.2335 25.3319 17.751 25.2341C18.6814 25.0035 19.3558 24.7541 20.0248 24.2916C20.8975 23.6896 21.2729 23.1386 22.009 22.2658C22.6484 23.2914 24.9034 23.5167 25.366 22.6305C24.5053 22.2658 24.3216 20.3688 24.6165 19.5497C24.9651 18.7694 25.2158 17.666 25.4974 16.6404C25.7507 15.7167 25.9076 14.3077 26.2106 13.5864C26.5726 12.6895 27.2764 12.4093 27.8046 11.9334C28.3328 11.4574 28.8584 11.0606 28.8423 9.97198C28.8369 9.61805 28.6546 9.42231 28.3208 9.43304Z" fill="#1F305F"/>
<path d="M5.673 24.2137C7.05522 24.2553 7.43061 24.2191 8.52324 23.7445C9.45232 23.341 10.6951 22.2537 11.7931 21.9024C13.4046 21.3849 15.1327 21.4627 16.8474 21.6651C17.4212 21.7335 17.9977 21.8287 18.4093 21.7844C19.0514 21.3903 19.0823 20.3204 19.4805 20.2346C19.3719 22.3046 18.4843 23.6292 17.5968 24.8304C19.467 24.5006 20.7165 23.3329 21.4727 21.8877C21.7019 21.4493 22.0827 20.732 22.257 20.2387C22.395 20.5658 22.0773 20.7736 22.2261 21.1302C23.43 20.1368 23.9985 19.0053 24.4865 17.3482C25.0522 15.4311 25.6327 13.7834 25.9974 13.2163C26.3527 12.6626 26.9064 12.3207 27.4118 11.9668C27.9856 11.5633 28.4991 11.1436 28.5875 10.3754C27.9816 10.3191 27.8421 10.1797 27.7523 9.87402C27.4493 10.0443 27.1705 10.0818 26.8554 10.0912C26.5819 10.0993 26.2816 10.0872 25.9143 10.1247C22.8804 10.4358 22.7396 13.4013 20.5342 15.5785C20.3921 15.7166 20.1494 15.9204 19.9886 16.0411C19.3075 16.5492 18.5782 16.828 17.81 17.1216C16.5658 17.5962 15.3861 17.7343 14.2197 18.1446C13.363 18.4449 12.5667 18.7894 11.8628 19.2707C11.6872 19.3914 11.4486 19.6059 11.2957 19.7306C10.8828 20.0684 10.612 20.4424 10.3492 20.8286C10.0784 21.2254 9.81831 21.6343 9.42014 22.0244C8.77528 22.6572 6.36746 22.2094 5.51882 22.7966C5.42497 22.8623 5.34855 22.9401 5.29761 23.0339C5.76014 23.2444 6.06982 23.1157 6.60207 23.1734C6.66776 23.6815 5.50005 23.9818 5.673 24.2137Z" fill="#C0765A"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.9033 11.3797C25.3323 11.7524 26.2333 11.4534 26.0724 10.712C25.4047 10.6557 25.0186 10.8823 24.9033 11.3797Z" fill="#1F305F"/>
<path d="M27.8971 10.5123C27.7831 10.7523 27.5646 11.0606 27.5646 11.6706C27.5632 11.7752 27.4855 11.8476 27.4841 11.6854C27.4895 11.0888 27.6477 10.8314 27.8153 10.4935C27.8917 10.3554 27.9386 10.4117 27.8971 10.5123Z" fill="#1F305F"/>
<path d="M27.7818 10.4225C27.6464 10.6504 27.322 11.0674 27.2697 11.676C27.2603 11.7806 27.1745 11.845 27.1879 11.6841C27.2469 11.0915 27.5057 10.7202 27.7028 10.3971C27.7912 10.2657 27.8328 10.326 27.7818 10.4225Z" fill="#1F305F"/>
<path d="M27.6772 10.303C27.523 10.5189 27.0243 11.0203 26.9197 11.6209C26.901 11.7241 26.8112 11.7804 26.838 11.6222C26.9466 11.0364 27.3769 10.5752 27.5995 10.2708C27.6987 10.1462 27.7362 10.2105 27.6772 10.303Z" fill="#1F305F"/>
<path d="M27.5835 10.1688C27.4012 10.3619 26.8059 11 26.6182 11.5805C26.5847 11.6797 26.4882 11.724 26.5365 11.5698C26.7255 11.0041 27.247 10.3954 27.5111 10.1259C27.6278 10.0173 27.6546 10.087 27.5835 10.1688Z" fill="#1F305F"/>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,6 @@
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="32" height="32" rx="8" fill="#081E2B"/>
<g transform="translate(11.4, 6.1)">
<path d="M6.03701 2.19958C5.24603 1.21687 4.56489 0.218806 4.42574 0.0115161C4.41109 -0.00383871 4.38911 -0.00383871 4.37447 0.0115161C4.23531 0.218806 3.55418 1.21687 2.76319 2.19958C-4.02614 11.2666 3.8325 17.3856 3.8325 17.3856L3.89841 17.4316C3.95699 18.3759 4.10348 19.7348 4.10348 19.7348H4.39644H4.6894C4.6894 19.7348 4.83588 18.3836 4.89447 17.4316L4.96038 17.3779C4.9677 17.3779 12.8264 11.2666 6.03701 2.19958ZM4.39644 17.2473C4.39644 17.2473 4.04489 16.9325 3.94968 16.7713V16.756L4.37447 6.88281C4.37447 6.8521 4.41842 6.8521 4.41842 6.88281L4.8432 16.756V16.7713C4.74799 16.9325 4.39644 17.2473 4.39644 17.2473Z" fill="#00ED64"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 861 B

@@ -0,0 +1,27 @@
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="0.5" y="0.5" width="31" height="31" rx="7.5" fill="white" stroke="#EDEDF0"/>
<g transform="translate(3.2, 3.2) scale(1)">
<svg viewBox="0 0 25.6 25.6" width="25.6" height="25.6">
<style><![CDATA[.B{stroke-linecap:round}.C{stroke-linejoin:round}.D{stroke-linejoin:miter}.E{stroke-width:.716}]]></style>
<g fill="none" stroke="#fff">
<path d="M18.983 18.636c.163-1.357.114-1.555 1.124-1.336l.257.023c.777.035 1.793-.125 2.4-.402 1.285-.596 2.047-1.592.78-1.33-2.89.596-3.1-.383-3.1-.383 3.053-4.53 4.33-10.28 3.227-11.687-3.004-3.84-8.205-2.024-8.292-1.976l-.028.005c-.57-.12-1.2-.19-1.93-.2-1.308-.02-2.3.343-3.054.914 0 0-9.277-3.822-8.846 4.807.092 1.836 2.63 13.9 5.66 10.25C8.29 15.987 9.36 14.86 9.36 14.86c.53.353 1.167.533 1.834.468l.052-.044a2.01 2.01 0 0 0 .021.518c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.162l-.046.183c.306.245.285 1.76.33 2.842s.116 2.093.337 2.688.48 2.13 2.53 1.7c1.713-.367 3.023-.896 3.143-5.81" fill="#000" stroke="#000" stroke-linecap="butt" stroke-width="2.149" class="D"/>
<path d="M23.535 15.6c-2.89.596-3.1-.383-3.1-.383 3.053-4.53 4.33-10.28 3.228-11.687-3.004-3.84-8.205-2.023-8.292-1.976l-.028.005a10.31 10.31 0 0 0-1.929-.201c-1.308-.02-2.3.343-3.054.914 0 0-9.278-3.822-8.846 4.807.092 1.836 2.63 13.9 5.66 10.25C8.29 15.987 9.36 14.86 9.36 14.86c.53.353 1.167.533 1.834.468l.052-.044a2.02 2.02 0 0 0 .021.518c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.162l-.046.183c.306.245.52 1.593.484 2.815s-.06 2.06.18 2.716.48 2.13 2.53 1.7c1.713-.367 2.6-1.32 2.725-2.906.088-1.128.286-.962.3-1.97l.16-.478c.183-1.53.03-2.023 1.085-1.793l.257.023c.777.035 1.794-.125 2.39-.402 1.285-.596 2.047-1.592.78-1.33z" fill="#336791" stroke="none"/>
<g class="E">
<g class="B">
<path d="M12.814 16.467c-.08 2.846.02 5.712.298 6.4s.875 2.05 2.926 1.612c1.713-.367 2.337-1.078 2.607-2.647l.633-5.017M10.356 2.2S1.072-1.596 1.504 7.033c.092 1.836 2.63 13.9 5.66 10.25C8.27 15.95 9.27 14.907 9.27 14.907m6.1-13.4c-.32.1 5.164-2.005 8.282 1.978 1.1 1.407-.175 7.157-3.228 11.687" class="C"/>
<path d="M20.425 15.17s.2.98 3.1.382c1.267-.262.504.734-.78 1.33-1.054.49-3.418.615-3.457-.06-.1-1.745 1.244-1.215 1.147-1.652-.088-.394-.69-.78-1.086-1.744-.347-.84-4.76-7.29 1.224-6.333.22-.045-1.56-5.7-7.16-5.782S7.99 8.196 7.99 8.196" stroke-linejoin="bevel"/>
</g>
<g class="C">
<path d="M11.247 15.768c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.163.35-.49-.002-1.27-.482-1.468-.232-.096-.542-.216-.94.23z"/>
<path d="M11.196 15.753c-.08-.513.168-1.122.433-1.836.398-1.07 1.316-2.14.582-5.537-.547-2.53-4.22-.527-4.22-.184s.166 1.74-.06 3.365c-.297 2.122 1.35 3.916 3.246 3.733" class="B"/>
</g>
</g>
<g fill="#fff" class="D">
<path d="M10.322 8.145c-.017.117.215.43.516.472s.558-.202.575-.32-.215-.246-.516-.288-.56.02-.575.136z" stroke-width=".239"/>
<path d="M19.486 7.906c.016.117-.215.43-.516.472s-.56-.202-.575-.32.215-.246.516-.288.56.02.575.136z" stroke-width=".119"/>
</g>
<path d="M20.562 7.095c.05.92-.198 1.545-.23 2.524-.046 1.422.678 3.05-.413 4.68" class="B C E"/>
</g>
</svg>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.6 KiB

@@ -0,0 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.99976 2C4.55204 2 4.99976 2.44772 4.99976 3V5.10125C6.26985 3.80489 8.04028 3 9.99976 3C13.0492 3 15.6407 4.94932 16.6012 7.66675C16.7852 8.18747 16.5123 8.75879 15.9916 8.94284C15.4709 9.12689 14.8996 8.85396 14.7155 8.33325C14.0286 6.38991 12.1752 5 9.99976 5C8.36482 5 6.91179 5.78502 5.99911 7H8.99976C9.55204 7 9.99976 7.44771 9.99976 8C9.99976 8.55228 9.55204 9 8.99976 9H3.99976C3.44747 9 2.99976 8.55228 2.99976 8V3C2.99976 2.44772 3.44747 2 3.99976 2ZM4.00792 11.0572C4.52864 10.8731 5.09996 11.146 5.28401 11.6668C5.97088 13.6101 7.82429 15 9.99976 15C11.6347 15 13.0877 14.215 14.0004 13L10.9998 13C10.4475 13 9.99976 12.5523 9.99976 12C9.99976 11.4477 10.4475 11 10.9998 11H15.9998C16.265 11 16.5193 11.1054 16.7069 11.2929C16.8944 11.4804 16.9998 11.7348 16.9998 12V17C16.9998 17.5523 16.552 18 15.9998 18C15.4475 18 14.9998 17.5523 14.9998 17V14.8987C13.7297 16.1951 11.9592 17 9.99976 17C6.95035 17 4.3588 15.0507 3.39833 12.3332C3.21428 11.8125 3.48721 11.2412 4.00792 11.0572Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="8" cy="8" r="3" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 157 B

@@ -0,0 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.25706 3.09882C9.02167 1.73952 10.9788 1.73952 11.7434 3.09882L17.3237 13.0194C18.0736 14.3526 17.1102 15.9999 15.5805 15.9999H4.4199C2.89025 15.9999 1.92682 14.3526 2.67675 13.0194L8.25706 3.09882ZM11.0001 13C11.0001 13.5523 10.5524 14 10.0001 14C9.44784 14 9.00012 13.5523 9.00012 13C9.00012 12.4477 9.44784 12 10.0001 12C10.5524 12 11.0001 12.4477 11.0001 13ZM10.0001 5C9.44784 5 9.00012 5.44772 9.00012 6V9C9.00012 9.55228 9.44784 10 10.0001 10C10.5524 10 11.0001 9.55228 11.0001 9V6C11.0001 5.44772 10.5524 5 10.0001 5Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 725 B

@@ -0,0 +1,11 @@
(() => {
window.InstallerConstants = Object.freeze({
stepTransitionMs: 260,
errorClearMs: 180,
installPollIntervalMs: 4000,
installFallbackDelayMs: 12000,
redirectDelayMs: 2500,
progressTransitionDelayMs: 320,
progressCompleteDelayMs: 140,
});
})();
+450
View File
@@ -0,0 +1,450 @@
(() => {
const stepContainer = document.querySelector('.installer-step');
const installerCard = document.querySelector('.installer-card');
const backButton = document.querySelector('[data-action="back"]');
const nextButton = document.querySelector('[data-action="next"]');
const installScreen = document.querySelector('.install-screen-content');
const indicatorNodes = Array.from(document.querySelectorAll('.step-indicator'));
const STEP_TRANSITION_TIMEOUT = window.InstallerConstants?.stepTransitionMs ?? 260;
if (!stepContainer || !installerCard) return;
const { validateInstallRequest } = window.InstallerStepsProgress || {};
const isUpgrade = document.body?.dataset.upgrade === 'true';
const stepFlow = isUpgrade ? [1, 4, 5] : [1, 2, 3, 4, 5];
const cardSteps = stepFlow.filter((step) => step !== 5);
const normalizeStep = (step) => {
const numeric = clampStep(step);
if (stepFlow.includes(numeric)) return numeric;
if (numeric <= stepFlow[0]) return stepFlow[0];
for (let i = 0; i < stepFlow.length; i += 1) {
if (numeric < stepFlow[i]) {
return stepFlow[i];
}
}
return stepFlow[stepFlow.length - 1];
};
const buildStepConfig = () => {
const config = {};
stepFlow.forEach((step, index) => {
if (step === 5) {
config[step] = { back: { target: null }, next: { target: null } };
return;
}
const prev = stepFlow[index - 1] ?? null;
const next = stepFlow[index + 1] ?? null;
const label = next === 5 ? (isUpgrade ? 'Update' : 'Install') : 'Next';
config[step] = {
back: { target: prev },
next: { label, target: next }
};
});
return config;
};
const STEP_CONFIG = buildStepConfig();
const stepCache = new Map();
let maxStepHeight = 0;
let isTransitioning = false;
let pendingStep = null;
let pendingPushState = false;
const clampStep = (step) => Math.max(1, Math.min(5, step));
const isInstallLocked = () => Boolean(window.InstallerSteps?.isInstallLocked?.());
const scrollToFirstError = (panel) => {
if (!panel) return;
const getErrorNode = () => panel.querySelector('.field-error.is-visible')
|| panel.querySelector('.field-error')
|| panel.querySelector('.input-field.is-error, .input-action.is-error');
const container = panel.closest('.step-panel') || panel;
const attemptScroll = () => {
const target = getErrorNode();
if (!target || typeof target.getBoundingClientRect !== 'function') return false;
const targetRect = target.getBoundingClientRect();
const containerRect = container.getBoundingClientRect();
const targetTop = targetRect.top - containerRect.top + container.scrollTop;
const targetBottom = targetTop + targetRect.height;
const viewTop = container.scrollTop;
const viewBottom = viewTop + containerRect.height;
const padding = 12;
let nextScrollTop = viewTop;
if (targetTop < viewTop + padding) {
nextScrollTop = Math.max(0, targetTop - padding);
} else if (targetBottom > viewBottom - padding) {
nextScrollTop = Math.max(0, targetBottom - containerRect.height + padding);
}
if (Math.abs(nextScrollTop - viewTop) < 1) {
return false;
}
container.scrollTo({ top: nextScrollTop, behavior: 'smooth' });
return true;
};
let remaining = 20;
let lastScrollTop = -1;
const settle = () => {
if (remaining <= 0) return;
const moved = attemptScroll();
remaining -= 1;
const currentTop = container.scrollTop;
const delta = Math.abs(currentTop - lastScrollTop);
lastScrollTop = currentTop;
if (!moved && delta < 0.5) {
return;
}
requestAnimationFrame(settle);
};
requestAnimationFrame(settle);
};
const getStepFromUrl = () => {
const url = new URL(window.location.href);
const step = Number(url.searchParams.get('step') || 1);
return normalizeStep(Number.isNaN(step) ? 1 : step);
};
const buildStepUrl = (step) => {
const url = new URL(window.location.href);
url.searchParams.set('step', step);
return url;
};
const setStepInUrl = (step, pushState) => {
const url = new URL(window.location.href);
url.searchParams.set('step', step);
if (pushState) {
window.history.pushState({ step }, '', url.toString());
}
return url;
};
const updateActionBar = (step) => {
const config = STEP_CONFIG[step] || STEP_CONFIG[1];
if (!backButton || !nextButton) return;
const locked = isInstallLocked();
const setButtonLabel = (button, label) => {
if (!button) return;
let text = button.querySelector('.button-text');
if (!text) {
text = document.createElement('span');
text.className = 'button-text typography-text-m-500';
button.textContent = '';
button.appendChild(text);
}
text.textContent = label;
};
if (!locked && config.back?.target) {
backButton.disabled = false;
backButton.setAttribute('data-step-target', String(config.back.target));
} else {
backButton.disabled = true;
backButton.removeAttribute('data-step-target');
}
setButtonLabel(backButton, 'Back');
if (!locked && config.next?.target) {
setButtonLabel(nextButton, config.next?.label || 'Next');
nextButton.setAttribute('data-step-target', String(config.next?.target || 1));
nextButton.disabled = false;
} else {
setButtonLabel(nextButton, config.next?.label || 'Next');
nextButton.removeAttribute('data-step-target');
nextButton.disabled = true;
}
indicatorNodes.forEach((node, index) => {
const isVisible = index < cardSteps.length;
node.classList.toggle('is-hidden', !isVisible);
if (!isVisible) {
node.classList.remove('is-active');
return;
}
node.classList.toggle('is-active', cardSteps[index] === step);
});
installerCard.setAttribute('data-step', String(step));
document.body.dataset.step = String(step);
if (locked) {
document.body.dataset.installLocked = 'true';
} else {
delete document.body.dataset.installLocked;
}
};
const measureStepHeight = (panel) => {
if (!panel) return;
const height = panel.getBoundingClientRect().height;
if (!height) return;
maxStepHeight = Math.max(maxStepHeight, height);
stepContainer.style.setProperty('--step-min-height', `${maxStepHeight}px`);
};
const runStepInit = (step, rootElement) => {
if (!window.InstallerSteps || typeof window.InstallerSteps.initStep !== 'function') return;
const root = rootElement || stepContainer;
window.InstallerSteps.initStep(step, root);
updateActionBar(step);
};
const fetchStepHtml = (step, url) => {
if (stepCache.has(step)) {
return Promise.resolve(stepCache.get(step));
}
const fetchUrl = new URL(url);
fetchUrl.searchParams.set('partial', '1');
return fetch(fetchUrl.toString(), {
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then((response) => {
if (!response.ok) {
throw new Error('Failed to load step');
}
return response.text();
})
.then((html) => {
stepCache.set(step, html);
return html;
});
};
const preloadSteps = (steps) => {
const current = getStepFromUrl();
const targets = steps.filter((step) => step !== current);
return Promise.all(
targets.map((step) => {
const url = buildStepUrl(step);
return fetchStepHtml(step, url)
.then((html) => {
const panel = document.createElement('div');
panel.className = 'step-panel is-measure';
panel.innerHTML = html;
stepContainer.appendChild(panel);
panel.getBoundingClientRect();
measureStepHeight(panel);
panel.remove();
})
.catch(() => null);
})
);
};
const swapPanels = (step, html, onDone) => {
const activePanel = stepContainer.querySelector('.step-panel');
const measurePanel = document.createElement('div');
measurePanel.className = 'step-panel is-measure';
measurePanel.innerHTML = html;
stepContainer.appendChild(measurePanel);
measurePanel.getBoundingClientRect();
measureStepHeight(measurePanel);
measurePanel.remove();
const newPanel = document.createElement('div');
newPanel.className = 'step-panel is-entering';
newPanel.innerHTML = html;
stepContainer.appendChild(newPanel);
runStepInit(step, newPanel);
newPanel.getBoundingClientRect();
requestAnimationFrame(() => {
newPanel.classList.remove('is-entering');
newPanel.classList.add('is-active');
if (activePanel) {
activePanel.classList.add('is-exiting');
}
});
const finalize = () => {
if (activePanel && activePanel.parentNode) {
activePanel.parentNode.removeChild(activePanel);
}
newPanel.classList.remove('is-entering');
if (typeof onDone === 'function') {
onDone();
}
};
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (prefersReduced) {
finalize();
return;
}
let finished = false;
const finishOnce = () => {
if (finished) return;
finished = true;
finalize();
};
newPanel.addEventListener(
'transitionend',
(event) => {
if (event.propertyName === 'opacity') {
finishOnce();
}
},
{ once: true }
);
setTimeout(finishOnce, STEP_TRANSITION_TIMEOUT);
};
const showInstallScreen = (step, html) => {
if (!installScreen) return;
installScreen.innerHTML = html;
runStepInit(step, installScreen);
};
const hideInstallScreen = () => {
if (!installScreen) return;
installScreen.innerHTML = '';
};
const loadStep = (step, pushState) => {
const targetStep = normalizeStep(Number(step));
const currentStep = getStepFromUrl();
if (targetStep === currentStep && pushState) return;
isTransitioning = true;
const url = setStepInUrl(targetStep, pushState);
fetchStepHtml(targetStep, url)
.then((html) => {
if (targetStep === 5) {
showInstallScreen(targetStep, html);
isTransitioning = false;
if (pendingStep !== null && pendingStep !== targetStep) {
const nextStep = pendingStep;
const nextPushState = pendingPushState;
pendingStep = null;
pendingPushState = false;
loadStep(nextStep, nextPushState);
return;
}
pendingStep = null;
pendingPushState = false;
return;
}
hideInstallScreen();
swapPanels(targetStep, html, () => {
isTransitioning = false;
if (pendingStep !== null && pendingStep !== targetStep) {
const nextStep = pendingStep;
const nextPushState = pendingPushState;
pendingStep = null;
pendingPushState = false;
loadStep(nextStep, nextPushState);
return;
}
pendingStep = null;
pendingPushState = false;
});
})
.catch(() => {
isTransitioning = false;
window.location.href = url.toString();
});
};
const requestStep = (step, pushState) => {
const targetStep = normalizeStep(Number(step));
if (isInstallLocked() && targetStep !== 5) {
loadStep(5, true);
return;
}
if (isTransitioning) {
pendingStep = targetStep;
pendingPushState = pendingPushState || pushState;
return;
}
loadStep(targetStep, pushState);
};
document.addEventListener('click', async (event) => {
const button = event.target.closest('[data-step-target]');
if (!button || button.disabled) return;
event.preventDefault();
const target = button.getAttribute('data-step-target');
if (!target) return;
const action = button.getAttribute('data-action');
if (action === 'next') {
const currentStep = getStepFromUrl();
const panel = stepContainer.querySelector('.step-panel') || stepContainer;
const validator = window.InstallerSteps?.validateStep;
if (typeof validator === 'function') {
const valid = validator(currentStep, panel);
if (!valid) {
scrollToFirstError(panel);
return;
}
}
}
if (action === 'next' && String(target) === '5' && typeof validateInstallRequest === 'function') {
const isValid = await validateInstallRequest();
if (!isValid) {
return;
}
}
if (isInstallLocked() && Number(target) !== 5) {
requestStep(5, true);
return;
}
requestStep(target, true);
});
window.addEventListener('popstate', (event) => {
const step = event.state?.step || getStepFromUrl();
if (isInstallLocked() && Number(step) !== 5) {
requestStep(5, false);
return;
}
requestStep(step, false);
});
document.addEventListener('DOMContentLoaded', () => {
let step = getStepFromUrl();
if (isInstallLocked() && step !== 5) {
const url = buildStepUrl(5);
window.history.replaceState({ step: 5 }, '', url.toString());
step = 5;
} else {
const url = buildStepUrl(step);
window.history.replaceState({ step }, '', url.toString());
}
const activePanel = stepContainer.querySelector('.step-panel') || stepContainer;
runStepInit(step, activePanel);
measureStepHeight(activePanel);
if (step === 5 && installScreen) {
runStepInit(step, installScreen);
}
const preload = () => {
measureStepHeight(activePanel);
preloadSteps(cardSteps);
};
if (document.fonts && document.fonts.ready) {
document.fonts.ready.then(preload).catch(preload);
} else {
preload();
}
});
})();
@@ -0,0 +1,105 @@
(() => {
const getBodyDataset = () => document.body?.dataset ?? {};
const isUpgradeMode = () => getBodyDataset().upgrade === 'true';
const getLockedDatabase = () => getBodyDataset().lockedDatabase || '';
const STEP_IDS = Object.freeze({
CONFIG_FILES: 'config-files',
DOCKER_COMPOSE: 'docker-compose',
ENV_VARS: 'env-vars',
DOCKER_CONTAINERS: 'docker-containers',
ACCOUNT_SETUP: 'account-setup'
});
const STATUS = Object.freeze({
IN_PROGRESS: 'in-progress',
COMPLETED: 'completed',
ERROR: 'error'
});
const SSE_EVENTS = Object.freeze({
PING: 'ping',
INSTALL_ID: 'install-id',
PROGRESS: 'progress',
DONE: 'done',
ERROR: 'error'
});
const buildInstallationSteps = (upgrade) => (upgrade ? [
{
id: STEP_IDS.CONFIG_FILES,
inProgress: 'Updating configuration files...',
done: 'Configuration files updated'
},
{
id: STEP_IDS.DOCKER_COMPOSE,
inProgress: 'Updating Docker Compose file...',
done: 'Docker Compose file updated'
},
{
id: STEP_IDS.ENV_VARS,
inProgress: 'Updating environment variables...',
done: 'Environment variables updated'
},
{
id: STEP_IDS.DOCKER_CONTAINERS,
inProgress: 'Restarting Docker containers...',
done: 'Docker containers restarted'
}
] : [
{
id: STEP_IDS.CONFIG_FILES,
inProgress: 'Creating configuration files...',
done: 'Configuration files created'
},
{
id: STEP_IDS.DOCKER_COMPOSE,
inProgress: 'Generating Docker Compose file...',
done: 'Docker Compose file generated'
},
{
id: STEP_IDS.ENV_VARS,
inProgress: 'Configuring environment variables...',
done: 'Environment variables configured'
},
{
id: STEP_IDS.DOCKER_CONTAINERS,
inProgress: 'Starting Docker containers...',
done: 'Docker containers started'
},
{
id: STEP_IDS.ACCOUNT_SETUP,
inProgress: 'Creating Appwrite account...',
done: 'Appwrite account created (redirecting...)'
}
]);
const INSTALLATION_STEPS = buildInstallationSteps(isUpgradeMode());
const CONSTANTS = window.InstallerConstants || {};
const TIMINGS = {
errorClear: CONSTANTS.errorClearMs ?? 180,
installPollInterval: CONSTANTS.installPollIntervalMs ?? 4000,
installFallbackDelay: CONSTANTS.installFallbackDelayMs ?? 12000,
redirectDelay: CONSTANTS.redirectDelayMs ?? 500,
progressTransitionDelay: CONSTANTS.progressTransitionDelayMs ?? 140,
progressCompleteDelay: CONSTANTS.progressCompleteDelayMs ?? 120
};
const clampStep = (step) => {
const numeric = Number(step);
if (Number.isNaN(numeric)) return 1;
return Math.max(1, Math.min(5, numeric));
};
window.InstallerStepsContext = Object.freeze({
getBodyDataset,
isUpgradeMode,
getLockedDatabase,
STEP_IDS,
STATUS,
SSE_EVENTS,
INSTALLATION_STEPS,
TIMINGS,
clampStep
});
})();
@@ -0,0 +1,905 @@
(() => {
const {
INSTALLATION_STEPS,
TIMINGS,
getBodyDataset,
STEP_IDS,
STATUS,
SSE_EVENTS
} = window.InstallerStepsContext;
const {
formState,
applyLockPayload,
applyBodyDefaults,
setInstallLock,
getInstallLock,
clearInstallLock,
isInstallLocked,
syncInstallLockFlag,
getStoredInstallId,
storeInstallId,
clearInstallId
} = window.InstallerStepsState || {};
const { extractHostname, isLocalHost } = window.InstallerStepsValidation || {};
const { generateSecretKey } = window.InstallerStepsUI || {};
const { showToast } = window.InstallerToast || {};
let activeInstall = null;
let unloadGuard = null;
const csrfToken = document.querySelector('meta[name="appwrite-installer-csrf"]')?.getAttribute('content') || '';
const withCsrfHeader = (headers = {}) => {
if (!csrfToken) {
return headers;
}
return { ...headers, 'X-Appwrite-Installer-CSRF': csrfToken };
};
const showCsrfToast = () => {
showToast?.({
status: 'error',
title: 'Session expired',
description: 'Refresh the page and try again.',
dismissible: true
});
};
const validateInstallRequest = async () => {
try {
const response = await fetch('/install/validate', {
method: 'POST',
headers: withCsrfHeader({
'Content-Type': 'application/json'
})
});
if (!response.ok) {
showCsrfToast();
return false;
}
const data = await response.json().catch(() => ({}));
if (!data?.success) {
showCsrfToast();
return false;
}
return true;
} catch (error) {
showCsrfToast();
return false;
}
};
const setUnloadGuard = (enabled) => {
if (!enabled && unloadGuard) {
window.removeEventListener('beforeunload', unloadGuard);
unloadGuard = null;
return;
}
if (enabled && !unloadGuard) {
unloadGuard = (event) => {
event.preventDefault();
event.returnValue = '';
return '';
};
window.addEventListener('beforeunload', unloadGuard);
}
};
const cleanupInstallFlow = () => {
if (activeInstall?.controller) {
activeInstall.controller.abort();
if (activeInstall.pollTimer) {
clearInterval(activeInstall.pollTimer);
}
if (activeInstall.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
}
activeInstall = null;
}
stopSyncedSpinnerRotation();
setUnloadGuard(false);
};
const getStepDefinition = (id) => INSTALLATION_STEPS.find((step) => step.id === id);
const getProgressLabel = (step, status, message) => {
if (!step) return message || '';
if (status === STATUS.ERROR) {
const normalized = normalizeInstallError(message || '');
return normalized.summary || 'Installation failed.';
}
if (status === STATUS.COMPLETED) return step.done;
return step.inProgress;
};
const updateInstallRow = (row, step, status, message) => {
if (!row || !step) return;
row.dataset.status = status;
row.dataset.step = step.id;
if (status !== STATUS.ERROR) {
row.classList.remove('is-open');
const toggle = row.querySelector('[data-install-toggle]');
if (toggle) {
toggle.setAttribute('aria-expanded', 'false');
}
}
const label = getProgressLabel(step, status, message);
const text = row.querySelector('[data-install-text]');
if (text) {
if (text.textContent !== label) {
text.classList.remove('is-enter');
text.textContent = label;
text.classList.add('is-enter');
requestAnimationFrame(() => {
text.classList.remove('is-enter');
});
}
}
// Show/hide "Navigate to Console" button for account setup errors
const consoleBtn = row.querySelector('[data-install-console]');
if (consoleBtn) {
const shouldShow = step.id === STEP_IDS.ACCOUNT_SETUP && status === STATUS.ERROR;
consoleBtn.classList.toggle('is-hidden', !shouldShow);
}
};
const normalizeInstallError = (message) => {
const text = String(message || '').trim();
if (!text) {
return { summary: '', details: '' };
}
const colonIndex = text.indexOf(':');
if (colonIndex > 0 && colonIndex < 80) {
const summary = text.slice(0, colonIndex).trim();
const details = text.slice(colonIndex + 1).trim();
return { summary, details };
}
if (text.length > 180) {
return { summary: text.slice(0, 180).trim() + '…', details: text };
}
return { summary: text, details: '' };
};
let spinnerAnimationFrame = null;
const stopSyncedSpinnerRotation = () => {
if (spinnerAnimationFrame) {
cancelAnimationFrame(spinnerAnimationFrame);
spinnerAnimationFrame = null;
}
};
const startSyncedSpinnerRotation = (container) => {
stopSyncedSpinnerRotation();
if (!container) return;
let startTime = null;
const animate = (timestamp) => {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const rotation = ((elapsed / 1000) * 360 * 1.5) % 360;
container.style.setProperty('--spinner-rotation', `${rotation}deg`);
spinnerAnimationFrame = requestAnimationFrame(animate);
};
spinnerAnimationFrame = requestAnimationFrame(animate);
};
const updateInstallErrorDetails = (row, error) => {
if (!row) return;
const traceNode = row.querySelector('[data-install-trace]');
const normalized = normalizeInstallError(error?.message || '');
const output = error?.output || '';
const trace = error?.trace || '';
const detailChunks = [];
if (normalized.details) detailChunks.push(normalized.details);
if (output) detailChunks.push(output);
if (trace) detailChunks.push(trace);
const detailText = detailChunks.join('\n\n');
if (traceNode) {
traceNode.textContent = detailText;
traceNode.style.display = detailText ? 'block' : 'none';
}
};
const createInstallRow = (template, step) => {
const fragment = template.content.cloneNode(true);
const row = fragment.querySelector('.install-row');
if (!row) return null;
const toggle = row.querySelector('[data-install-toggle]');
const setOpenState = (isOpen) => {
row.classList.toggle('is-open', isOpen);
if (toggle) {
toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
}
};
const toggleRow = () => {
if (!row.dataset.status || row.dataset.status !== STATUS?.ERROR) {
return;
}
setOpenState(!row.classList.contains('is-open'));
};
row.addEventListener('click', (event) => {
if (event.target.closest('[data-install-retry]')) {
return;
}
if (event.target.closest('[data-install-toggle]')) {
return;
}
if (event.target.closest('.install-row-details')) {
return;
}
toggleRow();
});
if (toggle) {
toggle.addEventListener('click', (event) => {
event.stopPropagation();
toggleRow();
});
}
updateInstallRow(row, step, STATUS.IN_PROGRESS);
return row;
};
const generateInstallId = () => {
if (window.crypto?.randomUUID) {
return window.crypto.randomUUID();
}
const bytes = new Uint8Array(16);
window.crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
};
const buildRedirectUrl = () => {
const dataset = getBodyDataset?.() ?? {};
const rawDomain = (formState?.appDomain || dataset.defaultAppDomain || '').trim();
if (!rawDomain) return '';
const httpPort = (formState?.httpPort || dataset.defaultHttpPort || '').trim();
const httpsPort = (formState?.httpsPort || dataset.defaultHttpsPort || '').trim();
const hasPort = rawDomain.includes(':') || rawDomain.startsWith('[');
let host = rawDomain;
const hostForProtocol = extractHostname?.(rawDomain);
const normalizedHost = hostForProtocol?.toLowerCase?.() ?? '';
if (hostForProtocol === '0.0.0.0') {
host = rawDomain.replace('0.0.0.0', 'localhost');
} else if (normalizedHost === 'traefik') {
host = rawDomain.replace(hostForProtocol, 'localhost');
}
let protocol = 'http';
let port = httpPort;
if (httpsPort && httpsPort !== '0' && !isLocalHost?.(normalizedHost)) {
protocol = 'https';
port = httpsPort;
}
if (!hasPort && port && ((protocol === 'http' && port !== '80') || (protocol === 'https' && port !== '443'))) {
host = `${host}:${port}`;
}
return `${protocol}://${host}`;
};
const redirectToApp = () => {
const url = buildRedirectUrl();
if (!url) return;
// Fire-and-forget: tell the installer server it can shut down
fetch('/install/shutdown', { method: 'POST', headers: withCsrfHeader() }).catch(() => {});
window.location.href = url;
};
const notifyInstallComplete = (installId, session) => {
if (!installId) return Promise.resolve();
const payload = { installId };
const sessionSecret = session?.sessionSecret || session?.secret;
const sessionId = session?.sessionId || session?.id;
const sessionExpire = session?.sessionExpire || session?.expire;
if (sessionSecret) {
payload.sessionSecret = sessionSecret;
}
if (sessionId) {
payload.sessionId = sessionId;
}
if (sessionExpire) {
payload.sessionExpire = sessionExpire;
}
return fetch('/install/complete', {
method: 'POST',
headers: withCsrfHeader({
'Content-Type': 'application/json'
}),
body: JSON.stringify(payload)
}).catch(() => {});
};
const buildInstallPayload = (installId) => {
const normalizedSecret = (formState?.opensslKey || '').trim();
if (!normalizedSecret && generateSecretKey) {
formState.opensslKey = generateSecretKey();
}
const normalizedDomain = (formState?.appDomain || '').trim() || 'localhost';
const normalizedHttpPort = (formState?.httpPort || '').trim() || '80';
const normalizedHttpsPort = (formState?.httpsPort || '').trim() || '443';
const normalizedEmail = (formState?.emailCertificates || '').trim();
const normalizedAssistantKey = (formState?.assistantOpenAIKey || '').trim();
const normalizedAccountEmail = (formState?.accountEmail || '').trim();
const normalizedAccountPassword = (formState?.accountPassword || '').trim();
return {
installId,
httpPort: normalizedHttpPort,
httpsPort: normalizedHttpsPort,
database: formState?.database || 'mongodb',
appDomain: normalizedDomain,
emailCertificates: normalizedEmail,
opensslKey: (formState?.opensslKey || '').trim(),
assistantOpenAIKey: normalizedAssistantKey,
accountEmail: normalizedAccountEmail,
accountPassword: normalizedAccountPassword
};
};
const fetchInstallStatus = async (installId) => {
if (!installId) return null;
const response = await fetch(`/install/status?installId=${encodeURIComponent(installId)}`, {
cache: 'no-store'
});
if (!response.ok) return null;
const json = await response.json();
return json.progress || null;
};
const readEventStream = async (stream, onEvent) => {
const reader = stream.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
try {
const processEvent = (rawEvent) => {
if (!rawEvent) return;
const lines = rawEvent.split('\n');
let eventName = 'message';
let data = '';
lines.forEach((line) => {
if (line.startsWith('event:')) {
eventName = line.replace('event:', '').trim();
} else if (line.startsWith('data:')) {
data += line.replace('data:', '').trim();
}
});
if (data) {
try {
const parsed = JSON.parse(data);
onEvent(eventName, parsed);
} catch (error) {
onEvent(eventName, { message: data });
}
}
};
while (true) {
const { value, done } = await reader.read();
if (done) {
buffer = buffer.replace(/\r\n/g, '\n');
if (buffer.trim()) {
processEvent(buffer);
}
break;
}
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
let separatorIndex = buffer.indexOf('\n\n');
while (separatorIndex !== -1) {
const rawEvent = buffer.slice(0, separatorIndex);
buffer = buffer.slice(separatorIndex + 2);
processEvent(rawEvent);
separatorIndex = buffer.indexOf('\n\n');
}
}
} finally {
try {
reader.releaseLock();
} catch (error) {}
}
};
const initStep5 = (root) => {
if (!root) return;
if (activeInstall?.controller) {
activeInstall.controller.abort();
}
if (activeInstall?.pollTimer) {
clearInterval(activeInstall.pollTimer);
}
if (activeInstall?.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
}
activeInstall = null;
const list = root.querySelector('[data-install-list]');
const template = root.querySelector('#install-row-template');
if (!list || !template) return;
startSyncedSpinnerRotation(list);
list.innerHTML = '';
const rowsById = new Map();
const progressState = new Map();
syncInstallLockFlag?.();
applyLockPayload?.();
applyBodyDefaults?.();
const ensureRow = (step) => {
if (!step) return null;
if (rowsById.has(step.id)) {
return rowsById.get(step.id);
}
const row = createInstallRow(template, step);
if (!row) return null;
row.classList.add('is-entering');
list.appendChild(row);
row.getBoundingClientRect();
requestAnimationFrame(() => {
row.classList.remove('is-entering');
});
rowsById.set(step.id, row);
return row;
};
const installPanel = root.querySelector('.install-panel');
let panelHeightCleanup = null;
const animatePanelHeight = (mutate) => {
if (!installPanel) {
mutate();
return;
}
if (panelHeightCleanup) {
panelHeightCleanup();
panelHeightCleanup = null;
}
const currentHeight = installPanel.getBoundingClientRect().height;
installPanel.style.height = `${currentHeight}px`;
installPanel.getBoundingClientRect();
mutate();
const nextHeight = installPanel.getBoundingClientRect().height;
if (currentHeight === nextHeight) {
installPanel.style.height = '';
return;
}
installPanel.style.height = `${currentHeight}px`;
installPanel.getBoundingClientRect();
installPanel.style.height = `${nextHeight}px`;
const cleanup = () => {
installPanel.style.height = '';
installPanel.removeEventListener('transitionend', onEnd);
};
const onEnd = (event) => {
if (event.propertyName === 'height') {
cleanup();
}
};
panelHeightCleanup = cleanup;
installPanel.addEventListener('transitionend', onEnd);
};
const renderProgress = () => {
animatePanelHeight(() => {
const visibleSteps = [];
for (const step of INSTALLATION_STEPS) {
const state = progressState.get(step.id);
if (!state) break;
visibleSteps.push(step);
}
visibleSteps.forEach((step) => {
const state = progressState.get(step.id);
if (!state) return;
const row = ensureRow(step);
if (row) {
updateInstallRow(row, step, state.status || STATUS.IN_PROGRESS, state.message);
if (state.status === STATUS?.ERROR) {
updateInstallErrorDetails(row, {
message: state.message,
trace: state.details?.trace,
output: state.details?.output
});
}
}
});
});
};
const firstStep = INSTALLATION_STEPS[0];
if (firstStep) {
progressState.set(firstStep.id, {
status: STATUS.IN_PROGRESS,
message: firstStep.inProgress
});
}
renderProgress();
const applyProgress = (payload) => {
const step = getStepDefinition(payload.step) || {
id: payload.step,
inProgress: payload.message || payload.step,
done: payload.message || payload.step
};
progressState.set(step.id, {
status: payload.status || STATUS.IN_PROGRESS,
message: payload.message,
details: payload.details
});
renderProgress();
if (activeInstall) {
activeInstall.lastEventAt = Date.now();
if (payload.status === STATUS.ERROR) {
if (activeInstall.pollTimer) {
clearInterval(activeInstall.pollTimer);
activeInstall.pollTimer = null;
}
if (activeInstall.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
activeInstall.fallbackTimer = null;
}
}
}
scheduleFallback();
};
const handleProgress = (payload) => {
if (!payload || !payload.step) return;
const existingState = progressState.get(payload.step);
if (existingState && existingState.status === STATUS.COMPLETED && payload.status === STATUS.IN_PROGRESS) {
return;
}
const step = getStepDefinition(payload.step) || {
id: payload.step,
inProgress: payload.message || payload.step,
done: payload.message || payload.step
};
if (payload.status === STATUS.IN_PROGRESS) {
const currentIndex = INSTALLATION_STEPS.findIndex((candidate) => candidate.id === step.id);
if (currentIndex > 0) {
for (let i = 0; i < currentIndex; i += 1) {
const previousStep = INSTALLATION_STEPS[i];
const previousState = progressState.get(previousStep.id);
if (previousState && previousState.status !== STATUS.COMPLETED) {
progressState.set(previousStep.id, {
status: STATUS.COMPLETED,
message: previousStep.done,
details: previousState.details
});
}
}
}
}
applyProgress(payload);
};
const applySnapshot = (snapshot) => {
if (!snapshot || !snapshot.steps) return;
INSTALLATION_STEPS.forEach((step) => {
const detail = snapshot.steps[step.id];
if (!detail) return;
progressState.set(step.id, {
status: detail.status,
message: detail.message,
details: snapshot.details?.[step.id]
});
});
renderProgress();
};
const checkAllCompleted = () => {
const allDone = INSTALLATION_STEPS.every((step) => {
const state = progressState.get(step.id);
return state && state.status === STATUS.COMPLETED;
});
if (!allDone) return;
const accountState = progressState.get(STEP_IDS.ACCOUNT_SETUP);
finalizeInstall();
notifyInstallComplete(activeInstall?.installId, accountState?.details).finally(() => {
setTimeout(() => redirectToApp(), TIMINGS?.redirectDelay ?? 0);
});
};
const startPolling = () => {
if (!activeInstall || activeInstall.pollTimer) return;
activeInstall.pollTimer = setInterval(async () => {
if (!activeInstall || activeInstall.completed) return;
const snapshot = await fetchInstallStatus(activeInstall.installId);
if (snapshot) {
applySnapshot(snapshot);
checkAllCompleted();
}
}, TIMINGS?.installPollInterval ?? 0);
};
const scheduleFallback = () => {
if (!activeInstall) return;
if (activeInstall.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
}
activeInstall.fallbackTimer = setTimeout(() => {
if (!activeInstall) return;
startPolling();
}, TIMINGS?.installFallbackDelay ?? 0);
};
const finalizeInstall = () => {
if (!activeInstall) return;
activeInstall.completed = true;
if (activeInstall.pollTimer) {
clearInterval(activeInstall.pollTimer);
}
if (activeInstall.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
}
stopSyncedSpinnerRotation();
setUnloadGuard(false);
};
const startInstallStream = async (installId, options = {}) => {
const isValid = await validateInstallRequest();
if (!isValid) {
return;
}
activeInstall = {
installId,
controller: new AbortController(),
lastEventAt: Date.now(),
pollTimer: null,
fallbackTimer: null,
completed: false
};
const payload = buildInstallPayload(installId);
if (options.retryStep) {
payload.retryStep = options.retryStep;
}
setInstallLock?.(installId, payload);
setUnloadGuard(true);
try {
scheduleFallback();
const response = await fetch('/install', {
method: 'POST',
headers: withCsrfHeader({
'Content-Type': 'application/json',
'Accept': 'text/event-stream'
}),
body: JSON.stringify(payload),
signal: activeInstall.controller.signal
});
if (!response.ok || !response.body) {
let errorMessage = null;
try {
const contentType = response.headers.get('Content-Type') || '';
if (contentType.includes('application/json')) {
const data = await response.json();
errorMessage = data?.message || null;
}
} catch (error) {
errorMessage = null;
}
if (errorMessage) {
handleProgress({
step: STEP_IDS.CONFIG_FILES,
status: STATUS.ERROR,
message: errorMessage
});
finalizeInstall();
return;
}
startPolling();
return;
}
await readEventStream(response.body, (event, data) => {
if (!activeInstall) return;
if (event === SSE_EVENTS.INSTALL_ID && data?.installId) {
activeInstall.installId = data.installId;
storeInstallId?.(data.installId);
return;
}
if (event === SSE_EVENTS.PROGRESS) {
handleProgress(data);
return;
}
if (event === SSE_EVENTS.DONE) {
// Mark every step as completed (preserving details
// from earlier progress events, e.g. session info).
INSTALLATION_STEPS.forEach((step) => {
const existing = progressState.get(step.id);
if (!existing || (existing.status !== STATUS.COMPLETED && existing.status !== STATUS.ERROR)) {
progressState.set(step.id, {
status: STATUS.COMPLETED,
message: step.done,
details: existing?.details
});
}
});
renderProgress();
const accountState = progressState.get(STEP_IDS.ACCOUNT_SETUP);
const accountRequired = INSTALLATION_STEPS.some((step) => step.id === STEP_IDS.ACCOUNT_SETUP);
if (accountRequired && accountState?.status === STATUS.ERROR) {
finalizeInstall();
return;
}
const sessionDetails = accountState?.details;
if (accountRequired && !(sessionDetails?.sessionSecret || sessionDetails?.secret)) {
handleProgress({
step: STEP_IDS.ACCOUNT_SETUP,
status: STATUS.ERROR,
message: 'Account creation did not complete. Please retry.'
});
finalizeInstall();
return;
}
finalizeInstall();
notifyInstallComplete(activeInstall?.installId, sessionDetails).finally(() => {
setTimeout(() => redirectToApp(), TIMINGS?.redirectDelay ?? 0);
});
return;
}
if (event === SSE_EVENTS.ERROR) {
if (data?.message) {
const existingError = Array.from(progressState.values()).some((state) => state?.status === STATUS.ERROR);
if (data.step || !existingError) {
let targetStep = data.step;
if (!targetStep) {
for (const candidate of INSTALLATION_STEPS) {
const state = progressState.get(candidate.id);
if (!state || state.status !== STATUS.COMPLETED) {
targetStep = candidate.id;
break;
}
}
}
handleProgress({
step: targetStep || STEP_IDS.CONFIG_FILES,
status: STATUS.ERROR,
message: data.message,
details: data.details
});
}
}
finalizeInstall();
}
});
if (activeInstall && !activeInstall.completed) {
// Stream ended without a "done" event (e.g. browser
// throttled the background tab). Check if we're done.
checkAllCompleted();
if (!activeInstall?.completed) {
startPolling();
}
}
} catch (error) {
if (!activeInstall || activeInstall.controller.signal.aborted) {
return;
}
startPolling();
}
};
const resumeInstall = async (installId) => {
const snapshot = await fetchInstallStatus(installId);
if (!snapshot) return false;
activeInstall = {
installId,
controller: new AbortController(),
lastEventAt: Date.now(),
pollTimer: null,
fallbackTimer: null,
completed: false
};
applySnapshot(snapshot);
startPolling();
setUnloadGuard(true);
return true;
};
const resetProgressFrom = (stepId) => {
const index = INSTALLATION_STEPS.findIndex((step) => step.id === stepId);
if (index === -1) return;
INSTALLATION_STEPS.slice(index).forEach((step) => {
progressState.delete(step.id);
const row = rowsById.get(step.id);
if (row && row.parentNode) {
row.parentNode.removeChild(row);
}
rowsById.delete(step.id);
});
};
const retryInstallStep = (stepId) => {
if (!stepId) return;
if (activeInstall?.controller) {
activeInstall.controller.abort();
}
if (activeInstall?.pollTimer) {
clearInterval(activeInstall.pollTimer);
}
if (activeInstall?.fallbackTimer) {
clearTimeout(activeInstall.fallbackTimer);
}
resetProgressFrom(stepId);
const step = getStepDefinition(stepId);
progressState.set(stepId, {
status: STATUS.IN_PROGRESS,
message: step?.inProgress || 'Retrying...'
});
const row = ensureRow(step);
if (row) {
updateInstallRow(row, step, STATUS.IN_PROGRESS, step.inProgress || 'Retrying...');
}
const installId = activeInstall?.installId || getInstallLock?.()?.installId || generateInstallId();
storeInstallId?.(installId);
startInstallStream(installId, { retryStep: stepId });
};
list.addEventListener('click', (event) => {
const consoleButton = event.target.closest('[data-install-console]');
const retryButton = event.target.closest('[data-install-retry]');
if (consoleButton) {
fetch('/install/cleanup', {
method: 'POST',
headers: withCsrfHeader({
'Content-Type': 'application/json'
})
}).catch(() => {});
// Redirect immediately
redirectToApp();
return;
}
if (retryButton) {
const row = retryButton.closest('.install-row');
const stepId = row?.dataset.step;
retryInstallStep(stepId);
}
});
// When the user switches back to this tab, check if installation
// finished while the tab was in the background.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && activeInstall && !activeInstall.completed) {
checkAllCompleted();
}
});
const lock = getInstallLock?.();
const existingInstallId = lock?.installId || getStoredInstallId?.();
if (existingInstallId) {
resumeInstall(existingInstallId).then((resumed) => {
if (!resumed) {
clearInstallId?.();
clearInstallLock?.();
const newInstallId = generateInstallId();
storeInstallId?.(newInstallId);
startInstallStream(newInstallId);
}
});
} else {
const newInstallId = generateInstallId();
storeInstallId?.(newInstallId);
startInstallStream(newInstallId);
}
};
window.InstallerStepsProgress = {
initStep5,
cleanupInstallFlow,
validateInstallRequest
};
})();
@@ -0,0 +1,155 @@
(() => {
const {
getBodyDataset,
isUpgradeMode,
getLockedDatabase
} = window.InstallerStepsContext || {};
const INSTALL_LOCK_KEY = 'appwrite-install-lock';
const INSTALL_ID_KEY = 'appwrite-install-id';
const formState = {
appDomain: null,
database: null,
httpPort: null,
httpsPort: null,
emailCertificates: null,
opensslKey: null,
assistantOpenAIKey: null,
accountEmail: null,
accountPassword: null
};
const dispatchStateChange = (key) => {
if (!key || typeof document === 'undefined') return;
try {
document.dispatchEvent(new CustomEvent('installer:state-change', {
detail: { key, value: formState[key] }
}));
} catch (error) {}
};
const setStateIfEmpty = (key, value) => {
if (value === null || value === undefined || value === '') return;
if (formState[key] === null || formState[key] === undefined || formState[key] === '') {
formState[key] = value;
}
};
const applyBodyDefaults = () => {
const data = getBodyDataset?.() ?? {};
setStateIfEmpty('appDomain', data.defaultAppDomain);
setStateIfEmpty('httpPort', data.defaultHttpPort);
setStateIfEmpty('httpsPort', data.defaultHttpsPort);
setStateIfEmpty('emailCertificates', data.defaultEmailCertificates);
setStateIfEmpty('opensslKey', data.defaultSecretKey);
setStateIfEmpty('assistantOpenAIKey', data.defaultAssistantOpenaiKey);
if (data.lockedDatabase) {
formState.database = data.lockedDatabase;
}
if (!isUpgradeMode?.()) {
setStateIfEmpty('database', data.defaultDatabase);
}
};
const getInstallLock = () => {
try {
const raw = sessionStorage.getItem(INSTALL_LOCK_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return null;
return parsed;
} catch (error) {
return null;
}
};
const setInstallLock = (installId, payload) => {
const lock = {
installId,
payload: payload || null,
startedAt: Date.now()
};
try {
sessionStorage.setItem(INSTALL_LOCK_KEY, JSON.stringify(lock));
} catch (error) {}
if (document.body) {
document.body.dataset.installLocked = 'true';
}
return lock;
};
const clearInstallLock = () => {
try {
sessionStorage.removeItem(INSTALL_LOCK_KEY);
} catch (error) {}
if (document.body) {
delete document.body.dataset.installLocked;
}
};
const isInstallLocked = () => {
return Boolean(getInstallLock());
};
const syncInstallLockFlag = () => {
if (!document.body) return;
if (isInstallLocked()) {
document.body.dataset.installLocked = 'true';
} else {
delete document.body.dataset.installLocked;
}
};
const applyLockPayload = () => {
const lock = getInstallLock();
if (!lock || !lock.payload) return;
const payload = lock.payload;
setStateIfEmpty('appDomain', payload.appDomain);
setStateIfEmpty('database', payload.database);
setStateIfEmpty('httpPort', payload.httpPort);
setStateIfEmpty('httpsPort', payload.httpsPort);
setStateIfEmpty('emailCertificates', payload.emailCertificates);
setStateIfEmpty('opensslKey', payload.opensslKey);
setStateIfEmpty('assistantOpenAIKey', payload.assistantOpenAIKey);
setStateIfEmpty('accountEmail', payload.accountEmail);
setStateIfEmpty('accountPassword', payload.accountPassword);
};
const getStoredInstallId = () => {
try {
return sessionStorage.getItem(INSTALL_ID_KEY);
} catch (error) {
return null;
}
};
const storeInstallId = (installId) => {
try {
sessionStorage.setItem(INSTALL_ID_KEY, installId);
} catch (error) {}
};
const clearInstallId = () => {
try {
sessionStorage.removeItem(INSTALL_ID_KEY);
} catch (error) {}
};
window.InstallerStepsState = {
formState,
dispatchStateChange,
setStateIfEmpty,
applyBodyDefaults,
applyLockPayload,
getInstallLock,
setInstallLock,
clearInstallLock,
isInstallLocked,
syncInstallLockFlag,
getStoredInstallId,
storeInstallId,
clearInstallId,
getLockedDatabase: getLockedDatabase || (() => '')
};
})();
@@ -0,0 +1,95 @@
(() => {
const TOAST_STACK_ID = 'installer-toast-stack';
const DEFAULT_TIMEOUT = 5000;
const MAX_TOASTS = 3;
const ICONS = {
error: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" fill-rule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0m-7 4a1 1 0 1 1-2 0 1 1 0 0 1 2 0m-1-9a1 1 0 0 0-1 1v4a1 1 0 1 0 2 0V6a1 1 0 0 0-1-1" clip-rule="evenodd"/></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" fill-rule="evenodd" d="M5.293 5.293a1 1 0 0 1 1.414 0L10 8.586l3.293-3.293a1 1 0 1 1 1.414 1.414L11.414 10l3.293 3.293a1 1 0 0 1-1.414 1.414L10 11.414l-3.293 3.293a1 1 0 0 1-1.414-1.414L8.586 10 5.293 6.707a1 1 0 0 1 0-1.414" clip-rule="evenodd"/></svg>'
};
const getStack = () => document.getElementById(TOAST_STACK_ID);
const dismissToast = (toast) => {
if (!toast) return;
if (toast.classList.contains('is-leaving')) return;
toast.classList.add('is-leaving');
const remove = () => toast.remove();
toast.addEventListener('transitionend', remove, { once: true });
setTimeout(remove, 450);
};
const showToast = ({
title = '',
description = '',
status = 'error',
dismissible = true,
timeout = DEFAULT_TIMEOUT
} = {}) => {
const stack = getStack();
if (!stack) return;
const visibleToasts = Array.from(
stack.querySelectorAll('.installer-toast:not(.is-leaving)')
);
if (visibleToasts.length >= MAX_TOASTS) {
dismissToast(visibleToasts[0]);
}
const toast = document.createElement('div');
toast.className = 'installer-toast is-entering';
toast.dataset.status = status;
toast.setAttribute('role', status === 'error' ? 'alert' : 'status');
const content = document.createElement('div');
content.className = 'installer-toast-content';
const icon = document.createElement('span');
icon.className = 'installer-toast-icon';
icon.dataset.status = status;
icon.innerHTML = ICONS.error;
content.appendChild(icon);
const body = document.createElement('section');
body.className = 'installer-toast-body';
if (title) {
const titleNode = document.createElement('p');
titleNode.className = 'installer-toast-title typography-text-m-500';
titleNode.textContent = title;
body.appendChild(titleNode);
}
if (description) {
const descNode = document.createElement('p');
descNode.className = 'installer-toast-description typography-text-m-400';
descNode.textContent = description;
body.appendChild(descNode);
}
content.appendChild(body);
toast.appendChild(content);
if (dismissible) {
const close = document.createElement('button');
close.type = 'button';
close.className = 'installer-toast-close';
close.setAttribute('aria-label', 'Dismiss notification');
close.innerHTML = ICONS.close;
close.addEventListener('click', () => dismissToast(toast));
toast.appendChild(close);
}
stack.appendChild(toast);
toast.getBoundingClientRect();
requestAnimationFrame(() => {
toast.classList.remove('is-entering');
});
if (timeout > 0) {
setTimeout(() => dismissToast(toast), timeout);
}
};
window.InstallerToast = Object.freeze({
showToast
});
})();
@@ -0,0 +1,281 @@
(() => {
const { TIMINGS } = window.InstallerStepsContext || {};
const { formState } = window.InstallerStepsState || {};
const clearFieldErrors = (root) => {
if (!root) return;
root.querySelectorAll('.field-error').forEach((node) => {
node.classList.remove('is-visible');
});
root.querySelectorAll('.input-field.is-error, .input-action.is-error').forEach((node) => {
node.classList.remove('is-error');
});
root.querySelectorAll('.field-helper').forEach((helper) => {
helper.style.display = '';
});
};
const setFieldError = (input, message) => {
if (!input) return;
const group = input.closest('.input-group');
if (!group) return;
let error = group.querySelector('.field-error');
let errorText = error?.querySelector('.field-error-text');
const hasSameMessage = Boolean(errorText && errorText.textContent === message);
const alreadyVisible = Boolean(error && error.classList.contains('is-visible'));
if (hasSameMessage && alreadyVisible) {
return;
}
if (!error) {
const template = document.getElementById('field-error-template');
if (template && template.content) {
const fragment = template.content.cloneNode(true);
error = fragment.querySelector('.field-error');
group.appendChild(fragment);
}
errorText = error?.querySelector('.field-error-text');
}
if (errorText) {
errorText.textContent = message;
}
if (!alreadyVisible) {
requestAnimationFrame(() => {
error.classList.add('is-visible');
});
}
input.classList.add('is-error');
const actionWrapper = input.closest('.input-action');
if (actionWrapper) {
actionWrapper.classList.add('is-error');
}
const helper = group.querySelector('.field-helper');
if (helper) {
helper.style.display = 'none';
}
};
const bindErrorClear = (input) => {
if (!input) return;
const handler = () => {
const group = input.closest('.input-group');
const error = group?.querySelector('.field-error');
if (error) {
error.classList.remove('is-visible');
}
input.classList.remove('is-error');
const actionWrapper = input.closest('.input-action');
if (actionWrapper) {
actionWrapper.classList.remove('is-error');
}
const helper = group?.querySelector('.field-helper');
if (helper) {
helper.style.display = '';
}
};
input.addEventListener('input', handler);
input.addEventListener('change', handler);
};
const toDatabaseLabel = (value) => {
if (!value) return '';
const lower = value.toLowerCase();
if (lower === 'mariadb') return 'MariaDB';
if (lower === 'postgresql') return 'PostgreSQL';
return 'MongoDB';
};
const updateDatabaseSelection = (radio, root) => {
if (!radio || !root) return;
const allOptions = root.querySelectorAll('.selector-card');
allOptions.forEach((option) => option.classList.remove('selected'));
const selectedOption = radio.closest('.selector-card');
if (selectedOption) {
selectedOption.classList.add('selected');
}
};
const syncResetButton = (input, button) => {
const defaultValue = input.dataset.default ?? '';
button.disabled = input.value === defaultValue;
};
const setupResetButtons = (root) => {
const inputs = root.querySelectorAll('.input-field[data-default]');
inputs.forEach((input) => {
const button = root.querySelector(`[data-reset-target="${input.id}"]`);
if (!button) return;
syncResetButton(input, button);
input.addEventListener('input', () => syncResetButton(input, button));
button.addEventListener('click', () => {
input.value = input.dataset.default ?? '';
syncResetButton(input, button);
input.dispatchEvent(new Event('input', { bubbles: true }));
});
});
};
const toggleAccordion = (button) => {
const content = button.nextElementSibling;
const icon = button.querySelector('.accordion-chevron');
const isOpen = button.classList.contains('is-open');
button.classList.toggle('is-open', !isOpen);
button.setAttribute('aria-expanded', String(!isOpen));
if (content) {
if (!isOpen) {
content.classList.add('open');
content.style.maxHeight = `${content.scrollHeight}px`;
} else {
content.style.maxHeight = '0px';
content.classList.remove('open');
}
}
if (icon) {
icon.setAttribute('data-open', String(!isOpen));
}
};
const setupAccordion = (root) => {
const buttons = root.querySelectorAll('.accordion-toggle');
buttons.forEach((button) => {
button.addEventListener('click', () => toggleAccordion(button));
});
};
const openAccordion = (root) => {
const toggle = root.querySelector('.accordion-toggle');
const content = root.querySelector('.accordion-content');
if (!toggle || !content) return;
if (!toggle.classList.contains('is-open')) {
toggle.classList.add('is-open');
toggle.setAttribute('aria-expanded', 'true');
content.classList.add('open');
content.style.maxHeight = `${content.scrollHeight}px`;
}
};
const disableControls = (root) => {
const inputs = root.querySelectorAll('input, select, textarea');
inputs.forEach((input) => {
if (input.type === 'radio' || input.type === 'checkbox') {
input.disabled = true;
} else {
input.readOnly = true;
input.setAttribute('aria-disabled', 'true');
}
});
const buttons = root.querySelectorAll('button');
buttons.forEach((button) => {
if (button.matches('[data-copy-target]')) return;
button.disabled = true;
button.setAttribute('aria-disabled', 'true');
});
root.classList.add('is-locked');
};
const generateSecretKey = () => {
const array = new Uint8Array(32);
window.crypto.getRandomValues(array);
return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');
};
const copyToClipboard = (value, input) => {
if (!value) return;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(value);
return;
}
if (input) {
input.select();
document.execCommand('copy');
input.setSelectionRange(0, 0);
return;
}
const textArea = document.createElement('textarea');
textArea.value = value;
textArea.style.position = 'fixed';
textArea.style.top = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (error) {} finally {
document.body.removeChild(textArea);
}
};
const setTooltipText = (wrapper, message) => {
if (!wrapper) return;
const tooltip = wrapper.querySelector('.tooltip');
if (tooltip && message) {
tooltip.textContent = message;
}
};
const resetTooltipText = (wrapper) => {
if (!wrapper) return;
const defaultText = wrapper.dataset.tooltipDefault;
if (!defaultText) return;
setTooltipText(wrapper, defaultText);
};
const updateReviewSummary = (root) => {
if (!root) return;
const valueNodes = root.querySelectorAll('[data-review-value]');
valueNodes.forEach((node) => {
const key = node.dataset.reviewValue;
if (!key) return;
let value = formState?.[key];
if (key === 'database') {
value = toDatabaseLabel(formState?.database);
}
if (value) {
node.textContent = value;
}
});
const badge = root.querySelector('[data-review-badge]');
if (badge) {
const hasKey = Boolean((formState?.opensslKey || '').trim());
badge.textContent = hasKey ? 'Generated' : 'Missing';
badge.classList.remove('badge-success', 'badge-warning');
badge.classList.add(hasKey ? 'badge-success' : 'badge-warning');
}
const assistantBadge = root.querySelector('[data-review-assistant-badge]');
if (assistantBadge) {
const hasAssistantKey = Boolean((formState?.assistantOpenAIKey || '').trim());
assistantBadge.textContent = hasAssistantKey ? 'Enabled' : 'Disabled';
assistantBadge.classList.remove('badge-success', 'badge-neutral');
assistantBadge.classList.add(hasAssistantKey ? 'badge-success' : 'badge-neutral');
}
};
window.InstallerStepsUI = {
clearFieldErrors,
setFieldError,
bindErrorClear,
toDatabaseLabel,
updateDatabaseSelection,
setupResetButtons,
setupAccordion,
openAccordion,
disableControls,
generateSecretKey,
copyToClipboard,
setTooltipText,
resetTooltipText,
updateReviewSummary
};
})();
@@ -0,0 +1,117 @@
(() => {
const isValidEmail = (email) => {
if (!email) return false;
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
};
const isValidPort = (value) => {
const numeric = Number(value);
if (!Number.isInteger(numeric)) return false;
return numeric >= 1 && numeric <= 65535;
};
const isValidPassword = (value) => {
if (!value) return false;
return value.length >= 8 && /\S/.test(value);
};
const isValidIPv4 = (host) => {
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return false;
return host.split('.').every((part) => {
const num = Number(part);
return num >= 0 && num <= 255;
});
};
const isValidIPv6 = (host) => {
try {
const url = new URL(`http://[${host}]`);
return url.hostname.toLowerCase() === host.toLowerCase();
} catch (error) {
return false;
}
};
const isValidHostnameLabel = (label) => {
if (!label || label.length > 63) return false;
if (label.startsWith('-') || label.endsWith('-')) return false;
return /^[a-zA-Z0-9-]+$/.test(label);
};
const isValidDomain = (host) => {
if (host.length > 253) return false;
const labels = host.split('.');
return labels.every((label) => isValidHostnameLabel(label));
};
const isValidHost = (host) => {
if (host === 'localhost') return true;
if (isValidIPv4(host)) return true;
if (isValidIPv6(host)) return true;
return isValidDomain(host);
};
const isValidHostnameInput = (value) => {
if (!value) return false;
const trimmed = value.trim();
if (!trimmed) return false;
let host = trimmed;
let port = null;
if (trimmed.startsWith('[')) {
const match = trimmed.match(/^\[([^\]]+)\](?::(\d+))?$/);
if (!match) return false;
host = match[1] || '';
port = match[2] || null;
} else {
const parts = trimmed.split(':');
if (parts.length > 2) return false;
if (parts.length === 2) {
host = parts[0];
port = parts[1];
}
}
if (port !== null && port !== '' && !isValidPort(port)) {
return false;
}
return isValidHost(host);
};
const extractHostname = (value) => {
if (!value) return '';
const trimmed = value.trim();
if (trimmed.startsWith('[')) {
const end = trimmed.indexOf(']');
if (end !== -1) {
return trimmed.slice(1, end);
}
return trimmed;
}
const colonCount = (trimmed.match(/:/g) || []).length;
if (colonCount === 1) {
return trimmed.split(':')[0];
}
return trimmed;
};
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']);
const isLocalHost = (host) => {
if (!host) return false;
const normalized = host.toLowerCase();
return LOCAL_HOSTS.has(normalized);
};
window.InstallerStepsValidation = {
isValidEmail,
isValidPort,
isValidPassword,
isValidHostnameInput,
extractHostname,
isLocalHost
};
})();
+434
View File
@@ -0,0 +1,434 @@
(() => {
const Context = window.InstallerStepsContext || {};
const State = window.InstallerStepsState || {};
const Validation = window.InstallerStepsValidation || {};
const UI = window.InstallerStepsUI || {};
const Progress = window.InstallerStepsProgress || {};
const Tooltips = window.InstallerTooltips || null;
const {
INSTALLATION_STEPS,
clampStep
} = Context;
const {
formState,
dispatchStateChange,
applyBodyDefaults,
applyLockPayload,
clearInstallLock,
clearInstallId,
isInstallLocked,
syncInstallLockFlag,
getInstallLock,
getLockedDatabase
} = State;
const {
isValidEmail,
isValidPort,
isValidHostnameInput,
isValidPassword
} = Validation;
const {
clearFieldErrors,
setFieldError,
bindErrorClear,
updateDatabaseSelection,
setupResetButtons,
setupAccordion,
openAccordion,
disableControls,
generateSecretKey,
copyToClipboard,
setTooltipText,
resetTooltipText,
updateReviewSummary
} = UI;
let reviewListener = null;
const bindInputToState = (input, key) => {
if (!input) return;
const update = () => {
formState[key] = input.value;
dispatchStateChange?.(key);
};
input.addEventListener('input', update);
input.addEventListener('change', update);
update();
};
const lockDatabaseSelection = (root, lockedDatabase) => {
if (lockedDatabase) {
const radios = root.querySelectorAll('input[name="database"]');
radios.forEach((radio) => {
const isLockedChoice = radio.value === lockedDatabase;
const card = radio.closest('.selector-card');
radio.disabled = !isLockedChoice;
if (card) {
card.classList.toggle('is-disabled', !isLockedChoice);
}
if (isLockedChoice) {
radio.checked = true;
updateDatabaseSelection?.(radio, root);
}
});
}
};
const bindDatabaseSelection = (root) => {
const radios = root.querySelectorAll('input[name="database"]');
radios.forEach((radio) => {
radio.addEventListener('change', () => {
formState.database = radio.value;
updateDatabaseSelection?.(radio, root);
});
});
};
const hydrateStep1State = (root) => {
State.setStateIfEmpty?.('appDomain', root.querySelector('#hostname')?.value);
State.setStateIfEmpty?.('database', root.querySelector('input[name="database"]:checked')?.value);
State.setStateIfEmpty?.('httpPort', root.querySelector('#http-port')?.value);
State.setStateIfEmpty?.('httpsPort', root.querySelector('#https-port')?.value);
State.setStateIfEmpty?.('emailCertificates', root.querySelector('#ssl-email')?.value);
State.setStateIfEmpty?.('assistantOpenAIKey', root.querySelector('#assistant-openai-key')?.value);
};
const applyStep1State = (root) => {
const hostname = root.querySelector('#hostname');
if (hostname && formState.appDomain) hostname.value = formState.appDomain;
const httpPort = root.querySelector('#http-port');
if (httpPort && formState.httpPort) httpPort.value = formState.httpPort;
const httpsPort = root.querySelector('#https-port');
if (httpsPort && formState.httpsPort) httpsPort.value = formState.httpsPort;
const sslEmail = root.querySelector('#ssl-email');
if (sslEmail && formState.emailCertificates) sslEmail.value = formState.emailCertificates;
const assistantKey = root.querySelector('#assistant-openai-key');
if (assistantKey && formState.assistantOpenAIKey) {
assistantKey.value = formState.assistantOpenAIKey;
}
if (formState.database) {
const radio = root.querySelector(`input[name="database"][value="${formState.database}"]`);
if (radio) {
radio.checked = true;
updateDatabaseSelection?.(radio, root);
}
}
};
const initStep1 = (root) => {
if (!root) return;
syncInstallLockFlag?.();
applyLockPayload?.();
applyBodyDefaults?.();
hydrateStep1State(root);
applyStep1State(root);
if (isInstallLocked?.()) {
openAccordion?.(root);
disableControls?.(root);
return;
}
const lockedDatabase = getLockedDatabase?.() || '';
if (lockedDatabase) {
lockDatabaseSelection(root, lockedDatabase);
} else {
bindDatabaseSelection(root);
}
const hostname = root.querySelector('#hostname');
const httpPort = root.querySelector('#http-port');
const httpsPort = root.querySelector('#https-port');
const sslEmail = root.querySelector('#ssl-email');
const assistantKey = root.querySelector('#assistant-openai-key');
bindInputToState(hostname, 'appDomain');
bindInputToState(httpPort, 'httpPort');
bindInputToState(httpsPort, 'httpsPort');
bindInputToState(sslEmail, 'emailCertificates');
bindInputToState(assistantKey, 'assistantOpenAIKey');
bindErrorClear?.(hostname);
bindErrorClear?.(httpPort);
bindErrorClear?.(httpsPort);
bindErrorClear?.(sslEmail);
bindErrorClear?.(assistantKey);
const checked = root.querySelector('input[name="database"]:checked');
if (checked) {
updateDatabaseSelection?.(checked, root);
}
setupResetButtons?.(root);
setupAccordion?.(root);
Tooltips?.setupTooltipPortals?.(root);
};
const hydrateStep2State = (root) => {
const value = root.querySelector('#secret-key')?.value;
if (formState.opensslKey) return;
if (value) {
formState.opensslKey = value;
}
};
const applyStep2State = (root) => {
const input = root.querySelector('#secret-key');
if (input && formState.opensslKey) {
input.value = formState.opensslKey;
}
};
const initStep2 = (root) => {
if (!root) return;
syncInstallLockFlag?.();
applyLockPayload?.();
applyBodyDefaults?.();
hydrateStep2State(root);
if (!formState.opensslKey || !formState.opensslKey.trim()) {
formState.opensslKey = generateSecretKey?.();
dispatchStateChange?.('opensslKey');
}
applyStep2State(root);
const input = root.querySelector('#secret-key');
if (input) {
bindInputToState(input, 'opensslKey');
bindErrorClear?.(input);
}
const copyButton = root.querySelector('[data-copy-target]');
const tooltipWrapper = copyButton?.closest('.tooltip-wrapper');
if (tooltipWrapper) {
tooltipWrapper.addEventListener('mouseenter', () => resetTooltipText?.(tooltipWrapper));
tooltipWrapper.addEventListener('focusin', () => resetTooltipText?.(tooltipWrapper));
}
if (copyButton) {
copyButton.addEventListener('click', () => {
const targetId = copyButton.getAttribute('data-copy-target');
const targetInput = targetId ? root.querySelector(`#${targetId}`) : null;
const value = targetInput?.value || '';
copyToClipboard?.(value, targetInput);
copyButton.blur();
if (tooltipWrapper) {
const successText = tooltipWrapper.dataset.tooltipSuccess || 'Copied';
setTooltipText?.(tooltipWrapper, successText);
}
});
}
const regenerateButton = root.querySelector('[data-regenerate-target]');
if (regenerateButton && !isInstallLocked?.()) {
regenerateButton.addEventListener('click', () => {
const targetId = regenerateButton.getAttribute('data-regenerate-target');
const targetInput = targetId ? root.querySelector(`#${targetId}`) : null;
if (!targetInput) return;
regenerateButton.classList.remove('is-rotating');
void regenerateButton.offsetWidth;
regenerateButton.classList.add('is-rotating');
const handleAnimationEnd = () => {
regenerateButton.classList.remove('is-rotating');
};
regenerateButton.addEventListener('animationend', handleAnimationEnd, { once: true });
targetInput.value = generateSecretKey?.();
targetInput.dispatchEvent(new Event('input', { bubbles: true }));
});
}
if (isInstallLocked?.()) {
disableControls?.(root);
}
};
const hydrateStep3State = (root) => {
State.setStateIfEmpty?.('accountEmail', root.querySelector('#account-email')?.value);
State.setStateIfEmpty?.('accountPassword', root.querySelector('#account-password')?.value);
};
const applyStep3State = (root) => {
const email = root.querySelector('#account-email');
if (email && formState.accountEmail) email.value = formState.accountEmail;
const password = root.querySelector('#account-password');
if (password && formState.accountPassword) password.value = formState.accountPassword;
};
const initStep3 = (root) => {
if (!root) return;
syncInstallLockFlag?.();
applyLockPayload?.();
applyBodyDefaults?.();
hydrateStep3State(root);
applyStep3State(root);
const email = root.querySelector('#account-email');
const password = root.querySelector('#account-password');
const passwordToggle = root.querySelector('[data-password-toggle="account-password"]');
bindInputToState(email, 'accountEmail');
bindInputToState(password, 'accountPassword');
bindErrorClear?.(email);
bindErrorClear?.(password);
if (password && passwordToggle) {
passwordToggle.addEventListener('click', () => {
const isVisible = passwordToggle.classList.toggle('is-visible');
password.type = isVisible ? 'text' : 'password';
passwordToggle.setAttribute('aria-label', isVisible ? 'Hide password' : 'Show password');
});
}
if (isInstallLocked?.()) {
disableControls?.(root);
}
};
const initStep4 = (root) => {
if (!root) return;
syncInstallLockFlag?.();
applyLockPayload?.();
applyBodyDefaults?.();
updateReviewSummary?.(root);
if (reviewListener) {
document.removeEventListener('installer:state-change', reviewListener);
}
reviewListener = () => updateReviewSummary?.(root);
document.addEventListener('installer:state-change', reviewListener);
if (isInstallLocked?.()) {
disableControls?.(root);
}
};
const initStep = (step, container) => {
if (!container) return;
const root = container.querySelector('.step-layout') || container;
const normalized = clampStep?.(step) ?? 1;
Tooltips?.cleanupTooltipPortals?.();
if (normalized !== 4 && reviewListener) {
document.removeEventListener('installer:state-change', reviewListener);
reviewListener = null;
}
if (normalized !== 5) {
Progress.cleanupInstallFlow?.();
}
if (normalized === 1) initStep1(root);
if (normalized === 2) initStep2(root);
if (normalized === 3) initStep3(root);
if (normalized === 4) initStep4(root);
if (normalized === 5) Progress.initStep5?.(root);
};
window.InstallerSteps = {
initStep1,
initStep2,
initStep3,
initStep4,
initStep5: Progress.initStep5,
installationSteps: INSTALLATION_STEPS || [],
isInstallLocked,
getInstallLock,
clearInstallLock,
initStep,
validateStep: (step, container) => {
const root = container?.querySelector('.step-layout') || container;
const normalized = clampStep?.(step) ?? 1;
if (normalized === 1) {
clearFieldErrors?.(root);
let valid = true;
const hostname = root?.querySelector('#hostname');
const httpPort = root?.querySelector('#http-port');
const httpsPort = root?.querySelector('#https-port');
const sslEmail = root?.querySelector('#ssl-email');
if (!hostname || !hostname.value.trim()) {
setFieldError?.(hostname, 'Please enter your Appwrite hostname');
valid = false;
} else if (!isValidHostnameInput?.(hostname.value.trim())) {
setFieldError?.(hostname, 'Please enter a valid hostname');
valid = false;
}
const parsePort = (input, label) => {
const value = input?.value;
if (!value || !isValidPort?.(value)) {
setFieldError?.(input, `Please enter a valid ${label} port (1-65535)`);
return false;
}
return true;
};
if (!parsePort(httpPort, 'HTTP')) valid = false;
if (!parsePort(httpsPort, 'HTTPS')) valid = false;
if (!sslEmail || !sslEmail.value.trim()) {
setFieldError?.(sslEmail, 'Please enter an email address for SSL certificates');
valid = false;
} else if (!isValidEmail?.(sslEmail.value.trim())) {
setFieldError?.(sslEmail, 'Please enter a valid email address');
valid = false;
}
if (!valid) {
openAccordion?.(root);
}
return valid;
}
if (normalized === 2) {
clearFieldErrors?.(root);
const secretKey = root?.querySelector('#secret-key');
const secretValue = secretKey?.value.trim() || '';
if (!secretKey || !secretValue) {
setFieldError?.(secretKey, 'Please enter or generate a secret API key');
return false;
}
if (secretValue.length > 64) {
setFieldError?.(secretKey, 'Secret API key must be 1-64 characters');
return false;
}
}
if (normalized === 3) {
clearFieldErrors?.(root);
let valid = true;
const email = root?.querySelector('#account-email');
const password = root?.querySelector('#account-password');
if (!email || !email.value.trim()) {
setFieldError?.(email, 'This field is required');
valid = false;
} else if (!isValidEmail?.(email.value.trim())) {
setFieldError?.(email, 'Please enter a valid email address');
valid = false;
}
const passwordValue = password?.value ?? '';
if (!password || !/\S/.test(passwordValue)) {
setFieldError?.(password, 'This field is required');
valid = false;
} else if (!isValidPassword?.(passwordValue)) {
setFieldError?.(password, 'Password must be at least 8 characters long');
valid = false;
}
return valid;
}
return true;
}
};
})();
@@ -0,0 +1,77 @@
(() => {
const tooltipPortals = new Set();
const positionTooltipPortal = (tooltip, anchor) => {
if (!tooltip || !anchor) return;
const rect = anchor.getBoundingClientRect();
const tooltipRect = tooltip.getBoundingClientRect();
const offset = Number(tooltip.dataset.tooltipOffset || 6);
const padding = 8;
let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
left = Math.max(padding, Math.min(left, window.innerWidth - tooltipRect.width - padding));
const top = rect.bottom + offset;
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
};
const attachTooltipPortal = (tooltip) => {
if (!tooltip || tooltip.dataset.portalInitialized === 'true') return;
const anchor = tooltip.parentElement;
if (!anchor) return;
tooltip.dataset.portalInitialized = 'true';
tooltip.classList.add('tooltip-portal');
document.body.appendChild(tooltip);
const show = () => {
tooltip.classList.add('is-open');
positionTooltipPortal(tooltip, anchor);
};
const hide = () => {
tooltip.classList.remove('is-open');
};
const refresh = () => {
if (tooltip.classList.contains('is-open')) {
positionTooltipPortal(tooltip, anchor);
}
};
anchor.addEventListener('mouseenter', show);
anchor.addEventListener('mouseleave', hide);
anchor.addEventListener('focusin', show);
anchor.addEventListener('focusout', hide);
window.addEventListener('scroll', refresh, true);
window.addEventListener('resize', refresh);
tooltipPortals.add({
tooltip,
cleanup: () => {
anchor.removeEventListener('mouseenter', show);
anchor.removeEventListener('mouseleave', hide);
anchor.removeEventListener('focusin', show);
anchor.removeEventListener('focusout', hide);
window.removeEventListener('scroll', refresh, true);
window.removeEventListener('resize', refresh);
if (tooltip.parentElement) {
tooltip.parentElement.removeChild(tooltip);
}
}
});
};
const setupTooltipPortals = (root) => {
if (!root) return;
const portalTooltips = root.querySelectorAll('.tooltip[data-tooltip-portal]');
portalTooltips.forEach((tooltip) => attachTooltipPortal(tooltip));
};
const cleanupTooltipPortals = () => {
tooltipPortals.forEach((entry) => entry.cleanup());
tooltipPortals.clear();
};
window.InstallerTooltips = {
setupTooltipPortals,
cleanupTooltipPortals
};
})();
@@ -0,0 +1,184 @@
<?php
$isUpgrade = $isUpgrade ?? false;
$lockedDatabase = $lockedDatabase ?? null;
$defaultAppDomain = $defaultAppDomain ?? 'localhost';
$defaultHttpPort = $defaultHttpPort ?? '80';
$defaultHttpsPort = $defaultHttpsPort ?? '443';
$defaultEmailCertificates = $defaultEmailCertificates ?? '';
$defaultAssistantOpenAIKey = $defaultAssistantOpenAIKey ?? '';
$defaultDatabase = $defaultDatabase ?? 'mongodb';
$selectedDatabase = $lockedDatabase ?: $defaultDatabase;
$isDatabaseLocked = !empty($lockedDatabase);
$mongoDisabled = $isDatabaseLocked && $selectedDatabase !== 'mongodb';
$mariaDisabled = $isDatabaseLocked && $selectedDatabase !== 'mariadb';
$postgresDisabled = $isDatabaseLocked && $selectedDatabase !== 'postgresql';
$hostnameValue = htmlspecialchars((string) $defaultAppDomain, ENT_QUOTES, 'UTF-8');
$httpPortValue = htmlspecialchars((string) $defaultHttpPort, ENT_QUOTES, 'UTF-8');
$httpsPortValue = htmlspecialchars((string) $defaultHttpsPort, ENT_QUOTES, 'UTF-8');
$sslEmailValue = htmlspecialchars((string) $defaultEmailCertificates, ENT_QUOTES, 'UTF-8');
$assistantOpenAIKeyValue = htmlspecialchars((string) $defaultAssistantOpenAIKey, ENT_QUOTES, 'UTF-8');
?>
<div class="step-layout" data-step="1">
<div class="stack-xl">
<div class="stack-xxxs">
<h1 class="typography-title-s text-neutral-primary"><?php echo $isUpgrade ? 'Update your app' : 'Setup your app'; ?></h1>
<p class="typography-text-m-400 text-neutral-secondary">
<?php echo $isUpgrade ? 'Review your current settings before updating.' : 'Choose where your app will live and how it will store data'; ?>
</p>
</div>
<div class="stack-xl">
<div class="input-group stack-xs">
<label for="hostname" class="label-text typography-text-m-500 text-neutral-secondary">Hostname</label>
<input
type="text"
id="hostname"
name="hostname"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="localhost"
value="<?php echo $hostnameValue; ?>"
>
</div>
<div class="input-group stack-xs">
<label class="label-text typography-text-m-500 text-neutral-secondary">Database</label>
<div class="selector-group<?php echo $isDatabaseLocked ? ' is-locked' : ''; ?>">
<label class="selector-card <?php echo ($selectedDatabase === 'mongodb') ? 'selected' : ''; ?><?php echo $mongoDisabled ? ' is-disabled has-tooltip' : ''; ?>"<?php echo $mongoDisabled ? ' aria-disabled="true"' : ''; ?>>
<input type="radio" name="database" value="mongodb" <?php echo ($selectedDatabase === 'mongodb') ? 'checked' : ''; ?> class="sr-only" <?php echo $mongoDisabled ? 'disabled' : ''; ?>>
<div class="selector-content">
<div class="typography-text-m-500 text-neutral-primary">MongoDB</div>
<div class="typography-text-xs-400 text-neutral-secondary">Document based database</div>
</div>
<img src="installer/icons/mongodb.svg" alt="MongoDB" class="selector-icon">
<?php if ($mongoDisabled) { ?>
<span class="tooltip tooltip-db-locked typography-text-m-400 text-on-invert" role="tooltip" data-tooltip-portal="true">Database cannot be changed after initial setup.</span>
<?php } ?>
</label>
<label class="selector-card <?php echo ($selectedDatabase === 'mariadb') ? 'selected' : ''; ?><?php echo $mariaDisabled ? ' is-disabled has-tooltip' : ''; ?>"<?php echo $mariaDisabled ? ' aria-disabled="true"' : ''; ?>>
<input type="radio" name="database" value="mariadb" <?php echo ($selectedDatabase === 'mariadb') ? 'checked' : ''; ?> class="sr-only" <?php echo $mariaDisabled ? 'disabled' : ''; ?>>
<div class="selector-content">
<div class="typography-text-m-500 text-neutral-primary">MariaDB</div>
<div class="typography-text-xs-400 text-neutral-secondary">Relational SQL database</div>
</div>
<img src="installer/icons/mariadb.svg" alt="MariaDB" class="selector-icon">
<?php if ($mariaDisabled) { ?>
<span class="tooltip tooltip-db-locked typography-text-m-400 text-on-invert" role="tooltip" data-tooltip-portal="true">Database cannot be changed after initial setup.</span>
<?php } ?>
</label>
<label class="selector-card <?php echo ($selectedDatabase === 'postgresql') ? 'selected' : ''; ?><?php echo $postgresDisabled ? ' is-disabled has-tooltip' : ''; ?>"<?php echo $postgresDisabled ? ' aria-disabled="true"' : ''; ?>>
<input type="radio" name="database" value="postgresql" <?php echo ($selectedDatabase === 'postgresql') ? 'checked' : ''; ?> class="sr-only" <?php echo $postgresDisabled ? 'disabled' : ''; ?>>
<div class="selector-content">
<div class="typography-text-m-500 text-neutral-primary">PostgreSQL</div>
<div class="typography-text-xs-400 text-neutral-secondary">Relational SQL database</div>
</div>
<img src="installer/icons/postgresql.svg" alt="PostgreSQL" class="selector-icon">
<?php if ($postgresDisabled) { ?>
<span class="tooltip tooltip-db-locked typography-text-m-400 text-on-invert" role="tooltip" data-tooltip-portal="true">Database cannot be changed after initial setup.</span>
<?php } ?>
</label>
</div>
</div>
<div class="accordion">
<button
type="button"
class="accordion-toggle"
aria-expanded="false"
>
<span class="label-text typography-text-m-500 text-neutral-secondary">Advanced settings</span>
<span class="accordion-chevron" data-open="false">
<?php include __DIR__ . '/../../icons/chevron-down.svg'; ?>
</span>
</button>
<div class="accordion-content">
<div class="input-row">
<div class="input-group stack-xs">
<label for="http-port" class="label-text typography-text-m-500 text-neutral-secondary">HTTP port</label>
<input
type="number"
id="http-port"
name="httpPort"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="<?php echo $httpPortValue; ?>"
value="<?php echo $httpPortValue; ?>"
data-default="<?php echo $httpPortValue; ?>"
min="1"
max="65535"
step="1"
>
</div>
<button type="button" class="button secondary" data-reset-target="http-port" disabled>
<span class="button-text typography-text-m-500">Reset</span>
</button>
</div>
<div class="input-row">
<div class="input-group stack-xs">
<label for="https-port" class="label-text typography-text-m-500 text-neutral-secondary">HTTPS port</label>
<input
type="number"
id="https-port"
name="httpsPort"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="<?php echo $httpsPortValue; ?>"
value="<?php echo $httpsPortValue; ?>"
data-default="<?php echo $httpsPortValue; ?>"
min="1"
max="65535"
step="1"
>
</div>
<button type="button" class="button secondary" data-reset-target="https-port" disabled>
<span class="button-text typography-text-m-500">Reset</span>
</button>
</div>
<div class="input-row">
<div class="input-group stack-xs">
<label for="ssl-email" class="label-text typography-text-m-500 text-neutral-secondary">SSL certificate email</label>
<input
type="email"
id="ssl-email"
name="sslEmail"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="you@example.com"
value="<?php echo $sslEmailValue; ?>"
data-default="<?php echo $sslEmailValue; ?>"
>
</div>
<button type="button" class="button secondary" data-reset-target="ssl-email" disabled>
<span class="button-text typography-text-m-500">Reset</span>
</button>
</div>
<div class="input-row">
<div class="input-group stack-xs">
<label for="assistant-openai-key" class="label-text typography-text-m-500 text-neutral-secondary">
OpenAI key
<span class="label-optional typography-text-m-400 text-neutral-tertiary">optional</span>
<span class="tooltip-wrapper">
<button type="button" class="label-info-button" aria-label="OpenAI key info">
<?php include __DIR__ . '/../../icons/info.svg'; ?>
</button>
<span class="tooltip tooltip-assistant typography-text-m-400 text-on-invert" role="tooltip">Add your OpenAI key to enable Appwrite Assistant. The key is stored locally and wont be shared.</span>
</span>
</label>
<input
type="text"
id="assistant-openai-key"
name="assistantOpenAIKey"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="Enter OpenAI key for Appwrite Assistant"
value="<?php echo $assistantOpenAIKeyValue; ?>"
data-default="<?php echo $assistantOpenAIKeyValue; ?>"
>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,58 @@
<?php
$isUpgrade = $isUpgrade ?? false;
$defaultSecretKey = $defaultSecretKey ?? '';
$secretKeyValue = htmlspecialchars((string) $defaultSecretKey, ENT_QUOTES, 'UTF-8');
?>
<div class="step-layout" data-step="2">
<div class="stack-xl">
<div class="stack-xxxs">
<h1 class="typography-title-s text-neutral-primary">Secure your app</h1>
<p class="typography-text-m-400 text-neutral-secondary">
<?php echo $isUpgrade ? 'Review your existing secret key or generate a new one.' : 'Your server\'s private secret key for encryption. Generate a random secure key, or provide your own.'; ?>
</p>
</div>
<div class="stack-xl">
<div class="inline-alert inline-alert--warning">
<div class="inline-alert-content">
<div class="inline-alert-icon" aria-hidden="true">
<?php include __DIR__ . '/../../icons/warning.svg'; ?>
</div>
<div class="inline-alert-text">
<div class="inline-alert-title typography-text-m-500 text-warning">Save your key</div>
<div class="inline-alert-description typography-text-m-400 text-neutral-primary">You won't be able to see this key again. Copy it somewhere safe before continuing.</div>
</div>
</div>
</div>
<div class="input-row">
<div class="input-group stack-xs">
<label for="secret-key" class="label-text typography-text-m-500 text-neutral-secondary">Secret API key</label>
<div class="input-action">
<input
type="text"
id="secret-key"
name="secretKey"
class="input-action-input typography-text-m-400 text-neutral-primary"
value="<?php echo $secretKeyValue; ?>"
minlength="1"
maxlength="64"
>
<div class="input-action-buttons">
<span class="tooltip-wrapper" data-tooltip-default="Copy" data-tooltip-success="Copied">
<button type="button" class="input-icon-button" aria-label="Copy secret key" aria-describedby="copy-tooltip" data-copy-target="secret-key">
<?php include __DIR__ . '/../../icons/copy.svg'; ?>
</button>
<span id="copy-tooltip" class="tooltip typography-text-m-400 text-on-invert" role="tooltip">Copy</span>
</span>
</div>
</div>
</div>
<button type="button" class="icon-button" aria-label="Regenerate secret key" data-regenerate-target="secret-key">
<?php include __DIR__ . '/../../icons/refresh.svg'; ?>
</button>
</div>
</div>
</div>
</div>
@@ -0,0 +1,61 @@
<?php
$defaultAccountEmail = $defaultAccountEmail ?? '';
$accountEmailValue = htmlspecialchars($defaultAccountEmail, ENT_QUOTES, 'UTF-8');
?>
<div class="step-layout" data-step="3">
<div class="stack-xl">
<div class="stack-xxxs">
<h1 class="typography-title-s text-neutral-primary">Create your account</h1>
<p class="typography-text-m-400 text-neutral-secondary">
Set up the email and password for your Appwrite account. You can use these
credentials to sign in later.
</p>
</div>
<div class="stack-l">
<div class="input-group stack-xs">
<label for="account-email" class="label-text typography-text-m-500 text-neutral-secondary">Email</label>
<input
type="email"
id="account-email"
name="accountEmail"
class="input-field typography-text-m-400 text-neutral-primary"
placeholder="you@example.com"
value="<?php echo $accountEmailValue; ?>"
autocomplete="email"
>
</div>
<div class="input-group stack-xs">
<label for="account-password"
class="label-text typography-text-m-500 text-neutral-secondary">Password</label>
<div class="input-action">
<input
type="password"
id="account-password"
name="accountPassword"
class="input-action-input typography-text-m-400 text-neutral-primary"
placeholder="Enter password"
autocomplete="new-password"
>
<div class="input-action-buttons">
<button type="button" class="input-icon-button password-toggle" aria-label="Show password" data-password-toggle="account-password">
<span class="password-toggle-icon" data-password-icon="hide">
<?php include __DIR__ . '/../../icons/eye-off.svg'; ?>
</span>
<span class="password-toggle-icon" data-password-icon="show">
<?php include __DIR__ . '/../../icons/eye.svg'; ?>
</span>
</button>
</div>
</div>
<div class="field-helper typography-caption-400 text-neutral-secondary">
<span class="field-helper-icon">
<?php include __DIR__ . '/../../icons/info.svg'; ?>
</span>
<span class="field-helper-text">Password must be at least 8 characters long</span>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,76 @@
<?php
$isUpgrade = $isUpgrade ?? false;
$lockedDatabase = $lockedDatabase ?? null;
$defaultAppDomain = $defaultAppDomain ?? 'localhost';
$defaultHttpPort = $defaultHttpPort ?? '80';
$defaultHttpsPort = $defaultHttpsPort ?? '443';
$defaultEmailCertificates = $defaultEmailCertificates ?? '';
$defaultSecretKey = $defaultSecretKey ?? '';
$defaultDatabase = $defaultDatabase ?? 'mongodb';
$selectedDatabase = $lockedDatabase ?: $defaultDatabase;
$defaultDatabaseLabel = match ($selectedDatabase) {
'mariadb' => 'MariaDB',
'postgresql' => 'PostgreSQL',
default => 'MongoDB',
};
$badgeLabel = $defaultSecretKey !== '' ? 'Generated' : 'Missing';
$badgeClass = $defaultSecretKey !== '' ? 'badge-success' : 'badge-warning';
?>
<div class="step-layout" data-step="4">
<div class="stack-xl">
<div class="stack-xxxs">
<h1 class="typography-title-s text-neutral-primary"><?php echo $isUpgrade ? 'Review your update' : 'Review your setup'; ?></h1>
<p class="typography-text-m-400 text-neutral-secondary">
<?php echo $isUpgrade ? 'Confirm your settings before updating Appwrite.' : 'Check your settings below before completing the installation.'; ?>
</p>
</div>
<div class="stack-xl">
<div class="review-card">
<div class="stack-s">
<div class="review-row">
<div class="typography-text-m-500 text-neutral-primary" data-review-value="appDomain">
<?php echo htmlspecialchars((string) $defaultAppDomain, ENT_QUOTES, 'UTF-8'); ?>
</div>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">Hostname</div>
</div>
<div class="review-row">
<div class="typography-text-m-500 text-neutral-primary" data-review-value="database">
<?php echo htmlspecialchars((string) $defaultDatabaseLabel, ENT_QUOTES, 'UTF-8'); ?>
</div>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">Database</div>
</div>
<div class="review-row">
<div class="typography-text-m-500 text-neutral-primary" data-review-value="httpPort">
<?php echo htmlspecialchars((string) $defaultHttpPort, ENT_QUOTES, 'UTF-8'); ?>
</div>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">HTTP port</div>
</div>
<div class="review-row">
<div class="typography-text-m-500 text-neutral-primary" data-review-value="httpsPort">
<?php echo htmlspecialchars((string) $defaultHttpsPort, ENT_QUOTES, 'UTF-8'); ?>
</div>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">HTTPS port</div>
</div>
<div class="review-row">
<div class="typography-text-m-500 text-neutral-primary" data-review-value="emailCertificates">
<?php echo htmlspecialchars((string) $defaultEmailCertificates, ENT_QUOTES, 'UTF-8'); ?>
</div>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">SSL certificate email</div>
</div>
<div class="review-row">
<span class="badge badge-neutral typography-text-xs-400" data-review-assistant-badge>Disabled</span>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">Appwrite Assistant</div>
</div>
<div class="review-row">
<span class="badge <?php echo $badgeClass; ?> typography-text-xs-400" data-review-badge>
<?php echo htmlspecialchars((string) $badgeLabel, ENT_QUOTES, 'UTF-8'); ?>
</span>
<div class="review-label typography-text-xs-400 text-neutral-tertiary">Secret API key</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,53 @@
<?php
$isUpgrade = $isUpgrade ?? false;
?>
<div class="step-layout install-layout" data-step="5">
<div class="install-card">
<div class="install-panel">
<div class="install-header">
<div class="typography-text-m-400 text-neutral-primary">
<?php echo $isUpgrade ? 'Updating your app…' : 'Installing your app…'; ?>
</div>
</div>
<div class="install-list" data-install-list></div>
</div>
</div>
<template id="install-row-template">
<div class="install-row" data-status="in-progress">
<div class="install-row-main">
<div class="install-row-label">
<span class="install-icon" aria-hidden="true">
<span class="install-icon-spinner">
<?php include __DIR__ . '/../../icons/install-spinner.svg'; ?>
</span>
<span class="install-icon-check">
<?php include __DIR__ . '/../../icons/install-check.svg'; ?>
</span>
<span class="install-icon-error">
<?php include __DIR__ . '/../../icons/exclamation-circle.svg'; ?>
</span>
</span>
<span class="install-text typography-text-m-400 text-neutral-primary" data-install-text></span>
</div>
<button type="button" class="install-row-toggle" aria-expanded="false" data-install-toggle>
<?php include __DIR__ . '/../../icons/chevron-down.svg'; ?>
</button>
</div>
<div class="install-row-details">
<div class="install-row-details-inner">
<pre class="install-error-code typography-text-xs-400" data-install-trace></pre>
<div class="install-error-actions">
<button type="button" class="button secondary" data-install-retry>
<span class="button-text typography-text-m-500">Retry</span>
</button>
<button type="button" class="button primary is-hidden" data-install-console>
<span class="button-text typography-text-m-500">Navigate to Console</span>
</button>
</div>
</div>
</div>
</div>
</template>
</div>
+12 -6
View File
@@ -14,7 +14,10 @@
"lint": "vendor/bin/pint --test --config pint.json",
"format": "vendor/bin/pint --config pint.json",
"bench": "vendor/bin/phpbench run --report=benchmark",
"check": "./vendor/bin/phpstan analyse -c phpstan.neon"
"check": "./vendor/bin/phpstan analyse -c phpstan.neon",
"installer:clean": "php src/Appwrite/Platform/Installer/Server.php --clean",
"installer:dev": "docker compose build && composer installer:clean && php src/Appwrite/Platform/Installer/Server.php --docker",
"installer:dev-upgrade": "docker compose build && php src/Appwrite/Platform/Installer/Server.php --docker --upgrade"
},
"autoload": {
"psr-4": {
@@ -29,6 +32,8 @@
"Appwrite\\Tests\\": "tests/extensions"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=8.3.0",
"ext-curl": "*",
@@ -77,22 +82,23 @@
"utopia-php/storage": "1.0.*",
"utopia-php/system": "0.10.*",
"utopia-php/telemetry": "0.2.*",
"utopia-php/vcs": "1.*",
"utopia-php/vcs": "2.*",
"utopia-php/websocket": "1.0.*",
"matomo/device-detector": "6.4.*",
"dragonmantank/cron-expression": "3.4.*",
"phpmailer/phpmailer": "6.9.*",
"chillerlan/php-qrcode": "4.4.*",
"chillerlan/php-qrcode": "4.3.*",
"adhocore/jwt": "1.1.*",
"spomky-labs/otphp": "^11.4.2",
"spomky-labs/otphp": "11.*",
"webonyx/graphql-php": "14.11.*",
"league/csv": "9.24.*",
"league/csv": "9.14.*",
"enshrined/svg-sanitize": "0.22.*"
},
"require-dev": {
"ext-fileinfo": "*",
"appwrite/sdk-generator": "*",
"phpunit/phpunit": "9.*",
"brianium/paratest": "7.*",
"phpunit/phpunit": "12.*",
"swoole/ide-helper": "6.*",
"phpstan/phpstan": "1.12.*",
"textalk/websocket": "1.5.*",
Generated
+689 -585
View File
File diff suppressed because it is too large Load Diff
+108 -29
View File
@@ -64,6 +64,7 @@ services:
networks:
- appwrite
dns:
- 127.0.0.11
- 172.16.238.100
labels:
- "traefik.enable=true"
@@ -98,9 +99,9 @@ services:
- ./public:/usr/src/code/public
- ./src:/usr/src/code/src
- ./dev:/usr/src/code/dev
# - ./vendor/utopia-php/framework:/usr/src/code/vendor/utopia-php/framework
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
- coredns
# - clamav
@@ -145,6 +146,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -285,7 +287,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -297,6 +299,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -321,7 +324,7 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -331,6 +334,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -352,7 +356,7 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- request-catcher-sms
- request-catcher-webhook
environment:
@@ -361,6 +365,7 @@ services:
- _APP_POOL_ADAPTER
- _APP_OPENSSL_KEY_V1
- _APP_EMAIL_SECURITY
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -384,7 +389,7 @@ services:
- appwrite
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
volumes:
- appwrite-uploads:/storage/uploads:rw
- appwrite-cache:/storage/cache:rw
@@ -403,6 +408,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -452,7 +458,7 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -462,6 +468,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -488,7 +495,7 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -500,6 +507,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -561,7 +569,7 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- mariadb
- ${_APP_DB_HOST:-mongodb}
environment:
# Specific
- _APP_BROWSER_HOST
@@ -578,6 +586,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -619,7 +628,7 @@ services:
- appwrite
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
volumes:
- appwrite-config:/storage/config:rw
- appwrite-certificates:/storage/certificates:rw
@@ -643,6 +652,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -663,10 +673,8 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
redis:
condition: service_started
mariadb:
condition: service_started
- redis
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -675,6 +683,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -694,7 +703,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -707,6 +716,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -792,6 +802,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -841,7 +852,7 @@ services:
- ./src:/usr/src/code/src
- ./tests:/usr/src/code/tests
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
@@ -858,6 +869,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -882,7 +894,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- mariadb
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -900,6 +912,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -928,7 +941,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- mariadb
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -947,6 +960,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -968,12 +982,13 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_POOL_ADAPTER
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1001,12 +1016,13 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_POOL_ADAPTER
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1034,12 +1050,13 @@ services:
- ./src:/usr/src/code/src
depends_on:
- redis
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_POOL_ADAPTER
- _APP_OPENSSL_KEY_V1
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1066,7 +1083,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -1077,6 +1094,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1096,7 +1114,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -1107,6 +1125,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1125,7 +1144,7 @@ services:
- ./app:/usr/src/code/app
- ./src:/usr/src/code/src
depends_on:
- ${_APP_DB_HOST:-mariadb}
- ${_APP_DB_HOST:-mongodb}
- redis
environment:
- _APP_ENV
@@ -1136,6 +1155,7 @@ services:
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
@@ -1218,6 +1238,7 @@ services:
start_period: 5s
mariadb:
profiles: ["mariadb"]
image: mariadb:10.11 # fix issues when upgrading using: mysql_upgrade -u root -p
container_name: appwrite-mariadb
<<: *x-logging
@@ -1235,14 +1256,70 @@ services:
- MARIADB_AUTO_UPGRADE=1
command: "mysqld --innodb-flush-method=fsync"
mongodb:
profiles: ["mongodb"]
image: mongo:8.2.5
container_name: appwrite-mongodb
<<: *x-logging
networks:
- appwrite
volumes:
- appwrite-mongodb:/data/db
- appwrite-mongodb-keyfile:/data/keyfile
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
- ./mongo-entrypoint.sh:/mongo-entrypoint.sh:ro
ports:
- "27017:27017"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=${_APP_DB_ROOT_PASS}
- MONGO_INITDB_DATABASE=${_APP_DB_SCHEMA}
- MONGO_INITDB_USERNAME=${_APP_DB_USER}
- MONGO_INITDB_PASSWORD=${_APP_DB_PASS}
entrypoint: ["/bin/bash", "/mongo-entrypoint.sh"]
healthcheck:
test: |
bash -c "
if mongosh -u root -p ${_APP_DB_ROOT_PASS} --authenticationDatabase admin --quiet --eval 'rs.status().ok' 2>/dev/null | grep -q 1; then
exit 0
else
mongosh -u root -p ${_APP_DB_ROOT_PASS} --authenticationDatabase admin --quiet --eval \"
rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'appwrite-mongodb:27017'}]})
\" 2>/dev/null || exit 1
fi
"
interval: 10s
timeout: 10s
retries: 10
start_period: 30s
appwrite-mongo-express:
profiles: ["mongodb"]
image: mongo-express
container_name: appwrite-mongo-express
networks:
- appwrite
ports:
- "8082:8081"
environment:
ME_CONFIG_MONGODB_URL: "mongodb://root:${_APP_DB_ROOT_PASS}@appwrite-mongodb:27017/?replicaSet=rs0&directConnection=true"
ME_CONFIG_BASICAUTH_USERNAME: ${_APP_DB_USER}
ME_CONFIG_BASICAUTH_PASSWORD: ${_APP_DB_PASS}
depends_on:
- mongodb
postgresql:
image: postgres:18
profiles: ["postgresql"]
build:
context: ./tests/resources/postgresql
args:
POSTGRES_VERSION: 17
container_name: appwrite-postgresql
<<: *x-logging
networks:
- appwrite
volumes:
- appwrite-postgresql:/var/lib/postgresql/data:rw
- appwrite-postgresql:/var/lib/postgresql:rw
ports:
- "5432:5432"
environment:
@@ -1252,7 +1329,7 @@ services:
command: "postgres"
redis:
image: redis:7.2.4-alpine
image: redis:7.4.7-alpine
<<: *x-logging
container_name: appwrite-redis
command: >
@@ -1320,7 +1397,7 @@ services:
- MAILDEV_INCOMING_PASS=${_APP_SMTP_PASSWORD}
request-catcher-webhook: # used mainly for dev tests (mock HTTP webhook)
image: appwrite/requestcatcher:1.0.0
image: appwrite/requestcatcher:1.1.0
container_name: appwrite-requestcatcher-webhook
<<: *x-logging
ports:
@@ -1329,7 +1406,7 @@ services:
- appwrite
request-catcher-sms: # used mainly for dev tests (mock SMS auth secret)
image: appwrite/requestcatcher:1.0.0
image: appwrite/requestcatcher:1.1.0
container_name: appwrite-requestcatcher-sms
<<: *x-logging
ports:
@@ -1478,6 +1555,8 @@ configs:
volumes:
appwrite-mariadb:
appwrite-mongodb:
appwrite-mongodb-keyfile:
appwrite-postgresql:
appwrite-redis:
appwrite-cache:
+131
View File
@@ -0,0 +1,131 @@
# Appwrite Web Installer
The Appwrite Web Installer provides a modern, user-friendly web interface for installing Appwrite. It runs in a
temporary Docker container with its own web server before the Appwrite stack is created.
## Architecture
The web installer runs as part of the installation task using a Swoole HTTP server with Utopia PHP routing:
```
docker run (temporary container)
└── Server.php
├── Swoole HTTP server (0.0.0.0:20080)
├── Module / Service / Action routes
├── State (progress tracking)
└── Config (installation settings)
```
## Features
- Retry failed steps with payload validation
- Step-by-step guided installation with real-time validation
- Progress tracking with Server-Sent Events and polling fallback
## Usage
### Docker
```bash
docker run -it --rm \
--name appwrite-installer \
-p 20080:20080 \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:<version>
```
Then open http://localhost:20080 in your browser.
### Composer (Development)
```bash
composer installer:dev # Start web installer in Docker
composer installer:dev-upgrade # Start web installer in upgrade mode
composer installer:clean # Clean up installer containers and temp files
```
### CLI Mode
```bash
docker run -it --rm \
--name appwrite-installer \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:<version> \
--interactive N
```
## Files
### Frontend
- `app/views/install/installer.phtml` - Main layout
- `app/views/install/installer/` - UI components (templates, CSS, JS, icons)
### Backend
- `src/Appwrite/Platform/Installer/**/*.php` - Installer backend (Server, Module, Actions, State, Config)
- `src/Appwrite/Platform/Tasks/Install.php` - Installation task execution
- `app/views/install/*.phtml` - Docker Compose and env templates
## Technical Details
### Endpoints
- `GET /` - Installer UI
- `POST /install` - Start installation (SSE stream or JSON)
- `GET /install/status?installId=...` - Progress polling
- `POST /install/validate` - CSRF validation
- `POST /install/complete` - Notify completion
### URL Parameters
- `?step=1..5` - Jump to specific installation step
### Installation Flow
1. User submits form → CSRF validation
2. Acquire global lock (prevents concurrent installs)
3. Stream progress via SSE (or poll if SSE fails)
4. Generate `docker-compose.yml` and `.env`
5. Run `docker compose up -d`
6. Redirect to console, shutdown server
## Security
- **CSRF**: Cookie tokens with timing-safe comparison
- **CSP**: Strict headers prevent XSS
- **Validation**: Ports (1-65535), emails, domains, env var names
- **Escaping**: All shell commands use `escapeshellarg()`
- **Path protection**: `realpath()` + `str_starts_with()` checks
- **File permissions**: Config files created with mode 0600
- **Global lock**: File-based with exception-safe cleanup
## Troubleshooting
### ERR_EMPTY_RESPONSE
Server binds to `0.0.0.0` (not `localhost`) for Docker port mapping. If `localhost` resolves to IPv6 `::1`, connection
will fail from host.
### Can't access localhost:20080
Ensure `-p 20080:20080` is in docker run command. Try `http://127.0.0.1:20080` instead.
### Installation fails
- Check Docker is running
- Verify write permissions for appwrite directory
- Check browser console for errors
- Review Docker logs: `docker logs appwrite-installer`
## Support
For issues or questions:
- [GitHub Issues](https://github.com/appwrite/appwrite/issues)
- [Discord Community](https://appwrite.io/discord)
- [Documentation](https://appwrite.io/docs)
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
set -e
# Fix keyfile permissions if mounted from volume
KEYFILE_PATH="/data/keyfile/mongo-keyfile"
if [ ! -f "$KEYFILE_PATH" ]; then
echo "Generating random MongoDB keyfile..."
mkdir -p /data/keyfile
openssl rand -base64 756 > "$KEYFILE_PATH"
fi
chmod 400 "$KEYFILE_PATH"
chown mongodb:mongodb "$KEYFILE_PATH" 2>/dev/null || chown 999:999 "$KEYFILE_PATH"
# Use MongoDB's standard entrypoint with our command
exec docker-entrypoint.sh mongod --replSet rs0 --bind_ip_all --auth --keyFile "$KEYFILE_PATH"
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
# MongoDB Replica Set Initialization Script
# Runs after MongoDB starts as part of docker-entrypoint-initdb.d
# Check if replica set is already initialized
RS_STATUS=$(mongosh --username root --password "${MONGO_INITDB_ROOT_PASSWORD}" --authenticationDatabase admin --eval "try { rs.status().ok } catch(e) { 0 }" --quiet 2>/dev/null || echo "0")
if [ "$RS_STATUS" = "1" ]; then
echo "Replica set already initialized"
exit 0
fi
# Initialize replica set
echo "Initializing replica set 'rs0'..."
# For single-node replica set, we can use localhost since clients connect directly
# The MongoDB driver will handle connection to this node
mongosh --username root --password "${MONGO_INITDB_ROOT_PASSWORD}" --authenticationDatabase admin --eval "rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: '127.0.0.1:27017' }] })"
# Wait for replica set to elect a primary and become stable
echo "Waiting for PRIMARY to be ready..."
MAX_WAIT=15
COUNTER=0
while [ $COUNTER -lt $MAX_WAIT ]; do
# Use try/catch to handle cases where rs.status() fails during initialization
PRIMARY_STATE=$(mongosh --username root --password "${MONGO_INITDB_ROOT_PASSWORD}" --authenticationDatabase admin --eval "try { rs.status().members[0].stateStr } catch(e) { 'WAITING' }" --quiet 2>/dev/null || echo "WAITING")
if [ "$PRIMARY_STATE" = "PRIMARY" ]; then
echo "PRIMARY is ready!"
break
fi
# Give it more time between checks
sleep 2
COUNTER=$((COUNTER+1))
# Only show status every few attempts to reduce log noise
if [ $((COUNTER % 3)) -eq 0 ]; then
echo "Still waiting for PRIMARY (attempt $COUNTER/$MAX_WAIT, current state: $PRIMARY_STATE)..."
fi
done
# Don't fail the init even if PRIMARY isn't ready immediately
# MongoDB will continue to elect a primary in the background
# Clients will wait for it to be ready via their connection retry logic
if [ $COUNTER -eq $MAX_WAIT ]; then
echo "NOTE: PRIMARY not confirmed within $((MAX_WAIT * 2)) seconds, but replica set is configured"
echo "MongoDB will continue initializing the replica set in the background"
fi
echo "Replica set initialization complete!"
+18
View File
@@ -0,0 +1,18 @@
// mongo-init.js
// Switch to the admin database
const adminDb = db.getSiblingDB('admin');
// Get username and password from environment variables
const username = process.env.MONGO_INITDB_USERNAME;
const password = process.env.MONGO_INITDB_PASSWORD;
const database = process.env.MONGO_INITDB_DATABASE;
// Create the user
adminDb.createUser({
user: username,
pwd: password,
roles: [
{ role: 'readWrite', db: database }
]
});
+16
View File
@@ -0,0 +1,16 @@
i4Ge9ZbzXgpP4ZLLX/9/pkfhZYlEpSCfhl3Gqr0iwx1UAf4z3egza5J5tjj+S1zl
flopL/FlHaBLQAbY9E6kQyaIFQHJ4Wd6bOkL5hajIizvBBLtKxgpKMPQdvnx6mwe
aeK866TFRx4rWWQs69Gz3nZb822YRmdC4m2H+1rx635/ICWMWv26EdmYayafe010
zKJW/Ty75MpAk9yxc3PFEooDZtmb9PQKkkA4c+P7hfg1HBnrkcqfOejmlwvr/tWE
P8JIQTtcruo8A/5BFq0x0BToLJzY/eOiGcNe1Qf8CO4/8ZKWnvk00FvxXuU1KQ1G
uDlhaCakwitUGEjkKSeIH7V1Qk96JlY8kR5qBhavmROEd/o3VceLfdbbZzd+bitH
PRIocDb06SuWWvJGnwLRoyQmpeXu8AEd5YD+yimhGMQqzCfRFhxlT9rIJbWc8Z+Y
M8uDgd3bHaVfQCQDxbOgo9xB0zqOx77HUBXqeU4xqMeiOkKJxDrt6Cz0osQyybZO
NL9lsJ2y+2S6RyUWNMWJTrVGhgKnse/Z0dgrHpShBMI02G/Q8MKTDXyJmeX1PToe
CCdDmVMKhQRkrvZqeNTvOiNGb/hUDqU/Px/lCmhZYzIKsOK7nhaH6U5FiIAzxeNi
g03gwyrwRfmJWRyTcTSuQKIprBoobl2xJG2CYjdc2UhtY2I3bSlOue1DOKYnOFjA
x58DNwUQdegadSsyd2IPlWpUGIY1GJjTV+J9vEf79TQtnzYSFH5lmg3J08Cq64wg
UAedRHUEnRHFlVfg4ZdkGTGL/2Q7l2Dk0jJQCFFq+tEFGncLgGlAJaWXkczaFaZy
r9h12ulCUq6trZ1RGS1DlDxwQU2J6bSz0ZFwux/3W0YyIQyq4rWcoDjEG98DSE5n
P3Qht2DsBjFkh55nfC0EgwXwnWzBTJiJo1GYf5RdEIVCmmWxmAfTfPYaKWOVcgGG
6QGX5TCPyI6+SZUT/qOfGxnIE/1R3N1wD+J1rORXwWucLOiR
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@appwrite.io/repo",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@appwrite.io/repo",
"version": "1.0.0",
"license": "ISC"
}
}
}
+16 -1
View File
@@ -8,5 +8,20 @@
"files": [
"docs/examples",
"app/config/specs"
]
],
"version": "1.0.0",
"description": "> We just announced Timestamp Overrides for Appwrite Databases - [Learn more](https://appwrite.io/blog/post/announcing-timestamp-overrides)",
"main": "index.js",
"directories": {
"doc": "docs",
"test": "tests"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"bugs": {
"url": "https://github.com/appwrite/appwrite/issues"
},
"homepage": "https://github.com/appwrite/appwrite#readme"
}
+6 -6
View File
@@ -1,15 +1,15 @@
<phpunit backupGlobals="false"
backupStaticAttributes="false"
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
bootstrap="app/init.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
cacheDirectory=".phpunit.cache"
>
<extensions>
<extension class="Appwrite\Tests\TestHook" />
<bootstrap class="Appwrite\Tests\TestHook" />
</extensions>
<testsuites>
<testsuite name="unit">
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64" viewBox="0 0 45.025 44.217"><defs><clipPath id="A"><use xlink:href="#B"/></clipPath><path id="B" d="M0 0h191.356v57.344H0z"/></defs><path clip-path="url(#A)" d="M75.198 5.328c-1.872.047-2.977.863-3.34 2.42.48.418 1.126.6 1.77.572 1.415-.06 2.817-1.138 2.42-2.965-.298-.025-.582-.035-.85-.027M84.84 0h-.167c-1.335.043-1.542.767-4.425 1.477-2.912.717-5.725.028-8.86 1.344C62.025 6.748 60.03 20.293 51.52 25.1c-6.36 3.593-12.512 5.188-18.28 6.995-3.792 1.188-7.552 2.556-10.988 5.516-2.667 2.3-3.4 4.085-6.177 6.97-2.835 2.933-11.553-2.258-15.8 1.54a.84.84 0 0 0 .014 1.253c.92.805 2.67 2.722 4.336 3.314-.528 1-3.513 3.946-2.904 5.42.64 1.55 8.04.497 14.88-3.633 3.185-1.924 5.723-4.696 10.685-5.357 6.42-.855 13.817.55 21.25 1.62-1.103 3.286-3.315 5.473-5.088 8.1-.55.592 1.103.658 2.986.3 3.4-.838 5.832-1.513 8.4-3 3.143-1.83 3.62-6.52 7.474-7.534 1.864 2.865 6.5 3.83 10.074 2.3.198-.084.392-.177.582-.275.43-.375.178-.813-.086-1.135a6.21 6.21 0 0 1-.362-.364c-2.012-2.162-2.472-7.266-1.58-9.748 1.017-2.824 2.022-7.343 3.046-11.075 1.1-4 1.506-9.063 2.837-11.106 2.002-3.072 4.215-4.127 6.136-5.86s3.68-3.42 3.62-7.384C86.547.734 85.946.03 84.84 0m.204 4.163C84.647 6.897 82.9 8.4 80.836 9.85c-1.8 1.27-3.794 2.493-5.07 4.477-1.305 2.03-2.134 8.985-4.16 15.852-1.68 5.698-4.184 11.335-8.467 14.05-.278.176-.645.015-.704-.3-.3-1.592-.24-4.5-.734-3.56-.62 1.77-1.322 3.458-2.143 5.027-2.52 4.816-6.166 8.505-12.057 9.95a.53.53 0 0 1-.552-.82c2.718-3.77 5.15-7.825 5.447-14.014.025-.534-.646-.778-.983-.364-1.284 1.583-1.6 5.347-3.477 6.506-1.474.16-2.967.16-4.47.07-6.17-.37-12.502-2.226-18.274-.373-3.93 1.262-8.057 4.85-11.386 6.293C9.894 54.33 8.04 55.93 3.1 55.82c-.505-.68 2.062-3.623 2.934-4.893.278-.407-.317-.835-.874-1.1-1.338-.614-2.68-2.28-4.107-2.93.183-.337.83-.674 1.187-.88 3.24-1.88 11.832 2.124 14.14-.143 1.425-1.398 2.385-2.626 3.353-4.05.94-1.38 2.368-2.838 3.847-4.047a31.3 31.3 0 0 1 1.94-1.435c2.52-1.724 3.907-1.852 7.17-3.064 4.152-1.544 9.293-2.898 13.747-4.6 2.752-1.053 5.744-2.35 8.183-4.17.58-.432 1.127-.893 1.634-1.386 6.964-6.8 8.345-18.766 19.2-19.882 1.314-.135 2.248-.192 3.228-.223 1.096-.03 2.18-.3 3.263-.818.334-.146 2.324-1.35 2.996-.768.448.388.115 2.492.086 2.72" transform="matrix(.52012 0 0 .52012 0 7.19564)" fill="#444b5e"/></svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 32 32"><path d="M15.9.087l.854 1.604c.192.296.4.558.645.802.715.715 1.394 1.464 2.004 2.266 1.447 1.9 2.423 4.01 3.12 6.292.418 1.394.645 2.824.662 4.27.07 4.323-1.412 8.035-4.4 11.12-.488.488-1.01.94-1.57 1.342-.296 0-.436-.227-.558-.436-.227-.383-.366-.82-.436-1.255-.105-.523-.174-1.046-.14-1.586v-.244C16.057 24.21 15.796.21 15.9.087z" fill="#599636"/><path d="M15.9.034c-.035-.07-.07-.017-.105.017.017.35-.105.662-.296.96-.21.296-.488.523-.767.767-1.55 1.342-2.77 2.963-3.747 4.776-1.3 2.44-1.97 5.055-2.16 7.808-.087.993.314 4.497.627 5.508.854 2.684 2.388 4.933 4.375 6.885.488.47 1.01.906 1.55 1.325.157 0 .174-.14.21-.244a4.78 4.78 0 0 0 .157-.68l.35-2.614L15.9.034z" fill="#6cac48"/><path d="M16.754 28.845c.035-.4.227-.732.436-1.063-.21-.087-.366-.26-.488-.453-.105-.174-.192-.383-.26-.575-.244-.732-.296-1.5-.366-2.248v-.453c-.087.07-.105.662-.105.75a17.37 17.37 0 0 1-.314 2.353c-.052.314-.087.627-.28.906 0 .035 0 .07.017.122.314.924.4 1.865.453 2.824v.35c0 .418-.017.33.33.47.14.052.296.07.436.174.105 0 .122-.087.122-.157l-.052-.575v-1.604c-.017-.28.035-.558.07-.82z" fill="#c2bfbf"/></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+66 -8
View File
@@ -518,10 +518,11 @@ class Event
*
* @param string $pattern
* @param array $params
* @param ?Document $database
* @return array
* @throws \InvalidArgumentException
*/
public static function generateEvents(string $pattern, array $params = []): array
public static function generateEvents(string $pattern, array $params = [], ?Document $database = null): array
{
// $params = \array_filter($params, fn($param) => !\is_array($param));
$paramKeys = \array_keys($params);
@@ -530,6 +531,12 @@ class Event
$patterns = [];
$parsed = self::parseEventPattern($pattern);
// to switch the resource types from databases to the required prefix
// eg; all databases events get fired with databases. prefix which mainly depicts legacy type
// so a projection from databases to the actual prefix
if ((str_contains($pattern, 'databases.') && $database && $database->getAttribute('type') !== 'legacy')) {
$parsed = self::getDatabaseTypeEvents($database, $parsed);
}
$type = $parsed['type'];
$resource = $parsed['resource'];
$subType = $parsed['subType'];
@@ -630,8 +637,8 @@ class Event
$eventValues = \array_values($events);
/**
* Return a combined list of table, collection events.
*/
* Return a combined list of table, collection events and if tablesdb present then include all for backward compatibility
*/
return Event::mirrorCollectionEvents($pattern, $eventValues[0], $eventValues);
}
@@ -671,16 +678,41 @@ class Event
'attributes' => 'columns',
];
$databasesEventMap = [
'tablesdb' => 'databases',
'tables' => 'collections',
'rows' => 'documents',
'columns' => 'attributes'
];
if (
str_contains($pattern, 'databases.') &&
str_contains($firstEvent, 'collections')
(
str_contains($pattern, 'databases.') &&
str_contains($firstEvent, 'collections')
) ||
(
str_contains($firstEvent, 'tablesdb.')
)
) {
$pairedEvents = [];
foreach ($events as $event) {
$pairedEvents[] = $event;
if (str_contains($event, 'collections')) {
// tablesdb needs databases event with tables and collections
if (str_contains($event, 'tablesdb')) {
$databasesSideEvent = str_replace(
array_keys($databasesEventMap),
array_values($databasesEventMap),
$event
);
$pairedEvents[] = $databasesSideEvent;
$tableSideEvent = str_replace(
array_keys($tableEventMap),
array_values($tableEventMap),
$databasesSideEvent
);
$pairedEvents[] = $tableSideEvent;
} elseif (str_contains($event, 'collections')) {
$tableSideEvent = str_replace(
array_keys($tableEventMap),
array_values($tableEventMap),
@@ -692,8 +724,34 @@ class Event
$events = $pairedEvents;
}
// mirrored events can have duplicates in case of smaller events
// array unique can turns list to hasmap in case duplicates present
// so forcing array value will turn this to array list always
return array_values(array_unique($events));
}
return $events;
/**
* Maps event terminology based on database type
*/
private static function getDatabaseTypeEvents(Document $database, array $event): array
{
$eventMap = [];
switch ($database->getAttribute('type')) {
case 'tablesdb':
$eventMap = [
'databases' => 'tablesdb',
'documents' => 'rows',
'collections' => 'tables',
'attributes' => 'columns',
];
break;
}
foreach ($event as $eventKey => $eventValue) {
if (isset($eventMap[$eventValue])) {
$event[$eventKey] = $eventMap[$eventValue];
}
}
return $event;
}
/**
+1 -1
View File
@@ -72,7 +72,7 @@ class Realtime extends Event
return false;
}
$allEvents = Event::generateEvents($this->getEvent(), $this->getParams());
$allEvents = Event::generateEvents($this->getEvent(), $this->getParams(), $this->getContext('database'));
$payload = new Document($this->getPayload());
+3
View File
@@ -55,6 +55,7 @@ class Exception extends \Exception
public const string GENERAL_CURSOR_NOT_FOUND = 'general_cursor_not_found';
public const string GENERAL_SERVER_ERROR = 'general_server_error';
public const string GENERAL_PROTOCOL_UNSUPPORTED = 'general_protocol_unsupported';
public const string GENERAL_FEATURE_UNSUPPORTED = 'general_feature_unsupported';
public const string GENERAL_CODES_DISABLED = 'general_codes_disabled';
public const string GENERAL_USAGE_DISABLED = 'general_usage_disabled';
public const string GENERAL_NOT_IMPLEMENTED = 'general_not_implemented';
@@ -165,6 +166,7 @@ class Exception extends \Exception
/** Sites */
public const string SITE_NOT_FOUND = 'site_not_found';
public const string SITE_ALREADY_EXISTS = 'site_already_exists';
public const string SITE_TEMPLATE_NOT_FOUND = 'site_template_not_found';
/** Functions */
@@ -364,6 +366,7 @@ class Exception extends \Exception
/** Message */
public const string MESSAGE_NOT_FOUND = 'message_not_found';
public const string MESSAGE_ALREADY_EXISTS = 'message_already_exists';
public const string MESSAGE_MISSING_TARGET = 'message_missing_target';
public const string MESSAGE_ALREADY_SENT = 'message_already_sent';
public const string MESSAGE_ALREADY_PROCESSING = 'message_already_processing';
+2 -1
View File
@@ -59,7 +59,8 @@ class Mapper
'none' => Types::json(),
'any' => Types::json(),
'array' => Types::json(),
'enum' => Type::string()
'enum' => Type::string(),
'id' => Type::string()
];
foreach ($defaults as $type => $default) {
+60 -7
View File
@@ -491,6 +491,7 @@ class Realtime extends MessagingAdapter
$roles = [Role::team(ID::custom($parts[1]))->toString()];
break;
case 'databases':
case 'tablesdb':
$resource = $parts[4] ?? '';
if (in_array($resource, ['columns', 'attributes', 'indexes'])) {
$channels[] = 'console';
@@ -508,14 +509,14 @@ class Realtime extends MessagingAdapter
$tableId = $payload->getAttribute('$tableId', '');
$collectionId = $payload->getAttribute('$collectionId', '');
$resourceId = $tableId ?: $collectionId;
$channels = [];
$channels[] = 'rows';
$channels[] = 'databases.' . $database->getId() . '.tables.' . $resourceId . '.rows';
$channels[] = 'databases.' . $database->getId() . '.tables.' . $resourceId . '.rows.' . $payload->getId();
$channels[] = 'documents';
$channels[] = 'databases.' . $database->getId() . '.collections.' . $resourceId . '.documents';
$channels[] = 'databases.' . $database->getId() . '.collections.' . $resourceId . '.documents.' . $payload->getId();
// sending legacy + tablesdb events to both legacy and tablesdb
$channels = array_values(array_unique(array_merge(
self::getDatabaseChannels('legacy', $database->getId(), $resourceId, $payload->getId(), 'databases'),
self::getDatabaseChannels('tablesdb', $database->getId(), $resourceId, $payload->getId(), 'databases'),
self::getDatabaseChannels('tablesdb', $database->getId(), $resourceId, $payload->getId())
)));
$roles = $collection->getAttribute('documentSecurity', false)
? \array_merge($collection->getRead(), $payload->getRead())
@@ -572,4 +573,56 @@ class Realtime extends MessagingAdapter
'projectId' => $projectId
];
}
/**
* Generate realtime channels for database events
*
* @param string $type The database API type
* @param string $databaseId The database ID
* @param string $resourceId The collection/table ID
* @param string $payloadId The document/row ID
* @param string $prefixOverride Override the channel prefix when different API types share the same terminology but need different prefixes
* @return array Array of channel names
*/
private static function getDatabaseChannels(
string $type = 'databases',
string $databaseId = '',
string $resourceId = '',
string $payloadId = '',
string $prefixOverride = '',
): array {
$basePrefix = $prefixOverride ?: $type;
if (!$databaseId || !$resourceId || !$payloadId) {
return [];
}
$channels = [];
switch ($type) {
case 'legacy':
if (empty($prefixOverride)) {
$basePrefix = 'databases';
}
$channels[] = 'documents';
$channels[] = "{$basePrefix}.{$databaseId}.collections.{$resourceId}.documents";
$channels[] = "{$basePrefix}.{$databaseId}.collections.{$resourceId}.documents.{$payloadId}";
break;
case 'tablesdb':
$channels[] = 'rows';
$channels[] = "{$basePrefix}.{$databaseId}.tables.{$resourceId}.rows";
$channels[] = "{$basePrefix}.{$databaseId}.tables.{$resourceId}.rows.{$payloadId}";
break;
default:
$basePrefix = 'databases';
$channels[] = 'documents';
$channels[] = "{$basePrefix}.{$databaseId}.collections.{$resourceId}.documents";
$channels[] = "{$basePrefix}.{$databaseId}.collections.{$resourceId}.documents.{$payloadId}";
break;
}
return $channels;
}
}
+2
View File
@@ -13,6 +13,7 @@ use Appwrite\Platform\Modules\Projects;
use Appwrite\Platform\Modules\Proxy;
use Appwrite\Platform\Modules\Sites;
use Appwrite\Platform\Modules\Storage;
use Appwrite\Platform\Modules\Teams;
use Appwrite\Platform\Modules\Tokens;
use Appwrite\Platform\Modules\VCS;
use Utopia\Platform\Platform;
@@ -31,6 +32,7 @@ class Appwrite extends Platform
$this->addModule(new Sites\Module());
$this->addModule(new Console\Module());
$this->addModule(new Proxy\Module());
$this->addModule(new Teams\Module());
$this->addModule(new Tokens\Module());
$this->addModule(new Storage\Module());
$this->addModule(new VCS\Module());
@@ -0,0 +1,42 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Platform\Installer\Server;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
class Cleanup extends Action
{
public static function getName(): string
{
return 'installerCleanup';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/install/cleanup')
->desc('Cleanup installer container')
->inject('request')
->inject('response')
->callback($this->action(...));
}
public function action(Request $request, Response $response): void
{
if (!Validate::validateCsrf($request)) {
$response->setStatusCode(Response::STATUS_CODE_BAD_REQUEST);
$response->json(['success' => false, 'message' => 'Invalid CSRF token']);
return;
}
// Remove the installer container
$container = escapeshellarg(Server::DEFAULT_CONTAINER);
@exec("docker rm -f $container >/dev/null 2>&1");
$response->json(['success' => true]);
}
}
@@ -0,0 +1,72 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Platform\Installer\Runtime\State;
use Appwrite\Platform\Installer\Server;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
use Utopia\Validator\Text;
class Complete extends Action
{
public static function getName(): string
{
return 'installerComplete';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/install/complete')
->desc('Complete installation')
->param('installId', '', new Text(64, 0), 'Installation ID', true)
->param('sessionId', '', new Text(256, 0), 'Session ID', true)
->param('sessionSecret', '', new Text(256, 0), 'Session secret', true)
->param('sessionExpire', '', new Text(64, 0), 'Session expiry timestamp', true)
->inject('request')
->inject('response')
->inject('installerState')
->callback($this->action(...));
}
public function action(string $installId, string $sessionId, string $sessionSecret, string $sessionExpire, Request $request, Response $response, State $state): void
{
if (!Validate::validateCsrf($request)) {
$response->setStatusCode(Response::STATUS_CODE_BAD_REQUEST);
$response->json(['success' => false, 'message' => 'Invalid CSRF token']);
return;
}
$installId = $state->sanitizeInstallId($installId);
if ($installId !== '') {
$state->updateGlobalLock($installId, Server::STATUS_COMPLETED);
}
@touch(Server::INSTALLER_COMPLETE_FILE);
if ($sessionSecret) {
$isHttps = $request->getProtocol() === 'https';
$sameSite = $isHttps ? Response::COOKIE_SAMESITE_NONE : Response::COOKIE_SAMESITE_LAX;
$expires = 0;
if ($sessionExpire) {
$timestamp = strtotime($sessionExpire);
if ($timestamp !== false) {
$expires = $timestamp;
}
}
$response->addCookie('a_session_console', $sessionSecret, $expires, '/', '', $isHttps, true, $sameSite);
$response->addCookie('a_session_console_legacy', $sessionSecret, $expires, '/', '', $isHttps, true, $sameSite);
if ($sessionId) {
$response->addHeader('X-Appwrite-Session', $sessionId);
}
}
@unlink(Server::INSTALLER_CONFIG_FILE);
$response->json(['success' => true]);
}
}
@@ -0,0 +1,37 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
class Error extends Action
{
public static function getName(): string
{
return 'installerError';
}
public function __construct()
{
$this
->setType(Action::TYPE_ERROR)
->inject('error')
->inject('response')
->callback($this->action(...));
}
public function action(\Throwable $error, Response $response): void
{
if ($response->isSent()) {
return;
}
$code = $error->getCode();
if ($code < 100 || $code > 599) {
$code = 500;
}
$response->setStatusCode($code);
$message = $code >= 500 ? 'Internal installer error' : $error->getMessage();
$response->json(['success' => false, 'message' => $message]);
}
}
@@ -0,0 +1,393 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Auth\Validator\Password;
use Appwrite\Platform\Installer\Runtime\Config;
use Appwrite\Platform\Installer\Runtime\State;
use Appwrite\Platform\Installer\Server;
use Appwrite\Platform\Installer\Validator\AppDomain;
use Swoole\Http\Response as SwooleResponse;
use Utopia\Emails\Validator\Email;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
use Utopia\Validator\Nullable;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
class Install extends Action
{
private const int SSE_KEEPALIVE_DELAY_MICROSECONDS = 500000;
public static function getName(): string
{
return 'installerInstall';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/install')
->desc('Run installation')
->param('appDomain', '', new AppDomain(), 'Application domain (hostname, IP, or bracket IPv6 with optional port)')
->param('httpPort', 80, new Range(1, 65535), 'HTTP port')
->param('httpsPort', 443, new Range(1, 65535), 'HTTPS port')
->param('emailCertificates', '', new Email(), 'Email for SSL certificates')
->param('opensslKey', '', new Text(64, 1), 'Secret API key')
->param('assistantOpenAIKey', '', new Text(256, 0), 'OpenAI API key for assistant', true)
->param('accountEmail', '', new Email(allowEmpty: true), 'Account email address', true)
->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)
->inject('request')
->inject('response')
->inject('swooleResponse')
->inject('installerState')
->inject('installerConfig')
->inject('installerPaths')
->callback($this->action(...));
}
public function action(
string $appDomain,
int $httpPort,
int $httpsPort,
string $emailCertificates,
string $opensslKey,
string $assistantOpenAIKey,
string $accountEmail,
string $accountPassword,
string $database,
string $installId,
?string $retryStep,
Request $request,
Response $response,
SwooleResponse $swooleResponse,
State $state,
Config $config,
array $paths
): void {
$acceptHeader = $request->getHeader('accept');
$wantsStream = stripos($acceptHeader, 'text/event-stream') !== false;
if ($wantsStream) {
$swooleResponse->header('Content-Type', 'text/event-stream');
$swooleResponse->header('Cache-Control', 'no-cache');
$swooleResponse->header('Connection', 'keep-alive');
$swooleResponse->header('X-Accel-Buffering', 'no');
$swooleResponse->write("event: ping\ndata: {\"time\":" . time() . "}\n\n");
}
if (!Validate::validateCsrf($request)) {
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Invalid CSRF token');
return;
}
$appDomain = trim($appDomain);
$emailCertificates = trim($emailCertificates);
$opensslKey = trim($opensslKey);
$assistantOpenAIKey = trim($assistantOpenAIKey);
$account = [];
if (!$config->isUpgrade()) {
$accountEmail = trim($accountEmail);
if ($accountEmail === '' || !$state->isValidEmailAddress($accountEmail)) {
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Please enter a valid email address', Server::STEP_ACCOUNT_SETUP);
return;
}
if (!$state->isValidPassword($accountPassword)) {
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Password must be at least 8 characters', Server::STEP_ACCOUNT_SETUP);
return;
}
$accountName = $this->deriveNameFromEmail($accountEmail);
$account = [
'name' => $accountName,
'email' => $accountEmail,
'password' => $accountPassword,
];
}
$lockedDatabase = $config->getLockedDatabase();
if (!$lockedDatabase) {
$database = strtolower(trim($database));
if (!$state->isValidDatabaseAdapter($database)) {
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Please select a supported database');
return;
}
}
$installId = $state->sanitizeInstallId($installId);
if ($installId === '') {
$installId = bin2hex(random_bytes(8));
}
@unlink(Server::INSTALLER_COMPLETE_FILE);
try {
$lockResult = $state->reserveGlobalLock($installId);
} catch (\Throwable $e) {
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, Server::STATUS_ERROR, ['message' => 'Lock failed: ' . $e->getMessage()]);
$swooleResponse->end();
} else {
$response->setStatusCode(Response::STATUS_CODE_INTERNAL_SERVER_ERROR);
$response->json(['success' => false, 'message' => 'Lock failed: ' . $e->getMessage()]);
}
return;
}
if ($lockResult !== 'ok') {
$lockMessage = $lockResult === 'locked'
? 'Installation already in progress'
: 'Installer lock unavailable';
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, Server::STATUS_ERROR, ['message' => $lockMessage]);
$swooleResponse->end();
} else {
$statusCode = $lockResult === 'locked'
? Response::STATUS_CODE_CONFLICT
: Response::STATUS_CODE_SERVICE_UNAVAILABLE;
$response->setStatusCode($statusCode);
$response->json(['success' => false, 'message' => $lockMessage]);
}
return;
}
$existingPath = $state->progressFilePath($installId);
$existing = null;
if (file_exists($existingPath)) {
$existing = $state->readProgressFile($installId);
if (!empty($existing['steps']) && $retryStep === null) {
$state->updateGlobalLock($installId, Server::STATUS_ERROR);
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, Server::STATUS_ERROR, ['message' => 'Installation already started']);
$swooleResponse->end();
} else {
$response->setStatusCode(Response::STATUS_CODE_CONFLICT);
$response->json(['success' => false, 'message' => 'Installation already started']);
}
return;
}
}
try {
$state->ensureBootstrapped();
$installer = new \Appwrite\Platform\Tasks\Install();
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, 'install-id', ['installId' => $installId]);
}
$state->updateGlobalLock($installId, Server::STATUS_IN_PROGRESS);
$payloadInput = [
'_APP_ENV' => 'production',
'_APP_OPENSSL_KEY_V1' => $opensslKey,
'_APP_DOMAIN' => $appDomain ?: 'localhost',
'_APP_DOMAIN_TARGET' => $appDomain ?: 'localhost',
'_APP_EMAIL_CERTIFICATES' => $emailCertificates,
'_APP_DB_ADAPTER' => $lockedDatabase ?? ($database ?: 'mongodb'),
'_APP_ASSISTANT_OPENAI_API_KEY' => $assistantOpenAIKey,
];
if ($this->hasPayload($existing)) {
$stored = $existing['payload'];
$inputValues = [
'httpPort' => (string) $httpPort,
'httpsPort' => (string) $httpsPort,
'database' => $database,
'appDomain' => $appDomain,
'emailCertificates' => $emailCertificates,
];
foreach ($inputValues as $field => $inputValue) {
if (isset($stored[$field]) && $inputValue !== '') {
$storedValue = (string) $stored[$field];
if (in_array($field, ['httpPort', 'httpsPort'], true)) {
$storedValue = trim($storedValue);
$inputValue = trim($inputValue);
}
if ($storedValue !== $inputValue) {
if ($installId !== '') {
$state->updateGlobalLock($installId, Server::STATUS_ERROR);
}
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Installation payload mismatch');
return;
}
}
}
$sensitiveFields = [
'opensslKey' => ['hash' => 'opensslKeyHash', 'value' => $opensslKey],
'assistantOpenAIKey' => ['hash' => 'assistantOpenAIKeyHash', 'value' => $assistantOpenAIKey],
];
foreach ($sensitiveFields as $field => $info) {
$hashField = $info['hash'];
$incomingValue = $info['value'];
if (!isset($stored[$hashField]) && !isset($stored[$field])) {
continue;
}
$incomingHash = $state->hashSensitiveValue($incomingValue);
if (isset($stored[$hashField])) {
if (!hash_equals((string) $stored[$hashField], $incomingHash)) {
if ($installId !== '') {
$state->updateGlobalLock($installId, Server::STATUS_ERROR);
}
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Installation payload mismatch');
return;
}
} elseif (isset($stored[$field]) && $incomingValue !== '' && (string) $stored[$field] !== $incomingValue) {
if ($installId !== '') {
$state->updateGlobalLock($installId, Server::STATUS_ERROR);
}
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Installation payload mismatch');
return;
}
}
$payloadInput['_APP_DOMAIN'] = $stored['appDomain'] ?? $payloadInput['_APP_DOMAIN'];
$payloadInput['_APP_DOMAIN_TARGET'] = $stored['appDomain'] ?? $payloadInput['_APP_DOMAIN_TARGET'];
$payloadInput['_APP_EMAIL_CERTIFICATES'] = $stored['emailCertificates'] ?? $payloadInput['_APP_EMAIL_CERTIFICATES'];
$payloadInput['_APP_DB_ADAPTER'] = $lockedDatabase ?? ($stored['database'] ?? $payloadInput['_APP_DB_ADAPTER']);
$httpPort = (int) ($stored['httpPort'] ?? $httpPort ?: $config->getDefaultHttpPort());
$httpsPort = (int) ($stored['httpsPort'] ?? $httpsPort ?: $config->getDefaultHttpsPort());
}
$vars = $config->getVars();
$shouldGenerateSecrets = !$installer->hasExistingConfig() && !$config->isUpgrade();
$envVars = $installer->prepareEnvironmentVariables($payloadInput, $vars, $shouldGenerateSecrets);
$state->writeProgressFile($installId, [
'payload' => [
'httpPort' => $httpPort ?: $config->getDefaultHttpPort(),
'httpsPort' => $httpsPort ?: $config->getDefaultHttpsPort(),
'database' => $lockedDatabase ?? ($database ?: 'mongodb'),
'appDomain' => $appDomain ?: 'localhost',
'emailCertificates' => $emailCertificates,
'opensslKeyHash' => $state->hashSensitiveValue($opensslKey),
'assistantOpenAIKeyHash' => $state->hashSensitiveValue($assistantOpenAIKey),
],
'step' => 'start',
'status' => Server::STATUS_IN_PROGRESS,
'message' => 'Installation started',
'updatedAt' => time(),
]);
$progress = function (string $step, string $status, string $message, array $details = []) use ($installId, $wantsStream, $swooleResponse, $state) {
$payload = [
'installId' => $installId,
'step' => $step,
'status' => $status,
'message' => $message,
'updatedAt' => time(),
];
if (!empty($details)) {
$payload['details'] = $details;
}
$state->writeProgressFile($installId, $payload);
$state->updateGlobalLock($installId, Server::STATUS_IN_PROGRESS);
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, 'progress', $payload);
}
};
$installer->performInstallation(
$httpPort ?: $config->getDefaultHttpPort(),
$httpsPort ?: $config->getDefaultHttpsPort(),
$config->getOrganization(),
$config->getImage(),
$envVars,
$config->getNoStart(),
$progress,
$retryStep,
$config->isUpgrade(),
$account
);
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, 'done', ['installId' => $installId, 'success' => true]);
usleep(self::SSE_KEEPALIVE_DELAY_MICROSECONDS);
$swooleResponse->write(": keepalive\n\n");
usleep(self::SSE_KEEPALIVE_DELAY_MICROSECONDS);
$swooleResponse->end();
} else {
$response->json([
'success' => true,
'installId' => $installId,
'message' => 'Installation completed successfully',
]);
}
$state->updateGlobalLock($installId, Server::STATUS_COMPLETED);
} catch (\Throwable $e) {
$this->handleInstallationError($e, $installId, $wantsStream, $response, $swooleResponse, $state);
}
}
private function writeSseEvent(SwooleResponse $swooleResponse, string $event, array $payload): void
{
$swooleResponse->write("event: $event\ndata: " . json_encode($payload) . "\n\n");
}
private function sendBadRequest(Response $response, SwooleResponse $swooleResponse, bool $wantsStream, string $message, string $step = Server::STEP_CONFIG_FILES): void
{
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, Server::STATUS_ERROR, ['message' => $message, 'step' => $step]);
$swooleResponse->end();
} else {
$response->setStatusCode(Response::STATUS_CODE_BAD_REQUEST);
$response->json(['success' => false, 'message' => $message]);
}
}
private function handleInstallationError(\Throwable $e, string $installId, bool $wantsStream, Response $response, SwooleResponse $swooleResponse, State $state): void
{
if ($installId !== '') {
$state->writeProgressFile($installId, [
'step' => Server::STATUS_ERROR,
'status' => Server::STATUS_ERROR,
'message' => $e->getMessage(),
'details' => $this->buildErrorDetails($e),
'updatedAt' => time(),
]);
$state->updateGlobalLock($installId, Server::STATUS_ERROR);
}
@unlink(Server::INSTALLER_CONFIG_FILE);
if ($wantsStream) {
$this->writeSseEvent($swooleResponse, Server::STATUS_ERROR, [
'message' => $e->getMessage(),
'details' => $this->buildErrorDetails($e)
]);
$swooleResponse->end();
} else {
$response->setStatusCode(Response::STATUS_CODE_INTERNAL_SERVER_ERROR);
$response->json(['success' => false, 'message' => $e->getMessage()]);
}
}
private function buildErrorDetails(\Throwable $e): array
{
return [];
}
private function hasPayload(mixed $data): bool
{
return is_array($data) && isset($data['payload']) && is_array($data['payload']);
}
private function deriveNameFromEmail(string $email): string
{
$parts = explode('@', $email);
$username = $parts[0] ?? '';
$cleaned = preg_replace('/[^a-zA-Z0-9]/', '', $username);
return ucfirst($cleaned);
}
}
@@ -0,0 +1,40 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Swoole\Http\Server as SwooleServer;
use Swoole\Timer;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
class Shutdown extends Action
{
private const int SHUTDOWN_DELAY_SECONDS = 2;
public static function getName(): string
{
return 'installerShutdown';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/install/shutdown')
->desc('Shutdown installer server')
->inject('response')
->inject('swooleServer')
->callback($this->action(...));
}
public function action(Response $response, ?SwooleServer $swooleServer): void
{
$response->json(['success' => true]);
if ($swooleServer) {
Timer::after(self::SHUTDOWN_DELAY_SECONDS * 1000, function () use ($swooleServer) {
$swooleServer->shutdown();
});
}
}
}
@@ -0,0 +1,56 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Platform\Installer\Runtime\State;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
use Utopia\Validator\Text;
class Status extends Action
{
public static function getName(): string
{
return 'installerStatus';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/install/status')
->desc('Poll installation progress')
->param('installId', '', new Text(64, 0), 'Installation ID', true)
->inject('response')
->inject('installerState')
->callback($this->action(...));
}
public function action(string $installId, Response $response, State $state): void
{
$installId = $state->sanitizeInstallId($installId);
if ($installId === '') {
$response->setStatusCode(Response::STATUS_CODE_BAD_REQUEST);
$response->json(['success' => false, 'message' => 'Missing installId']);
return;
}
$path = $state->progressFilePath($installId);
if (!file_exists($path)) {
$response->setStatusCode(Response::STATUS_CODE_NOT_FOUND);
$response->json(['success' => false, 'message' => 'Install not found']);
return;
}
$data = $state->readProgressFile($installId);
if (is_array($data) && isset($data['payload']) && is_array($data['payload'])) {
unset(
$data['payload']['opensslKey'],
$data['payload']['assistantOpenAIKey'],
$data['payload']['opensslKeyHash'],
$data['payload']['assistantOpenAIKeyHash'],
);
}
$response->json(['success' => true, 'progress' => $data]);
}
}
@@ -0,0 +1,45 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Platform\Installer\Server;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
class Validate extends Action
{
public static function getName(): string
{
return 'installerValidate';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/install/validate')
->desc('Validate CSRF token')
->inject('request')
->inject('response')
->callback($this->action(...));
}
public function action(Request $request, Response $response): void
{
if (!self::validateCsrf($request)) {
$response->setStatusCode(Response::STATUS_CODE_BAD_REQUEST);
$response->json(['success' => false, 'message' => 'Invalid CSRF token']);
return;
}
$response->json(['success' => true]);
}
public static function validateCsrf(Request $request): bool
{
$cookie = $request->getCookie(Server::CSRF_COOKIE);
$header = $request->getHeader('x-appwrite-installer-csrf');
return $cookie !== '' && $header !== '' && hash_equals($cookie, $header);
}
}
@@ -0,0 +1,90 @@
<?php
namespace Appwrite\Platform\Installer\Http\Installer;
use Appwrite\Platform\Installer\Runtime\Config;
use Appwrite\Platform\Installer\Server;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Platform\Action;
use Utopia\Validator\Integer;
use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
class View extends Action
{
public static function getName(): string
{
return 'installerView';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/')
->desc('Serve installer UI')
->param('step', 1, new Integer(true), 'Step number (1-5)', true)
->param('partial', null, new Nullable(new Text(1, 0)), 'Render partial step only', true)
->inject('request')
->inject('response')
->inject('installerConfig')
->inject('installerPaths')
->callback($this->action(...));
}
public function action(int $step, ?string $partial, Request $request, Response $response, Config $config, array $paths): void
{
$csrfToken = $this->makeCsrf($request, $response);
$response->addHeader('Content-Security-Policy', implode('; ', Server::INSTALLER_CSP));
$vars = $config->getVars();
$defaultHttpPort = $config->getDefaultHttpPort();
$defaultHttpsPort = $config->getDefaultHttpsPort();
$isUpgrade = $config->isUpgrade();
$lockedDatabase = $config->getLockedDatabase();
$isLocalInstall = $config->isLocal();
$defaultEmailCertificates = $vars['_APP_EMAIL_CERTIFICATES']['default'] ?? '';
if ($isLocalInstall && empty($defaultEmailCertificates)) {
$defaultEmailCertificates = 'walterobrien@example.com';
}
$step = max(1, min(5, $step));
if ($isUpgrade && ($step === 2 || $step === 3)) {
$step = 4;
}
$partialFile = $paths['views'] . "/installer/templates/steps/step-{$step}.phtml";
if (!is_file($partialFile)) {
$partialFile = $paths['views'] . '/installer/templates/steps/step-1.phtml';
}
if ($partial !== null) {
ob_start();
include $partialFile;
$html = ob_get_clean();
$response->html($html);
return;
}
ob_start();
include $paths['views'] . '/installer.phtml';
$html = ob_get_clean();
$response->html($html);
}
private function makeCsrf(Request $request, Response $response): string
{
$existing = $request->getCookie(Server::CSRF_COOKIE);
if ($existing !== '') {
return $existing;
}
$token = bin2hex(random_bytes(16));
$response->addCookie(Server::CSRF_COOKIE, $token, null, '/', null, null, true, Response::COOKIE_SAMESITE_STRICT);
return $token;
}
}
@@ -0,0 +1,13 @@
<?php
namespace Appwrite\Platform\Installer;
use Utopia\Platform\Platform;
class Installer extends Platform
{
public function __construct()
{
parent::__construct(new Module());
}
}
@@ -0,0 +1,14 @@
<?php
namespace Appwrite\Platform\Installer;
use Appwrite\Platform\Installer\Services\Http;
use Utopia\Platform;
class Module extends Platform\Module
{
public function __construct()
{
$this->addService('http', new Http());
}
}
@@ -0,0 +1,205 @@
<?php
namespace Appwrite\Platform\Installer\Runtime;
final class Config
{
private const array KNOWN_KEYS = [
'defaultHttpPort',
'defaultHttpsPort',
'organization',
'image',
'noStart',
'isUpgrade',
'isLocal',
'hostPath',
'lockedDatabase',
'vars',
];
private string $defaultHttpPort = '80';
private string $defaultHttpsPort = '443';
private string $organization = 'appwrite';
private string $image = 'appwrite';
private bool $noStart = false;
private bool $isUpgrade = false;
private bool $isLocal = false;
private ?string $hostPath = null;
private ?string $lockedDatabase = null;
private array $vars = [];
public function __construct(array $values = [])
{
if (!$this->containsKnownKeys($values)) {
$this->setVars($values);
return;
}
$this->apply($values);
}
public function apply(array $values): void
{
if ($this->hasValidStringValue($values, 'defaultHttpPort')) {
$this->setDefaultHttpPort((string) $values['defaultHttpPort']);
}
if ($this->hasValidStringValue($values, 'defaultHttpsPort')) {
$this->setDefaultHttpsPort((string) $values['defaultHttpsPort']);
}
if ($this->hasValidStringValue($values, 'organization')) {
$this->setOrganization((string) $values['organization']);
}
if ($this->hasValidStringValue($values, 'image')) {
$this->setImage((string) $values['image']);
}
if (array_key_exists('noStart', $values) && $values['noStart'] !== null) {
$this->setNoStart((bool) $values['noStart']);
}
if (array_key_exists('isUpgrade', $values) && $values['isUpgrade'] !== null) {
$this->setIsUpgrade((bool) $values['isUpgrade']);
}
if (array_key_exists('isLocal', $values) && $values['isLocal'] !== null) {
$this->setIsLocal((bool) $values['isLocal']);
}
if (array_key_exists('hostPath', $values)) {
$hostPath = $values['hostPath'];
$this->setHostPath($hostPath !== null && $hostPath !== '' ? (string) $hostPath : null);
}
if ($this->hasValidStringValue($values, 'lockedDatabase')) {
$this->setLockedDatabase((string) $values['lockedDatabase']);
}
if (array_key_exists('vars', $values) && is_array($values['vars'])) {
$this->setVars($values['vars']);
}
}
private function hasValidStringValue(array $values, string $key): bool
{
return array_key_exists($key, $values) && $values[$key] !== null && $values[$key] !== '';
}
private function containsKnownKeys(array $values): bool
{
foreach (self::KNOWN_KEYS as $key) {
if (array_key_exists($key, $values)) {
return true;
}
}
return false;
}
public function toArray(): array
{
return [
'defaultHttpPort' => $this->defaultHttpPort,
'defaultHttpsPort' => $this->defaultHttpsPort,
'organization' => $this->organization,
'image' => $this->image,
'noStart' => $this->noStart,
'vars' => $this->vars,
'isUpgrade' => $this->isUpgrade,
'isLocal' => $this->isLocal,
'hostPath' => $this->hostPath,
'lockedDatabase' => $this->lockedDatabase,
];
}
public function getDefaultHttpPort(): string
{
return $this->defaultHttpPort;
}
public function setDefaultHttpPort(string $value): void
{
$this->defaultHttpPort = $value;
}
public function getDefaultHttpsPort(): string
{
return $this->defaultHttpsPort;
}
public function setDefaultHttpsPort(string $value): void
{
$this->defaultHttpsPort = $value;
}
public function getOrganization(): string
{
return $this->organization;
}
public function setOrganization(string $value): void
{
$this->organization = $value;
}
public function getImage(): string
{
return $this->image;
}
public function setImage(string $value): void
{
$this->image = $value;
}
public function getNoStart(): bool
{
return $this->noStart;
}
public function setNoStart(bool $value): void
{
$this->noStart = $value;
}
public function getVars(): array
{
return $this->vars;
}
public function setVars(array $vars): void
{
$this->vars = $vars;
}
public function isUpgrade(): bool
{
return $this->isUpgrade;
}
public function setIsUpgrade(bool $value): void
{
$this->isUpgrade = $value;
}
public function isLocal(): bool
{
return $this->isLocal;
}
public function setIsLocal(bool $value): void
{
$this->isLocal = $value;
}
public function getHostPath(): ?string
{
return $this->hostPath;
}
public function setHostPath(?string $value): void
{
$this->hostPath = $value;
}
public function getLockedDatabase(): ?string
{
return $this->lockedDatabase;
}
public function setLockedDatabase(?string $value): void
{
$this->lockedDatabase = $value;
}
}
@@ -0,0 +1,420 @@
<?php
namespace Appwrite\Platform\Installer\Runtime;
use Appwrite\Platform\Installer\Server;
class State
{
private const string PATTERN_DIGITS_ONLY = '/^\d+$/';
private const string PATTERN_HAS_NON_WHITESPACE = '/\S/';
private const string PATTERN_LINE_BREAKS = '/\r\n|\n|\r/';
private const string PATTERN_INSTALL_ID_SANITIZE = '/[^a-zA-Z0-9_-]/';
private const string PATTERN_IPV6_WITH_PORT = '/^\[(.+)](?::(\d+))?$/';
private const int CONFIG_FILE_PERMISSION = 0600;
private const int GLOBAL_LOCK_TIMEOUT_SECONDS = 3600;
private const int PORT_MIN = 1;
private const int PORT_MAX = 65535;
private array $paths;
private bool $bootstrapped = false;
public function __construct(array $paths)
{
$this->paths = $paths;
}
public function buildConfig(array $overrides = [], bool $useEnv = true): Config
{
$cfg = new Config();
$configJson = null;
$decodedOk = false;
if ($useEnv) {
$configJson = getenv('APPWRITE_INSTALLER_CONFIG');
if ($configJson !== false && $configJson !== '') {
$decoded = json_decode($configJson, true);
if (is_array($decoded)) {
$cfg->apply($decoded);
$decodedOk = true;
}
}
}
if ($useEnv && (!$decodedOk)) {
$fileConfig = $this->readConfigFile();
if (is_array($fileConfig)) {
$cfg->apply($fileConfig);
}
}
if ($cfg->isLocal() && empty($cfg->getVars())) {
$envPath = dirname(__DIR__, 5) . '/.env';
if (file_exists($envPath)) {
$envContent = file_get_contents($envPath);
if ($envContent !== false) {
$vars = $this->parseEnvFile($envContent);
if (!empty($vars)) {
$cfg->setVars($vars);
}
}
}
}
$cfg->apply($overrides);
return $cfg;
}
public function applyEnvConfig(Config|array $cfg): void
{
$values = $cfg instanceof Config ? $cfg->toArray() : $cfg;
$json = json_encode($values, JSON_UNESCAPED_SLASHES);
if (!is_string($json)) {
return;
}
putenv('APPWRITE_INSTALLER_CONFIG=' . $json);
$this->writeConfigFile($json);
}
private function readConfigFile(): ?array
{
$path = Server::INSTALLER_CONFIG_FILE;
if (!file_exists($path)) {
return null;
}
$contents = file_get_contents($path);
if ($contents === false || $contents === '') {
return null;
}
$decoded = json_decode($contents, true);
return is_array($decoded) ? $decoded : null;
}
private function writeConfigFile(string $json): void
{
$path = Server::INSTALLER_CONFIG_FILE;
if (@file_put_contents($path, $json) === false) {
return;
}
@chmod($path, self::CONFIG_FILE_PERMISSION);
}
public function ensureBootstrapped(): void
{
if ($this->bootstrapped) {
return;
}
require_once __DIR__ . '/../../../../../app/init.php';
$this->bootstrapped = true;
}
public function sanitizeInstallId($value): string
{
if (!is_string($value)) {
return '';
}
$clean = preg_replace(self::PATTERN_INSTALL_ID_SANITIZE, '', $value);
if (!is_string($clean)) {
return '';
}
return substr($clean, 0, 64);
}
public function hashSensitiveValue(string $value): string
{
$trimmed = trim($value);
if ($trimmed === '') {
return '';
}
return hash('sha256', $trimmed);
}
public function isValidPort($value): bool
{
$string = (string) $value;
if ($string === '' || !preg_match(self::PATTERN_DIGITS_ONLY, $string)) {
return false;
}
$port = (int) $string;
return $port >= self::PORT_MIN && $port <= self::PORT_MAX;
}
public function isValidEmailAddress(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
public function isValidPassword(string $value): bool
{
return strlen($value) >= 8 && preg_match(self::PATTERN_HAS_NON_WHITESPACE, $value) === 1;
}
public function isValidSecretKey(string $value): bool
{
return $value !== '' && strlen($value) <= 64;
}
public function isValidAccountName(string $value): bool
{
return trim($value) !== '';
}
public function isValidAppDomainInput(string $value): bool
{
$value = trim($value);
if ($value === '') {
return false;
}
$host = $value;
$port = null;
if (str_starts_with($value, '[')) {
if (!preg_match(self::PATTERN_IPV6_WITH_PORT, $value, $matches)) {
return false;
}
$host = $matches[1] ?? '';
$port = $matches[2] ?? null;
} else {
$parts = explode(':', $value);
if (count($parts) > 2) {
return false;
}
if (count($parts) === 2) {
[$host, $port] = $parts;
}
}
if ($port !== null && $port !== '' && !$this->isValidPort($port)) {
return false;
}
return $this->isValidAppDomain($host);
}
public function isValidDatabaseAdapter(string $value): bool
{
return in_array($value, ['mongodb', 'mariadb', 'postgresql'], true);
}
public function progressFilePath(string $installId): string
{
return sys_get_temp_dir() . '/appwrite-install-' . $installId . '.json';
}
public function reserveGlobalLock(string $installId): string
{
return (string) $this->withGlobalLock(function ($handle, $lock) use ($installId) {
if (!$handle) {
return 'unavailable';
}
if ($this->isGlobalLockActive($lock) && ($lock['installId'] ?? '') !== $installId) {
return 'locked';
}
$payload = [
'installId' => $installId,
'status' => Server::STATUS_IN_PROGRESS,
'updatedAt' => time(),
];
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, json_encode($payload));
return 'ok';
});
}
public function updateGlobalLock(string $installId, string $status): void
{
$this->withGlobalLock(function ($handle, $lock) use ($installId, $status) {
if (!$handle) {
return;
}
if ($this->isGlobalLockActive($lock) && ($lock['installId'] ?? '') !== $installId) {
return;
}
$payload = [
'installId' => $installId,
'status' => $status,
'updatedAt' => time(),
];
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, json_encode($payload));
});
}
public function readProgressFile(string $installId): array
{
$path = $this->progressFilePath($installId);
if (!file_exists($path)) {
return [
'installId' => $installId,
'steps' => [],
];
}
$contents = file_get_contents($path);
if ($contents === false) {
return [
'installId' => $installId,
'steps' => [],
];
}
$data = json_decode($contents, true);
if (!is_array($data)) {
return [
'installId' => $installId,
'steps' => [],
];
}
return $data;
}
public function writeProgressFile(string $installId, array $payload): void
{
$data = $this->readProgressFile($installId);
if (!isset($data['steps']) || !is_array($data['steps'])) {
$data['steps'] = [];
}
if (!empty($payload['step'])) {
$data['steps'][$payload['step']] = [
'status' => $payload['status'] ?? Server::STATUS_IN_PROGRESS,
'message' => $payload['message'] ?? '',
'updatedAt' => $payload['updatedAt'] ?? time(),
];
}
if (!empty($payload['status']) && $payload['status'] === Server::STATUS_ERROR) {
$data['error'] = $payload['message'] ?? 'Installation failed';
}
if (isset($payload['details']) && is_array($payload['details'])) {
$data['details'][$payload['step']] = $payload['details'];
}
if (isset($payload['payload']) && is_array($payload['payload'])) {
$data['payload'] = $payload['payload'];
if (!isset($data['startedAt'])) {
$data['startedAt'] = $payload['updatedAt'] ?? time();
}
}
$data['updatedAt'] = $payload['updatedAt'] ?? time();
file_put_contents($this->progressFilePath($installId), json_encode($data));
}
private function parseEnvFile(string $contents): array
{
$vars = [];
foreach ((array) preg_split(self::PATTERN_LINE_BREAKS, $contents) as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') {
continue;
}
$pos = strpos($line, '=');
if ($pos === false) {
continue;
}
$key = trim(substr($line, 0, $pos));
$value = trim(substr($line, $pos + 1));
if ($key === '') {
continue;
}
$value = $this->stripEnvQuotes($value);
$vars[] = [
'name' => $key,
'default' => $value,
];
}
return $vars;
}
private function stripEnvQuotes(string $value): string
{
if ($value === '') {
return $value;
}
$first = $value[0];
$last = substr($value, -1);
if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
$value = substr($value, 1, -1);
}
return $value;
}
private function globalLockPath(): string
{
return Server::INSTALLER_LOCK_FILE;
}
private function isGlobalLockActive(?array $lock): bool
{
if (!$lock || !isset($lock['updatedAt'])) {
return false;
}
if (isset($lock['status']) && in_array($lock['status'], [Server::STATUS_COMPLETED, Server::STATUS_ERROR], true)) {
return false;
}
if (time() - (int) $lock['updatedAt'] > self::GLOBAL_LOCK_TIMEOUT_SECONDS) {
return false;
}
return true;
}
private function withGlobalLock(callable $callback)
{
$path = $this->globalLockPath();
$handle = fopen($path, 'c+');
if ($handle === false) {
return $callback(null, null);
}
if (!flock($handle, LOCK_EX)) {
fclose($handle);
return $callback(null, null);
}
$contents = stream_get_contents($handle);
$lock = null;
if ($contents !== false && $contents !== '') {
$decoded = json_decode($contents, true);
if (is_array($decoded)) {
$lock = $decoded;
}
}
try {
$result = $callback($handle, $lock);
} finally {
fflush($handle);
flock($handle, LOCK_UN);
fclose($handle);
}
return $result;
}
private function isValidAppDomain(string $value): bool
{
if ($value === 'localhost') {
return true;
}
if (filter_var($value, FILTER_VALIDATE_IP) !== false) {
return true;
}
return filter_var($value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
}
}
+330
View File
@@ -0,0 +1,330 @@
<?php
namespace Appwrite\Platform\Installer;
require_once __DIR__ . '/../../../../vendor/autoload.php';
use Appwrite\Platform\Installer\Http\Installer\Error;
use Appwrite\Platform\Installer\Runtime\State;
use Swoole\Http\Server as SwooleServer;
use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Http\Adapter\Swoole\Response;
use Utopia\Http\Adapter\Swoole\Server as SwooleAdapter;
use Utopia\Http\Files;
use Utopia\Http\Http;
use Utopia\Platform\Service;
class Server
{
public const int INSTALLER_WEB_PORT = 20080;
public const string INSTALLER_WEB_HOST = '0.0.0.0';
// temp files for state and config management!
public const string INSTALLER_LOCK_FILE = '/tmp/appwrite-install-lock.json';
public const string INSTALLER_CONFIG_FILE = '/tmp/appwrite-installer-config.json';
public const string INSTALLER_COMPLETE_FILE = '/tmp/appwrite-installer-complete';
public const string STEP_ENV_VARS = 'env-vars';
public const string STEP_CONFIG_FILES = 'config-files';
public const string STEP_DOCKER_COMPOSE = 'docker-compose';
public const string STEP_DOCKER_CONTAINERS = 'docker-containers';
public const string STEP_ACCOUNT_SETUP = 'account-setup';
public const string STATUS_IN_PROGRESS = 'in-progress';
public const string STATUS_COMPLETED = 'completed';
public const string STATUS_ERROR = 'error';
public const string CSRF_COOKIE = 'appwrite-installer-csrf';
public const array INSTALLER_CSP = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"font-src 'self' data:",
"connect-src 'self'",
"base-uri 'none'",
"form-action 'self'",
"frame-ancestors 'none'",
];
private const string DEFAULT_IMAGE = 'appwrite-dev';
public const string DEFAULT_CONTAINER = 'appwrite-installer';
private State $state;
private array $paths = [];
public function run(): void
{
$this->initPaths();
$this->state = new State($this->paths);
if (PHP_SAPI === 'cli') {
$this->runCli();
return;
}
}
private function initPaths(): void
{
if (!empty($this->paths)) {
return;
}
$root = dirname(__DIR__, 4);
$this->paths = [
'public' => $root . '/public',
'views' => $root . '/app/views/install',
];
}
private function runCli(): void
{
$opts = getopt('', ['upgrade', 'locked-database::', 'docker', 'clean', 'port::', 'ready-file::']);
$cfg = $this->state->buildConfig([], true);
$isDocker = isset($opts['docker']);
if ($isDocker) {
$cfg->setIsLocal(true);
if ($cfg->getHostPath() === null) {
$cwd = getcwd();
if ($cwd !== false) {
$cfg->setHostPath($cwd);
}
}
}
if (isset($opts['upgrade'])) {
$cfg->setIsUpgrade(true);
}
if (!empty($opts['locked-database'])) {
$cfg->setLockedDatabase($opts['locked-database']);
}
$this->state->applyEnvConfig($cfg);
$host = self::INSTALLER_WEB_HOST;
$port = !empty($opts['port']) ? (string) $opts['port'] : (string) self::INSTALLER_WEB_PORT;
$readyFile = !empty($opts['ready-file']) ? (string) $opts['ready-file'] : null;
if (isset($opts['clean'])) {
$this->removeDockerInstallerContainer(self::DEFAULT_CONTAINER);
$this->cleanupWebInstallerFiles();
exit(0);
}
if (isset($opts['docker'])) {
$this->printInstallerUrl($host, $port);
$this->startDockerInstaller($opts);
}
$this->printInstallerUrl($host, $port);
$this->startSwooleServer($host, (int) $port, $readyFile);
}
private function printInstallerUrl(string $host, string $port): void
{
$displayHost = $host === self::INSTALLER_WEB_HOST ? 'localhost' : $host;
$url = "http://$displayHost:$port";
fwrite(STDOUT, "Open $url" . PHP_EOL);
}
private function startSwooleServer(string $host, int $port, ?string $readyFile = null): void
{
// Preload static files into memory
$files = new Files();
$files->load($this->paths['views']);
// Register resources for dependency injection into actions
$config = $this->state->buildConfig();
$paths = $this->paths;
$state = $this->state;
Http::setResource('installerState', fn () => $state);
Http::setResource('installerConfig', fn () => $config);
Http::setResource('installerPaths', fn () => $paths);
// Register routes via Utopia Platform
$platform = new Installer();
$platform->init(Service::TYPE_HTTP);
// Register error handler directly so Http::error() preserves the '*' group
$errorHandler = new Error();
Http::error()
->inject('error')
->inject('response')
->action($errorHandler->action(...));
$adapter = new class ($host, $port, ['worker_num' => 1]) extends SwooleAdapter {
public function getNativeServer(): SwooleServer
{
return $this->server;
}
};
$nativeServer = $adapter->getNativeServer();
Http::setResource('swooleServer', fn () => $nativeServer);
$nativeServer->on('start', function () use ($nativeServer, $port, $readyFile) {
\Swoole\Process::signal(SIGTERM, fn () => $nativeServer->shutdown());
\Swoole\Process::signal(SIGINT, fn () => $nativeServer->shutdown());
if ($readyFile !== null) {
file_put_contents($readyFile, json_encode(['port' => $port, 'pid' => getmypid()]));
}
});
$adapter->onRequest(function (Request $request, Response $response) use ($files) {
// Serve static files from memory
$uri = $request->getURI();
if ($files->isFileLoaded($uri)) {
$response
->setContentType($files->getFileMimeType($uri))
->send($files->getFileContents($uri));
return;
}
$app = new Http('UTC');
$app->run($request, $response);
});
$adapter->start();
}
private function removeDockerInstallerContainer(string $container): void
{
$name = escapeshellarg($container);
exec("docker rm -f $name >/dev/null 2>&1");
}
private function cleanupWebInstallerFiles(): void
{
$baseDir = null;
try {
$cfg = $this->state->buildConfig();
if ($cfg->isLocal() && !empty($cfg->getHostPath())) {
$baseDir = rtrim($cfg->getHostPath(), '/') . '/appwrite';
}
} catch (\Throwable) {
// Fall back to cwd
}
if ($baseDir === null) {
$cwd = getcwd();
if ($cwd === false) {
return;
}
$baseDir = $cwd;
}
$filesToRemove = [
$baseDir . '/.env.web-installer',
$baseDir . '/docker-compose.web-installer.yml',
];
foreach ($filesToRemove as $file) {
if (file_exists($file)) {
@unlink($file);
}
}
$tempDir = sys_get_temp_dir();
@unlink(self::INSTALLER_LOCK_FILE);
@unlink(self::INSTALLER_CONFIG_FILE);
foreach ((array) glob($tempDir . '/appwrite-install-*.json') as $file) {
@unlink($file);
}
}
private function dockerImageExists(string $image): bool
{
$result = 1;
exec("docker image inspect " . escapeshellarg($image) . " >/dev/null 2>&1", $output, $result);
return $result === 0;
}
private function buildDockerInstallerImage(string $image): void
{
fwrite(STDOUT, "Building Docker image: {$image}\n");
$buildCommand = 'docker compose build appwrite';
passthru($buildCommand, $status);
if ($status !== 0 || !$this->dockerImageExists($image)) {
fwrite(STDERR, "Failed to build Docker image: $image\n");
fwrite(STDERR, "Try: docker compose build appwrite\n");
exit(1);
}
}
private function ensureCorrectTag(string $source, string $target): void
{
$sourceArg = escapeshellarg($source);
$targetArg = escapeshellarg($target);
exec("docker tag {$sourceArg} {$targetArg}", $tagOutput, $tagStatus);
if ($tagStatus !== 0) {
fwrite(STDERR, "Failed to tag Docker image {$source} as {$target}\n");
exit(1);
}
}
private function startDockerInstaller(array $opts): void
{
$image = self::DEFAULT_IMAGE;
$container = self::DEFAULT_CONTAINER;
if (!$this->dockerImageExists($image)) {
$this->buildDockerInstallerImage($image);
}
$this->ensureCorrectTag($image, 'appwrite/appwrite:local');
$port = (string)self::INSTALLER_WEB_PORT;
$entrypoint = isset($opts['upgrade']) ? 'upgrade' : 'install';
$this->removeDockerInstallerContainer($container);
$root = realpath(dirname(__DIR__, 4));
$volumePath = $root !== false ? $root : (getcwd() ?: '.');
$dockerConfig = $this->state->buildConfig([], false);
$dockerConfig->setIsLocal(true);
$dockerConfig->setHostPath($volumePath);
if (isset($opts['upgrade'])) {
$dockerConfig->setIsUpgrade(true);
}
if (!empty($opts['locked-database'])) {
$dockerConfig->setLockedDatabase($opts['locked-database']);
}
$configJson = json_encode($dockerConfig->toArray(), JSON_UNESCAPED_SLASHES);
if (!is_string($configJson)) {
$configJson = '{}';
}
$args = [
'docker',
'run',
'-i',
'--rm',
'--name', $container,
'-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;
$args[] = '--entrypoint=' . $entrypoint;
$args[] = $image;
$command = implode(' ', array_map(escapeshellarg(...), $args));
passthru($command, $status);
exit($status);
}
}
/**
* Run server only on direct CLI execution.
*/
function shouldRunInstallerServer(): bool
{
return PHP_SAPI === 'cli' && realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === realpath(__FILE__);
}
if (shouldRunInstallerServer()) {
$server = new Server();
$server->run();
}
@@ -0,0 +1,28 @@
<?php
namespace Appwrite\Platform\Installer\Services;
use Appwrite\Platform\Installer\Http\Installer\Cleanup;
use Appwrite\Platform\Installer\Http\Installer\Complete;
use Appwrite\Platform\Installer\Http\Installer\Install;
use Appwrite\Platform\Installer\Http\Installer\Shutdown;
use Appwrite\Platform\Installer\Http\Installer\Status;
use Appwrite\Platform\Installer\Http\Installer\Validate;
use Appwrite\Platform\Installer\Http\Installer\View;
use Utopia\Platform\Service;
class Http extends Service
{
public function __construct()
{
$this->type = Service::TYPE_HTTP;
$this->addAction(View::getName(), new View());
$this->addAction(Status::getName(), new Status());
$this->addAction(Validate::getName(), new Validate());
$this->addAction(Cleanup::getName(), new Cleanup());
$this->addAction(Complete::getName(), new Complete());
$this->addAction(Shutdown::getName(), new Shutdown());
$this->addAction(Install::getName(), new Install());
}
}
@@ -0,0 +1,82 @@
<?php
namespace Appwrite\Platform\Installer\Validator;
use Utopia\Validator;
/**
* AppDomain
*
* Validates an app domain input: hostname, IP, localhost,
* or IPv6 bracket notation with optional port (e.g. [::1]:8080).
*/
class AppDomain extends Validator
{
private const string PATTERN_IPV6_WITH_PORT = '/^\[(.+)](?::(\d+))?$/';
public function getDescription(): string
{
return 'Value must be a valid hostname, IP address, or bracket-notation IPv6 address with optional port';
}
public function isArray(): bool
{
return false;
}
public function getType(): string
{
return self::TYPE_STRING;
}
public function isValid($value): bool
{
if (!is_string($value)) {
return false;
}
$value = trim($value);
if ($value === '') {
return false;
}
$host = $value;
$port = null;
if (str_starts_with($value, '[')) {
if (!preg_match(self::PATTERN_IPV6_WITH_PORT, $value, $matches)) {
return false;
}
$host = $matches[1] ?? '';
$port = $matches[2] ?? null;
} else {
$parts = explode(':', $value);
if (count($parts) > 2) {
return false;
}
if (count($parts) === 2) {
[$host, $port] = $parts;
}
}
if ($port !== null && $port !== '') {
$portInt = (int) $port;
if ((string) $portInt !== $port || $portInt < 1 || $portInt > 65535) {
return false;
}
}
return $this->isValidDomain($host);
}
private function isValidDomain(string $value): bool
{
if ($value === 'localhost') {
return true;
}
if (filter_var($value, FILTER_VALIDATE_IP) !== false) {
return true;
}
return filter_var($value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
}
}

Some files were not shown because too many files have changed in this diff Show More