mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Revert "Merge pull request #12195 from appwrite/feat-notifications-worker"
This reverts commitcb6570124b, reversing changes made toa6f753e17b.
This commit is contained in:
78 files changed
+53
-6067
No files matched your search
@@ -2,7 +2,6 @@ _APP_ENV=development
|
||||
_APP_EDITION=self-hosted
|
||||
_APP_LOCALE=en
|
||||
_APP_OPENSSL_KEY_V1=your-secret-key
|
||||
_APP_NOTIFICATIONS_TRACKING_SECRET=your-secret-key
|
||||
_APP_RULES_FORMAT=md5
|
||||
_APP_SYSTEM_RESPONSE_FORMAT=
|
||||
_APP_TRUSTED_HEADERS=x-forwarded-for
|
||||
|
||||
@@ -213,7 +213,6 @@ jobs:
|
||||
{ name: 'Webhooks', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'VCS', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Messaging', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Notifications', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Migrations', runner: runner4, functional: true, processes: 1, timeout: 15 },
|
||||
{ name: 'Project', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
{ name: 'Presences', runner: runner4, functional: true, processes: null, timeout: 15 },
|
||||
|
||||
@@ -93,7 +93,6 @@ RUN chmod +x /usr/local/bin/doctor && \
|
||||
chmod +x /usr/local/bin/worker-functions && \
|
||||
chmod +x /usr/local/bin/worker-mails && \
|
||||
chmod +x /usr/local/bin/worker-messaging && \
|
||||
chmod +x /usr/local/bin/worker-notifications && \
|
||||
chmod +x /usr/local/bin/worker-migrations && \
|
||||
chmod +x /usr/local/bin/worker-webhooks && \
|
||||
chmod +x /usr/local/bin/worker-stats-usage && \
|
||||
|
||||
@@ -485,17 +485,6 @@ $platformCollections = [
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('projectInternalId'),
|
||||
'type' => Database::VAR_ID,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('schedule'),
|
||||
'type' => Database::VAR_STRING,
|
||||
@@ -556,13 +545,6 @@ $platformCollections = [
|
||||
'lengths' => [],
|
||||
'orders' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_region_resourceType_projectInternalId_resourceId'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['region', 'resourceType', 'projectInternalId', 'resourceId'],
|
||||
'lengths' => [],
|
||||
'orders' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_project_id_region'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
@@ -570,13 +552,6 @@ $platformCollections = [
|
||||
'lengths' => [],
|
||||
'orders' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_project_internal_id_region'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['projectInternalId', 'region'],
|
||||
'lengths' => [],
|
||||
'orders' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_region_rt_active'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
@@ -1068,238 +1043,6 @@ $platformCollections = [
|
||||
],
|
||||
],
|
||||
|
||||
'notifications' => [
|
||||
'$collection' => ID::custom(Database::METADATA),
|
||||
'$id' => ID::custom('notifications'),
|
||||
'name' => 'Notifications',
|
||||
'attributes' => [
|
||||
[
|
||||
'$id' => ID::custom('messageId'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => Database::LENGTH_KEY,
|
||||
'signed' => true,
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('recipientHash'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 64,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('type'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 100,
|
||||
'signed' => true,
|
||||
'required' => false,
|
||||
'default' => 'info',
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('channel'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 64,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('resourceType'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 64,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('resourceId'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => Database::LENGTH_KEY,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('projectId'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => Database::LENGTH_KEY,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('projectInternalId'),
|
||||
'type' => Database::VAR_ID,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('resourceInternalId'),
|
||||
'type' => Database::VAR_ID,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('parentResourceType'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 64,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('parentResourceId'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => Database::LENGTH_KEY,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('parentResourceInternalId'),
|
||||
'type' => Database::VAR_ID,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('title'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 256,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('body'),
|
||||
'type' => Database::VAR_STRING,
|
||||
'format' => '',
|
||||
'size' => 65535,
|
||||
'signed' => true,
|
||||
'required' => true,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('read'),
|
||||
'type' => Database::VAR_BOOLEAN,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => false,
|
||||
'default' => false,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('firstSeen'),
|
||||
'type' => Database::VAR_DATETIME,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => false,
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => ['datetime'],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('lastSeen'),
|
||||
'type' => Database::VAR_DATETIME,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => false,
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => ['datetime'],
|
||||
],
|
||||
],
|
||||
'indexes' => [
|
||||
[
|
||||
'$id' => ID::custom('_key_messageId'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['messageId'],
|
||||
'lengths' => [Database::LENGTH_KEY],
|
||||
'orders' => [Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_recipient'),
|
||||
'type' => Database::INDEX_UNIQUE,
|
||||
'attributes' => ['messageId', 'channel', 'recipientHash'],
|
||||
'lengths' => [Database::LENGTH_KEY, 64, 64],
|
||||
'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_project'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['projectId', 'projectInternalId'],
|
||||
'lengths' => [Database::LENGTH_KEY, 0],
|
||||
'orders' => [Database::ORDER_ASC, Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_project_resource'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['projectId', 'projectInternalId', 'resourceType', 'resourceId', 'resourceInternalId'],
|
||||
'lengths' => [Database::LENGTH_KEY, 0, 64, Database::LENGTH_KEY, 0],
|
||||
'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_project_parent_resource'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['projectId', 'projectInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'],
|
||||
'lengths' => [Database::LENGTH_KEY, 0, 64, Database::LENGTH_KEY, 0],
|
||||
'orders' => [Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC, Database::ORDER_ASC],
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
'certificates' => [
|
||||
'$collection' => ID::custom(Database::METADATA),
|
||||
'$id' => ID::custom('certificates'),
|
||||
|
||||
@@ -79,15 +79,6 @@ return [
|
||||
'question' => 'Choose a secret API key, make sure to make a backup of your key in a secure location',
|
||||
'filter' => 'token'
|
||||
],
|
||||
[
|
||||
'name' => '_APP_NOTIFICATIONS_TRACKING_SECRET',
|
||||
'description' => 'Secret key used to sign notification logo tracking tokens. This must be the same value for API containers and notification workers. Change it from the default value before running in production.',
|
||||
'introduction' => '1.9.0',
|
||||
'default' => 'your-secret-key',
|
||||
'required' => true,
|
||||
'question' => '',
|
||||
'filter' => 'token'
|
||||
],
|
||||
[
|
||||
'name' => '_APP_DOMAIN',
|
||||
'description' => 'Your Appwrite domain address. When setting a public suffix domain, Appwrite will attempt to issue a valid SSL certificate automatically. When used with a dev domain, Appwrite will assign a self-signed SSL certificate. The default value is \'localhost\'. Multiple domains can be separated by commas.',
|
||||
|
||||
@@ -3501,7 +3501,6 @@ Http::post('/v1/messaging/messages/email')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => true,
|
||||
]));
|
||||
@@ -3648,7 +3647,6 @@ Http::post('/v1/messaging/messages/sms')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => true,
|
||||
]));
|
||||
@@ -3871,7 +3869,6 @@ Http::post('/v1/messaging/messages/push')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => true,
|
||||
]));
|
||||
@@ -4266,7 +4263,6 @@ Http::patch('/v1/messaging/messages/email/:messageId')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => $status === MessageStatus::SCHEDULED,
|
||||
]));
|
||||
@@ -4283,7 +4279,6 @@ Http::patch('/v1/messaging/messages/email/:messageId')
|
||||
}
|
||||
|
||||
$schedule
|
||||
->setAttribute('projectInternalId', $project->getSequence())
|
||||
->setAttribute('resourceUpdatedAt', DateTime::now())
|
||||
->setAttribute('active', $scheduledStatus);
|
||||
|
||||
@@ -4492,7 +4487,6 @@ Http::patch('/v1/messaging/messages/sms/:messageId')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => $status === MessageStatus::SCHEDULED,
|
||||
]));
|
||||
@@ -4509,7 +4503,6 @@ Http::patch('/v1/messaging/messages/sms/:messageId')
|
||||
}
|
||||
|
||||
$schedule
|
||||
->setAttribute('projectInternalId', $project->getSequence())
|
||||
->setAttribute('resourceUpdatedAt', DateTime::now())
|
||||
->setAttribute('active', $scheduledStatus);
|
||||
|
||||
@@ -4671,7 +4664,6 @@ Http::patch('/v1/messaging/messages/push/:messageId')
|
||||
'resourceInternalId' => $message->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'active' => $status === MessageStatus::SCHEDULED,
|
||||
]));
|
||||
@@ -4688,7 +4680,6 @@ Http::patch('/v1/messaging/messages/push/:messageId')
|
||||
}
|
||||
|
||||
$schedule
|
||||
->setAttribute('projectInternalId', $project->getSequence())
|
||||
->setAttribute('resourceUpdatedAt', DateTime::now())
|
||||
->setAttribute('active', $scheduledStatus);
|
||||
|
||||
|
||||
@@ -168,7 +168,6 @@ const SESSION_PROVIDER_SERVER = 'server';
|
||||
const ACTOR_TYPE_USER = 'user';
|
||||
const ACTOR_TYPE_ADMIN = 'admin';
|
||||
const ACTOR_TYPE_GUEST = 'guest';
|
||||
const ACTOR_TYPE_HIDDEN = 'hidden';
|
||||
const ACTOR_TYPE_KEY_PROJECT = 'keyProject';
|
||||
const ACTOR_TYPE_KEY_ACCOUNT = 'keyAccount';
|
||||
const ACTOR_TYPE_KEY_ORGANIZATION = 'keyOrganization';
|
||||
@@ -279,13 +278,6 @@ const FUNCTION_ALLOWLIST_HEADERS_RESPONSE = ['content-type', 'content-length'];
|
||||
const MESSAGE_TYPE_EMAIL = 'email';
|
||||
const MESSAGE_TYPE_SMS = 'sms';
|
||||
const MESSAGE_TYPE_PUSH = 'push';
|
||||
// Notification types
|
||||
const NOTIFICATION_TYPE_EMAIL = MESSAGE_TYPE_EMAIL;
|
||||
const NOTIFICATION_TYPE_SMS = MESSAGE_TYPE_SMS;
|
||||
const NOTIFICATION_TYPE_PUSH = MESSAGE_TYPE_PUSH;
|
||||
const NOTIFICATION_TYPE_CONSOLE = 'console';
|
||||
const NOTIFICATION_TYPE_WEBHOOK = 'webhook';
|
||||
const NOTIFICATION_TRACKING_JWT_TTL = 60 * 60 * 24 * 7;
|
||||
const MAIL_TEMPLATE_CERTIFICATE_FAILED = 'certificate-failed';
|
||||
const MAIL_TEMPLATE_DATA_EXPORT = 'data-export';
|
||||
const MAIL_TEMPLATE_INVITATION = 'invitation';
|
||||
@@ -471,8 +463,6 @@ const RESOURCE_TYPE_SUBSCRIBERS = 'subscribers';
|
||||
const RESOURCE_TYPE_MESSAGES = 'messages';
|
||||
const RESOURCE_TYPE_EXECUTIONS = 'executions';
|
||||
const RESOURCE_TYPE_VCS = 'vcs';
|
||||
const RESOURCE_TYPE_USERS = 'users';
|
||||
const RESOURCE_TYPE_TEAMS = 'teams';
|
||||
const RESOURCE_TYPE_EMBEDDINGS_TEXT = 'embeddingsText';
|
||||
const RESOURCE_TYPE_INSIGHTS = 'insights';
|
||||
const RESOURCE_TYPE_REPORTS = 'reports';
|
||||
|
||||
@@ -115,7 +115,6 @@ use Appwrite\Utopia\Response\Model\MigrationReport;
|
||||
use Appwrite\Utopia\Response\Model\Mock;
|
||||
use Appwrite\Utopia\Response\Model\MockNumber;
|
||||
use Appwrite\Utopia\Response\Model\None;
|
||||
use Appwrite\Utopia\Response\Model\Notification;
|
||||
use Appwrite\Utopia\Response\Model\OAuth2Amazon;
|
||||
use Appwrite\Utopia\Response\Model\OAuth2Apple;
|
||||
use Appwrite\Utopia\Response\Model\OAuth2Auth0;
|
||||
@@ -251,7 +250,6 @@ Response::setModel(new BaseList('Column Indexes List', Response::MODEL_COLUMN_IN
|
||||
Response::setModel(new BaseList('Users List', Response::MODEL_USER_LIST, 'users', Response::MODEL_USER));
|
||||
Response::setModel(new BaseList('Sessions List', Response::MODEL_SESSION_LIST, 'sessions', Response::MODEL_SESSION));
|
||||
Response::setModel(new BaseList('Identities List', Response::MODEL_IDENTITY_LIST, 'identities', Response::MODEL_IDENTITY));
|
||||
Response::setModel(new BaseList('Notifications List', Response::MODEL_NOTIFICATION_LIST, 'notifications', Response::MODEL_NOTIFICATION));
|
||||
Response::setModel(new BaseList('Logs List', Response::MODEL_LOG_LIST, 'logs', Response::MODEL_LOG));
|
||||
Response::setModel(new BaseList('Files List', Response::MODEL_FILE_LIST, 'files', Response::MODEL_FILE));
|
||||
Response::setModel(new BaseList('Buckets List', Response::MODEL_BUCKET_LIST, 'buckets', Response::MODEL_BUCKET));
|
||||
@@ -383,7 +381,6 @@ Response::setModel(new Account());
|
||||
Response::setModel(new Preferences());
|
||||
Response::setModel(new Session());
|
||||
Response::setModel(new Identity());
|
||||
Response::setModel(new Notification());
|
||||
Response::setModel(new Token());
|
||||
Response::setModel(new JWT());
|
||||
Response::setModel(new Locale());
|
||||
|
||||
@@ -12,7 +12,6 @@ use Appwrite\Event\Publisher\Func as FunctionPublisher;
|
||||
use Appwrite\Event\Publisher\Mail as MailPublisher;
|
||||
use Appwrite\Event\Publisher\Messaging as MessagingPublisher;
|
||||
use Appwrite\Event\Publisher\Migration as MigrationPublisher;
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Event\Publisher\Screenshot as ScreenshotPublisher;
|
||||
use Appwrite\Event\Publisher\StatsResources as StatsResourcesPublisher;
|
||||
use Appwrite\Event\Publisher\Usage as UsagePublisher;
|
||||
@@ -151,11 +150,6 @@ $container->set('publisherForMessaging', fn (Publisher $publisher) => new Messag
|
||||
new Queue(System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME))
|
||||
), ['publisher']);
|
||||
|
||||
$container->set('publisherForNotifications', fn (Publisher $publisher) => new NotificationPublisher(
|
||||
$publisher,
|
||||
new Queue(System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME))
|
||||
), ['publisher']);
|
||||
|
||||
$container->set('databaseFactory', fn (Group $pools, Cache $cache, Authorization $authorization) => new DatabaseFactory(
|
||||
$pools,
|
||||
$cache,
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
use Appwrite\Database\Factory as DatabaseFactory;
|
||||
use Appwrite\Event\Event;
|
||||
use Appwrite\Event\Publisher\Func as FunctionPublisher;
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Event\Realtime;
|
||||
use Appwrite\Event\Webhook;
|
||||
use Appwrite\Usage\Context;
|
||||
@@ -19,7 +17,6 @@ use Utopia\DI\Container;
|
||||
use Utopia\Logger\Log;
|
||||
use Utopia\Pools\Group;
|
||||
use Utopia\Queue\Publisher;
|
||||
use Utopia\Queue\Queue;
|
||||
use Utopia\Registry\Registry;
|
||||
use Utopia\Span\Span;
|
||||
use Utopia\Storage\Device\Telemetry as TelemetryDevice;
|
||||
@@ -148,16 +145,6 @@ return function (Container $container): void {
|
||||
return new Webhook($publisher);
|
||||
}, ['publisher']);
|
||||
|
||||
$container->set('publisherForNotifications', fn (Publisher $publisher) => new NotificationPublisher(
|
||||
$publisher,
|
||||
new Queue(System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME))
|
||||
), ['publisher']);
|
||||
|
||||
$container->set('publisherForFunctions', fn (Publisher $publisher) => new FunctionPublisher(
|
||||
$publisher,
|
||||
new Queue(System::getEnv('_APP_FUNCTIONS_QUEUE_NAME', Event::FUNCTIONS_QUEUE_NAME), 'utopia-queue', Event::FUNCTIONS_QUEUE_TTL)
|
||||
), ['publisher']);
|
||||
|
||||
$container->set('queueForRealtime', function () {
|
||||
return new Realtime();
|
||||
}, []);
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
#!/bin/sh
|
||||
|
||||
exec php /usr/src/code/app/worker.php mails "$@"
|
||||
exec php /usr/src/code/app/worker.php mails "$@"
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
exec php /usr/src/code/app/worker.php notifications "$@"
|
||||
@@ -99,7 +99,6 @@ services:
|
||||
- _APP_OPTIONS_FORCE_HTTPS
|
||||
- _APP_OPTIONS_ROUTER_FORCE_HTTPS
|
||||
- _APP_OPENSSL_KEY_V1
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_DOMAIN
|
||||
- _APP_CONSOLE_DOMAIN
|
||||
- _APP_CONSOLE_TRUSTED_PROJECTS
|
||||
@@ -748,7 +747,6 @@ services:
|
||||
- _APP_WORKER_PER_CORE
|
||||
- _APP_POOL_ADAPTER
|
||||
- _APP_OPENSSL_KEY_V1
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_SYSTEM_EMAIL_NAME
|
||||
- _APP_SYSTEM_EMAIL_ADDRESS
|
||||
- _APP_REDIS_HOST
|
||||
@@ -771,48 +769,6 @@ services:
|
||||
- _APP_OPTIONS_FORCE_HTTPS
|
||||
- _APP_DATABASE_SHARED_TABLES
|
||||
|
||||
appwrite-worker-notifications:
|
||||
entrypoint: worker-notifications
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-file: "5"
|
||||
max-size: 10m
|
||||
container_name: appwrite-worker-notifications
|
||||
restart: unless-stopped
|
||||
image: ${_APP_IMAGE:-appwrite/appwrite}:${_APP_VERSION:-latest}
|
||||
networks:
|
||||
- appwrite
|
||||
depends_on:
|
||||
- redis
|
||||
- ${_APP_DB_HOST:-mariadb}
|
||||
environment:
|
||||
- _APP_ENV
|
||||
- _APP_WORKER_PER_CORE
|
||||
- _APP_POOL_ADAPTER
|
||||
- _APP_OPENSSL_KEY_V1
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_SYSTEM_EMAIL_NAME
|
||||
- _APP_SYSTEM_EMAIL_ADDRESS
|
||||
- _APP_REDIS_HOST
|
||||
- _APP_REDIS_PORT
|
||||
- _APP_REDIS_USER
|
||||
- _APP_REDIS_PASS
|
||||
- _APP_DB_HOST
|
||||
- _APP_DB_PORT
|
||||
- _APP_DB_SCHEMA
|
||||
- _APP_DB_USER
|
||||
- _APP_DB_PASS
|
||||
- _APP_DB_ADAPTER
|
||||
- _APP_SMTP_HOST
|
||||
- _APP_SMTP_PORT
|
||||
- _APP_SMTP_SECURE
|
||||
- _APP_SMTP_USERNAME
|
||||
- _APP_SMTP_PASSWORD
|
||||
- _APP_LOGGING_CONFIG
|
||||
- _APP_DOMAIN
|
||||
- _APP_OPTIONS_FORCE_HTTPS
|
||||
- _APP_DATABASE_SHARED_TABLES
|
||||
appwrite-worker-messaging:
|
||||
entrypoint: worker-messaging
|
||||
logging:
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
Get the number of jobs in the notifications queue.
|
||||
@@ -1 +0,0 @@
|
||||
Get the Appwrite logo SVG used in notification emails. When loaded with a valid tracking token, the related notification is marked as read and its view timestamps are updated.
|
||||
@@ -1 +0,0 @@
|
||||
Get the list of notifications for the currently logged in console user. Use queries to filter the results by attributes such as read status, view timestamps, or creation date.
|
||||
@@ -1 +0,0 @@
|
||||
Update a notification by its unique ID. Use the `read` parameter to mark the notification as read or unread.
|
||||
@@ -37,7 +37,6 @@
|
||||
<directory>./tests/e2e/Services/ProjectWebhooks</directory>
|
||||
<directory>./tests/e2e/Services/Messaging</directory>
|
||||
<directory>./tests/e2e/Services/Migrations</directory>
|
||||
<directory>./tests/e2e/Services/Notifications</directory>
|
||||
<directory>./tests/e2e/Services/Project</directory>
|
||||
<directory>./tests/e2e/Services/Advisor</directory>
|
||||
<file>./tests/e2e/Services/Functions/FunctionsBase.php</file>
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace Appwrite\Docker;
|
||||
|
||||
use Appwrite\Docker\Compose\Service;
|
||||
use Exception;
|
||||
use Spyc;
|
||||
|
||||
class Compose
|
||||
{
|
||||
@@ -15,8 +14,7 @@ class Compose
|
||||
|
||||
public function __construct(string $data)
|
||||
{
|
||||
$compose = \function_exists('yaml_parse') ? \yaml_parse($data) : Spyc::YAMLLoadString($data);
|
||||
$this->compose = \is_array($compose) ? $compose : [];
|
||||
$this->compose = yaml_parse($data);
|
||||
|
||||
$this->compose['services'] = (isset($this->compose['services']) && is_array($this->compose['services']))
|
||||
? $this->compose['services'] : [];
|
||||
|
||||
@@ -54,11 +54,6 @@ class Service
|
||||
return substr($image, ((int)strpos($image, ':')) + 1);
|
||||
}
|
||||
|
||||
public function getEntrypoint(): string
|
||||
{
|
||||
return (isset($this->service['entrypoint'])) ? $this->service['entrypoint'] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Env
|
||||
*/
|
||||
|
||||
@@ -21,9 +21,6 @@ class Event
|
||||
public const MAILS_QUEUE_NAME = 'v1-mails';
|
||||
public const MAILS_CLASS_NAME = 'MailsV1';
|
||||
|
||||
public const NOTIFICATIONS_QUEUE_NAME = 'v1-notifications';
|
||||
public const NOTIFICATIONS_CLASS_NAME = 'NotificationsV1';
|
||||
|
||||
public const FUNCTIONS_QUEUE_NAME = 'v1-functions';
|
||||
public const FUNCTIONS_CLASS_NAME = 'FunctionsV1';
|
||||
public const FUNCTIONS_QUEUE_TTL = 60 * 60 * 24 * 7; // 7 days
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Event\Message;
|
||||
|
||||
use Appwrite\Event\Event;
|
||||
use Utopia\Config\Config;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
final class Notification extends Base
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string}> $recipients
|
||||
* @param array<string> $channels
|
||||
* @param array<string, mixed> $templateParams
|
||||
* @param array<string> $permissions
|
||||
* @param array<string, mixed> $variables
|
||||
* @param array<string, mixed> $attachment
|
||||
* @param array<string> $events
|
||||
* @param array<string, mixed> $params
|
||||
* @param array<string, mixed> $platform
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ?Document $project = null,
|
||||
public readonly string $recipient = '',
|
||||
public readonly array $recipients = [],
|
||||
public readonly array $channels = [],
|
||||
public readonly string $template = '',
|
||||
public readonly array $templateParams = [],
|
||||
public readonly string $deduplicationKey = '',
|
||||
public readonly array $permissions = [],
|
||||
public readonly string $name = '',
|
||||
public readonly string $subject = '',
|
||||
public readonly string $bodyTemplate = '',
|
||||
public readonly string $body = '',
|
||||
public readonly string $preview = '',
|
||||
public readonly array $variables = [],
|
||||
public readonly array $attachment = [],
|
||||
public readonly array $events = [],
|
||||
public readonly string $event = '',
|
||||
public readonly array $params = [],
|
||||
public readonly array $platform = [],
|
||||
) {
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
$recipients = $this->recipients;
|
||||
if (empty($recipients) && $this->recipient !== '') {
|
||||
$recipients = [[
|
||||
'address' => $this->recipient,
|
||||
'channel' => NOTIFICATION_TYPE_EMAIL,
|
||||
]];
|
||||
}
|
||||
|
||||
$platform = !empty($this->platform) ? $this->platform : Config::getParam('platform', []);
|
||||
|
||||
return [
|
||||
'project' => $this->project === null ? null : [
|
||||
'$id' => $this->project->getId(),
|
||||
'$sequence' => $this->project->getSequence(),
|
||||
'database' => $this->project->getAttribute('database'),
|
||||
],
|
||||
'recipient' => $this->recipient,
|
||||
'recipients' => $recipients,
|
||||
'channels' => $this->channels,
|
||||
'template' => $this->template,
|
||||
'templateParams' => $this->templateParams,
|
||||
'deduplicationKey' => $this->deduplicationKey,
|
||||
'permissions' => $this->permissions,
|
||||
'name' => $this->name,
|
||||
'subject' => $this->subject,
|
||||
'bodyTemplate' => $this->bodyTemplate,
|
||||
'body' => $this->body,
|
||||
'preview' => $this->preview,
|
||||
'variables' => $this->variables,
|
||||
'attachment' => $this->attachment,
|
||||
'events' => !empty($this->events) ? $this->events : $this->generateEvents(),
|
||||
'platform' => $platform,
|
||||
];
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): static
|
||||
{
|
||||
return new self(
|
||||
project: !empty($data['project']) ? new Document($data['project']) : null,
|
||||
recipient: $data['recipient'] ?? '',
|
||||
recipients: $data['recipients'] ?? [],
|
||||
channels: $data['channels'] ?? [],
|
||||
template: $data['template'] ?? '',
|
||||
templateParams: $data['templateParams'] ?? [],
|
||||
deduplicationKey: $data['deduplicationKey'] ?? '',
|
||||
permissions: $data['permissions'] ?? [],
|
||||
name: $data['name'] ?? '',
|
||||
subject: $data['subject'] ?? '',
|
||||
bodyTemplate: $data['bodyTemplate'] ?? '',
|
||||
body: $data['body'] ?? '',
|
||||
preview: $data['preview'] ?? '',
|
||||
variables: $data['variables'] ?? [],
|
||||
attachment: $data['attachment'] ?? [],
|
||||
events: $data['events'] ?? [],
|
||||
platform: $data['platform'] ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
private function generateEvents(): array
|
||||
{
|
||||
if ($this->event === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Event::generateEvents($this->event, $this->params);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Event\Publisher;
|
||||
|
||||
use Appwrite\Event\Message\Notification as NotificationMessage;
|
||||
use Utopia\Queue\Publisher;
|
||||
use Utopia\Queue\Queue;
|
||||
|
||||
readonly class Notification extends Base
|
||||
{
|
||||
public function __construct(
|
||||
Publisher $publisher,
|
||||
protected Queue $queue,
|
||||
) {
|
||||
parent::__construct($publisher);
|
||||
}
|
||||
|
||||
public function enqueue(NotificationMessage $message, ?Queue $queue = null): string|bool
|
||||
{
|
||||
return $this->publish($queue ?? $this->queue, $message);
|
||||
}
|
||||
|
||||
public function getSize(bool $failed = false, ?Queue $queue = null): int
|
||||
{
|
||||
return $this->getQueueSize($queue ?? $this->queue, $failed);
|
||||
}
|
||||
}
|
||||
@@ -736,7 +736,6 @@ class V19 extends Migration
|
||||
'resourceInternalId' => $document->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $this->project->getId(),
|
||||
'projectInternalId' => $this->project->getSequence(),
|
||||
'schedule' => $document->getAttribute('schedule'),
|
||||
'active' => !empty($document->getAttribute('schedule')) && !empty($document->getAttribute('deployment')),
|
||||
]));
|
||||
|
||||
@@ -90,12 +90,6 @@ class V24 extends Migration
|
||||
};
|
||||
|
||||
$collections = $this->collections[$collectionType];
|
||||
$notificationsCollectionExists = false;
|
||||
|
||||
if ($collectionType === 'console') {
|
||||
$notificationsCollectionExists = !$this->dbForProject->getCollection('notifications')->isEmpty();
|
||||
$this->createCollection('notifications');
|
||||
}
|
||||
|
||||
foreach ($collections as $collection) {
|
||||
$id = $collection['$id'];
|
||||
@@ -159,42 +153,6 @@ class V24 extends Migration
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'schedules':
|
||||
if ($collectionType === 'console') {
|
||||
try {
|
||||
$this->createAttributeFromCollection($this->dbForProject, $id, 'projectInternalId');
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create attribute \"projectInternalId\" in collection {$id}: {$th->getMessage()}");
|
||||
}
|
||||
|
||||
$indexes = [
|
||||
'_key_region_resourceType_projectInternalId_resourceId',
|
||||
'_key_project_internal_id_region',
|
||||
];
|
||||
foreach ($indexes as $index) {
|
||||
try {
|
||||
$this->createIndexFromCollection($this->dbForProject, $id, $index);
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create index \"{$index}\" from {$id}: {$th->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'notifications':
|
||||
if ($collectionType === 'console' && $notificationsCollectionExists) {
|
||||
foreach (['firstSeen', 'lastSeen'] as $attribute) {
|
||||
try {
|
||||
$this->createAttributeFromCollection($this->dbForProject, $id, $attribute);
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create attribute \"{$attribute}\" in collection {$id}: {$th->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'rules':
|
||||
if ($collectionType === 'console') {
|
||||
try {
|
||||
@@ -495,17 +453,6 @@ class V24 extends Migration
|
||||
$document->setAttribute('resourceInternalId', $projectInternalId);
|
||||
}
|
||||
break;
|
||||
case 'schedules':
|
||||
if (empty($document->getAttribute('projectInternalId'))) {
|
||||
$projectId = $document->getAttribute('projectId', '');
|
||||
if ($projectId !== '') {
|
||||
$project = $this->dbForProject->getDocument('projects', $projectId);
|
||||
if (!$project->isEmpty()) {
|
||||
$document->setAttribute('projectInternalId', $project->getSequence());
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ use Appwrite\Platform\Modules\Databases;
|
||||
use Appwrite\Platform\Modules\Functions;
|
||||
use Appwrite\Platform\Modules\Health;
|
||||
use Appwrite\Platform\Modules\Migrations;
|
||||
use Appwrite\Platform\Modules\Notifications;
|
||||
use Appwrite\Platform\Modules\Organization;
|
||||
use Appwrite\Platform\Modules\Presences;
|
||||
use Appwrite\Platform\Modules\Project;
|
||||
@@ -37,7 +36,6 @@ class Appwrite extends Platform
|
||||
$this->addModule(new Presences\Module());
|
||||
$this->addModule(new Functions\Module());
|
||||
$this->addModule(new Health\Module());
|
||||
$this->addModule(new Notifications\Module());
|
||||
$this->addModule(new Sites\Module());
|
||||
$this->addModule(new Console\Module());
|
||||
$this->addModule(new Proxy\Module());
|
||||
|
||||
@@ -325,7 +325,6 @@ class Create extends Base
|
||||
'resourceInternalId' => $execution->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $scheduledAt,
|
||||
'data' => $data,
|
||||
'active' => true,
|
||||
|
||||
@@ -276,7 +276,6 @@ class Create extends Base
|
||||
'resourceInternalId' => $function->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $function->getAttribute('schedule'),
|
||||
'active' => false,
|
||||
]))
|
||||
|
||||
@@ -325,7 +325,6 @@ class Update extends Base
|
||||
'resourceInternalId' => $function->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $function->getAttribute('schedule'),
|
||||
'active' => false,
|
||||
]))
|
||||
@@ -338,7 +337,6 @@ class Update extends Base
|
||||
}
|
||||
|
||||
$schedule
|
||||
->setAttribute('projectInternalId', $project->getSequence())
|
||||
->setAttribute('resourceUpdatedAt', DateTime::now())
|
||||
->setAttribute('schedule', $function->getAttribute('schedule'))
|
||||
->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deploymentId')));
|
||||
|
||||
@@ -12,7 +12,6 @@ use Appwrite\Event\Publisher\Func as FunctionPublisher;
|
||||
use Appwrite\Event\Publisher\Mail as MailPublisher;
|
||||
use Appwrite\Event\Publisher\Messaging as MessagingPublisher;
|
||||
use Appwrite\Event\Publisher\Migration as MigrationPublisher;
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Event\Publisher\Screenshot;
|
||||
use Appwrite\Event\Publisher\StatsResources as StatsResourcesPublisher;
|
||||
use Appwrite\Event\Publisher\Usage as UsagePublisher;
|
||||
@@ -73,7 +72,6 @@ class Get extends Base
|
||||
System::getEnv('_APP_SCREENSHOTS_QUEUE_NAME', Event::SCREENSHOTS_QUEUE_NAME),
|
||||
System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME),
|
||||
System::getEnv('_APP_MIGRATIONS_QUEUE_NAME', Event::MIGRATIONS_QUEUE_NAME),
|
||||
System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME),
|
||||
]), 'The name of the queue', enum: new Enum(name: 'HealthQueueName'))
|
||||
->param('threshold', 5000, new Integer(true), 'Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000.', true)
|
||||
->inject('response')
|
||||
@@ -90,7 +88,6 @@ class Get extends Base
|
||||
->inject('publisherForMessaging')
|
||||
->inject('publisherForMigrations')
|
||||
->inject('publisherForScreenshots')
|
||||
->inject('publisherForNotifications')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
@@ -111,7 +108,6 @@ class Get extends Base
|
||||
MessagingPublisher $publisherForMessaging,
|
||||
MigrationPublisher $publisherForMigrations,
|
||||
Screenshot $publisherForScreenshots,
|
||||
NotificationPublisher $publisherForNotifications,
|
||||
): void {
|
||||
$threshold = (int) $threshold;
|
||||
|
||||
@@ -129,7 +125,6 @@ class Get extends Base
|
||||
System::getEnv('_APP_SCREENSHOTS_QUEUE_NAME', Event::SCREENSHOTS_QUEUE_NAME) => $publisherForScreenshots,
|
||||
System::getEnv('_APP_MESSAGING_QUEUE_NAME', Event::MESSAGING_QUEUE_NAME) => $publisherForMessaging,
|
||||
System::getEnv('_APP_MIGRATIONS_QUEUE_NAME', Event::MIGRATIONS_QUEUE_NAME) => $publisherForMigrations,
|
||||
System::getEnv('_APP_NOTIFICATIONS_QUEUE_NAME', Event::NOTIFICATIONS_QUEUE_NAME) => $publisherForNotifications,
|
||||
default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown queue name: ' . $name),
|
||||
};
|
||||
$failed = $queue->getSize(failed: true);
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Health\Http\Health\Queue\Notifications;
|
||||
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Base;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Validator\Integer;
|
||||
|
||||
class Get extends Base
|
||||
{
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'getQueueNotifications';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Base::HTTP_REQUEST_METHOD_GET)
|
||||
->setHttpPath('/v1/health/queue/notifications')
|
||||
->desc('Get notifications queue')
|
||||
->groups(['api', 'health'])
|
||||
->label('scope', 'health.read')
|
||||
->label('sdk', new Method(
|
||||
namespace: 'health',
|
||||
group: 'queue',
|
||||
name: 'getQueueNotifications',
|
||||
description: '/docs/references/health/get-queue-notifications.md',
|
||||
auth: [AuthType::ADMIN, AuthType::KEY],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_HEALTH_QUEUE,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::JSON
|
||||
))
|
||||
->param('threshold', 5000, new Integer(true), 'Queue size threshold. When hit (equal or higher), endpoint returns server error. Default value is 5000.', true)
|
||||
->inject('publisherForNotifications')
|
||||
->inject('response')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(int|string $threshold, NotificationPublisher $publisherForNotifications, Response $response): void
|
||||
{
|
||||
$threshold = (int) $threshold;
|
||||
|
||||
$size = $publisherForNotifications->getSize();
|
||||
|
||||
$this->assertQueueThreshold($size, $threshold);
|
||||
|
||||
$response->dynamic(new Document(['size' => $size]), Response::MODEL_HEALTH_QUEUE);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ use Appwrite\Platform\Modules\Health\Http\Health\Queue\Logs\Get as GetQueueLogs;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Mails\Get as GetQueueMails;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Messaging\Get as GetQueueMessaging;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Migrations\Get as GetQueueMigrations;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Notifications\Get as GetQueueNotifications;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\StatsResources\Get as GetQueueStatsResources;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\StatsUsage\Get as GetQueueUsage;
|
||||
use Appwrite\Platform\Modules\Health\Http\Health\Queue\Webhooks\Get as GetQueueWebhooks;
|
||||
@@ -57,7 +56,6 @@ class Http extends Service
|
||||
$this->addAction(GetQueueMails::getName(), new GetQueueMails());
|
||||
$this->addAction(GetQueueMessaging::getName(), new GetQueueMessaging());
|
||||
$this->addAction(GetQueueMigrations::getName(), new GetQueueMigrations());
|
||||
$this->addAction(GetQueueNotifications::getName(), new GetQueueNotifications());
|
||||
$this->addAction(GetQueueFunctions::getName(), new GetQueueFunctions());
|
||||
$this->addAction(GetQueueStatsResources::getName(), new GetQueueStatsResources());
|
||||
$this->addAction(GetQueueUsage::getName(), new GetQueueUsage());
|
||||
|
||||
-209
@@ -1,209 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Notifications\Http\Notifications\Logos\Appwrite;
|
||||
|
||||
use Ahc\Jwt\JWT;
|
||||
use Appwrite\Event\Message\Audit as AuditMessage;
|
||||
use Appwrite\Event\Publisher\Audit as AuditPublisher;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\MethodType;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Request;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\DateTime;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\System\System;
|
||||
use Utopia\Validator\Text;
|
||||
use Utopia\Validator\WhiteList;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'getNotificationLogo';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
|
||||
->setHttpPath('/v1/notifications/logos/appwrite')
|
||||
->desc('Get notification logo')
|
||||
->groups(['api', 'notifications'])
|
||||
->label('scope', 'public')
|
||||
->label('sdk', new Method(
|
||||
namespace: 'notifications',
|
||||
group: 'logos',
|
||||
name: 'getLogo',
|
||||
description: '/docs/references/notifications/get-logo.md',
|
||||
auth: [],
|
||||
type: MethodType::LOCATION,
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_NONE,
|
||||
),
|
||||
],
|
||||
contentType: ContentType::IMAGE_SVG,
|
||||
))
|
||||
->param('jwt', '', new Text(2048, 0), 'Tracking token.', true)
|
||||
->param('theme', 'system', new WhiteList(['system', 'light', 'dark']), 'Logo color theme.', true)
|
||||
->inject('request')
|
||||
->inject('response')
|
||||
->inject('dbForPlatform')
|
||||
->inject('authorization')
|
||||
->inject('publisherForAudits')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(
|
||||
string $jwt,
|
||||
string $theme,
|
||||
Request $request,
|
||||
Response $response,
|
||||
Database $dbForPlatform,
|
||||
Authorization $authorization,
|
||||
AuditPublisher $publisherForAudits,
|
||||
): void {
|
||||
$secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET');
|
||||
|
||||
if (!empty($secret) && $jwt !== '') {
|
||||
try {
|
||||
$decoder = new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0);
|
||||
$decoded = $decoder->decode($jwt);
|
||||
|
||||
$result = $authorization->skip(fn () => $this->trackView($decoded, $dbForPlatform));
|
||||
|
||||
if ($result !== null) {
|
||||
$this->logView(
|
||||
$result['notification'],
|
||||
$result['project'],
|
||||
$result['seenAt'],
|
||||
$request,
|
||||
$publisherForAudits,
|
||||
);
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Always return the logo and avoid exposing token validity.
|
||||
}
|
||||
}
|
||||
|
||||
$response
|
||||
->setContentType('image/svg+xml')
|
||||
->addHeader('Cache-Control', 'no-store')
|
||||
->send($this->renderLogo($theme));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{notification: Document, project: Document, seenAt: string}|null
|
||||
*/
|
||||
private function trackView(array $decoded, Database $dbForPlatform): ?array
|
||||
{
|
||||
if (
|
||||
!isset($decoded['messageId'], $decoded['recipientHash'], $decoded['channel'], $decoded['projectId'], $decoded['purpose'])
|
||||
|| $decoded['purpose'] !== 'notification_track'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$notifications = $dbForPlatform->find('notifications', [
|
||||
Query::equal('messageId', [(string) $decoded['messageId']]),
|
||||
Query::equal('channel', [(string) $decoded['channel']]),
|
||||
Query::equal('recipientHash', [(string) $decoded['recipientHash']]),
|
||||
Query::limit(1),
|
||||
]);
|
||||
|
||||
if (empty($notifications)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$notification = $notifications[0];
|
||||
if (
|
||||
$notification->getAttribute('projectId') !== (string) $decoded['projectId']
|
||||
|| (isset($decoded['projectInternalId']) && $notification->getAttribute('projectInternalId') !== (string) $decoded['projectInternalId'])
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$seenAt = DateTime::now();
|
||||
$updates = [
|
||||
'read' => true,
|
||||
'lastSeen' => $seenAt,
|
||||
];
|
||||
|
||||
if (empty($notification->getAttribute('firstSeen'))) {
|
||||
$updates['firstSeen'] = $seenAt;
|
||||
}
|
||||
|
||||
$updated = $dbForPlatform->updateDocument('notifications', $notification->getId(), new Document($updates));
|
||||
$project = $dbForPlatform->getDocument('projects', $notification->getAttribute('projectId'));
|
||||
|
||||
if ($project->isEmpty()) {
|
||||
$project = new Document([
|
||||
'$id' => 'console',
|
||||
'$sequence' => 'console',
|
||||
]);
|
||||
}
|
||||
|
||||
return [
|
||||
'notification' => $updated,
|
||||
'project' => $project,
|
||||
'seenAt' => $seenAt,
|
||||
];
|
||||
}
|
||||
|
||||
private function logView(Document $notification, Document $project, string $seenAt, Request $request, AuditPublisher $publisherForAudits): void
|
||||
{
|
||||
$publisherForAudits->enqueue(new AuditMessage(
|
||||
event: 'notification.view',
|
||||
payload: [
|
||||
'notificationId' => $notification->getId(),
|
||||
'messageId' => $notification->getAttribute('messageId', ''),
|
||||
'channel' => $notification->getAttribute('channel', ''),
|
||||
'projectId' => $notification->getAttribute('projectId', ''),
|
||||
'firstSeen' => $notification->getAttribute('firstSeen'),
|
||||
'lastSeen' => $notification->getAttribute('lastSeen'),
|
||||
'seenAt' => $seenAt,
|
||||
],
|
||||
project: $project,
|
||||
user: new Document([
|
||||
'$id' => $notification->getAttribute('resourceId', ''),
|
||||
'$sequence' => $notification->getAttribute('resourceInternalId', ''),
|
||||
'name' => '',
|
||||
'email' => '',
|
||||
'type' => ACTOR_TYPE_HIDDEN,
|
||||
]),
|
||||
resource: 'notification/' . $notification->getId(),
|
||||
mode: APP_MODE_DEFAULT,
|
||||
ip: $request->getIP(),
|
||||
userAgent: $request->getUserAgent(''),
|
||||
hostname: $request->getHostname(),
|
||||
));
|
||||
}
|
||||
|
||||
private function renderLogo(string $theme): string
|
||||
{
|
||||
$style = match ($theme) {
|
||||
'light' => '.wordmark { fill: #19191C; }',
|
||||
'dark' => '.wordmark { fill: #F5F5F7; }',
|
||||
default => '.wordmark { fill: #19191C; } @media (prefers-color-scheme: dark) { .wordmark { fill: #F5F5F7; } }',
|
||||
};
|
||||
|
||||
return <<<SVG
|
||||
<svg width="120" height="28" viewBox="0 0 120 28" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Appwrite">
|
||||
<style>{$style}</style>
|
||||
<path d="M24.4429 17.4322V22.9096H10.7519C6.76318 22.9096 3.28044 20.7067 1.4171 17.4322C1.14622 16.9561 0.909137 16.4567 0.710264 15.9383C0.319864 14.9225 0.0744552 13.8325 0 12.6952V11.2143C0.0161646 10.9609 0.0416361 10.7094 0.0749451 10.4609C0.143032 9.95105 0.245898 9.45211 0.381093 8.96711C1.66006 4.36909 5.81877 1 10.7519 1C15.6851 1 19.8433 4.36909 21.1223 8.96711H15.2682C14.3072 7.4683 12.6437 6.4774 10.7519 6.4774C8.86017 6.4774 7.19668 7.4683 6.23562 8.96711C5.9427 9.42274 5.71542 9.92516 5.56651 10.4609C5.43425 10.936 5.36371 11.4369 5.36371 11.9548C5.36371 13.5248 6.01324 14.94 7.05463 15.9383C8.01961 16.865 9.32061 17.4322 10.7519 17.4322H24.4429Z" fill="#FD366E"/>
|
||||
<path d="M24.4429 10.4609V15.9383H14.4492C15.4906 14.94 16.1401 13.5248 16.1401 11.9548C16.1401 11.4369 16.0696 10.936 15.9373 10.4609H24.4429Z" fill="#FD366E"/>
|
||||
<text class="wordmark" x="34" y="19" font-family="Arial, Helvetica, sans-serif" font-size="16" font-weight="700">Appwrite</text>
|
||||
</svg>
|
||||
SVG;
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Notifications\Http\Notifications;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\Validator\Boolean;
|
||||
|
||||
class Update extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'updateNotification';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH)
|
||||
->setHttpPath('/v1/notifications/:notificationId')
|
||||
->desc('Update notification')
|
||||
->groups(['api', 'notifications'])
|
||||
->label('scope', 'account')
|
||||
->label('sdk', new Method(
|
||||
namespace: 'notifications',
|
||||
group: null,
|
||||
name: 'update',
|
||||
description: '/docs/references/notifications/update-notification.md',
|
||||
auth: [AuthType::SESSION, AuthType::JWT],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_NOTIFICATION,
|
||||
)
|
||||
]
|
||||
))
|
||||
->param('notificationId', '', new UID(), 'Notification ID.')
|
||||
->param('read', null, new Boolean(), 'Notification read status.')
|
||||
->inject('response')
|
||||
->inject('dbForPlatform')
|
||||
->inject('authorization')
|
||||
->inject('project')
|
||||
->inject('user')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(
|
||||
string $notificationId,
|
||||
bool $read,
|
||||
Response $response,
|
||||
Database $dbForPlatform,
|
||||
Authorization $authorization,
|
||||
Document $project,
|
||||
Document $user,
|
||||
): void {
|
||||
if ($project->getId() !== 'console') {
|
||||
throw new Exception(Exception::USER_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
$notification = $dbForPlatform->getDocument('notifications', $notificationId);
|
||||
|
||||
if ($notification->isEmpty()) {
|
||||
$exists = $authorization->skip(fn () => !$dbForPlatform->getDocument('notifications', $notificationId)->isEmpty());
|
||||
if ($exists) {
|
||||
throw new Exception(Exception::USER_UNAUTHORIZED);
|
||||
}
|
||||
throw new Exception(Exception::DOCUMENT_NOT_FOUND);
|
||||
}
|
||||
|
||||
$updated = $dbForPlatform->updateDocument('notifications', $notificationId, new Document([
|
||||
'read' => $read,
|
||||
]));
|
||||
|
||||
$response->dynamic($updated, Response::MODEL_NOTIFICATION);
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Notifications\Http\Notifications;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Database\Validator\Queries\Notifications as NotificationQueries;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Exception\Order as OrderException;
|
||||
use Utopia\Database\Exception\Query as QueryException;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Query\Cursor;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
|
||||
class XList extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'listNotifications';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
|
||||
->setHttpPath('/v1/notifications')
|
||||
->desc('List notifications')
|
||||
->groups(['api', 'notifications'])
|
||||
->label('scope', 'account')
|
||||
->label('sdk', new Method(
|
||||
namespace: 'notifications',
|
||||
group: null,
|
||||
name: 'list',
|
||||
description: '/docs/references/notifications/list-notifications.md',
|
||||
auth: [AuthType::SESSION, AuthType::JWT],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_NOTIFICATION_LIST,
|
||||
)
|
||||
]
|
||||
))
|
||||
->param('queries', [], new NotificationQueries(), '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(', ', NotificationQueries::ALLOWED_ATTRIBUTES), true)
|
||||
->inject('response')
|
||||
->inject('dbForPlatform')
|
||||
->inject('project')
|
||||
->inject('user')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string> $queries
|
||||
*/
|
||||
public function action(
|
||||
array $queries,
|
||||
Response $response,
|
||||
Database $dbForPlatform,
|
||||
Document $project,
|
||||
Document $user
|
||||
): void {
|
||||
if ($project->getId() !== 'console') {
|
||||
throw new Exception(Exception::USER_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
try {
|
||||
$queries = Query::parseQueries($queries);
|
||||
} catch (QueryException $e) {
|
||||
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
|
||||
}
|
||||
|
||||
$cursor = \array_filter($queries, function ($query) {
|
||||
return \in_array($query->getMethod(), [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE]);
|
||||
});
|
||||
$cursor = reset($cursor);
|
||||
if ($cursor) {
|
||||
/** @var Query $cursor */
|
||||
|
||||
$validator = new Cursor();
|
||||
if (!$validator->isValid($cursor)) {
|
||||
throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription());
|
||||
}
|
||||
|
||||
$notificationId = $cursor->getValue();
|
||||
$cursorDocument = $dbForPlatform->getDocument('notifications', $notificationId);
|
||||
|
||||
if ($cursorDocument->isEmpty()) {
|
||||
throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Notification '{$notificationId}' for the 'cursor' value not found.");
|
||||
}
|
||||
|
||||
$cursor->setValue($cursorDocument);
|
||||
}
|
||||
|
||||
$queries[] = Query::equal('channel', [NOTIFICATION_TYPE_CONSOLE]);
|
||||
$queries[] = Query::equal('resourceType', [RESOURCE_TYPE_USERS]);
|
||||
$queries[] = Query::equal('resourceId', [$user->getId()]);
|
||||
|
||||
$filterQueries = Query::groupByType($queries)['filters'];
|
||||
|
||||
try {
|
||||
$results = $dbForPlatform->find('notifications', $queries);
|
||||
$total = $dbForPlatform->count('notifications', $filterQueries, APP_LIMIT_COUNT);
|
||||
} catch (OrderException $e) {
|
||||
throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null.");
|
||||
}
|
||||
|
||||
$response->dynamic(new Document([
|
||||
'notifications' => $results,
|
||||
'total' => $total,
|
||||
]), Response::MODEL_NOTIFICATION_LIST);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Notifications;
|
||||
|
||||
use Appwrite\Platform\Modules\Notifications\Services\Http;
|
||||
use Utopia\Platform;
|
||||
|
||||
class Module extends Platform\Module
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->addService('http', new Http());
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Notifications\Services;
|
||||
|
||||
use Appwrite\Platform\Modules\Notifications\Http\Notifications\Logos\Appwrite\Get as GetAppwriteLogo;
|
||||
use Appwrite\Platform\Modules\Notifications\Http\Notifications\Update as UpdateNotification;
|
||||
use Appwrite\Platform\Modules\Notifications\Http\Notifications\XList as ListNotifications;
|
||||
use Utopia\Platform\Service;
|
||||
|
||||
class Http extends Service
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->type = Service::TYPE_HTTP;
|
||||
|
||||
$this
|
||||
->addAction(ListNotifications::getName(), new ListNotifications())
|
||||
->addAction(UpdateNotification::getName(), new UpdateNotification())
|
||||
->addAction(GetAppwriteLogo::getName(), new GetAppwriteLogo());
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,6 @@ class Update extends Action
|
||||
$labels = (array) \array_values(\array_unique($labels));
|
||||
|
||||
$project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document(['labels' => $labels])));
|
||||
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
|
||||
|
||||
$response->dynamic($project, Response::MODEL_PROJECT);
|
||||
}
|
||||
|
||||
@@ -101,7 +101,6 @@ class Create extends Action
|
||||
]);
|
||||
|
||||
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
|
||||
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
|
||||
|
||||
$queueForEvents->setParam('number', $number);
|
||||
|
||||
|
||||
@@ -95,7 +95,6 @@ class Delete extends Action
|
||||
]);
|
||||
|
||||
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
|
||||
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
|
||||
|
||||
$queueForEvents->setParam('number', $number);
|
||||
|
||||
|
||||
@@ -97,7 +97,6 @@ class Update extends Action
|
||||
]);
|
||||
|
||||
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
|
||||
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
|
||||
|
||||
$queueForEvents->setParam('number', $number);
|
||||
|
||||
|
||||
@@ -78,7 +78,6 @@ class Update extends Action
|
||||
'teamInternalId' => $team->getSequence(),
|
||||
'$permissions' => $permissions,
|
||||
]));
|
||||
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
|
||||
|
||||
$installations = $dbForPlatform->find('installations', [
|
||||
Query::equal('projectInternalId', [$project->getSequence()]),
|
||||
|
||||
@@ -72,7 +72,6 @@ class Update extends Action
|
||||
->setAttribute('legalAddress', $legalAddress)
|
||||
->setAttribute('legalTaxId', $legalTaxId)
|
||||
->setAttribute('search', implode(' ', [$projectId, $name])));
|
||||
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
|
||||
|
||||
$response->dynamic($project, Response::MODEL_PROJECT);
|
||||
}
|
||||
|
||||
@@ -132,7 +132,6 @@ class Create extends Action
|
||||
'resourceInternalId' => $resource->getSequence(),
|
||||
'resourceUpdatedAt' => DateTime::now(),
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'schedule' => $schedule,
|
||||
'active' => $active,
|
||||
];
|
||||
|
||||
@@ -67,12 +67,7 @@ class Get extends Action
|
||||
throw new Exception(Exception::SCHEDULE_NOT_FOUND);
|
||||
}
|
||||
|
||||
$projectInternalId = $schedule->getAttribute('projectInternalId');
|
||||
|
||||
if (
|
||||
$schedule->getAttribute('projectId') !== $project->getId()
|
||||
|| ($projectInternalId !== null && $projectInternalId !== '' && $projectInternalId !== $project->getSequence())
|
||||
) {
|
||||
if ($schedule->getAttribute('projectId') !== $project->getId()) {
|
||||
throw new Exception(Exception::SCHEDULE_NOT_FOUND);
|
||||
}
|
||||
|
||||
|
||||
@@ -77,10 +77,6 @@ class XList extends Action
|
||||
}
|
||||
|
||||
$queries[] = Query::equal('projectId', [$project->getId()]);
|
||||
$queries[] = Query::or([
|
||||
Query::equal('projectInternalId', [$project->getSequence()]),
|
||||
Query::isNull('projectInternalId'),
|
||||
]);
|
||||
|
||||
$cursor = Query::getCursorQueries($queries, false);
|
||||
$cursor = \reset($cursor);
|
||||
@@ -94,11 +90,7 @@ class XList extends Action
|
||||
$scheduleId = $cursor->getValue();
|
||||
$cursorDocument = $dbForPlatform->getDocument('schedules', $scheduleId);
|
||||
|
||||
if (
|
||||
$cursorDocument->isEmpty()
|
||||
|| $cursorDocument->getAttribute('projectId') !== $project->getId()
|
||||
|| !$this->matchesProjectInternalId($cursorDocument, $project)
|
||||
) {
|
||||
if ($cursorDocument->isEmpty()) {
|
||||
throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Schedule '{$scheduleId}' for the 'cursor' value not found.");
|
||||
}
|
||||
|
||||
@@ -119,13 +111,4 @@ class XList extends Action
|
||||
'total' => $total,
|
||||
]), Response::MODEL_SCHEDULE_LIST);
|
||||
}
|
||||
|
||||
private function matchesProjectInternalId(Document $schedule, Document $project): bool
|
||||
{
|
||||
$projectInternalId = $schedule->getAttribute('projectInternalId');
|
||||
|
||||
return $projectInternalId === null
|
||||
|| $projectInternalId === ''
|
||||
|| $projectInternalId === $project->getSequence();
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ use Appwrite\Platform\Workers\Functions;
|
||||
use Appwrite\Platform\Workers\Mails;
|
||||
use Appwrite\Platform\Workers\Messaging;
|
||||
use Appwrite\Platform\Workers\Migrations;
|
||||
use Appwrite\Platform\Workers\Notifications;
|
||||
use Appwrite\Platform\Workers\StatsResources;
|
||||
use Appwrite\Platform\Workers\StatsUsage;
|
||||
use Appwrite\Platform\Workers\Webhooks;
|
||||
@@ -29,7 +28,6 @@ class Workers extends Service
|
||||
->addAction(Functions::getName(), new Functions())
|
||||
->addAction(Mails::getName(), new Mails())
|
||||
->addAction(Messaging::getName(), new Messaging())
|
||||
->addAction(Notifications::getName(), new Notifications())
|
||||
->addAction(Webhooks::getName(), new Webhooks())
|
||||
->addAction(StatsUsage::getName(), new StatsUsage())
|
||||
->addAction(Migrations::getName(), new Migrations())
|
||||
|
||||
@@ -788,17 +788,6 @@ class Deletes extends Action
|
||||
Console::error('Failed to delete schedules: ' . $th->getMessage());
|
||||
}
|
||||
|
||||
// Delete Notifications
|
||||
try {
|
||||
$this->deleteByGroup('notifications', [
|
||||
Query::equal('projectId', [$projectId]),
|
||||
Query::equal('projectInternalId', [$projectInternalId]),
|
||||
Query::orderAsc()
|
||||
], $dbForPlatform);
|
||||
} catch (Throwable $th) {
|
||||
Console::error('Failed to delete notifications: ' . $th->getMessage());
|
||||
}
|
||||
|
||||
// Delete Advisor insights
|
||||
try {
|
||||
$this->deleteByGroup('insights', [
|
||||
|
||||
@@ -1,661 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Workers;
|
||||
|
||||
use Ahc\Jwt\JWT;
|
||||
use Appwrite\Template\Template;
|
||||
use Appwrite\Utopia\Messaging\Adapter\Console as ConsoleAdapter;
|
||||
use Appwrite\Utopia\Messaging\Adapter\Webhook as WebhookAdapter;
|
||||
use Appwrite\Utopia\Messaging\Messages\Console as ConsoleMessage;
|
||||
use Appwrite\Utopia\Messaging\Messages\Webhook as WebhookMessage;
|
||||
use Exception;
|
||||
use Swoole\Runtime;
|
||||
use Throwable;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Exception\Duplicate as DuplicateException;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Logger\Log;
|
||||
use Utopia\Messaging\Adapter\Email as EmailAdapter;
|
||||
use Utopia\Messaging\Adapter\Email\SMTP;
|
||||
use Utopia\Messaging\Messages\Email as EmailMessage;
|
||||
use Utopia\Messaging\Messages\Email\Attachment;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Queue\Message;
|
||||
use Utopia\Registry\Registry;
|
||||
use Utopia\System\System;
|
||||
|
||||
class Notifications extends Action
|
||||
{
|
||||
protected int $previewMaxLen = 150;
|
||||
protected string $whitespaceCodes = ' ‌​‍‎‏';
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected array $richTextParams = [
|
||||
'b' => '<strong>',
|
||||
'/b' => '</strong>',
|
||||
];
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'notifications';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->desc('Notifications worker')
|
||||
->inject('message')
|
||||
->inject('project')
|
||||
->inject('register')
|
||||
->inject('dbForPlatform')
|
||||
->inject('log')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(Message $message, Document $project, Registry $register, Database $dbForPlatform, Log $log): void
|
||||
{
|
||||
if (\class_exists(Runtime::class)) {
|
||||
Runtime::setHookFlags(SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_TCP);
|
||||
}
|
||||
$payload = $message->getPayload();
|
||||
|
||||
if (empty($payload)) {
|
||||
throw new Exception('Missing payload');
|
||||
}
|
||||
|
||||
$deduplicationKey = $payload['deduplicationKey'] ?? '';
|
||||
$messageId = $deduplicationKey !== '' ? \md5($deduplicationKey) : '';
|
||||
|
||||
$recipients = $this->resolveRecipients($payload);
|
||||
if (empty($recipients)) {
|
||||
throw new Exception('No recipients in payload');
|
||||
}
|
||||
|
||||
$failure = null;
|
||||
foreach ($recipients as $recipient) {
|
||||
$recipient = $this->normalizeRecipient($recipient, $project);
|
||||
$channel = $recipient['channel'];
|
||||
|
||||
if ($messageId !== '') {
|
||||
if ($channel === NOTIFICATION_TYPE_CONSOLE) {
|
||||
$this->validateConsoleRecipient($recipient);
|
||||
}
|
||||
$this->validateAlertResource($recipient);
|
||||
}
|
||||
|
||||
if ($messageId !== '' && $this->alreadyDelivered($dbForPlatform, self::buildAlertId($messageId, $recipient))) {
|
||||
$log->addTag('dedup', 'hit');
|
||||
$log->addTag('channel', $channel);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$alertId = $this->dispatch($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $log);
|
||||
if ($messageId !== '' && $channel === NOTIFICATION_TYPE_WEBHOOK && $alertId === null) {
|
||||
$this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project);
|
||||
}
|
||||
} catch (Throwable $error) {
|
||||
$log->addTag('channel', $channel);
|
||||
$log->addTag('error', $error->getMessage());
|
||||
$failure ??= $error;
|
||||
}
|
||||
}
|
||||
|
||||
if ($failure !== null) {
|
||||
throw $failure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string}>
|
||||
*/
|
||||
private function resolveRecipients(array $payload): array
|
||||
{
|
||||
$recipients = $payload['recipients'] ?? [];
|
||||
if (!empty($recipients)) {
|
||||
return $recipients;
|
||||
}
|
||||
|
||||
$address = $payload['recipient'] ?? '';
|
||||
if ($address === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [['address' => $address, 'channel' => NOTIFICATION_TYPE_EMAIL]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string} $recipient
|
||||
* @return array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string}
|
||||
*/
|
||||
private function normalizeRecipient(array $recipient, Document $project): array
|
||||
{
|
||||
$recipient['resourceType'] = $recipient['resourceType'] ?? '';
|
||||
$recipient['resourceId'] = $recipient['resourceId'] ?? '';
|
||||
$recipient['resourceInternalId'] = $recipient['resourceInternalId'] ?? '';
|
||||
$recipient['parentResourceType'] = $recipient['parentResourceType'] ?? RESOURCE_TYPE_PROJECTS;
|
||||
$recipient['parentResourceId'] = $recipient['parentResourceId'] ?? (string) $project->getId();
|
||||
$recipient['parentResourceInternalId'] = $recipient['parentResourceInternalId'] ?? (string) $project->getSequence();
|
||||
|
||||
if (
|
||||
$recipient['channel'] === NOTIFICATION_TYPE_CONSOLE
|
||||
&& $recipient['resourceId'] === ''
|
||||
) {
|
||||
$recipient['resourceType'] = RESOURCE_TYPE_USERS;
|
||||
$recipient['resourceId'] = $recipient['address'];
|
||||
}
|
||||
|
||||
foreach (['resourceType', 'resourceId', 'resourceInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'] as $key) {
|
||||
$recipient[$key] = (string) $recipient[$key];
|
||||
}
|
||||
|
||||
return $recipient;
|
||||
}
|
||||
|
||||
private function alreadyDelivered(Database $dbForPlatform, string $alertId): bool
|
||||
{
|
||||
return !$dbForPlatform->getDocument('notifications', $alertId)->isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a single recipient through the channel-appropriate adapter.
|
||||
*
|
||||
* Returns the alertId when the dispatcher (or its adapter) has already
|
||||
* persisted an alert row, so the action loop knows to skip persistence.
|
||||
* Returns null when persistence is the caller's responsibility.
|
||||
*
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
protected function dispatch(
|
||||
array $recipient,
|
||||
string $messageId,
|
||||
array $payload,
|
||||
Document $project,
|
||||
Registry $register,
|
||||
Database $dbForPlatform,
|
||||
Log $log,
|
||||
): ?string {
|
||||
$channel = $recipient['channel'];
|
||||
|
||||
return match ($channel) {
|
||||
NOTIFICATION_TYPE_EMAIL => $this->dispatchEmail($recipient, $messageId, $payload, $project, $register, $dbForPlatform, $log),
|
||||
NOTIFICATION_TYPE_CONSOLE => $this->dispatchConsole($recipient, $messageId, $payload, $project, $dbForPlatform),
|
||||
NOTIFICATION_TYPE_WEBHOOK => $this->dispatchWebhook($recipient, $payload, $log),
|
||||
default => throw new Exception('Unsupported notification channel: ' . $channel),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
protected function dispatchEmail(
|
||||
array $recipient,
|
||||
string $messageId,
|
||||
array $payload,
|
||||
Document $project,
|
||||
Registry $register,
|
||||
Database $dbForPlatform,
|
||||
Log $log,
|
||||
): ?string {
|
||||
$address = $recipient['address'];
|
||||
$smtp = $this->resolveSmtpConfig($project, $payload);
|
||||
|
||||
if (empty($smtp) && empty(System::getEnv('_APP_SMTP_HOST'))) {
|
||||
$log->addTag('email_skipped', 'no_smtp');
|
||||
throw new Exception('Skipped mail processing. No SMTP configuration has been set.');
|
||||
}
|
||||
|
||||
$type = empty($smtp) ? 'cloud' : 'smtp';
|
||||
$log->addTag('type', $type);
|
||||
|
||||
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https';
|
||||
$consoleHostname = System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost'));
|
||||
|
||||
$subject = $payload['subject'] ?? '';
|
||||
$variables = $payload['variables'] ?? [];
|
||||
$variables = \array_merge($variables, $payload['templateParams'] ?? []);
|
||||
$variables['host'] = $protocol . '://' . $consoleHostname;
|
||||
$name = $payload['name'] ?? '';
|
||||
$body = $payload['body'] ?? '';
|
||||
$preview = $payload['preview'] ?? '';
|
||||
|
||||
$variables['subject'] = $subject;
|
||||
$variables['heading'] = $variables['heading'] ?? $subject;
|
||||
$variables['year'] = \date('Y');
|
||||
|
||||
$attachment = $payload['attachment'] ?? [];
|
||||
$bodyTemplate = $payload['bodyTemplate'] ?? '';
|
||||
if (empty($bodyTemplate)) {
|
||||
$bodyTemplate = $payload['template'] ?? '';
|
||||
}
|
||||
if (empty($bodyTemplate)) {
|
||||
$bodyTemplate = __DIR__ . '/../../../../app/config/locale/templates/email-base.tpl';
|
||||
}
|
||||
|
||||
$bodyTemplate = Template::fromFile($bodyTemplate);
|
||||
$bodyTemplate->setParam('{{body}}', $body, escapeHtml: false);
|
||||
foreach ($variables as $key => $value) {
|
||||
$bodyTemplate->setParam('{{' . $key . '}}', $value, escapeHtml: $key !== 'redirect');
|
||||
}
|
||||
foreach ($this->richTextParams as $key => $value) {
|
||||
$bodyTemplate->setParam('{{' . $key . '}}', $value, escapeHtml: false);
|
||||
}
|
||||
|
||||
$previewWhitespace = '';
|
||||
if (!empty($preview)) {
|
||||
$previewTemplate = Template::fromString($preview);
|
||||
foreach ($variables as $key => $value) {
|
||||
$previewTemplate->setParam('{{' . $key . '}}', $value);
|
||||
}
|
||||
$preview = \strip_tags($previewTemplate->render());
|
||||
|
||||
$previewLen = \strlen($preview);
|
||||
if ($previewLen < $this->previewMaxLen) {
|
||||
$previewWhitespace = \str_repeat($this->whitespaceCodes, $this->previewMaxLen - $previewLen);
|
||||
}
|
||||
}
|
||||
|
||||
$bodyTemplate->setParam('{{preview}}', $preview);
|
||||
$bodyTemplate->setParam('{{previewWhitespace}}', $previewWhitespace, false);
|
||||
|
||||
$body = $bodyTemplate->render();
|
||||
|
||||
$subjectTemplate = Template::fromString($subject);
|
||||
foreach ($variables as $key => $value) {
|
||||
$subjectTemplate->setParam('{{' . $key . '}}', $value);
|
||||
}
|
||||
$subject = \strip_tags($subjectTemplate->render());
|
||||
|
||||
$recipientHash = self::buildRecipientHash($recipient);
|
||||
$trackingSecret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET');
|
||||
if ($messageId !== '' && !empty($trackingSecret)) {
|
||||
$body = $this->injectTrackingLogo($body, $messageId, $recipient['channel'], $recipientHash, $project, $trackingSecret);
|
||||
}
|
||||
|
||||
/** @var EmailAdapter $adapter */
|
||||
$adapter = empty($smtp)
|
||||
? $register->get('smtp')
|
||||
: new SMTP(
|
||||
host: $smtp['host'],
|
||||
port: (int) $smtp['port'],
|
||||
username: $smtp['username'] ?? '',
|
||||
password: $smtp['password'] ?? '',
|
||||
smtpSecure: $smtp['secure'] ?? '',
|
||||
smtpAutoTLS: false,
|
||||
xMailer: 'Appwrite Mailer',
|
||||
timeout: 10,
|
||||
keepAlive: true,
|
||||
timelimit: 30,
|
||||
);
|
||||
|
||||
$defaultFromEmail = System::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
|
||||
$defaultFromName = \urldecode(System::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server'));
|
||||
|
||||
$fromEmail = !empty($smtp) ? ($smtp['senderEmail'] ?? $defaultFromEmail) : $defaultFromEmail;
|
||||
$fromName = !empty($smtp) ? ($smtp['senderName'] ?? $defaultFromName) : $defaultFromName;
|
||||
$replyTo = $defaultFromEmail;
|
||||
$replyToName = $defaultFromName;
|
||||
|
||||
$customMailOptions = $payload['customMailOptions'] ?? [];
|
||||
if (!\is_array($customMailOptions)) {
|
||||
$customMailOptions = [];
|
||||
}
|
||||
|
||||
if (!empty($customMailOptions['senderEmail'])) {
|
||||
$fromEmail = (string) $customMailOptions['senderEmail'];
|
||||
}
|
||||
if (!empty($customMailOptions['senderName'])) {
|
||||
$fromName = (string) $customMailOptions['senderName'];
|
||||
}
|
||||
|
||||
if (!empty($customMailOptions['replyToEmail']) || !empty($customMailOptions['replyToName'])) {
|
||||
$replyTo = (string) ($customMailOptions['replyToEmail'] ?? $replyTo);
|
||||
$replyToName = (string) ($customMailOptions['replyToName'] ?? $replyToName);
|
||||
} elseif (!empty($smtp)) {
|
||||
$smtpReplyToEmail = $smtp['replyToEmail'] ?? $smtp['replyTo'] ?? '';
|
||||
$replyTo = !empty($smtpReplyToEmail) ? $smtpReplyToEmail : ($smtp['senderEmail'] ?? $replyTo);
|
||||
$replyToName = !empty($smtp['replyToName']) ? $smtp['replyToName'] : ($smtp['senderName'] ?? $replyToName);
|
||||
}
|
||||
|
||||
$attachments = null;
|
||||
if (!empty($attachment['content'] ?? '')) {
|
||||
$attachments = [
|
||||
new Attachment(
|
||||
name: $attachment['filename'] ?? 'unknown.file',
|
||||
path: '',
|
||||
type: $attachment['type'] ?? 'plain/text',
|
||||
content: \base64_decode($attachment['content']),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
$emailMessage = new EmailMessage(
|
||||
to: [['email' => $address, 'name' => $name]],
|
||||
subject: $subject,
|
||||
content: $body,
|
||||
fromName: $fromName,
|
||||
fromEmail: $fromEmail,
|
||||
replyToName: $replyToName,
|
||||
replyToEmail: $replyTo,
|
||||
attachments: $attachments,
|
||||
html: true,
|
||||
);
|
||||
|
||||
try {
|
||||
$adapter->send($emailMessage);
|
||||
} catch (Throwable $error) {
|
||||
throw new Exception('Error sending notification: ' . $error->getMessage(), $type === 'smtp' ? 401 : 500);
|
||||
}
|
||||
|
||||
if ($messageId !== '') {
|
||||
return $this->persistAlert($dbForPlatform, $messageId, $recipient, $payload, $project);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
protected function dispatchConsole(array $recipient, string $messageId, array $payload, Document $project, Database $dbForPlatform): ?string
|
||||
{
|
||||
$this->validateConsoleRecipient($recipient);
|
||||
|
||||
$params = $payload['templateParams'] ?? ($payload['variables'] ?? []);
|
||||
$title = self::renderText($payload['subject'] ?? '', $params);
|
||||
$body = self::renderText($payload['preview'] ?? '', $params);
|
||||
if ($body === '') {
|
||||
$body = self::renderText($payload['body'] ?? '', $params);
|
||||
}
|
||||
|
||||
$alertId = $messageId !== '' ? self::buildAlertId($messageId, $recipient) : null;
|
||||
$recipientHash = $messageId !== '' ? self::buildRecipientHash($recipient) : null;
|
||||
|
||||
$consoleRecipient = [
|
||||
'address' => $recipient['address'],
|
||||
'resourceType' => $recipient['resourceType'],
|
||||
'resourceId' => $recipient['resourceId'],
|
||||
'resourceInternalId' => $recipient['resourceInternalId'],
|
||||
'parentResourceType' => $recipient['parentResourceType'],
|
||||
'parentResourceId' => $recipient['parentResourceId'],
|
||||
'parentResourceInternalId' => $recipient['parentResourceInternalId'],
|
||||
];
|
||||
if ($alertId !== null) {
|
||||
$consoleRecipient['alertId'] = $alertId;
|
||||
$consoleRecipient['recipientHash'] = $recipientHash;
|
||||
}
|
||||
|
||||
$consoleMessage = new ConsoleMessage(
|
||||
recipients: [$consoleRecipient],
|
||||
title: $title,
|
||||
body: $body,
|
||||
type: $payload['type'] ?? 'info',
|
||||
messageId: $messageId !== '' ? $messageId : null,
|
||||
projectId: $project->getId(),
|
||||
projectInternalId: $project->getSequence(),
|
||||
);
|
||||
|
||||
$adapter = new ConsoleAdapter($dbForPlatform);
|
||||
$result = $adapter->send($consoleMessage);
|
||||
|
||||
if (($result['deliveredTo'] ?? 0) === 0) {
|
||||
$error = $result['results'][0]['error'] ?? 'unknown error';
|
||||
throw new Exception('Console alert delivery failed: ' . $error);
|
||||
}
|
||||
|
||||
return $alertId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
protected function dispatchWebhook(array $recipient, array $payload, Log $log): ?string
|
||||
{
|
||||
$address = $recipient['address'];
|
||||
$signatureKey = $recipient['signatureKey'] ?? null;
|
||||
|
||||
$body = [
|
||||
'subject' => $payload['subject'] ?? '',
|
||||
'body' => $payload['body'] ?? '',
|
||||
'template' => $payload['template'] ?? '',
|
||||
'params' => $payload['templateParams'] ?? [],
|
||||
'project' => \is_array($payload['project'] ?? null) ? ($payload['project']['$id'] ?? null) : null,
|
||||
'deduplicationKey' => $payload['deduplicationKey'] ?? '',
|
||||
'events' => $payload['events'] ?? [],
|
||||
];
|
||||
|
||||
if ($signatureKey === null || $signatureKey === '') {
|
||||
$log->addTag('webhook_signed', 'false');
|
||||
}
|
||||
|
||||
$message = new WebhookMessage(
|
||||
urls: [$address],
|
||||
payload: $body,
|
||||
signingSecret: $signatureKey,
|
||||
);
|
||||
|
||||
$adapter = new WebhookAdapter();
|
||||
$result = $adapter->send($message);
|
||||
|
||||
if (($result['deliveredTo'] ?? 0) === 0) {
|
||||
$error = $result['results'][0]['error'] ?? 'Unknown error';
|
||||
throw new Exception('Webhook delivery failed: ' . $error);
|
||||
}
|
||||
|
||||
// Caller persists the alert AFTER successful dispatch.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist an alert row. Returns the alertId so callers can reference the row.
|
||||
*
|
||||
* Idempotent: on a duplicate composite-key violation the existing
|
||||
* row's id is returned.
|
||||
*
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType?: string, resourceId?: string, resourceInternalId?: string, parentResourceType?: string, parentResourceId?: string, parentResourceInternalId?: string} $recipient
|
||||
*/
|
||||
protected function persistAlert(Database $dbForPlatform, string $messageId, array $recipient, array $payload, Document $project): string
|
||||
{
|
||||
$recipient = $this->normalizeRecipient($recipient, $project);
|
||||
|
||||
$channel = $recipient['channel'];
|
||||
|
||||
$alertId = self::buildAlertId($messageId, $recipient);
|
||||
$recipientHash = self::buildRecipientHash($recipient);
|
||||
|
||||
$permissions = $this->buildAlertPermissions($recipient['resourceType'], $recipient['resourceId'], $project->getId());
|
||||
if (empty($permissions)) {
|
||||
$permissions = $payload['permissions'] ?? [];
|
||||
}
|
||||
|
||||
$params = $payload['templateParams'] ?? ($payload['variables'] ?? []);
|
||||
$body = self::renderText($payload['preview'] ?? '', $params);
|
||||
if ($body === '') {
|
||||
$body = self::renderText($payload['body'] ?? '', $params);
|
||||
}
|
||||
|
||||
$document = new Document([
|
||||
'$id' => $alertId,
|
||||
'$permissions' => $permissions,
|
||||
'messageId' => $messageId,
|
||||
'recipientHash' => $recipientHash,
|
||||
'type' => $payload['type'] ?? 'info',
|
||||
'channel' => $channel,
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'resourceType' => $recipient['resourceType'],
|
||||
'resourceId' => $recipient['resourceId'],
|
||||
'resourceInternalId' => $recipient['resourceInternalId'],
|
||||
'parentResourceType' => $recipient['parentResourceType'],
|
||||
'parentResourceId' => $recipient['parentResourceId'],
|
||||
'parentResourceInternalId' => $recipient['parentResourceInternalId'],
|
||||
'title' => self::renderText($payload['subject'] ?? '', $params),
|
||||
'body' => $body,
|
||||
'read' => false,
|
||||
]);
|
||||
|
||||
try {
|
||||
$dbForPlatform->createDocument('notifications', $document);
|
||||
return $alertId;
|
||||
} catch (DuplicateException) {
|
||||
$existing = $dbForPlatform->getDocument('notifications', $alertId);
|
||||
return $existing->isEmpty() ? $alertId : $existing->getId();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the deterministic alertId composed of the messageId plus a
|
||||
* recipient hash.
|
||||
*
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
private static function buildAlertId(string $messageId, array $recipient): string
|
||||
{
|
||||
return \substr($messageId, 0, 19) . '_' . self::buildRecipientHash($recipient);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
private static function buildRecipientHash(array $recipient): string
|
||||
{
|
||||
$channel = $recipient['channel'];
|
||||
$address = $recipient['address'];
|
||||
|
||||
return \substr(\md5(
|
||||
$channel
|
||||
. ':' . $address
|
||||
. ':' . $recipient['resourceType']
|
||||
. ':' . $recipient['resourceId']
|
||||
. ':' . $recipient['resourceInternalId']
|
||||
. ':' . $recipient['parentResourceType']
|
||||
. ':' . $recipient['parentResourceId']
|
||||
. ':' . $recipient['parentResourceInternalId']
|
||||
), 0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
private function buildAlertPermissions(string $resourceType, string $resourceId, string $projectId): array
|
||||
{
|
||||
$permissions = [];
|
||||
if ($resourceType === RESOURCE_TYPE_USERS) {
|
||||
$permissions[] = Permission::read(Role::user($resourceId));
|
||||
$permissions[] = Permission::update(Role::user($resourceId));
|
||||
$permissions[] = Permission::delete(Role::user($resourceId));
|
||||
}
|
||||
if ($resourceType === RESOURCE_TYPE_TEAMS) {
|
||||
$permissions[] = Permission::read(Role::team($resourceId));
|
||||
$permissions[] = Permission::update(Role::team($resourceId, 'owner'));
|
||||
$permissions[] = Permission::delete(Role::team($resourceId, 'owner'));
|
||||
if ($projectId !== '') {
|
||||
$permissions[] = Permission::read(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
$permissions[] = Permission::update(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
$permissions[] = Permission::delete(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
}
|
||||
}
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function resolveSmtpConfig(Document $project, array $payload): array
|
||||
{
|
||||
$payloadSmtp = $payload['smtp'] ?? [];
|
||||
if (\is_array($payloadSmtp) && !empty($payloadSmtp)) {
|
||||
return $payloadSmtp;
|
||||
}
|
||||
|
||||
$smtp = $project->getAttribute('smtp', []);
|
||||
if (!\is_array($smtp) || empty($smtp['enabled'] ?? false)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'host' => $smtp['host'] ?? '',
|
||||
'port' => $smtp['port'] ?? '',
|
||||
'username' => $smtp['username'] ?? '',
|
||||
'password' => $smtp['password'] ?? '',
|
||||
'secure' => $smtp['secure'] ?? '',
|
||||
'senderEmail' => $smtp['senderEmail'] ?? '',
|
||||
'senderName' => $smtp['senderName'] ?? '',
|
||||
'replyToEmail' => $smtp['replyToEmail'] ?? $smtp['replyTo'] ?? '',
|
||||
'replyToName' => $smtp['replyToName'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
private function validateConsoleRecipient(array $recipient): void
|
||||
{
|
||||
$validator = new UID();
|
||||
|
||||
if (!$validator->isValid($recipient['resourceId'])) {
|
||||
throw new Exception('Invalid console alert resourceId: ' . $validator->getDescription());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address: string, channel: string, signatureKey?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
private function validateAlertResource(array $recipient): void
|
||||
{
|
||||
foreach (['resourceType', 'resourceId', 'resourceInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'] as $key) {
|
||||
if ($recipient[$key] === '') {
|
||||
throw new Exception('Missing notification ' . $key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function renderText(string $value, array $params): string
|
||||
{
|
||||
if ($value !== '' && !empty($params)) {
|
||||
$template = Template::fromString($value);
|
||||
foreach ($params as $key => $param) {
|
||||
$template->setParam('{{' . $key . '}}', (string) $param);
|
||||
}
|
||||
$value = $template->render();
|
||||
}
|
||||
|
||||
return \trim(\strip_tags($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice a visible tracking logo before the last `</body>` tag (or
|
||||
* append at the end if the body has no closing tag). The logo URL
|
||||
* carries a signed JWT identifying the notification recipient, which the
|
||||
* `/v1/notifications/logos/appwrite` endpoint verifies before marking
|
||||
* the notification as read and recording view timestamps.
|
||||
*/
|
||||
private function injectTrackingLogo(string $body, string $messageId, string $channel, string $recipientHash, Document $project, string $trackingSecret): string
|
||||
{
|
||||
$jwt = (new JWT($trackingSecret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))
|
||||
->encode([
|
||||
'messageId' => $messageId,
|
||||
'channel' => $channel,
|
||||
'recipientHash' => $recipientHash,
|
||||
'projectId' => $project->getId(),
|
||||
'projectInternalId' => $project->getSequence(),
|
||||
'purpose' => 'notification_track',
|
||||
]);
|
||||
|
||||
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https';
|
||||
$hostname = System::getEnv('_APP_DOMAIN', 'localhost');
|
||||
|
||||
$logoUrl = $protocol . '://' . $hostname . '/v1/notifications/logos/appwrite?jwt=' . \urlencode($jwt);
|
||||
$logo = '<img src="' . \htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') . '" width="120" height="28" alt="Appwrite logo" style="display:block;border:0;margin-top:24px" />';
|
||||
|
||||
// Case-insensitive splice before the LAST </body>.
|
||||
if (\preg_match('/<\/body\s*>(?!.*<\/body\s*>)/is', $body)) {
|
||||
return \preg_replace('/<\/body\s*>(?!.*<\/body\s*>)/is', $logo . '$0', $body, 1) ?? ($body . $logo);
|
||||
}
|
||||
|
||||
return $body . $logo;
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Appwrite\Platform\Workers;
|
||||
|
||||
use Appwrite\Event\Message\Notification as NotificationMessage;
|
||||
use Appwrite\Event\Message\Mail as MailMessage;
|
||||
use Appwrite\Event\Message\Usage as UsageMessage;
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Event\Publisher\Mail as MailPublisher;
|
||||
use Appwrite\Event\Publisher\Usage as UsagePublisher;
|
||||
use Appwrite\Network\Validator\PublicHostname;
|
||||
use Appwrite\Template\Template;
|
||||
@@ -37,7 +37,7 @@ class Webhooks extends Action
|
||||
->inject('message')
|
||||
->inject('project')
|
||||
->inject('dbForPlatform')
|
||||
->inject('publisherForNotifications')
|
||||
->inject('publisherForMails')
|
||||
->inject('publisherForUsage')
|
||||
->inject('log')
|
||||
->inject('plan')
|
||||
@@ -48,14 +48,14 @@ class Webhooks extends Action
|
||||
* @param Message $message
|
||||
* @param Document $project
|
||||
* @param Database $dbForPlatform
|
||||
* @param NotificationPublisher $publisherForNotifications
|
||||
* @param MailPublisher $publisherForMails
|
||||
* @param UsagePublisher $publisherForUsage
|
||||
* @param Log $log
|
||||
* @param array $plan
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function action(Message $message, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, Log $log, array $plan): void
|
||||
public function action(Message $message, Document $project, Database $dbForPlatform, MailPublisher $publisherForMails, UsagePublisher $publisherForUsage, Log $log, array $plan): void
|
||||
{
|
||||
$payload = $message->getPayload();
|
||||
|
||||
@@ -72,7 +72,7 @@ class Webhooks extends Action
|
||||
$errors = [];
|
||||
foreach ($project->getAttribute('webhooks', []) as $webhook) {
|
||||
if (array_intersect($webhook->getAttribute('events', []), $events)) {
|
||||
$error = $this->execute($events, $webhookPayload, $webhook, $user, $project, $dbForPlatform, $publisherForNotifications, $publisherForUsage, $plan);
|
||||
$error = $this->execute($events, $webhookPayload, $webhook, $user, $project, $dbForPlatform, $publisherForMails, $publisherForUsage, $plan);
|
||||
if ($error !== null) {
|
||||
$errors[] = $error;
|
||||
}
|
||||
@@ -91,12 +91,11 @@ class Webhooks extends Action
|
||||
* @param Document $user
|
||||
* @param Document $project
|
||||
* @param Database $dbForPlatform
|
||||
* @param NotificationPublisher $publisherForNotifications
|
||||
* @param UsagePublisher $publisherForUsage
|
||||
* @param MailPublisher $publisherForMails
|
||||
* @param array $plan
|
||||
* @return string|null The error log if the delivery failed, otherwise null
|
||||
*/
|
||||
private function execute(array $events, string $payload, Document $webhook, Document $user, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, UsagePublisher $publisherForUsage, array $plan): ?string
|
||||
private function execute(array $events, string $payload, Document $webhook, Document $user, Document $project, Database $dbForPlatform, MailPublisher $publisherForMails, UsagePublisher $publisherForUsage, array $plan): ?string
|
||||
{
|
||||
if ($webhook->getAttribute('enabled') !== true) {
|
||||
return null;
|
||||
@@ -185,7 +184,7 @@ class Webhooks extends Action
|
||||
if ($attempts >= \intval(System::getEnv('_APP_WEBHOOK_MAX_FAILED_ATTEMPTS', '10'))) {
|
||||
$webhook->setAttribute('enabled', false);
|
||||
$updatePayload['enabled'] = false;
|
||||
$this->sendAlert($attempts, $statusCode, $webhook, $project, $dbForPlatform, $publisherForNotifications, $plan);
|
||||
$this->sendEmailAlert($attempts, $statusCode, $webhook, $project, $dbForPlatform, $publisherForMails, $plan);
|
||||
}
|
||||
|
||||
$dbForPlatform->updateDocument('webhooks', $webhook->getId(), new Document($updatePayload));
|
||||
@@ -219,136 +218,65 @@ class Webhooks extends Action
|
||||
* @param Document $webhook
|
||||
* @param Document $project
|
||||
* @param Database $dbForPlatform
|
||||
* @param NotificationPublisher $publisherForNotifications
|
||||
* @param MailPublisher $publisherForMails
|
||||
* @param array $plan
|
||||
* @return void
|
||||
*/
|
||||
public function sendAlert(int $attempts, mixed $statusCode, Document $webhook, Document $project, Database $dbForPlatform, NotificationPublisher $publisherForNotifications, array $plan): void
|
||||
public function sendEmailAlert(int $attempts, mixed $statusCode, Document $webhook, Document $project, Database $dbForPlatform, MailPublisher $publisherForMails, array $plan): void
|
||||
{
|
||||
$memberships = $dbForPlatform->find('memberships', [
|
||||
Query::equal('teamInternalId', [$project->getAttribute('teamInternalId')]),
|
||||
Query::limit(APP_LIMIT_SUBQUERY)
|
||||
]);
|
||||
|
||||
$ownerMemberships = \array_filter(
|
||||
$memberships,
|
||||
fn (Document $membership) => self::hasOwnerRole($membership)
|
||||
);
|
||||
|
||||
if (empty($ownerMemberships)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userIds = \array_values(\array_unique(\array_filter(\array_map(
|
||||
fn (Document $membership) => $membership->getAttribute('userId'),
|
||||
$ownerMemberships
|
||||
))));
|
||||
|
||||
if (empty($userIds)) {
|
||||
return;
|
||||
}
|
||||
$userIds = array_column(\array_map(fn ($membership) => $membership->getArrayCopy(), $memberships), 'userId');
|
||||
|
||||
$users = $dbForPlatform->find('users', [
|
||||
Query::equal('$id', $userIds),
|
||||
Query::limit(APP_LIMIT_SUBQUERY),
|
||||
]);
|
||||
|
||||
if (empty($users)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$projectId = $project->getId();
|
||||
$projectInternalId = $project->getSequence();
|
||||
$region = $project->getAttribute('region', 'default');
|
||||
$webhookId = $webhook->getId();
|
||||
|
||||
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'disabled' ? 'http' : 'https';
|
||||
$consoleHostname = System::getEnv('_APP_CONSOLE_DOMAIN', System::getEnv('_APP_DOMAIN', 'localhost'));
|
||||
$template = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-webhook-failed.tpl');
|
||||
|
||||
$template->setParam('{{webhook}}', $webhook->getAttribute('name'));
|
||||
$template->setParam('{{project}}', $project->getAttribute('name'));
|
||||
$template->setParam('{{url}}', $webhook->getAttribute('url'));
|
||||
$template->setParam('{{error}}', 'The server returned ' . $statusCode . ' status code');
|
||||
$template->setParam('{{path}}', "/console/project-$region-$projectId/settings/webhooks/$webhookId");
|
||||
$template->setParam('{{attempts}}', $attempts);
|
||||
|
||||
$template->setParam('{{logoUrl}}', $plan['logoUrl'] ?? APP_EMAIL_LOGO_URL);
|
||||
$template->setParam('{{accentColor}}', $plan['accentColor'] ?? APP_EMAIL_ACCENT_COLOR);
|
||||
$template->setParam('{{twitterUrl}}', $plan['twitterUrl'] ?? APP_SOCIAL_TWITTER);
|
||||
$template->setParam('{{discordUrl}}', $plan['discordUrl'] ?? APP_SOCIAL_DISCORD);
|
||||
$template->setParam('{{githubUrl}}', $plan['githubUrl'] ?? APP_SOCIAL_GITHUB_APPWRITE);
|
||||
$template->setParam('{{termsUrl}}', $plan['termsUrl'] ?? APP_EMAIL_TERMS_URL);
|
||||
$template->setParam('{{privacyUrl}}', $plan['privacyUrl'] ?? APP_EMAIL_PRIVACY_URL);
|
||||
|
||||
// TODO: Use setbodyTemplate once #7307 is merged
|
||||
$subject = 'Webhook deliveries have been paused';
|
||||
$preview = 'Webhook "' . $webhook->getAttribute('name') . '" has been paused after ' . $attempts . ' failed delivery attempts.';
|
||||
$preview = 'Webhook deliveries to your endpoint have been paused.';
|
||||
$body = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl');
|
||||
|
||||
$body
|
||||
->setParam('{{subject}}', $subject)
|
||||
->setParam('{{message}}', $template->render())
|
||||
->setParam('{{year}}', date("Y"));
|
||||
|
||||
foreach ($users as $user) {
|
||||
$email = $user->getAttribute('email');
|
||||
$userId = $user->getId();
|
||||
|
||||
$recipients = [[
|
||||
'address' => $userId,
|
||||
'channel' => NOTIFICATION_TYPE_CONSOLE,
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => $userId,
|
||||
'resourceInternalId' => (string) $user->getSequence(),
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => $projectId,
|
||||
'parentResourceInternalId' => (string) $projectInternalId,
|
||||
]];
|
||||
|
||||
if (!empty($email)) {
|
||||
$recipients[] = [
|
||||
'address' => $email,
|
||||
'channel' => NOTIFICATION_TYPE_EMAIL,
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => $userId,
|
||||
'resourceInternalId' => (string) $user->getSequence(),
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => $projectId,
|
||||
'parentResourceInternalId' => (string) $projectInternalId,
|
||||
];
|
||||
}
|
||||
|
||||
$template = Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-webhook-failed.tpl');
|
||||
$userName = (string) ($user->getAttribute('name', 'there') ?: 'there');
|
||||
$template->setParam('{{user}}', $userName);
|
||||
$template->setParam('{{webhook}}', $webhook->getAttribute('name'));
|
||||
$template->setParam('{{project}}', $project->getAttribute('name'));
|
||||
$template->setParam('{{url}}', $webhook->getAttribute('url'));
|
||||
$template->setParam('{{error}}', 'The server returned ' . $statusCode . ' status code');
|
||||
$template->setParam('{{host}}', $protocol . '://' . $consoleHostname);
|
||||
$template->setParam('{{path}}', "/console/project-$region-$projectId/settings/webhooks/$webhookId");
|
||||
$template->setParam('{{attempts}}', $attempts);
|
||||
|
||||
$publisherForNotifications->enqueue(new NotificationMessage(
|
||||
$publisherForMails->enqueue(new MailMessage(
|
||||
project: $project,
|
||||
recipients: $recipients,
|
||||
deduplicationKey: 'webhook:' . $webhook->getId() . ':paused:' . $webhook->getUpdatedAt(),
|
||||
recipient: $user->getAttribute('email'),
|
||||
name: $user->getAttribute('name', ''),
|
||||
subject: $subject,
|
||||
bodyTemplate: __DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl',
|
||||
body: $template->render(),
|
||||
template: MAIL_TEMPLATE_WEBHOOK_FAILED,
|
||||
body: $body->render(),
|
||||
preview: $preview,
|
||||
variables: [
|
||||
'logoUrl' => $plan['logoUrl'] ?? APP_EMAIL_LOGO_URL,
|
||||
'accentColor' => $plan['accentColor'] ?? APP_EMAIL_ACCENT_COLOR,
|
||||
'twitter' => $plan['twitterUrl'] ?? APP_SOCIAL_TWITTER,
|
||||
'discord' => $plan['discordUrl'] ?? APP_SOCIAL_DISCORD,
|
||||
'github' => $plan['githubUrl'] ?? APP_SOCIAL_GITHUB_APPWRITE,
|
||||
'terms' => $plan['termsUrl'] ?? APP_EMAIL_TERMS_URL,
|
||||
'privacy' => $plan['privacyUrl'] ?? APP_EMAIL_PRIVACY_URL,
|
||||
'platform' => $plan['platformName'] ?? APP_NAME,
|
||||
],
|
||||
variables: ['user' => $user->getAttribute('name', '')],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private static function hasOwnerRole(Document $membership): bool
|
||||
{
|
||||
$roles = $membership->getAttribute('roles', []);
|
||||
if (\is_string($roles)) {
|
||||
$roles = \array_map('trim', \explode(',', $roles));
|
||||
}
|
||||
if (!\is_array($roles)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($roles as $role) {
|
||||
if (!\is_string($role)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (\strtolower($role) === 'owner') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ enum ContentType: string
|
||||
case JSON = 'application/json';
|
||||
case IMAGE = 'image/*';
|
||||
case IMAGE_PNG = 'image/png';
|
||||
case IMAGE_SVG = 'image/svg+xml';
|
||||
case MULTIPART = 'multipart/form-data';
|
||||
case HTML = 'text/html';
|
||||
case TEXT = 'text/plain';
|
||||
|
||||
@@ -318,7 +318,6 @@ class OpenAPI3 extends Format
|
||||
'image/jpeg',
|
||||
'image/gif',
|
||||
'image/png',
|
||||
'image/svg+xml',
|
||||
'image/webp',
|
||||
'image/svg-x',
|
||||
'image/x-icon',
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Database\Validator\Queries;
|
||||
|
||||
class Notifications extends Base
|
||||
{
|
||||
public const ALLOWED_ATTRIBUTES = [
|
||||
'read',
|
||||
'type',
|
||||
'channel',
|
||||
'messageId',
|
||||
'projectId',
|
||||
'resourceType',
|
||||
'resourceId',
|
||||
'parentResourceType',
|
||||
'parentResourceId',
|
||||
'firstSeen',
|
||||
'lastSeen',
|
||||
];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('notifications', self::ALLOWED_ATTRIBUTES);
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Messaging\Adapter;
|
||||
|
||||
use Appwrite\Utopia\Messaging\Messages\Console as ConsoleMessage;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Exception\Duplicate as DuplicateException;
|
||||
use Utopia\Database\Helpers\ID;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Messaging\Adapter;
|
||||
use Utopia\Messaging\Message;
|
||||
use Utopia\Messaging\Response;
|
||||
|
||||
class Console extends Adapter
|
||||
{
|
||||
protected const NAME = 'Console';
|
||||
protected const TYPE = 'console';
|
||||
protected const MESSAGE_TYPE = ConsoleMessage::class;
|
||||
|
||||
public function __construct(protected Database $database)
|
||||
{
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return static::NAME;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return static::TYPE;
|
||||
}
|
||||
|
||||
public function getMessageType(): string
|
||||
{
|
||||
return static::MESSAGE_TYPE;
|
||||
}
|
||||
|
||||
public function getMaxMessagesPerRequest(): int
|
||||
{
|
||||
return 1000;
|
||||
}
|
||||
|
||||
public function send(Message $message): array
|
||||
{
|
||||
if (!$message instanceof ConsoleMessage) {
|
||||
throw new \Exception('Invalid message type.');
|
||||
}
|
||||
|
||||
return $this->process($message);
|
||||
}
|
||||
|
||||
protected function process(ConsoleMessage $message): array
|
||||
{
|
||||
$response = new Response($this->getType());
|
||||
$delivered = 0;
|
||||
|
||||
foreach ($message->getRecipients() as $recipient) {
|
||||
$resourceType = $recipient['resourceType'];
|
||||
$resourceId = $recipient['resourceId'];
|
||||
$key = $resourceType . ':' . $resourceId;
|
||||
|
||||
$messageId = $message->getMessageId();
|
||||
$recipientKey = self::buildRecipientKey($recipient);
|
||||
$recipientHash = $recipient['recipientHash'] ?? \substr(\md5($recipientKey), 0, 16);
|
||||
$documentId = $messageId !== null
|
||||
? ($recipient['alertId'] ?? \substr($messageId, 0, 19) . '_' . $recipientHash)
|
||||
: ID::unique();
|
||||
|
||||
try {
|
||||
$document = new Document([
|
||||
'$id' => $documentId,
|
||||
'$permissions' => $this->buildPermissions($resourceType, $resourceId, $message->getProjectId() ?? ''),
|
||||
'messageId' => $messageId,
|
||||
'recipientHash' => $recipientHash,
|
||||
'type' => $message->getType(),
|
||||
'channel' => self::TYPE,
|
||||
'projectId' => $message->getProjectId(),
|
||||
'projectInternalId' => $message->getProjectInternalId(),
|
||||
'resourceType' => $resourceType,
|
||||
'resourceId' => $resourceId,
|
||||
'resourceInternalId' => $recipient['resourceInternalId'],
|
||||
'parentResourceType' => $recipient['parentResourceType'],
|
||||
'parentResourceId' => $recipient['parentResourceId'],
|
||||
'parentResourceInternalId' => $recipient['parentResourceInternalId'],
|
||||
'title' => $message->getTitle(),
|
||||
'body' => $message->getBody(),
|
||||
]);
|
||||
|
||||
$this->database->createDocument('notifications', $document);
|
||||
$delivered++;
|
||||
$response->addResult($key);
|
||||
} catch (DuplicateException) {
|
||||
// Idempotent retry: row already exists for this messageId/recipient.
|
||||
// Treat as a successful (already-delivered) result so the worker
|
||||
// does not throw and re-queue.
|
||||
$delivered++;
|
||||
$response->addResult($key);
|
||||
} catch (\Throwable $error) {
|
||||
$response->addResult($key, $error->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$response->setDeliveredTo($delivered);
|
||||
return $response->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
private function buildPermissions(string $resourceType, string $resourceId, string $projectId): array
|
||||
{
|
||||
$permissions = [];
|
||||
if ($resourceType === RESOURCE_TYPE_USERS) {
|
||||
$permissions[] = Permission::read(Role::user($resourceId));
|
||||
$permissions[] = Permission::update(Role::user($resourceId));
|
||||
$permissions[] = Permission::delete(Role::user($resourceId));
|
||||
}
|
||||
if ($resourceType === RESOURCE_TYPE_TEAMS) {
|
||||
$permissions[] = Permission::read(Role::team($resourceId));
|
||||
$permissions[] = Permission::update(Role::team($resourceId, 'owner'));
|
||||
$permissions[] = Permission::delete(Role::team($resourceId, 'owner'));
|
||||
if ($projectId !== '') {
|
||||
$permissions[] = Permission::read(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
$permissions[] = Permission::update(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
$permissions[] = Permission::delete(Role::team($resourceId, 'project-' . $projectId . '-owner'));
|
||||
}
|
||||
}
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{address?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string} $recipient
|
||||
*/
|
||||
private static function buildRecipientKey(array $recipient): string
|
||||
{
|
||||
return ($recipient['address'] ?? '')
|
||||
. ':' . $recipient['resourceType']
|
||||
. ':' . $recipient['resourceId']
|
||||
. ':' . $recipient['resourceInternalId']
|
||||
. ':' . $recipient['parentResourceType']
|
||||
. ':' . $recipient['parentResourceId']
|
||||
. ':' . $recipient['parentResourceInternalId'];
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Messaging\Adapter;
|
||||
|
||||
use Appwrite\Utopia\Messaging\Messages\Webhook as WebhookMessage;
|
||||
use Utopia\Fetch\Client as FetchClient;
|
||||
use Utopia\Fetch\Exception as FetchException;
|
||||
use Utopia\Messaging\Adapter;
|
||||
use Utopia\Messaging\Message;
|
||||
use Utopia\Messaging\Response;
|
||||
|
||||
class Webhook extends Adapter
|
||||
{
|
||||
protected const NAME = 'Webhook';
|
||||
protected const TYPE = 'webhook';
|
||||
protected const MESSAGE_TYPE = WebhookMessage::class;
|
||||
|
||||
protected const SIGNATURE_HEADER = 'X-Appwrite-Webhook-Signature';
|
||||
protected const TIMESTAMP_HEADER = 'X-Appwrite-Webhook-Timestamp';
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return static::NAME;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return static::TYPE;
|
||||
}
|
||||
|
||||
public function getMessageType(): string
|
||||
{
|
||||
return static::MESSAGE_TYPE;
|
||||
}
|
||||
|
||||
public function getMaxMessagesPerRequest(): int
|
||||
{
|
||||
return 100;
|
||||
}
|
||||
|
||||
public function send(Message $message): array
|
||||
{
|
||||
if (!$message instanceof WebhookMessage) {
|
||||
throw new \Exception('Invalid message type.');
|
||||
}
|
||||
|
||||
return $this->process($message);
|
||||
}
|
||||
|
||||
protected function process(WebhookMessage $message): array
|
||||
{
|
||||
$response = new Response($this->getType());
|
||||
$body = \json_encode($message->getPayload(), JSON_THROW_ON_ERROR);
|
||||
$timestamp = (string) \time();
|
||||
|
||||
$headers = [
|
||||
'Content-Type: application/json',
|
||||
self::TIMESTAMP_HEADER . ': ' . $timestamp,
|
||||
];
|
||||
|
||||
$secret = $message->getSigningSecret();
|
||||
if ($secret !== null && $secret !== '') {
|
||||
$signature = \hash_hmac('sha256', $timestamp . '.' . $body, $secret);
|
||||
$headers[] = self::SIGNATURE_HEADER . ': sha256=' . $signature;
|
||||
}
|
||||
|
||||
foreach ($message->getHeaders() as $name => $value) {
|
||||
$headers[] = $name . ': ' . $value;
|
||||
}
|
||||
|
||||
$delivered = 0;
|
||||
foreach ($message->getUrls() as $url) {
|
||||
$result = $this->dispatch('POST', $url, $headers, $body, $message->getTimeout());
|
||||
if ($result['statusCode'] >= 200 && $result['statusCode'] < 300 && empty($result['error'])) {
|
||||
$delivered++;
|
||||
$response->addResult($url);
|
||||
} else {
|
||||
$response->addResult($url, $result['error'] ?: ('HTTP ' . $result['statusCode']));
|
||||
}
|
||||
}
|
||||
|
||||
$response->setDeliveredTo($delivered);
|
||||
return $response->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $headers
|
||||
* @return array{statusCode: int, response: string|null, error: string|null}
|
||||
*/
|
||||
protected function dispatch(string $method, string $url, array $headers, string $body, int $timeout): array
|
||||
{
|
||||
$client = new FetchClient();
|
||||
$client
|
||||
->setTimeout($timeout * 1000)
|
||||
->setConnectTimeout(\min(10, $timeout) * 1000)
|
||||
->setAllowRedirects(false)
|
||||
->setUserAgent('Appwrite Webhook');
|
||||
|
||||
foreach ($headers as $header) {
|
||||
$parts = \explode(':', $header, 2);
|
||||
if (\count($parts) === 2) {
|
||||
$client->addHeader(\trim($parts[0]), \trim($parts[1]));
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $client->fetch($url, $method, $body);
|
||||
} catch (FetchException $exception) {
|
||||
return [
|
||||
'statusCode' => 0,
|
||||
'response' => null,
|
||||
'error' => $exception->getMessage(),
|
||||
];
|
||||
}
|
||||
|
||||
$output = $response->getBody();
|
||||
|
||||
return [
|
||||
'statusCode' => $response->getStatusCode(),
|
||||
'response' => \is_string($output) ? $output : null,
|
||||
'error' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Messaging\Messages;
|
||||
|
||||
use Utopia\Messaging\Message;
|
||||
|
||||
class Console implements Message
|
||||
{
|
||||
private ?string $origin = null;
|
||||
|
||||
/**
|
||||
* @param array<int, array{address?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string, alertId?: string, recipientHash?: string}> $recipients
|
||||
*/
|
||||
public function __construct(
|
||||
protected array $recipients,
|
||||
protected string $title,
|
||||
protected string $body,
|
||||
protected string $type = 'info',
|
||||
protected ?string $messageId = null,
|
||||
protected ?string $projectId = null,
|
||||
protected ?string $projectInternalId = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{address?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string, alertId?: string, recipientHash?: string}>
|
||||
*/
|
||||
public function getRecipients(): array
|
||||
{
|
||||
return $this->recipients;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{address?: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string, alertId?: string, recipientHash?: string}>
|
||||
*/
|
||||
public function getTo(): array
|
||||
{
|
||||
return $this->recipients;
|
||||
}
|
||||
|
||||
public function getTitle(): string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
public function getBody(): string
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
public function getMessageId(): ?string
|
||||
{
|
||||
return $this->messageId;
|
||||
}
|
||||
|
||||
public function getProjectId(): ?string
|
||||
{
|
||||
return $this->projectId;
|
||||
}
|
||||
|
||||
public function getProjectInternalId(): ?string
|
||||
{
|
||||
return $this->projectInternalId;
|
||||
}
|
||||
|
||||
public function setOrigin(?string $origin): self
|
||||
{
|
||||
$this->origin = $origin;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getOrigin(): ?string
|
||||
{
|
||||
return $this->origin;
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Messaging\Messages;
|
||||
|
||||
use Utopia\Messaging\Message;
|
||||
|
||||
class Webhook implements Message
|
||||
{
|
||||
private ?string $origin = null;
|
||||
|
||||
/**
|
||||
* @param array<int, string> $urls
|
||||
* @param array<string, mixed> $payload
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
public function __construct(
|
||||
protected array $urls,
|
||||
protected array $payload,
|
||||
protected ?string $signingSecret = null,
|
||||
protected array $headers = [],
|
||||
protected int $timeout = 30,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function getUrls(): array
|
||||
{
|
||||
return $this->urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias used by the base adapter to bound max messages per request.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function getTo(): array
|
||||
{
|
||||
return $this->urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getPayload(): array
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
|
||||
public function getSigningSecret(): ?string
|
||||
{
|
||||
return $this->signingSecret;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
public function getTimeout(): int
|
||||
{
|
||||
return $this->timeout;
|
||||
}
|
||||
|
||||
public function setOrigin(?string $origin): self
|
||||
{
|
||||
$this->origin = $origin;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getOrigin(): ?string
|
||||
{
|
||||
return $this->origin;
|
||||
}
|
||||
}
|
||||
@@ -70,10 +70,6 @@ class Response extends SwooleResponse
|
||||
public const MODEL_ROW = 'row';
|
||||
public const MODEL_ROW_LIST = 'rowList';
|
||||
|
||||
// Notifications
|
||||
public const MODEL_NOTIFICATION = 'notification';
|
||||
public const MODEL_NOTIFICATION_LIST = 'notificationList';
|
||||
|
||||
// Database Attributes
|
||||
public const MODEL_ATTRIBUTE = 'attribute';
|
||||
public const MODEL_ATTRIBUTE_LIST = 'attributeList';
|
||||
|
||||
@@ -42,7 +42,7 @@ class Log extends Model
|
||||
])
|
||||
->addRule('userType', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'User type who triggered the audit log. Possible values: user, admin, guest, hidden, keyProject, keyAccount, keyOrganization.',
|
||||
'description' => 'User type who triggered the audit log. Possible values: user, admin, guest, keyProject, keyAccount, keyOrganization.',
|
||||
'default' => '',
|
||||
'example' => 'user',
|
||||
])
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Response\Model;
|
||||
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Utopia\Response\Model;
|
||||
|
||||
class Notification extends Model
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->addRule('$id', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Notification ID.',
|
||||
'default' => '',
|
||||
'example' => '5e5ea5c16897e',
|
||||
])
|
||||
->addRule('$createdAt', [
|
||||
'type' => self::TYPE_DATETIME,
|
||||
'description' => 'Notification creation date in ISO 8601 format.',
|
||||
'default' => '',
|
||||
'example' => self::TYPE_DATETIME_EXAMPLE,
|
||||
])
|
||||
->addRule('$updatedAt', [
|
||||
'type' => self::TYPE_DATETIME,
|
||||
'description' => 'Notification update date in ISO 8601 format.',
|
||||
'default' => '',
|
||||
'example' => self::TYPE_DATETIME_EXAMPLE,
|
||||
])
|
||||
->addRule('messageId', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Stable message ID used for dedup.',
|
||||
'default' => '',
|
||||
'example' => 'session.create',
|
||||
'required' => false,
|
||||
])
|
||||
->addRule('type', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Notification type: info, warning, error.',
|
||||
'default' => 'info',
|
||||
'example' => 'info',
|
||||
])
|
||||
->addRule('channel', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Channel: email, sms, push, console, webhook.',
|
||||
'default' => '',
|
||||
'example' => 'email',
|
||||
])
|
||||
->addRule('resourceType', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Resource type this notification is addressed to.',
|
||||
'default' => '',
|
||||
'example' => 'users',
|
||||
])
|
||||
->addRule('resourceId', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Resource ID this notification is addressed to.',
|
||||
'default' => '',
|
||||
'example' => '5e5bb8c16897e',
|
||||
])
|
||||
->addRule('parentResourceType', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Parent resource type for the notification.',
|
||||
'default' => '',
|
||||
'example' => 'projects',
|
||||
])
|
||||
->addRule('parentResourceId', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Parent resource ID for the notification.',
|
||||
'default' => '',
|
||||
'example' => '5e5bb8c16897e',
|
||||
])
|
||||
->addRule('projectId', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Project the notification pertains to.',
|
||||
'default' => '',
|
||||
'example' => '5e5bb8c16897e',
|
||||
'required' => false,
|
||||
])
|
||||
->addRule('title', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Notification title.',
|
||||
'default' => '',
|
||||
'example' => 'New sign-in detected',
|
||||
])
|
||||
->addRule('body', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Notification body.',
|
||||
'default' => '',
|
||||
'example' => 'A new device signed in to your account.',
|
||||
])
|
||||
->addRule('read', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether the notification has been read.',
|
||||
'default' => false,
|
||||
'example' => false,
|
||||
'required' => false,
|
||||
])
|
||||
->addRule('firstSeen', [
|
||||
'type' => self::TYPE_DATETIME,
|
||||
'description' => 'First time the notification was viewed from a notification logo.',
|
||||
'default' => null,
|
||||
'example' => self::TYPE_DATETIME_EXAMPLE,
|
||||
'required' => false,
|
||||
])
|
||||
->addRule('lastSeen', [
|
||||
'type' => self::TYPE_DATETIME,
|
||||
'description' => 'Most recent time the notification was viewed from a notification logo.',
|
||||
'default' => null,
|
||||
'example' => self::TYPE_DATETIME_EXAMPLE,
|
||||
'required' => false,
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'Notification';
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return Response::MODEL_NOTIFICATION;
|
||||
}
|
||||
}
|
||||
@@ -1,632 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\E2E\Services\Notifications;
|
||||
|
||||
use Ahc\Jwt\JWT;
|
||||
use Tests\E2E\Client;
|
||||
use Utopia\Database\Helpers\ID;
|
||||
use Utopia\System\System;
|
||||
|
||||
/**
|
||||
* End-to-end coverage for the notifications queue health surface and the
|
||||
* notifications user-facing API.
|
||||
*
|
||||
* The notification worker itself is exercised in unit tests with a pinned
|
||||
* queue payload; the server side cannot deterministically inject a
|
||||
* Notification onto the live queue without an admin endpoint, so the health
|
||||
* portion validates the public contract that ops and KEDA scale on:
|
||||
*
|
||||
* - GET /v1/health/queue/notifications returns the live queue depth
|
||||
* - the threshold guard returns 503 when the depth exceeds the budget
|
||||
* - the failed-jobs surface accepts the notifications queue name
|
||||
*
|
||||
* The notifications portion exercises the full webhook-paused fanout end-to-end:
|
||||
*
|
||||
* - GET /v1/notifications (empty + populated)
|
||||
* - PATCH /v1/notifications/:notificationId (happy + unauthorized)
|
||||
* - GET /v1/notifications/logos/appwrite (valid JWT + invalid JWT)
|
||||
*
|
||||
* The same webhook-paused fanout drives both channels of a single
|
||||
* Notification, so the email channel is asserted end-to-end through maildev
|
||||
* (Notifications worker → SMTP → maildev inbox) alongside the console alert.
|
||||
*
|
||||
* Dedup, per-channel dispatch, and webhook signing are covered by:
|
||||
* - tests/unit/Platform/Workers/NotificationsTest.php
|
||||
* - tests/unit/Utopia/Messaging/Adapter/ConsoleTest.php
|
||||
* - tests/unit/Utopia/Messaging/Adapter/WebhookTest.php
|
||||
*/
|
||||
trait NotificationsBase
|
||||
{
|
||||
public function testHealthQueueNotificationsReportsSize(): void
|
||||
{
|
||||
$response = $this->client->call(Client::METHOD_GET, '/health/queue/notifications', \array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $this->getProject()['$id'],
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertIsInt($response['body']['size']);
|
||||
$this->assertGreaterThanOrEqual(0, $response['body']['size']);
|
||||
}
|
||||
|
||||
public function testHealthQueueNotificationsThresholdGuard(): void
|
||||
{
|
||||
$response = $this->client->call(Client::METHOD_GET, '/health/queue/notifications', \array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $this->getProject()['$id'],
|
||||
], $this->getHeaders()), ['threshold' => '0']);
|
||||
|
||||
$this->assertContains($response['headers']['status-code'], [200, 503]);
|
||||
}
|
||||
|
||||
public function testHealthQueueFailedAcceptsNotifications(): void
|
||||
{
|
||||
$response = $this->client->call(Client::METHOD_GET, '/health/queue/failed/v1-notifications', \array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $this->getProject()['$id'],
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertIsInt($response['body']['size']);
|
||||
}
|
||||
|
||||
public function testListNotificationsEmpty(): void
|
||||
{
|
||||
// Always read notifications as the console-authenticated owner of the team.
|
||||
// The /v1/notifications endpoint is platform-scoped (dbForPlatform) and
|
||||
// requires a session; server-mode API keys do not satisfy it.
|
||||
$response = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertArrayHasKey('notifications', $response['body']);
|
||||
$this->assertArrayHasKey('total', $response['body']);
|
||||
$this->assertIsArray($response['body']['notifications']);
|
||||
$this->assertIsInt($response['body']['total']);
|
||||
|
||||
// The shared root console user may carry notifications from prior tests in the
|
||||
// same suite — assert only that the response shape is correct and that
|
||||
// counts agree.
|
||||
$this->assertSame(\count($response['body']['notifications']), \min(\count($response['body']['notifications']), $response['body']['total']));
|
||||
}
|
||||
|
||||
public function testWebhookFailureCreatesConsoleAlert(): void
|
||||
{
|
||||
$alertId = $this->seedWebhookFailureAlert();
|
||||
|
||||
$this->assertNotEmpty($alertId);
|
||||
|
||||
$list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
$this->assertSame(200, $list['headers']['status-code']);
|
||||
|
||||
$found = null;
|
||||
foreach ($list['body']['notifications'] as $alert) {
|
||||
if ($alert['$id'] === $alertId) {
|
||||
$found = $alert;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull($found, 'Seeded alert not present in /notifications response.');
|
||||
$this->assertSame('console', $found['channel']);
|
||||
$this->assertStringContainsStringIgnoringCase('webhook', $found['title']);
|
||||
|
||||
// Cache the seeded alert id for downstream tests in the same process.
|
||||
self::$seededAlertId = $alertId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The webhook-paused fanout enqueues a single Notification with both a
|
||||
* console and an email recipient. The console side is asserted above; this
|
||||
* verifies the email channel travels the full path — Notifications worker
|
||||
* → SMTP → maildev — by polling the maildev inbox for the rendered email
|
||||
* addressed to the project owner.
|
||||
*/
|
||||
public function testWebhookFailureSendsEmailNotification(): void
|
||||
{
|
||||
// Reuse the fanout from the console-alert test when it already ran in
|
||||
// this process; otherwise drive a fresh one. Either way the owner email
|
||||
// lands in maildev for the root user this suite created.
|
||||
if (self::$seededAlertId === null) {
|
||||
self::$seededAlertId = $this->seedWebhookFailureAlert();
|
||||
}
|
||||
|
||||
$ownerEmail = $this->getRoot()['email'];
|
||||
|
||||
$this->assertEventually(function () use ($ownerEmail) {
|
||||
$this->assertGreaterThanOrEqual(
|
||||
1,
|
||||
$this->countNotificationEmails($ownerEmail, 'Webhook deliveries have been paused'),
|
||||
'No webhook-paused email observed in maildev for ' . $ownerEmail
|
||||
);
|
||||
}, 30000, 1000);
|
||||
}
|
||||
|
||||
public function testMarkNotificationReadTogglesFlag(): void
|
||||
{
|
||||
$alertId = self::$seededAlertId ?? $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
|
||||
$patch = $this->client->call(
|
||||
Client::METHOD_PATCH,
|
||||
'/notifications/' . $alertId,
|
||||
$this->getConsoleAlertHeaders(),
|
||||
['read' => true]
|
||||
);
|
||||
|
||||
$this->assertSame(200, $patch['headers']['status-code']);
|
||||
$this->assertSame($alertId, $patch['body']['$id']);
|
||||
$this->assertTrue($patch['body']['read']);
|
||||
|
||||
$list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
$this->assertSame(200, $list['headers']['status-code']);
|
||||
|
||||
$found = null;
|
||||
foreach ($list['body']['notifications'] as $alert) {
|
||||
if ($alert['$id'] === $alertId) {
|
||||
$found = $alert;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull($found);
|
||||
$this->assertTrue($found['read']);
|
||||
|
||||
self::$seededAlertId = null; // notification is read, downstream tests will seed fresh
|
||||
}
|
||||
|
||||
public function testMarkNotificationReadUnauthorized(): void
|
||||
{
|
||||
$alertId = $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
|
||||
// Create a stranger console user with their own session.
|
||||
$stranger = $this->createConsoleUser();
|
||||
|
||||
$unauthorized = $this->client->call(
|
||||
Client::METHOD_PATCH,
|
||||
'/notifications/' . $alertId,
|
||||
[
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'cookie' => 'a_session_console=' . $stranger['session'],
|
||||
'x-appwrite-project' => 'console',
|
||||
],
|
||||
['read' => true]
|
||||
);
|
||||
|
||||
$this->assertSame(401, $unauthorized['headers']['status-code']);
|
||||
$this->assertSame('user_unauthorized', $unauthorized['body']['type'] ?? '');
|
||||
|
||||
// Owner re-fetches — alert must still be unread.
|
||||
$list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
$this->assertSame(200, $list['headers']['status-code']);
|
||||
|
||||
$found = null;
|
||||
foreach ($list['body']['notifications'] as $alert) {
|
||||
if ($alert['$id'] === $alertId) {
|
||||
$found = $alert;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull($found);
|
||||
$this->assertFalse($found['read']);
|
||||
|
||||
self::$seededAlertId = $alertId;
|
||||
}
|
||||
|
||||
public function testProjectAccountCannotListPlatformNotificationsWithCollidingUserId(): void
|
||||
{
|
||||
$alertId = $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
|
||||
$attackerProject = $this->getProject(true);
|
||||
$projectId = $attackerProject['$id'];
|
||||
$email = \uniqid('colliding-alert-user-', true) . '@localhost.test';
|
||||
$password = 'password';
|
||||
|
||||
$created = $this->client->call(Client::METHOD_POST, '/users', [
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-key' => $attackerProject['apiKey'],
|
||||
], [
|
||||
'userId' => $this->getRoot()['$id'],
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'name' => 'Colliding Alert User',
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $created['headers']['status-code']);
|
||||
|
||||
$session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], [
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $session['headers']['status-code']);
|
||||
$this->assertNotEmpty($session['cookies']['a_session_' . $projectId] ?? '');
|
||||
|
||||
$response = $this->client->call(Client::METHOD_GET, '/notifications', [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId],
|
||||
'x-appwrite-project' => $projectId,
|
||||
]);
|
||||
|
||||
$this->assertSame(401, $response['headers']['status-code']);
|
||||
$this->assertSame('user_unauthorized', $response['body']['type'] ?? '');
|
||||
|
||||
self::$seededAlertId = $alertId;
|
||||
}
|
||||
|
||||
public function testNotificationLogoTracksViews(): void
|
||||
{
|
||||
$alertId = self::$seededAlertId ?? $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
$alert = $this->findConsoleAlert($alertId);
|
||||
$this->assertFalse($alert['read']);
|
||||
$this->assertEmpty($alert['firstSeen'] ?? null);
|
||||
$this->assertEmpty($alert['lastSeen'] ?? null);
|
||||
|
||||
$secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET');
|
||||
$this->assertNotEmpty($secret, '_APP_NOTIFICATIONS_TRACKING_SECRET must be set for notification logo test');
|
||||
$recipientHash = \substr($alertId, \strrpos($alertId, '_') + 1);
|
||||
|
||||
// Logo endpoint requires `purpose: 'notification_track'`. Other claim
|
||||
// purposes are silently ignored, which the purpose-claim test covers.
|
||||
$jwt = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([
|
||||
'messageId' => $alert['messageId'],
|
||||
'channel' => $alert['channel'],
|
||||
'recipientHash' => $recipientHash,
|
||||
'projectId' => $alert['projectId'],
|
||||
'purpose' => 'notification_track',
|
||||
]);
|
||||
|
||||
$response = $this->client->call(
|
||||
Client::METHOD_GET,
|
||||
'/notifications/logos/appwrite',
|
||||
['x-appwrite-project' => 'console'],
|
||||
[
|
||||
'jwt' => $jwt,
|
||||
'theme' => 'dark',
|
||||
]
|
||||
);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']);
|
||||
$this->assertNotEmpty($response['body']);
|
||||
$this->assertStringStartsWith('<svg', $response['body']);
|
||||
$this->assertStringContainsString('Appwrite', $response['body']);
|
||||
|
||||
$tracked = $this->findConsoleAlert($alertId);
|
||||
$this->assertTrue($tracked['read']);
|
||||
$this->assertNotEmpty($tracked['firstSeen']);
|
||||
$this->assertNotEmpty($tracked['lastSeen']);
|
||||
|
||||
\sleep(1);
|
||||
|
||||
$secondResponse = $this->client->call(
|
||||
Client::METHOD_GET,
|
||||
'/notifications/logos/appwrite',
|
||||
['x-appwrite-project' => 'console'],
|
||||
['jwt' => $jwt]
|
||||
);
|
||||
|
||||
$this->assertSame(200, $secondResponse['headers']['status-code']);
|
||||
|
||||
$viewedAgain = $this->findConsoleAlert($alertId);
|
||||
$this->assertSame($tracked['firstSeen'], $viewedAgain['firstSeen']);
|
||||
$this->assertNotSame($tracked['lastSeen'], $viewedAgain['lastSeen']);
|
||||
|
||||
self::$seededAlertId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reviewer M7: a tracking JWT without a `purpose: 'notification_track'` claim
|
||||
* must be silently rejected. Without the purpose check, any JWT minted
|
||||
* with the same secret (sessions, password reset, etc.) could be
|
||||
* replayed against this endpoint to mark arbitrary notifications as read.
|
||||
*
|
||||
* The endpoint always returns the SVG logo (200 image/svg+xml) — the only
|
||||
* observable difference is whether the alert flips to `read: true`.
|
||||
*/
|
||||
public function testNotificationLogoRejectsJwtWithoutPurposeClaim(): void
|
||||
{
|
||||
$alertId = $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
$alert = $this->findConsoleAlert($alertId);
|
||||
|
||||
$secret = System::getEnv('_APP_NOTIFICATIONS_TRACKING_SECRET');
|
||||
$this->assertNotEmpty($secret, '_APP_NOTIFICATIONS_TRACKING_SECRET must be set for the JWT purpose-claim test');
|
||||
$recipientHash = \substr($alertId, \strrpos($alertId, '_') + 1);
|
||||
|
||||
// Mint a JWT with valid message/recipient claims but NO purpose claim.
|
||||
$jwtNoPurpose = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([
|
||||
'messageId' => $alert['messageId'],
|
||||
'channel' => $alert['channel'],
|
||||
'recipientHash' => $recipientHash,
|
||||
'projectId' => $alert['projectId'],
|
||||
]);
|
||||
|
||||
$response = $this->client->call(
|
||||
Client::METHOD_GET,
|
||||
'/notifications/logos/appwrite',
|
||||
['x-appwrite-project' => 'console'],
|
||||
['jwt' => $jwtNoPurpose]
|
||||
);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code'], 'endpoint must always return 200');
|
||||
$this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']);
|
||||
|
||||
$found = $this->findConsoleAlert($alertId);
|
||||
$this->assertFalse($found['read'], 'JWT without purpose claim must not flip the read flag');
|
||||
$this->assertEmpty($found['firstSeen'] ?? null);
|
||||
$this->assertEmpty($found['lastSeen'] ?? null);
|
||||
|
||||
// Mint a JWT with a wrong purpose value: same expectation, silently rejected.
|
||||
$jwtWrongPurpose = (new JWT($secret, 'HS256', NOTIFICATION_TRACKING_JWT_TTL, 0))->encode([
|
||||
'messageId' => $alert['messageId'],
|
||||
'channel' => $alert['channel'],
|
||||
'recipientHash' => $recipientHash,
|
||||
'projectId' => $alert['projectId'],
|
||||
'purpose' => 'something_else',
|
||||
]);
|
||||
|
||||
$response = $this->client->call(
|
||||
Client::METHOD_GET,
|
||||
'/notifications/logos/appwrite',
|
||||
['x-appwrite-project' => 'console'],
|
||||
['jwt' => $jwtWrongPurpose]
|
||||
);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']);
|
||||
|
||||
$found = $this->findConsoleAlert($alertId);
|
||||
$this->assertFalse($found['read'], 'JWT with wrong purpose value must not flip the read flag');
|
||||
$this->assertEmpty($found['firstSeen'] ?? null);
|
||||
$this->assertEmpty($found['lastSeen'] ?? null);
|
||||
|
||||
self::$seededAlertId = $alertId;
|
||||
}
|
||||
|
||||
public function testNotificationLogoInvalidTokenReturnsSvg(): void
|
||||
{
|
||||
$alertId = $this->seedWebhookFailureAlert();
|
||||
$this->assertNotEmpty($alertId);
|
||||
|
||||
$response = $this->client->call(
|
||||
Client::METHOD_GET,
|
||||
'/notifications/logos/appwrite',
|
||||
['x-appwrite-project' => 'console'],
|
||||
['jwt' => 'tampered-or-empty']
|
||||
);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertStringContainsString('image/svg+xml', $response['headers']['content-type']);
|
||||
$this->assertNotEmpty($response['body']);
|
||||
$this->assertStringStartsWith('<svg', $response['body']);
|
||||
|
||||
// Notification must remain unread: invalid JWT is silently ignored, no DB write.
|
||||
$found = $this->findConsoleAlert($alertId);
|
||||
$this->assertFalse($found['read']);
|
||||
$this->assertEmpty($found['firstSeen'] ?? null);
|
||||
$this->assertEmpty($found['lastSeen'] ?? null);
|
||||
|
||||
self::$seededAlertId = $alertId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @var string|null Cached seeded alert id so consecutive tests can reuse it
|
||||
* without paying the cost of another 10-failure webhook drive.
|
||||
*/
|
||||
protected static ?string $seededAlertId = null;
|
||||
|
||||
/**
|
||||
* Build the auth header set used to talk to the platform-scoped
|
||||
* /v1/notifications endpoints. Always console session, regardless of
|
||||
* the trait's host (server vs console) — the endpoint requires a session
|
||||
* and the root user owns the project team.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function getConsoleAlertHeaders(): array
|
||||
{
|
||||
return [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
|
||||
'x-appwrite-project' => 'console',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Count emails sitting in the maildev inbox that are addressed to the given
|
||||
* recipient and carry the given subject. Mirrors the maildev polling used
|
||||
* by the session-alert e2e suite.
|
||||
*/
|
||||
protected function countNotificationEmails(string $address, string $subject): int
|
||||
{
|
||||
$host = System::getEnv('_APP_SMTP_HOST', 'maildev');
|
||||
$inbox = \file_get_contents('http://' . $host . ':1080/email');
|
||||
if ($inbox === false) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$emails = \json_decode($inbox, true) ?? [];
|
||||
$count = 0;
|
||||
foreach ($emails as $email) {
|
||||
if (($email['subject'] ?? '') !== $subject) {
|
||||
continue;
|
||||
}
|
||||
foreach ($email['to'] ?? [] as $recipient) {
|
||||
if (($recipient['address'] ?? '') === $address) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function findConsoleAlert(string $alertId): array
|
||||
{
|
||||
$list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
$this->assertSame(200, $list['headers']['status-code']);
|
||||
|
||||
foreach ($list['body']['notifications'] as $alert) {
|
||||
if ($alert['$id'] === $alertId) {
|
||||
return $alert;
|
||||
}
|
||||
}
|
||||
|
||||
$this->fail('Alert not present in /notifications response: ' . $alertId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive a webhook past the failure threshold so the
|
||||
* Webhooks worker emits a console+email alert fanout to the project
|
||||
* owner. Returns the alert id.
|
||||
*
|
||||
* Uses a unique webhook-per-call so concurrent tests don't share
|
||||
* attempt counters.
|
||||
*/
|
||||
protected function seedWebhookFailureAlert(): string
|
||||
{
|
||||
$project = $this->getProject();
|
||||
$projectId = $project['$id'];
|
||||
|
||||
// Register a webhook pointing at an unroutable address. The Webhook
|
||||
// worker will fail every delivery and after 10 attempts pause it
|
||||
// and enqueue a console+email alert for the project owner.
|
||||
$webhookName = 'Failing Webhook ' . \uniqid();
|
||||
$webhook = $this->client->call(Client::METHOD_POST, '/webhooks', [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-mode' => 'admin',
|
||||
], [
|
||||
'webhookId' => ID::unique(),
|
||||
'name' => $webhookName,
|
||||
'events' => ['users.*.create'],
|
||||
'url' => 'http://request-catcher-webhook:1/',
|
||||
'tls' => false,
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $webhook['headers']['status-code']);
|
||||
$webhookId = $webhook['body']['$id'];
|
||||
|
||||
$maxAttempts = (int) System::getEnv('_APP_WEBHOOK_MAX_FAILED_ATTEMPTS', '10');
|
||||
|
||||
// Drive the webhook past its failure threshold by issuing user-create
|
||||
// events, each of which triggers a delivery attempt the worker will
|
||||
// fail. Each create event is also dispatched to the project's
|
||||
// pre-existing reachable webhook — that one stays healthy.
|
||||
for ($i = 0; $i < $maxAttempts + 2; $i++) {
|
||||
$email = \uniqid('alert-seed-', true) . '@localhost.test';
|
||||
$created = $this->client->call(Client::METHOD_POST, '/users', \array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'userId' => ID::unique(),
|
||||
'email' => $email,
|
||||
'password' => 'password',
|
||||
'name' => 'Webhook Failure Driver',
|
||||
]);
|
||||
|
||||
// Tolerate transient 409s under parallel load.
|
||||
$this->assertContains(
|
||||
$created['headers']['status-code'],
|
||||
[201, 409],
|
||||
'User create failed while seeding webhook failure: ' . ($created['body']['message'] ?? '')
|
||||
);
|
||||
}
|
||||
|
||||
// Poll for the alert. Alert creation is async (notification worker)
|
||||
// and webhook deliveries also queue up — give them generous time.
|
||||
$alertId = null;
|
||||
$this->assertEventually(function () use (&$alertId, $projectId, $webhookId, $webhookName) {
|
||||
$list = $this->client->call(Client::METHOD_GET, '/notifications', $this->getConsoleAlertHeaders());
|
||||
$this->assertSame(200, $list['headers']['status-code']);
|
||||
|
||||
foreach ($list['body']['notifications'] as $alert) {
|
||||
if (
|
||||
($alert['channel'] ?? '') === 'console'
|
||||
&& ($alert['projectId'] ?? '') === $projectId
|
||||
&& ($alert['parentResourceId'] ?? '') === $projectId
|
||||
&& ($alert['title'] ?? '') === 'Webhook deliveries have been paused'
|
||||
&& \str_contains($alert['body'] ?? '', $webhookName)
|
||||
) {
|
||||
$alertId = $alert['$id'];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->fail('No webhook-paused console alert observed yet for webhook ' . $webhookId);
|
||||
}, 60000, 1000);
|
||||
|
||||
// Cleanup the failing webhook so it doesn't keep firing in the
|
||||
// background for subsequent tests in the same process.
|
||||
$this->client->call(Client::METHOD_DELETE, '/webhooks/' . $webhookId, [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-mode' => 'admin',
|
||||
]);
|
||||
|
||||
return $alertId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fresh console user with its own session, separate from the
|
||||
* shared root user. Used to assert that strangers cannot mark someone
|
||||
* else's alert as read.
|
||||
*
|
||||
* @return array{'$id': string, email: string, session: string}
|
||||
*/
|
||||
protected function createConsoleUser(): array
|
||||
{
|
||||
$email = \uniqid('stranger-', true) . \getmypid() . \bin2hex(\random_bytes(4)) . '@localhost.test';
|
||||
$password = 'password';
|
||||
|
||||
$user = $this->client->call(Client::METHOD_POST, '/account', [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => 'console',
|
||||
], [
|
||||
'userId' => ID::unique(),
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'name' => 'Stranger',
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $user['headers']['status-code']);
|
||||
|
||||
$session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [
|
||||
'origin' => 'http://localhost',
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => 'console',
|
||||
], [
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $session['headers']['status-code']);
|
||||
$this->assertNotEmpty($session['cookies']['a_session_console'] ?? '');
|
||||
|
||||
return [
|
||||
'$id' => $user['body']['$id'],
|
||||
'email' => $email,
|
||||
'session' => $session['cookies']['a_session_console'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\E2E\Services\Notifications;
|
||||
|
||||
use Tests\E2E\Scopes\ProjectCustom;
|
||||
use Tests\E2E\Scopes\Scope;
|
||||
use Tests\E2E\Scopes\SideConsole;
|
||||
|
||||
final class NotificationsCustomConsoleTest extends Scope
|
||||
{
|
||||
use NotificationsBase;
|
||||
use ProjectCustom;
|
||||
use SideConsole;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\E2E\Services\Notifications;
|
||||
|
||||
use Tests\E2E\Scopes\ProjectCustom;
|
||||
use Tests\E2E\Scopes\Scope;
|
||||
use Tests\E2E\Scopes\SideServer;
|
||||
|
||||
final class NotificationsCustomServerTest extends Scope
|
||||
{
|
||||
use NotificationsBase;
|
||||
use ProjectCustom;
|
||||
use SideServer;
|
||||
}
|
||||
@@ -66,7 +66,6 @@ services:
|
||||
- _APP_OPTIONS_FORCE_HTTPS
|
||||
- _APP_OPTIONS_ROUTER_FORCE_HTTPS
|
||||
- _APP_OPENSSL_KEY_V1
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_DOMAIN
|
||||
- _APP_DOMAIN_FUNCTIONS
|
||||
- _APP_DOMAIN_TARGET
|
||||
@@ -282,29 +281,6 @@ services:
|
||||
# - smtp
|
||||
environment:
|
||||
- _APP_ENV
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_REDIS_HOST
|
||||
- _APP_REDIS_PORT
|
||||
- _APP_DB_HOST
|
||||
- _APP_DB_PORT
|
||||
- _APP_DB_SCHEMA
|
||||
- _APP_DB_USER
|
||||
- _APP_DB_PASS
|
||||
|
||||
appwrite-worker-notifications:
|
||||
entrypoint: worker-notifications
|
||||
container_name: appwrite-worker-notifications
|
||||
build:
|
||||
context: .
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- appwrite
|
||||
depends_on:
|
||||
- redis
|
||||
- maildev
|
||||
environment:
|
||||
- _APP_ENV
|
||||
- _APP_NOTIFICATIONS_TRACKING_SECRET
|
||||
- _APP_REDIS_HOST
|
||||
- _APP_REDIS_PORT
|
||||
- _APP_DB_HOST
|
||||
|
||||
@@ -25,15 +25,11 @@ final class ComposeTest extends TestCase
|
||||
|
||||
public function testServices(): void
|
||||
{
|
||||
$this->assertCount(17, $this->object->getServices());
|
||||
$this->assertCount(16, $this->object->getServices());
|
||||
$this->assertSame('appwrite', $this->object->getService('appwrite')->getContainerName());
|
||||
$this->assertSame('', $this->object->getService('appwrite')->getImageVersion());
|
||||
$this->assertSame('3.6', $this->object->getService('traefik')->getImageVersion());
|
||||
$this->assertEquals('3.6', $this->object->getService('traefik')->getImageVersion());
|
||||
$this->assertSame(['2080' => '80', '2443' => '443', '8080' => '8080'], $this->object->getService('traefik')->getPorts());
|
||||
$this->assertSame('appwrite-worker-mails', $this->object->getService('appwrite-worker-mails')->getContainerName());
|
||||
$this->assertSame('worker-mails', $this->object->getService('appwrite-worker-mails')->getEntrypoint());
|
||||
$this->assertSame('appwrite-worker-notifications', $this->object->getService('appwrite-worker-notifications')->getContainerName());
|
||||
$this->assertSame('worker-notifications', $this->object->getService('appwrite-worker-notifications')->getEntrypoint());
|
||||
}
|
||||
|
||||
public function testNetworks(): void
|
||||
@@ -44,8 +40,8 @@ final class ComposeTest extends TestCase
|
||||
public function testVolumes(): void
|
||||
{
|
||||
$this->assertCount(7, $this->object->getVolumes());
|
||||
$this->assertSame('appwrite-mariadb', $this->object->getVolumes()[0]);
|
||||
$this->assertSame('appwrite-redis', $this->object->getVolumes()[1]);
|
||||
$this->assertSame('appwrite-cache', $this->object->getVolumes()[2]);
|
||||
$this->assertEquals('appwrite-mariadb', $this->object->getVolumes()[0]);
|
||||
$this->assertEquals('appwrite-redis', $this->object->getVolumes()[1]);
|
||||
$this->assertEquals('appwrite-cache', $this->object->getVolumes()[2]);
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Event\Message;
|
||||
|
||||
use Appwrite\Event\Message\Notification as NotificationMessage;
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Tests\Unit\Event\MockPublisher;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Queue\Queue;
|
||||
|
||||
require_once __DIR__ . '/../../../../app/init.php';
|
||||
|
||||
final class NotificationTest extends TestCase
|
||||
{
|
||||
public function testNotificationMessageSerializesPublisherPayload(): void
|
||||
{
|
||||
$message = new NotificationMessage(
|
||||
project: new Document([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'database' => 'mysql://database',
|
||||
]),
|
||||
recipient: 'owner@example.test',
|
||||
subject: 'Subject',
|
||||
body: 'Body',
|
||||
preview: 'Preview',
|
||||
event: 'databases.[databaseId].collections.[collectionId].documents.[documentId].create',
|
||||
params: [
|
||||
'databaseId' => 'database-1',
|
||||
'collectionId' => 'collection-1',
|
||||
'documentId' => 'document-1',
|
||||
],
|
||||
platform: ['name' => 'test-platform'],
|
||||
);
|
||||
|
||||
$payload = $message->toArray();
|
||||
|
||||
$this->assertSame([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'database' => 'mysql://database',
|
||||
], $payload['project']);
|
||||
$this->assertSame([
|
||||
[
|
||||
'address' => 'owner@example.test',
|
||||
'channel' => NOTIFICATION_TYPE_EMAIL,
|
||||
],
|
||||
], $payload['recipients']);
|
||||
$this->assertSame('Subject', $payload['subject']);
|
||||
$this->assertSame('Body', $payload['body']);
|
||||
$this->assertSame('Preview', $payload['preview']);
|
||||
$this->assertContains(
|
||||
'databases.database-1.collections.collection-1.documents.document-1.create',
|
||||
$payload['events']
|
||||
);
|
||||
$this->assertSame(['name' => 'test-platform'], $payload['platform']);
|
||||
|
||||
$this->assertSame($payload, NotificationMessage::fromArray($payload)->toArray());
|
||||
}
|
||||
|
||||
public function testNotificationPublisherUsesConfiguredQueue(): void
|
||||
{
|
||||
$publisher = new MockPublisher();
|
||||
$publisherForNotifications = new NotificationPublisher($publisher, new Queue('custom-notifications'));
|
||||
|
||||
$publisherForNotifications->enqueue(new NotificationMessage(
|
||||
project: new Document(['$id' => 'project-1']),
|
||||
recipients: [
|
||||
[
|
||||
'address' => 'user-1',
|
||||
'channel' => NOTIFICATION_TYPE_CONSOLE,
|
||||
],
|
||||
],
|
||||
subject: 'Alert',
|
||||
));
|
||||
|
||||
$events = $publisher->getEvents('custom-notifications');
|
||||
|
||||
$this->assertCount(1, $events);
|
||||
$this->assertSame('Alert', $events[0]['subject']);
|
||||
$this->assertSame(1, $publisherForNotifications->getSize());
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,6 @@ class MockPublisher implements Publisher
|
||||
|
||||
public function getQueueSize(Queue $queue, bool $failedJobs = false): int
|
||||
{
|
||||
return count($this->events[$queue->name] ?? []);
|
||||
return count($this->events[$queue->name]);
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,7 @@ declare(strict_types=1);
|
||||
namespace Tests\Unit\Migration;
|
||||
|
||||
use Appwrite\Migration\Migration;
|
||||
use Appwrite\Migration\Version\V24;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
final class MigrationVersionsTest extends TestCase
|
||||
{
|
||||
@@ -33,103 +26,4 @@ final class MigrationVersionsTest extends TestCase
|
||||
$this->assertArrayHasKey(APP_VERSION_STABLE, Migration::$versions);
|
||||
}
|
||||
}
|
||||
|
||||
public function testV24CreatesAlertsCollectionForConsoleProject(): void
|
||||
{
|
||||
require_once __DIR__ . '/../../../app/init.php';
|
||||
|
||||
$authorization = new Authorization();
|
||||
$database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$database
|
||||
->setAuthorization($authorization)
|
||||
->setDatabase('migrationV24')
|
||||
->setNamespace('migration_' . \uniqid());
|
||||
$database->create();
|
||||
|
||||
$migration = new V24();
|
||||
$migration->setProject(
|
||||
new Document(['$id' => 'console', '$sequence' => 'console']),
|
||||
$database,
|
||||
$database,
|
||||
$authorization,
|
||||
);
|
||||
|
||||
$migrateCollections = new \ReflectionMethod($migration, 'migrateCollections');
|
||||
\ob_start();
|
||||
try {
|
||||
$migrateCollections->invoke($migration);
|
||||
} finally {
|
||||
\ob_end_clean();
|
||||
}
|
||||
|
||||
$collection = $database->getCollection('notifications');
|
||||
$this->assertFalse($collection->isEmpty());
|
||||
|
||||
$attributes = [];
|
||||
foreach ($collection->getAttribute('attributes', []) as $attribute) {
|
||||
$id = $attribute instanceof Document ? $attribute->getAttribute('$id') : ($attribute['$id'] ?? '');
|
||||
$attributes[$id] = $attribute;
|
||||
}
|
||||
$this->assertArrayHasKey('resourceInternalId', $attributes);
|
||||
$this->assertArrayHasKey('parentResourceInternalId', $attributes);
|
||||
$this->assertArrayHasKey('firstSeen', $attributes);
|
||||
$this->assertArrayHasKey('lastSeen', $attributes);
|
||||
|
||||
$indexes = [];
|
||||
foreach ($collection->getAttribute('indexes', []) as $index) {
|
||||
$id = $index instanceof Document ? $index->getAttribute('$id') : ($index['$id'] ?? '');
|
||||
$indexes[$id] = $index instanceof Document ? $index->getAttribute('attributes') : ($index['attributes'] ?? []);
|
||||
}
|
||||
|
||||
$this->assertSame([
|
||||
'_key_messageId',
|
||||
'_key_recipient',
|
||||
'_key_project',
|
||||
'_key_project_resource',
|
||||
'_key_project_parent_resource',
|
||||
], \array_keys($indexes));
|
||||
$this->assertSame(['projectId', 'projectInternalId'], $indexes['_key_project']);
|
||||
$this->assertSame(['projectId', 'projectInternalId', 'resourceType', 'resourceId', 'resourceInternalId'], $indexes['_key_project_resource']);
|
||||
$this->assertSame(['projectId', 'projectInternalId', 'parentResourceType', 'parentResourceId', 'parentResourceInternalId'], $indexes['_key_project_parent_resource']);
|
||||
}
|
||||
|
||||
public function testV24AddsSeenAttributesToExistingAlertsCollection(): void
|
||||
{
|
||||
require_once __DIR__ . '/../../../app/init.php';
|
||||
|
||||
$authorization = new Authorization();
|
||||
$database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$database
|
||||
->setAuthorization($authorization)
|
||||
->setDatabase('migrationV24ExistingAlerts')
|
||||
->setNamespace('migration_existing_alerts_' . \uniqid());
|
||||
$database->create();
|
||||
$database->createCollection('notifications');
|
||||
|
||||
$migration = new V24();
|
||||
$migration->setProject(
|
||||
new Document(['$id' => 'console', '$sequence' => 'console']),
|
||||
$database,
|
||||
$database,
|
||||
$authorization,
|
||||
);
|
||||
|
||||
$migrateCollections = new \ReflectionMethod($migration, 'migrateCollections');
|
||||
\ob_start();
|
||||
try {
|
||||
$migrateCollections->invoke($migration);
|
||||
} finally {
|
||||
\ob_end_clean();
|
||||
}
|
||||
|
||||
$collection = $database->getCollection('notifications');
|
||||
$attributes = [];
|
||||
foreach ($collection->getAttribute('attributes', []) as $attribute) {
|
||||
$id = $attribute instanceof Document ? $attribute->getAttribute('$id') : ($attribute['$id'] ?? '');
|
||||
$attributes[$id] = $attribute;
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('firstSeen', $attributes);
|
||||
$this->assertArrayHasKey('lastSeen', $attributes);
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Modules\Notifications;
|
||||
|
||||
use Appwrite\Platform\Modules\Notifications\Http\Notifications\XList;
|
||||
use Appwrite\Utopia\Response;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
require_once __DIR__ . '/../../../../../app/init.php';
|
||||
|
||||
final class CapturingNotificationsResponse extends Response
|
||||
{
|
||||
public Document $document;
|
||||
public string $model = '';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function dynamic(Document $document, string $model): void
|
||||
{
|
||||
$this->document = $document;
|
||||
$this->model = $model;
|
||||
}
|
||||
}
|
||||
|
||||
final class NotificationsTest extends TestCase
|
||||
{
|
||||
private Authorization $authorization;
|
||||
private Database $database;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->authorization = new Authorization();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
|
||||
$this->database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$this->database
|
||||
->setAuthorization($this->authorization)
|
||||
->setDatabase('notificationEndpointTests')
|
||||
->setNamespace('notifications_' . \uniqid());
|
||||
|
||||
$permissions = [
|
||||
Permission::create(Role::any()),
|
||||
Permission::read(Role::any()),
|
||||
Permission::update(Role::any()),
|
||||
Permission::delete(Role::any()),
|
||||
];
|
||||
|
||||
$this->database->create();
|
||||
$this->database->createCollection('notifications', [], [], $permissions, false);
|
||||
$this->database->createAttribute('notifications', 'messageId', Database::VAR_STRING, 255, false);
|
||||
$this->database->createAttribute('notifications', 'recipientHash', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'type', Database::VAR_STRING, 64, false, 'info');
|
||||
$this->database->createAttribute('notifications', 'channel', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'projectId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'projectInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'resourceType', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'resourceId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'resourceInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceType', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'title', Database::VAR_STRING, 256, true);
|
||||
$this->database->createAttribute('notifications', 'body', Database::VAR_STRING, 16384, true);
|
||||
$this->database->createAttribute('notifications', 'read', Database::VAR_BOOLEAN, 0, false, false);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->authorization->cleanRoles();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
}
|
||||
|
||||
public function testListReturnsOnlyCurrentUserNotifications(): void
|
||||
{
|
||||
$this->createNotification('user-alert', RESOURCE_TYPE_USERS, 'user-a');
|
||||
$this->createNotification('team-alert', RESOURCE_TYPE_TEAMS, 'team-a');
|
||||
$this->createNotification('user-email-receipt', RESOURCE_TYPE_USERS, 'user-a', NOTIFICATION_TYPE_EMAIL);
|
||||
|
||||
$response = new CapturingNotificationsResponse();
|
||||
|
||||
(new XList())->action(
|
||||
[],
|
||||
$response,
|
||||
$this->database,
|
||||
new Document(['$id' => 'console']),
|
||||
new Document(['$id' => 'user-a']),
|
||||
);
|
||||
|
||||
$notifications = $response->document->getAttribute('notifications');
|
||||
|
||||
$this->assertCount(1, $notifications);
|
||||
$this->assertSame('user-alert', $notifications[0]->getId());
|
||||
$this->assertSame(1, $response->document->getAttribute('total'));
|
||||
$this->assertSame(Response::MODEL_NOTIFICATION_LIST, $response->model);
|
||||
}
|
||||
|
||||
private function createNotification(string $id, string $resourceType, string $resourceId, string $channel = NOTIFICATION_TYPE_CONSOLE): Document
|
||||
{
|
||||
return $this->database->createDocument('notifications', new Document([
|
||||
'$id' => $id,
|
||||
'messageId' => $id,
|
||||
'recipientHash' => \substr(\md5($id), 0, 16),
|
||||
'type' => 'info',
|
||||
'channel' => $channel,
|
||||
'projectId' => 'project',
|
||||
'projectInternalId' => '10',
|
||||
'resourceType' => $resourceType,
|
||||
'resourceId' => $resourceId,
|
||||
'resourceInternalId' => '20',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project',
|
||||
'parentResourceInternalId' => '10',
|
||||
'title' => 'Title',
|
||||
'body' => 'Body',
|
||||
'read' => false,
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Modules\Projects;
|
||||
|
||||
use Appwrite\Extend\Exception as AppwriteException;
|
||||
use Appwrite\Platform\Modules\Projects\Http\Schedules\Get;
|
||||
use Appwrite\Platform\Modules\Projects\Http\Schedules\XList;
|
||||
use Appwrite\Utopia\Response;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
require_once __DIR__ . '/../../../../../app/init.php';
|
||||
|
||||
final class CapturingSchedulesResponse extends Response
|
||||
{
|
||||
public Document $document;
|
||||
public string $model = '';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function dynamic(Document $document, string $model): void
|
||||
{
|
||||
$this->document = $document;
|
||||
$this->model = $model;
|
||||
}
|
||||
}
|
||||
|
||||
final class SchedulesTest extends TestCase
|
||||
{
|
||||
private Authorization $authorization;
|
||||
private Database $database;
|
||||
private Document $project;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->authorization = new Authorization();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
|
||||
$this->database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$this->database
|
||||
->setAuthorization($this->authorization)
|
||||
->setDatabase('scheduleTests')
|
||||
->setNamespace('schedules_' . \uniqid());
|
||||
|
||||
$permissions = [
|
||||
Permission::create(Role::any()),
|
||||
Permission::read(Role::any()),
|
||||
Permission::update(Role::any()),
|
||||
Permission::delete(Role::any()),
|
||||
];
|
||||
|
||||
$this->database->create();
|
||||
$this->database->createCollection('projects', [], [], $permissions, false);
|
||||
$this->database->createCollection('schedules', [], [], $permissions, false);
|
||||
$this->database->createAttribute('schedules', 'projectId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('schedules', 'projectInternalId', Database::VAR_ID, 0, false);
|
||||
|
||||
$this->project = $this->database->createDocument('projects', new Document([
|
||||
'$id' => 'project-a',
|
||||
]));
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->authorization->cleanRoles();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
}
|
||||
|
||||
public function testGetAllowsLegacyScheduleWithoutProjectInternalId(): void
|
||||
{
|
||||
$this->createSchedule('legacy');
|
||||
|
||||
$response = new CapturingSchedulesResponse();
|
||||
|
||||
(new Get())->action('project-a', 'legacy', $response, $this->database);
|
||||
|
||||
$this->assertSame('legacy', $response->document->getId());
|
||||
$this->assertSame(Response::MODEL_SCHEDULE, $response->model);
|
||||
}
|
||||
|
||||
public function testGetRejectsScheduleWithMismatchedProjectInternalId(): void
|
||||
{
|
||||
$this->createSchedule('mismatch', projectInternalId: '999');
|
||||
|
||||
$this->expectException(AppwriteException::class);
|
||||
|
||||
(new Get())->action('project-a', 'mismatch', new CapturingSchedulesResponse(), $this->database);
|
||||
}
|
||||
|
||||
public function testListIncludesLegacyAndCurrentProjectSchedules(): void
|
||||
{
|
||||
$this->createSchedule('legacy');
|
||||
$this->createSchedule('current', projectInternalId: $this->project->getSequence());
|
||||
$this->createSchedule('mismatch', projectInternalId: '999');
|
||||
$this->createSchedule('other-project', projectId: 'project-b');
|
||||
|
||||
$response = new CapturingSchedulesResponse();
|
||||
|
||||
(new XList())->action('project-a', [], true, $response, $this->database);
|
||||
|
||||
$schedules = $response->document->getAttribute('schedules');
|
||||
$scheduleIds = \array_map(
|
||||
fn (Document $schedule) => $schedule->getId(),
|
||||
$schedules,
|
||||
);
|
||||
|
||||
$this->assertContains('legacy', $scheduleIds);
|
||||
$this->assertContains('current', $scheduleIds);
|
||||
$this->assertNotContains('mismatch', $scheduleIds);
|
||||
$this->assertNotContains('other-project', $scheduleIds);
|
||||
$this->assertSame(2, $response->document->getAttribute('total'));
|
||||
$this->assertSame(Response::MODEL_SCHEDULE_LIST, $response->model);
|
||||
}
|
||||
|
||||
public function testListCursorAllowsLegacyScheduleWithoutProjectInternalId(): void
|
||||
{
|
||||
$legacy = $this->createSchedule('legacy');
|
||||
$this->createSchedule('current', projectInternalId: $this->project->getSequence());
|
||||
|
||||
$response = new CapturingSchedulesResponse();
|
||||
|
||||
(new XList())->action(
|
||||
'project-a',
|
||||
[Query::cursorAfter($legacy)->toString()],
|
||||
true,
|
||||
$response,
|
||||
$this->database,
|
||||
);
|
||||
|
||||
$this->assertSame(Response::MODEL_SCHEDULE_LIST, $response->model);
|
||||
}
|
||||
|
||||
private function createSchedule(
|
||||
string $id,
|
||||
string $projectId = 'project-a',
|
||||
int|string|null $projectInternalId = null,
|
||||
): Document {
|
||||
$attributes = [
|
||||
'$id' => $id,
|
||||
'projectId' => $projectId,
|
||||
];
|
||||
|
||||
if ($projectInternalId !== null) {
|
||||
$attributes['projectInternalId'] = $projectInternalId;
|
||||
}
|
||||
|
||||
return $this->database->createDocument('schedules', new Document($attributes));
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Workers;
|
||||
|
||||
use Appwrite\Certificates\Adapter as CertificatesAdapter;
|
||||
use Appwrite\Platform\Workers\Deletes;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Storage\Device;
|
||||
|
||||
require_once __DIR__ . '/../../../../app/init.php';
|
||||
|
||||
final class DeletesTest extends TestCase
|
||||
{
|
||||
public function testProjectDeleteScopesAlertsByProjectIdAndProjectInternalId(): void
|
||||
{
|
||||
$database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$project = new Document([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'database' => 'mysql://localhost/appwrite',
|
||||
]);
|
||||
|
||||
$worker = new class () extends Deletes {
|
||||
/**
|
||||
* @var array<string, array<Query>>
|
||||
*/
|
||||
public array $groups = [];
|
||||
|
||||
public function runProjectDelete(
|
||||
Database $database,
|
||||
Document $project,
|
||||
callable $getProjectDB,
|
||||
callable $getDatabasesDB,
|
||||
Device $device,
|
||||
CertificatesAdapter $certificates,
|
||||
): void {
|
||||
$this->deleteProject(
|
||||
$database,
|
||||
$getProjectDB,
|
||||
$getDatabasesDB,
|
||||
$device,
|
||||
$device,
|
||||
$device,
|
||||
$device,
|
||||
$device,
|
||||
$certificates,
|
||||
$project,
|
||||
);
|
||||
}
|
||||
|
||||
protected function deleteByGroup(string $collection, array $queries, Database $database, ?callable $callback = null): void
|
||||
{
|
||||
$this->groups[$collection] = $queries;
|
||||
}
|
||||
};
|
||||
$getProjectDB = static fn () => throw new \RuntimeException('stop');
|
||||
$getDatabasesDB = static fn () => $database;
|
||||
|
||||
try {
|
||||
$worker->runProjectDelete(
|
||||
$database,
|
||||
$project,
|
||||
$getProjectDB,
|
||||
$getDatabasesDB,
|
||||
$this->createStub(Device::class),
|
||||
$this->createStub(CertificatesAdapter::class),
|
||||
);
|
||||
} catch (\RuntimeException $exception) {
|
||||
$this->assertSame('stop', $exception->getMessage());
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('notifications', $worker->groups);
|
||||
|
||||
$queries = $worker->groups['notifications'];
|
||||
$this->assertSame(Query::TYPE_EQUAL, $queries[0]->getMethod());
|
||||
$this->assertSame('projectId', $queries[0]->getAttribute());
|
||||
$this->assertSame(['project-1'], $queries[0]->getValues());
|
||||
|
||||
$this->assertSame(Query::TYPE_EQUAL, $queries[1]->getMethod());
|
||||
$this->assertSame('projectInternalId', $queries[1]->getAttribute());
|
||||
$this->assertSame(['project-internal-1'], $queries[1]->getValues());
|
||||
|
||||
$this->assertSame(Query::TYPE_ORDER_ASC, $queries[2]->getMethod());
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Workers;
|
||||
|
||||
use Appwrite\Platform\Workers\Mails;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Logger\Log;
|
||||
use Utopia\Messaging\Adapter\Email as EmailAdapter;
|
||||
use Utopia\Messaging\Messages\Email as EmailMessage;
|
||||
use Utopia\Queue\Message;
|
||||
use Utopia\Registry\Registry;
|
||||
use Utopia\Telemetry\Adapter\None;
|
||||
|
||||
final class SpyMailAdapter extends EmailAdapter
|
||||
{
|
||||
public ?EmailMessage $captured = null;
|
||||
public int $sendCount = 0;
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'SpySMTP';
|
||||
}
|
||||
|
||||
public function getMaxMessagesPerRequest(): int
|
||||
{
|
||||
return 1000;
|
||||
}
|
||||
|
||||
protected function process(EmailMessage $message): array
|
||||
{
|
||||
$this->sendCount++;
|
||||
$this->captured = $message;
|
||||
|
||||
return [
|
||||
'deliveredTo' => 1,
|
||||
'type' => $this->getType(),
|
||||
'results' => [['recipient' => $message->getTo()[0]['email'] ?? '', 'status' => 'sent']],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
final class MailsTest extends TestCase
|
||||
{
|
||||
public function testLegacyMailPayloadIsSentByMailsWorker(): void
|
||||
{
|
||||
$adapter = new SpyMailAdapter();
|
||||
$registry = new Registry();
|
||||
$registry->set('smtp', static fn () => $adapter);
|
||||
|
||||
$previousSmtpHost = \getenv('_APP_SMTP_HOST');
|
||||
\putenv('_APP_SMTP_HOST=spy.smtp.test');
|
||||
|
||||
try {
|
||||
$worker = new Mails();
|
||||
$worker->action(
|
||||
new Message([
|
||||
'pid' => 'pid',
|
||||
'queue' => 'v1-mails',
|
||||
'timestamp' => \time(),
|
||||
'payload' => [
|
||||
'recipient' => 'legacy@example.test',
|
||||
'name' => 'Legacy User',
|
||||
'subject' => 'Hello {{name}}',
|
||||
'body' => 'Body {{name}}',
|
||||
'variables' => ['name' => 'Legacy'],
|
||||
'customMailOptions' => [
|
||||
'senderEmail' => 'sender@example.test',
|
||||
'senderName' => 'Custom Sender',
|
||||
'replyToEmail' => 'reply@example.test',
|
||||
'replyToName' => 'Custom Reply',
|
||||
],
|
||||
],
|
||||
]),
|
||||
new Document(['$id' => 'project-x']),
|
||||
$registry,
|
||||
new Log(),
|
||||
new None(),
|
||||
);
|
||||
} finally {
|
||||
\putenv($previousSmtpHost === false ? '_APP_SMTP_HOST' : '_APP_SMTP_HOST=' . $previousSmtpHost);
|
||||
}
|
||||
|
||||
$this->assertSame(1, $adapter->sendCount);
|
||||
$this->assertInstanceOf(\Utopia\Messaging\Messages\Email::class, $adapter->captured);
|
||||
|
||||
$message = $adapter->captured;
|
||||
$this->assertSame('legacy@example.test', $message->getTo()[0]['email'] ?? '');
|
||||
$this->assertSame('Legacy User', $message->getTo()[0]['name'] ?? '');
|
||||
$this->assertSame('Hello Legacy', $message->getSubject());
|
||||
$this->assertSame('sender@example.test', $message->getFromEmail());
|
||||
$this->assertSame('Custom Sender', $message->getFromName());
|
||||
$this->assertSame('reply@example.test', $message->getReplyToEmail());
|
||||
$this->assertSame('Custom Reply', $message->getReplyToName());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Workers;
|
||||
|
||||
use Appwrite\Platform\Services\Workers;
|
||||
use Appwrite\Platform\Workers\Mails;
|
||||
use Appwrite\Platform\Workers\Notifications;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class RegistrationTest extends TestCase
|
||||
{
|
||||
public function testMailsAndNotificationsWorkersAreRegisteredSeparately(): void
|
||||
{
|
||||
$service = new Workers();
|
||||
|
||||
$this->assertInstanceOf(Mails::class, $service->getAction('mails'));
|
||||
$this->assertInstanceOf(Notifications::class, $service->getAction('notifications'));
|
||||
}
|
||||
|
||||
public function testEntrypointDoesNotAliasMailsToNotifications(): void
|
||||
{
|
||||
$contents = \file_get_contents(__DIR__ . '/../../../../app/worker.php');
|
||||
|
||||
$this->assertIsString($contents);
|
||||
$this->assertStringNotContainsString("mails' ? 'notifications'", $contents);
|
||||
$this->assertStringContainsString('\'workerName\' => strtolower($workerName)', $contents);
|
||||
}
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Platform\Workers;
|
||||
|
||||
use Appwrite\Event\Publisher\Notification as NotificationPublisher;
|
||||
use Appwrite\Platform\Workers\Webhooks;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Tests\Unit\Event\MockPublisher;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\Queue\Queue;
|
||||
|
||||
require_once __DIR__ . '/../../../../app/init.php';
|
||||
|
||||
final class WebhooksTest extends TestCase
|
||||
{
|
||||
public function testSendAlertPublishesNotificationMessage(): void
|
||||
{
|
||||
$database = $this->createPlatformDatabase();
|
||||
$this->seedOwnerUser($database);
|
||||
|
||||
$publisher = new MockPublisher();
|
||||
$publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications'));
|
||||
$worker = new Webhooks();
|
||||
|
||||
$worker->sendAlert(
|
||||
attempts: 10,
|
||||
statusCode: 500,
|
||||
webhook: new Document([
|
||||
'$id' => 'webhook-1',
|
||||
'$updatedAt' => '2026-01-01T00:00:00.000+00:00',
|
||||
'name' => 'Payments',
|
||||
'url' => 'https://example.test/webhook',
|
||||
]),
|
||||
project: new Document([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'name' => 'Production',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'region' => 'fra',
|
||||
]),
|
||||
dbForPlatform: $database,
|
||||
publisherForNotifications: $publisherForNotifications,
|
||||
plan: []
|
||||
);
|
||||
|
||||
$events = $publisher->getEvents('v1-notifications');
|
||||
|
||||
$this->assertCount(1, $events);
|
||||
|
||||
$payload = $events[0];
|
||||
$this->assertSame('project-1', $payload['project']['$id']);
|
||||
$this->assertSame('project-internal-1', $payload['project']['$sequence']);
|
||||
$this->assertSame('Webhook deliveries have been paused', $payload['subject']);
|
||||
$this->assertSame('Webhook "Payments" has been paused after 10 failed delivery attempts.', $payload['preview']);
|
||||
$this->assertSame('webhook:webhook-1:paused:2026-01-01T00:00:00.000+00:00', $payload['deduplicationKey']);
|
||||
$this->assertSame(
|
||||
\realpath(__DIR__ . '/../../../../app/config/locale/templates/email-base-styled.tpl'),
|
||||
\realpath($payload['bodyTemplate'])
|
||||
);
|
||||
$this->assertStringContainsString('Payments', (string) $payload['body']);
|
||||
$this->assertStringContainsString('Ada Lovelace', (string) $payload['body']);
|
||||
$this->assertStringContainsString('/console/project-fra-project-1/settings/webhooks/webhook-1', (string) $payload['body']);
|
||||
$this->assertStringNotContainsString('{{', (string) $payload['body']);
|
||||
$this->assertSame(APP_NAME, $payload['variables']['platform']);
|
||||
$this->assertSame(APP_EMAIL_LOGO_URL, $payload['variables']['logoUrl']);
|
||||
$this->assertCount(2, $payload['recipients']);
|
||||
$this->assertSame([
|
||||
'address' => 'user-1',
|
||||
'channel' => NOTIFICATION_TYPE_CONSOLE,
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => 'user-1',
|
||||
'resourceInternalId' => '101',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project-1',
|
||||
'parentResourceInternalId' => 'project-internal-1',
|
||||
], $payload['recipients'][0]);
|
||||
$this->assertSame([
|
||||
'address' => 'owner@example.test',
|
||||
'channel' => NOTIFICATION_TYPE_EMAIL,
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => 'user-1',
|
||||
'resourceInternalId' => '101',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project-1',
|
||||
'parentResourceInternalId' => 'project-internal-1',
|
||||
], $payload['recipients'][1]);
|
||||
}
|
||||
|
||||
public function testSendAlertPersonalizesBodyPerOwner(): void
|
||||
{
|
||||
$database = $this->createPlatformDatabase();
|
||||
$this->seedOwnerUser($database);
|
||||
$database->createDocument('memberships', new Document([
|
||||
'$id' => 'membership-3',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'userId' => 'user-3',
|
||||
'roles' => 'owner',
|
||||
]));
|
||||
$database->createDocument('users', new Document([
|
||||
'$id' => 'user-3',
|
||||
'$sequence' => 103,
|
||||
'email' => 'grace@example.test',
|
||||
'name' => 'Grace Hopper',
|
||||
]));
|
||||
|
||||
$publisher = new MockPublisher();
|
||||
$publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications'));
|
||||
$worker = new Webhooks();
|
||||
|
||||
$worker->sendAlert(
|
||||
attempts: 10,
|
||||
statusCode: 500,
|
||||
webhook: new Document([
|
||||
'$id' => 'webhook-1',
|
||||
'$updatedAt' => '2026-01-01T00:00:00.000+00:00',
|
||||
'name' => 'Payments',
|
||||
'url' => 'https://example.test/webhook',
|
||||
]),
|
||||
project: new Document([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'name' => 'Production',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'region' => 'fra',
|
||||
]),
|
||||
dbForPlatform: $database,
|
||||
publisherForNotifications: $publisherForNotifications,
|
||||
plan: []
|
||||
);
|
||||
|
||||
$events = $publisher->getEvents('v1-notifications');
|
||||
|
||||
$this->assertCount(2, $events);
|
||||
|
||||
$bodies = [];
|
||||
foreach ($events as $event) {
|
||||
foreach ($event['recipients'] as $recipient) {
|
||||
if ($recipient['channel'] === NOTIFICATION_TYPE_EMAIL) {
|
||||
$bodies[$recipient['address']] = $event['body'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('owner@example.test', $bodies);
|
||||
$this->assertArrayHasKey('grace@example.test', $bodies);
|
||||
$this->assertStringContainsString('Ada Lovelace', (string) $bodies['owner@example.test']);
|
||||
$this->assertStringNotContainsString('Grace Hopper', (string) $bodies['owner@example.test']);
|
||||
$this->assertStringContainsString('Grace Hopper', (string) $bodies['grace@example.test']);
|
||||
$this->assertStringNotContainsString('Ada Lovelace', (string) $bodies['grace@example.test']);
|
||||
}
|
||||
|
||||
public function testSendAlertDeduplicationKeyChangesPerPauseCycle(): void
|
||||
{
|
||||
$database = $this->createPlatformDatabase();
|
||||
$this->seedOwnerUser($database);
|
||||
$publisher = new MockPublisher();
|
||||
$publisherForNotifications = new NotificationPublisher($publisher, new Queue('v1-notifications'));
|
||||
$worker = new Webhooks();
|
||||
$project = new Document([
|
||||
'$id' => 'project-1',
|
||||
'$sequence' => 'project-internal-1',
|
||||
'name' => 'Production',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'region' => 'fra',
|
||||
]);
|
||||
|
||||
foreach (['2026-01-01T00:00:00.000+00:00', '2026-01-02T00:00:00.000+00:00'] as $updatedAt) {
|
||||
$worker->sendAlert(
|
||||
attempts: 10,
|
||||
statusCode: 500,
|
||||
webhook: new Document([
|
||||
'$id' => 'webhook-1',
|
||||
'$updatedAt' => $updatedAt,
|
||||
'name' => 'Payments',
|
||||
'url' => 'https://example.test/webhook',
|
||||
]),
|
||||
project: $project,
|
||||
dbForPlatform: $database,
|
||||
publisherForNotifications: $publisherForNotifications,
|
||||
plan: []
|
||||
);
|
||||
}
|
||||
|
||||
$events = $publisher->getEvents('v1-notifications');
|
||||
|
||||
$this->assertCount(2, $events);
|
||||
$this->assertSame('webhook:webhook-1:paused:2026-01-01T00:00:00.000+00:00', $events[0]['deduplicationKey']);
|
||||
$this->assertSame('webhook:webhook-1:paused:2026-01-02T00:00:00.000+00:00', $events[1]['deduplicationKey']);
|
||||
}
|
||||
|
||||
#[DataProvider('ownerRoleProvider')]
|
||||
public function testOwnerRoleDetectionAcceptsArrayAndCommaStringRoles(mixed $roles, bool $expected): void
|
||||
{
|
||||
$method = new \ReflectionMethod(Webhooks::class, 'hasOwnerRole');
|
||||
$membership = new Document([
|
||||
'$id' => 'membership-1',
|
||||
'roles' => $roles,
|
||||
]);
|
||||
|
||||
$this->assertSame($expected, $method->invoke(null, $membership));
|
||||
}
|
||||
|
||||
public static function ownerRoleProvider(): \Iterator
|
||||
{
|
||||
yield 'array owner' => [['owner'], true];
|
||||
yield 'array mixed case owner' => [['Owner'], true];
|
||||
yield 'comma string owner' => ['developer, owner', true];
|
||||
yield 'project-scoped owner string not recognized' => [['project-project-1-owner'], false];
|
||||
yield 'mixed case project-scoped owner string not recognized' => [['Project-Project-1-Owner'], false];
|
||||
yield 'comma string project-scoped owner not recognized' => ['developer, project-project-1-owner', false];
|
||||
yield 'other project owner' => [['project-project-2-owner'], false];
|
||||
yield 'non owner' => [['developer'], false];
|
||||
yield 'invalid roles' => [null, false];
|
||||
}
|
||||
|
||||
private function createPlatformDatabase(): Database
|
||||
{
|
||||
$authorization = new Authorization();
|
||||
$authorization->addRole(Role::any()->toString());
|
||||
|
||||
$database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$database
|
||||
->setAuthorization($authorization)
|
||||
->setDatabase('webhookTests')
|
||||
->setNamespace('webhook_' . \uniqid());
|
||||
|
||||
$permissions = [
|
||||
Permission::create(Role::any()),
|
||||
Permission::read(Role::any()),
|
||||
Permission::update(Role::any()),
|
||||
Permission::delete(Role::any()),
|
||||
];
|
||||
|
||||
$database->create();
|
||||
$database->createCollection('memberships', [], [], $permissions, false);
|
||||
$database->createAttribute('memberships', 'teamInternalId', Database::VAR_STRING, 255, true);
|
||||
$database->createAttribute('memberships', 'userId', Database::VAR_STRING, 255, true);
|
||||
$database->createAttribute('memberships', 'roles', Database::VAR_STRING, 1024, true);
|
||||
$database->createCollection('users', [], [], $permissions, false);
|
||||
$database->createAttribute('users', 'email', Database::VAR_STRING, 320, false);
|
||||
$database->createAttribute('users', 'name', Database::VAR_STRING, 256, false);
|
||||
|
||||
return $database;
|
||||
}
|
||||
|
||||
private function seedOwnerUser(Database $database): void
|
||||
{
|
||||
$database->createDocument('memberships', new Document([
|
||||
'$id' => 'membership-1',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'userId' => 'user-1',
|
||||
'roles' => 'owner',
|
||||
]));
|
||||
$database->createDocument('memberships', new Document([
|
||||
'$id' => 'membership-2',
|
||||
'teamInternalId' => 'team-internal-1',
|
||||
'userId' => 'user-2',
|
||||
'roles' => 'developer',
|
||||
]));
|
||||
$database->createDocument('users', new Document([
|
||||
'$id' => 'user-1',
|
||||
'$sequence' => 101,
|
||||
'email' => 'owner@example.test',
|
||||
'name' => 'Ada Lovelace',
|
||||
]));
|
||||
$database->createDocument('users', new Document([
|
||||
'$id' => 'user-2',
|
||||
'$sequence' => 102,
|
||||
'email' => 'developer@example.test',
|
||||
'name' => 'Developer User',
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Utopia\Messaging\Adapter;
|
||||
|
||||
use Appwrite\Utopia\Messaging\Adapter\Webhook;
|
||||
|
||||
/**
|
||||
* Test double that captures the curl request the adapter would issue and
|
||||
* returns a scripted response, so callers exercise the real signing/header
|
||||
* logic without touching the network. Lives in its own file so PSR-4
|
||||
* autoload resolves it from any test file.
|
||||
*/
|
||||
class CapturingWebhook extends Webhook
|
||||
{
|
||||
/**
|
||||
* @var array<int, array{method: string, url: string, headers: array<int, string>, body: string, timeout: int}>
|
||||
*/
|
||||
public array $captured = [];
|
||||
|
||||
/** @var array{statusCode: int, response: string|null, error: string|null} */
|
||||
public array $response = ['statusCode' => 200, 'response' => 'OK', 'error' => null];
|
||||
|
||||
protected function dispatch(string $method, string $url, array $headers, string $body, int $timeout): array
|
||||
{
|
||||
$this->captured[] = [
|
||||
'method' => $method,
|
||||
'url' => $url,
|
||||
'headers' => $headers,
|
||||
'body' => $body,
|
||||
'timeout' => $timeout,
|
||||
];
|
||||
return $this->response;
|
||||
}
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Utopia\Messaging\Adapter;
|
||||
|
||||
use Appwrite\Utopia\Messaging\Adapter\Console;
|
||||
use Appwrite\Utopia\Messaging\Messages\Console as ConsoleMessage;
|
||||
use Appwrite\Utopia\Messaging\Messages\Webhook as WebhookMessage;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\None as NoCache;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Database\Adapter\Memory;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Helpers\ID;
|
||||
use Utopia\Database\Helpers\Permission;
|
||||
use Utopia\Database\Helpers\Role;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
final class ConsoleTest extends TestCase
|
||||
{
|
||||
private Database $database;
|
||||
private Authorization $authorization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->authorization = new Authorization();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
|
||||
$this->database = new Database(new Memory(), new Cache(new NoCache()));
|
||||
$this->database
|
||||
->setAuthorization($this->authorization)
|
||||
->setDatabase('alertsTests')
|
||||
->setNamespace('alerts_' . \uniqid());
|
||||
|
||||
$this->database->create();
|
||||
$this->database->createCollection('notifications', [], [], [Permission::create(Role::any()), Permission::read(Role::any())], false);
|
||||
$this->database->createAttribute('notifications', 'messageId', Database::VAR_STRING, 255, false);
|
||||
$this->database->createAttribute('notifications', 'recipientHash', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'type', Database::VAR_STRING, 64, false, 'info');
|
||||
$this->database->createAttribute('notifications', 'channel', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'projectId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'projectInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'resourceType', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'resourceId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'resourceInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceType', Database::VAR_STRING, 64, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceId', Database::VAR_STRING, 255, true);
|
||||
$this->database->createAttribute('notifications', 'parentResourceInternalId', Database::VAR_ID, 0, true);
|
||||
$this->database->createAttribute('notifications', 'title', Database::VAR_STRING, 256, true);
|
||||
$this->database->createAttribute('notifications', 'body', Database::VAR_STRING, 16384, true);
|
||||
$this->database->createAttribute('notifications', 'read', Database::VAR_BOOLEAN, 0, false, false);
|
||||
$this->database->createAttribute('notifications', 'firstSeen', Database::VAR_DATETIME, 0, false);
|
||||
$this->database->createAttribute('notifications', 'lastSeen', Database::VAR_DATETIME, 0, false);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->authorization->cleanRoles();
|
||||
$this->authorization->addRole(Role::any()->toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors the per-recipient `$id` derivation in
|
||||
* Appwrite\Utopia\Messaging\Adapter\Console::process().
|
||||
*/
|
||||
private function alertId(string $messageId, string $address, string $resourceType, string $resourceId): string
|
||||
{
|
||||
$key = $address
|
||||
. ':' . $resourceType
|
||||
. ':' . $resourceId
|
||||
. ':' . $resourceId . '-internal'
|
||||
. ':projects:project-1:project-internal-1';
|
||||
return \substr($messageId, 0, 19) . '_' . \substr(\md5($key), 0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{address: string, resourceType: string, resourceId: string, resourceInternalId: string, parentResourceType: string, parentResourceId: string, parentResourceInternalId: string}
|
||||
*/
|
||||
private function recipient(string $address, string $resourceId, string $resourceType = RESOURCE_TYPE_USERS): array
|
||||
{
|
||||
return [
|
||||
'address' => $address,
|
||||
'resourceType' => $resourceType,
|
||||
'resourceId' => $resourceId,
|
||||
'resourceInternalId' => $resourceId . '-internal',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project-1',
|
||||
'parentResourceInternalId' => 'project-internal-1',
|
||||
];
|
||||
}
|
||||
|
||||
public function testWritesAlertWithCorrectSchema(): void
|
||||
{
|
||||
$message = new ConsoleMessage(
|
||||
recipients: [$this->recipient('user-1', 'user-1')],
|
||||
title: 'Hello',
|
||||
body: 'World',
|
||||
type: 'info',
|
||||
messageId: ID::custom('msg-aaa'),
|
||||
projectId: 'project-1',
|
||||
projectInternalId: 'project-internal-1',
|
||||
);
|
||||
|
||||
$adapter = new Console($this->database);
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(1, $result['deliveredTo']);
|
||||
|
||||
$stored = $this->database->getDocument('notifications', $this->alertId('msg-aaa', 'user-1', RESOURCE_TYPE_USERS, 'user-1'));
|
||||
$this->assertFalse($stored->isEmpty());
|
||||
$this->assertSame('msg-aaa', $stored->getAttribute('messageId'));
|
||||
$this->assertSame('console', $stored->getAttribute('channel'));
|
||||
$this->assertSame('project-1', $stored->getAttribute('projectId'));
|
||||
$this->assertSame('project-internal-1', $stored->getAttribute('projectInternalId'));
|
||||
$this->assertSame(RESOURCE_TYPE_USERS, $stored->getAttribute('resourceType'));
|
||||
$this->assertSame('user-1', $stored->getAttribute('resourceId'));
|
||||
$this->assertSame('user-1-internal', $stored->getAttribute('resourceInternalId'));
|
||||
$this->assertSame(RESOURCE_TYPE_PROJECTS, $stored->getAttribute('parentResourceType'));
|
||||
$this->assertSame('project-1', $stored->getAttribute('parentResourceId'));
|
||||
$this->assertSame('project-internal-1', $stored->getAttribute('parentResourceInternalId'));
|
||||
$this->assertSame('Hello', $stored->getAttribute('title'));
|
||||
$this->assertSame('World', $stored->getAttribute('body'));
|
||||
$this->assertSame('info', $stored->getAttribute('type'));
|
||||
$this->assertFalse($stored->getAttribute('read'));
|
||||
$this->assertNull($stored->getAttribute('firstSeen'));
|
||||
$this->assertNull($stored->getAttribute('lastSeen'));
|
||||
}
|
||||
|
||||
public function testUserPermissionsScopedToRecipient(): void
|
||||
{
|
||||
$message = new ConsoleMessage(
|
||||
recipients: [$this->recipient('user-2', 'user-2')],
|
||||
title: 'Title',
|
||||
body: 'Body',
|
||||
messageId: ID::custom('msg-perms-user'),
|
||||
projectId: 'project-1',
|
||||
projectInternalId: 'project-internal-1',
|
||||
);
|
||||
|
||||
(new Console($this->database))->send($message);
|
||||
|
||||
$stored = $this->database->getDocument('notifications', $this->alertId('msg-perms-user', 'user-2', RESOURCE_TYPE_USERS, 'user-2'));
|
||||
$permissions = $stored->getPermissions();
|
||||
|
||||
$this->assertContains(Permission::read(Role::user('user-2')), $permissions);
|
||||
$this->assertContains(Permission::update(Role::user('user-2')), $permissions);
|
||||
$this->assertContains(Permission::delete(Role::user('user-2')), $permissions);
|
||||
}
|
||||
|
||||
public function testTeamRecipientGrantsTeamReadAndOwnerWrite(): void
|
||||
{
|
||||
$message = new ConsoleMessage(
|
||||
recipients: [$this->recipient('team-9', 'team-9', RESOURCE_TYPE_TEAMS)],
|
||||
title: 'Heads up',
|
||||
body: '...',
|
||||
messageId: ID::custom('msg-team'),
|
||||
projectId: 'project-1',
|
||||
projectInternalId: 'project-internal-1',
|
||||
);
|
||||
|
||||
(new Console($this->database))->send($message);
|
||||
|
||||
$stored = $this->database->getDocument('notifications', $this->alertId('msg-team', 'team-9', RESOURCE_TYPE_TEAMS, 'team-9'));
|
||||
$permissions = $stored->getPermissions();
|
||||
|
||||
$this->assertContains(Permission::read(Role::team('team-9')), $permissions);
|
||||
$this->assertContains(Permission::update(Role::team('team-9', 'owner')), $permissions);
|
||||
$this->assertContains(Permission::delete(Role::team('team-9', 'owner')), $permissions);
|
||||
$this->assertContains(Permission::read(Role::team('team-9', 'project-project-1-owner')), $permissions);
|
||||
$this->assertContains(Permission::update(Role::team('team-9', 'project-project-1-owner')), $permissions);
|
||||
$this->assertContains(Permission::delete(Role::team('team-9', 'project-project-1-owner')), $permissions);
|
||||
}
|
||||
|
||||
public function testMultiRecipientWithSameMessageIdGeneratesDistinctIds(): void
|
||||
{
|
||||
$message = new ConsoleMessage(
|
||||
recipients: [
|
||||
$this->recipient('a', 'a'),
|
||||
$this->recipient('b', 'b'),
|
||||
],
|
||||
title: 'Heads up',
|
||||
body: 'multi',
|
||||
messageId: ID::custom('same-msg'),
|
||||
projectId: 'project-1',
|
||||
projectInternalId: 'project-internal-1',
|
||||
);
|
||||
|
||||
$adapter = new Console($this->database);
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(2, $result['deliveredTo']);
|
||||
|
||||
$idA = $this->alertId('same-msg', 'a', RESOURCE_TYPE_USERS, 'a');
|
||||
$idB = $this->alertId('same-msg', 'b', RESOURCE_TYPE_USERS, 'b');
|
||||
|
||||
$this->assertNotSame($idA, $idB, 'recipient suffixes must be distinct');
|
||||
|
||||
$rowA = $this->database->getDocument('notifications', $idA);
|
||||
$rowB = $this->database->getDocument('notifications', $idB);
|
||||
$this->assertFalse($rowA->isEmpty(), 'first recipient row must exist');
|
||||
$this->assertFalse($rowB->isEmpty(), 'second recipient row must exist');
|
||||
|
||||
$this->assertSame('same-msg', $rowA->getAttribute('messageId'));
|
||||
$this->assertSame('same-msg', $rowB->getAttribute('messageId'));
|
||||
$this->assertSame('a', $rowA->getAttribute('resourceId'));
|
||||
$this->assertSame('b', $rowB->getAttribute('resourceId'));
|
||||
|
||||
$this->assertMatchesRegularExpression('/^same-msg_[0-9a-f]{16}$/', $idA);
|
||||
$this->assertMatchesRegularExpression('/^same-msg_[0-9a-f]{16}$/', $idB);
|
||||
}
|
||||
|
||||
public function testRejectsForeignMessageType(): void
|
||||
{
|
||||
$adapter = new Console($this->database);
|
||||
$this->expectException(\Exception::class);
|
||||
$this->expectExceptionMessage('Invalid message type.');
|
||||
|
||||
// ConsoleMessage extends nothing; pass an unrelated Message implementation
|
||||
$adapter->send(new WebhookMessage(urls: ['https://example.test'], payload: []));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reviewer C4: a `DuplicateException` thrown by `createDocument` must be
|
||||
* treated as a SUCCESSFUL delivery, not a failure. The adapter previously
|
||||
* lumped Duplicate into the generic Throwable catch, which surfaced as a
|
||||
* per-recipient `error` and caused the worker to throw, re-queueing the
|
||||
* notification and never marking the duplicate as delivered.
|
||||
*/
|
||||
public function testConsoleAdapterTreatsDuplicateAsDelivered(): void
|
||||
{
|
||||
$userId = 'user-dup';
|
||||
$messageId = 'msg-dup';
|
||||
$documentId = $this->alertId($messageId, $userId, RESOURCE_TYPE_USERS, $userId);
|
||||
|
||||
// Pre-insert an alert with the SAME id the adapter will compute. The
|
||||
// adapter's createDocument will hit the primary-key DuplicateException
|
||||
// and must treat it as a successful (idempotent) send.
|
||||
$this->database->createDocument('notifications', new Document([
|
||||
'$id' => $documentId,
|
||||
'$permissions' => [Permission::read(Role::any())],
|
||||
'messageId' => $messageId,
|
||||
'recipientHash' => \substr(\md5($userId . ':' . RESOURCE_TYPE_USERS . ':' . $userId . ':' . $userId . '-internal:projects:project-1:project-internal-1'), 0, 16),
|
||||
'channel' => 'console',
|
||||
'projectId' => 'project-x',
|
||||
'projectInternalId' => 'project-internal-x',
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => $userId,
|
||||
'resourceInternalId' => $userId . '-internal',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project-1',
|
||||
'parentResourceInternalId' => 'project-internal-1',
|
||||
'title' => 'pre-existing',
|
||||
'body' => 'pre-existing',
|
||||
]));
|
||||
|
||||
$message = new ConsoleMessage(
|
||||
recipients: [$this->recipient($userId, $userId)],
|
||||
title: 'Same alert resent',
|
||||
body: 'b',
|
||||
messageId: ID::custom($messageId),
|
||||
projectId: 'project-x',
|
||||
projectInternalId: 'project-internal-x',
|
||||
);
|
||||
|
||||
$adapter = new Console($this->database);
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(1, $result['deliveredTo'], 'duplicate must count as a successful delivery');
|
||||
$this->assertCount(1, $result['results']);
|
||||
$this->assertSame('success', $result['results'][0]['status'] ?? '', 'duplicate must report success status');
|
||||
$this->assertSame('', $result['results'][0]['error'] ?? 'unset', 'duplicate must not surface a per-recipient error');
|
||||
|
||||
// Still exactly ONE row: the pre-existing one. The adapter must not
|
||||
// overwrite it nor create a sibling.
|
||||
$rows = $this->database->find('notifications');
|
||||
$this->assertCount(1, $rows);
|
||||
$this->assertSame($documentId, $rows[0]->getId());
|
||||
$this->assertSame('pre-existing', $rows[0]->getAttribute('title'), 'duplicate path must not overwrite existing row');
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Utopia\Messaging\Adapter;
|
||||
|
||||
use Appwrite\Utopia\Messaging\Messages\Webhook as WebhookMessage;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class WebhookTest extends TestCase
|
||||
{
|
||||
public function testPostsExpectedBodyShape(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$payload = [
|
||||
'subject' => 'Hello',
|
||||
'body' => 'World',
|
||||
'recipient' => 'ops@example.test',
|
||||
'metadata' => ['foo' => 'bar'],
|
||||
];
|
||||
|
||||
$message = new WebhookMessage(
|
||||
urls: ['https://hooks.example.test/notify'],
|
||||
payload: $payload,
|
||||
);
|
||||
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(1, $result['deliveredTo']);
|
||||
$this->assertCount(1, $adapter->captured);
|
||||
|
||||
$request = $adapter->captured[0];
|
||||
$this->assertSame('POST', $request['method']);
|
||||
$this->assertSame('https://hooks.example.test/notify', $request['url']);
|
||||
|
||||
$sent = \json_decode($request['body'], true);
|
||||
$this->assertSame($payload, $sent);
|
||||
|
||||
$headerLine = \implode("\n", $request['headers']);
|
||||
$this->assertStringContainsString('Content-Type: application/json', $headerLine);
|
||||
$this->assertStringContainsString('X-Appwrite-Webhook-Timestamp:', $headerLine);
|
||||
}
|
||||
|
||||
public function testSigningSecretProducesHmacSha256Signature(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$payload = ['subject' => 'Signed', 'body' => 'B'];
|
||||
$secret = 'super-secret';
|
||||
|
||||
$message = new WebhookMessage(
|
||||
urls: ['https://hooks.example.test/signed'],
|
||||
payload: $payload,
|
||||
signingSecret: $secret,
|
||||
);
|
||||
|
||||
$adapter->send($message);
|
||||
|
||||
$headers = $adapter->captured[0]['headers'];
|
||||
$body = $adapter->captured[0]['body'];
|
||||
|
||||
$timestamp = null;
|
||||
$signature = null;
|
||||
foreach ($headers as $header) {
|
||||
if (\str_starts_with($header, 'X-Appwrite-Webhook-Timestamp: ')) {
|
||||
$timestamp = \substr($header, \strlen('X-Appwrite-Webhook-Timestamp: '));
|
||||
} elseif (\str_starts_with($header, 'X-Appwrite-Webhook-Signature: ')) {
|
||||
$signature = \substr($header, \strlen('X-Appwrite-Webhook-Signature: '));
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull($timestamp, 'timestamp header must be present');
|
||||
$this->assertNotNull($signature, 'signature header must be present when secret is set');
|
||||
$this->assertStringStartsWith('sha256=', $signature);
|
||||
|
||||
$expected = 'sha256=' . \hash_hmac('sha256', $timestamp . '.' . $body, $secret);
|
||||
$this->assertSame($expected, $signature);
|
||||
}
|
||||
|
||||
public function testNoSecretLeavesPayloadUnsigned(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$message = new WebhookMessage(
|
||||
urls: ['https://hooks.example.test/unsigned'],
|
||||
payload: ['x' => 1],
|
||||
signingSecret: null,
|
||||
);
|
||||
|
||||
$adapter->send($message);
|
||||
|
||||
$headerLine = \implode("\n", $adapter->captured[0]['headers']);
|
||||
$this->assertStringNotContainsString('X-Appwrite-Webhook-Signature', $headerLine);
|
||||
}
|
||||
|
||||
public function testEmptySecretIsTreatedAsUnsigned(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$message = new WebhookMessage(
|
||||
urls: ['https://hooks.example.test/empty-secret'],
|
||||
payload: ['x' => 1],
|
||||
signingSecret: '',
|
||||
);
|
||||
|
||||
$adapter->send($message);
|
||||
|
||||
$headerLine = \implode("\n", $adapter->captured[0]['headers']);
|
||||
$this->assertStringNotContainsString('X-Appwrite-Webhook-Signature', $headerLine);
|
||||
}
|
||||
|
||||
public function testTwoXxIsSuccess(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$adapter->response = ['statusCode' => 204, 'response' => '', 'error' => null];
|
||||
$message = new WebhookMessage(urls: ['https://hooks.example.test/ok'], payload: []);
|
||||
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(1, $result['deliveredTo']);
|
||||
}
|
||||
|
||||
public function testNonTwoXxSurfacesError(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$adapter->response = ['statusCode' => 503, 'response' => 'Server', 'error' => null];
|
||||
$message = new WebhookMessage(urls: ['https://hooks.example.test/fail'], payload: []);
|
||||
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(0, $result['deliveredTo']);
|
||||
$error = $result['results'][0]['error'] ?? null;
|
||||
$this->assertSame('HTTP 503', $error);
|
||||
}
|
||||
|
||||
public function testCurlErrorSurfacesAsResultError(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$adapter->response = ['statusCode' => 0, 'response' => null, 'error' => 'connection refused'];
|
||||
$message = new WebhookMessage(urls: ['https://hooks.example.test/down'], payload: []);
|
||||
|
||||
$result = $adapter->send($message);
|
||||
|
||||
$this->assertSame(0, $result['deliveredTo']);
|
||||
$this->assertSame('connection refused', $result['results'][0]['error']);
|
||||
}
|
||||
|
||||
public function testCustomHeadersForwarded(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$message = new WebhookMessage(
|
||||
urls: ['https://hooks.example.test/with-headers'],
|
||||
payload: [],
|
||||
headers: ['X-Custom' => 'value'],
|
||||
);
|
||||
|
||||
$adapter->send($message);
|
||||
|
||||
$headerLine = \implode("\n", $adapter->captured[0]['headers']);
|
||||
$this->assertStringContainsString('X-Custom: value', $headerLine);
|
||||
}
|
||||
|
||||
public function testRejectsForeignMessageType(): void
|
||||
{
|
||||
$adapter = new CapturingWebhook();
|
||||
$this->expectException(\Exception::class);
|
||||
$this->expectExceptionMessage('Invalid message type.');
|
||||
|
||||
$adapter->send(new \Appwrite\Utopia\Messaging\Messages\Console(
|
||||
recipients: [[
|
||||
'address' => 'u',
|
||||
'resourceType' => RESOURCE_TYPE_USERS,
|
||||
'resourceId' => 'u',
|
||||
'resourceInternalId' => 'u-internal',
|
||||
'parentResourceType' => RESOURCE_TYPE_PROJECTS,
|
||||
'parentResourceId' => 'project',
|
||||
'parentResourceInternalId' => 'project-internal',
|
||||
]],
|
||||
title: 't',
|
||||
body: 'b',
|
||||
));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user