Skip to content

Logs for sites #9047

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions app/config/collections.php
Original file line number Diff line number Diff line change
Expand Up @@ -4097,7 +4097,7 @@
'name' => 'Executions',
'attributes' => [
[
'$id' => ID::custom('functionInternalId'),
'$id' => ID::custom('resourceInternalId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
Expand All @@ -4108,7 +4108,18 @@
'filters' => [],
],
[
'$id' => ID::custom('functionId'),
'$id' => ID::custom('resourceId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('resourceType'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
Expand Down Expand Up @@ -4297,9 +4308,9 @@
],
'indexes' => [
[
'$id' => ID::custom('_key_function'),
'$id' => ID::custom('_key_resource'),
'type' => Database::INDEX_KEY,
'attributes' => ['functionId'],
'attributes' => ['resourceId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
],
Expand Down
7 changes: 7 additions & 0 deletions app/config/errors.php
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,13 @@
'code' => 400,
],

/** Logs */
Exception::LOG_NOT_FOUND => [
'name' => Exception::LOG_NOT_FOUND,
'description' => 'Log with the requested ID could not be found.',
'code' => 404,
],

/** Databases */
Exception::DATABASE_NOT_FOUND => [
'name' => Exception::DATABASE_NOT_FOUND,
Expand Down
2 changes: 2 additions & 0 deletions app/config/roles.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@
'functions.write',
'sites.read',
'sites.write',
'log.read',
'log.write',
'execution.read',
'execution.write',
'rules.read',
Expand Down
6 changes: 6 additions & 0 deletions app/config/scopes.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@
'sites.write' => [
'description' => 'Access to create, update, and delete your project\'s sites and deployments',
],
'log.read' => [
'description' => 'Access to read your site\'s logs',
],
'log.write' => [
'description' => 'Access to update, and delete your site\'s logs',
],
'execution.read' => [
'description' => 'Access to read your project\'s execution logs',
],
Expand Down
12 changes: 7 additions & 5 deletions app/controllers/api/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -1904,8 +1904,9 @@
$execution = new Document([
'$id' => $executionId,
'$permissions' => !$user->isEmpty() ? [Permission::read(Role::user($user->getId()))] : [],
'functionInternalId' => $function->getInternalId(),
'functionId' => $function->getId(),
'resourceInternalId' => $function->getInternalId(),
'resourceId' => $function->getId(),
'resourceType' => 'functions',
'deploymentInternalId' => $deployment->getInternalId(),
'deploymentId' => $deployment->getId(),
'trigger' => (!is_null($scheduledAt)) ? 'schedule' : 'http',
Expand Down Expand Up @@ -2172,7 +2173,8 @@
}

// Set internal queries
$queries[] = Query::equal('functionId', [$function->getId()]);
$queries[] = Query::equal('resourceId', [$function->getId()]);
$queries[] = Query::equal('resourceType', ['functions']);

/**
* Get cursor document if there was a cursor query, we use array_filter and reset for reference $cursor to $queries
Expand Down Expand Up @@ -2250,7 +2252,7 @@

$execution = $dbForProject->getDocument('executions', $executionId);

if ($execution->getAttribute('functionId') !== $function->getId()) {
if ($execution->getAttribute('resourceType') !== 'functions' && $execution->getAttribute('resourceId') !== $function->getId()) {
throw new Exception(Exception::EXECUTION_NOT_FOUND);
}

Expand Down Expand Up @@ -2301,7 +2303,7 @@
throw new Exception(Exception::EXECUTION_NOT_FOUND);
}

if ($execution->getAttribute('functionId') !== $function->getId()) {
if ($execution->getAttribute('resourceType') !== 'functions' && $execution->getAttribute('resourceId') !== $function->getId()) {
throw new Exception(Exception::EXECUTION_NOT_FOUND);
}
$status = $execution->getAttribute('status');
Expand Down
34 changes: 24 additions & 10 deletions app/controllers/general.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,23 +245,29 @@ function router(App $utopia, Database $dbForConsole, callable $getProjectDB, Swo
$execution = new Document([
'$id' => $executionId,
'$permissions' => [],
'functionInternalId' => $resource->getInternalId(),
'functionId' => $resource->getId(),
'resourceInternalId' => $resource->getInternalId(),
'resourceId' => $resource->getId(),
'deploymentInternalId' => $deployment->getInternalId(),
'deploymentId' => $deployment->getId(),
'trigger' => 'http', // http / schedule / event
'status' => 'processing', // waiting / processing / completed / failed
'responseStatusCode' => 0,
'responseHeaders' => [],
'requestPath' => $path,
'requestMethod' => $method,
'requestHeaders' => $headersFiltered,
'errors' => '',
'logs' => '',
'duration' => 0.0,
'search' => implode(' ', [$resourceId, $executionId]),
]);

if ($type === 'function') {
$execution->setAttribute('resourceType', 'functions');
$execution->setAttribute('trigger', 'http'); // http / schedule / event
$execution->setAttribute('status', 'processing'); // waiting / processing / completed / failed
$execution->setAttribute('errors', '');
$execution->setAttribute('logs', '');
} elseif ($type === 'site') {
$execution->setAttribute('resourceType', 'sites');
}

$queueForEvents
->setParam('functionId', $resource->getId())
->setParam('executionId', $execution->getId())
Expand Down Expand Up @@ -370,20 +376,26 @@ function router(App $utopia, Database $dbForConsole, callable $getProjectDB, Swo

/** Update execution status */
$status = $executionResponse['statusCode'] >= 500 ? 'failed' : 'completed';
$execution->setAttribute('status', $status);
if ($type === 'function') {
$execution->setAttribute('status', $status);
$execution->setAttribute('logs', $executionResponse['logs']);
$execution->setAttribute('errors', $executionResponse['errors']);
}
$execution->setAttribute('responseStatusCode', $executionResponse['statusCode']);
$execution->setAttribute('responseHeaders', $headersFiltered);
$execution->setAttribute('logs', $executionResponse['logs']);
$execution->setAttribute('errors', $executionResponse['errors']);
$execution->setAttribute('duration', $executionResponse['duration']);
} catch (\Throwable $th) {
$durationEnd = \microtime(true);

$execution
->setAttribute('duration', $durationEnd - $durationStart)
->setAttribute('responseStatusCode', 500);

if ($type === 'function') {
$execution
->setAttribute('status', 'failed')
->setAttribute('responseStatusCode', 500)
->setAttribute('errors', $th->getMessage() . '\nError Code: ' . $th->getCode());
}
Console::error($th->getMessage());

if ($th instanceof AppwriteException) {
Expand Down Expand Up @@ -421,6 +433,8 @@ function router(App $utopia, Database $dbForConsole, callable $getProjectDB, Swo
->setExecution($execution)
->setProject($project)
->trigger();
} elseif ($type === 'site') { // TODO: Move it to logs worker later
$dbForProject->createDocument('executions', $execution);
}
}

Expand Down
1 change: 1 addition & 0 deletions app/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@

const RESOURCE_TYPE_PROJECTS = 'projects';
const RESOURCE_TYPE_FUNCTIONS = 'functions';
const RESOURCE_TYPE_SITES = 'sites';
const RESOURCE_TYPE_DATABASES = 'databases';
const RESOURCE_TYPE_BUCKETS = 'buckets';
const RESOURCE_TYPE_PROVIDERS = 'providers';
Expand Down
3 changes: 3 additions & 0 deletions src/Appwrite/Extend/Exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ class Exception extends \Exception
public const EXECUTION_NOT_FOUND = 'execution_not_found';
public const EXECUTION_IN_PROGRESS = 'execution_in_progress';

/** Log */
public const LOG_NOT_FOUND = 'log_not_found';

/** Databases */
public const DATABASE_NOT_FOUND = 'database_not_found';
public const DATABASE_ALREADY_EXISTS = 'database_already_exists';
Expand Down
77 changes: 77 additions & 0 deletions src/Appwrite/Platform/Modules/Sites/Http/Logs/DeleteLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Appwrite\Platform\Modules\Sites\Http\Logs;

use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;

class DeleteLog extends Base
{
use HTTP;

public static function getName()
{
return 'deleteLog';
}

public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
->setHttpPath('/v1/sites/:siteId/logs/:logId')
->desc('Delete log')
->groups(['api', 'sites'])
->label('scope', 'log.write')
->label('resourceType', RESOURCE_TYPE_SITES)
->label('event', 'sites.[siteId].logs.[logId].delete')
->label('audits.event', 'logs.delete')
->label('audits.resource', 'site/{request.siteId}')
->label('sdk.auth', [APP_AUTH_TYPE_KEY])
->label('sdk.namespace', 'sites')
->label('sdk.method', 'deleteLog')
->label('sdk.description', '/docs/references/sites/delete-log.md') // TODO: add this file
->label('sdk.response.code', Response::STATUS_CODE_NOCONTENT)
->label('sdk.response.model', Response::MODEL_NONE)
->param('siteId', '', new UID(), 'Site ID.')
->param('logId', '', new UID(), 'Log ID.')
->inject('response')
->inject('dbForProject')
->inject('queueForEvents')
->callback([$this, 'action']);
}

public function action(string $siteId, string $logId, Response $response, Database $dbForProject, Event $queueForEvents)
{
$site = $dbForProject->getDocument('sites', $siteId);

if ($site->isEmpty()) {
throw new Exception(Exception::SITE_NOT_FOUND);
}

$log = $dbForProject->getDocument('executions', $logId);
if ($log->isEmpty()) {
throw new Exception(Exception::LOG_NOT_FOUND);
}

if ($log->getAttribute('resourceType') !== 'sites' && $log->getAttribute('resourceId') !== $site->getId()) {
throw new Exception(Exception::LOG_NOT_FOUND);
}

if (!$dbForProject->deleteDocument('executions', $log->getId())) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove log from DB');
}

$queueForEvents
->setParam('siteId', $site->getId())
->setParam('logId', $log->getId())
->setPayload($response->output($log, Response::MODEL_EXECUTION)); // TODO: Update model

$response->noContent();
}
}
64 changes: 64 additions & 0 deletions src/Appwrite/Platform/Modules/Sites/Http/Logs/GetLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace Appwrite\Platform\Modules\Sites\Http\Logs;

use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;

class GetLog extends Base
{
use HTTP;

public static function getName()
{
return 'getLog';
}

public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/sites/:siteId/logs/:logId')
->desc('Get log')
->groups(['api', 'sites'])
->label('scope', 'log.read')
->label('sdk.auth', [APP_AUTH_TYPE_KEY])
->label('sdk.namespace', 'sites')
->label('sdk.method', 'getLog')
->label('sdk.description', '/docs/references/sites/get-log.md') // TODO: add this file
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_EXECUTION)
->param('siteId', '', new UID(), 'Site ID.')
->param('logId', '', new UID(), 'Log ID.')
->inject('response')
->inject('dbForProject')
->callback([$this, 'action']);
}

public function action(string $siteId, string $logId, Response $response, Database $dbForProject)
{
$site = $dbForProject->getDocument('sites', $siteId);

if ($site->isEmpty() || !$site->getAttribute('enabled')) {
throw new Exception(Exception::SITE_NOT_FOUND);
}

$log = $dbForProject->getDocument('executions', $logId);

if ($log->getAttribute('resourceType') !== 'sites' && $log->getAttribute('resourceId') !== $site->getId()) {
throw new Exception(Exception::LOG_NOT_FOUND);
}

if ($log->isEmpty()) {
throw new Exception(Exception::LOG_NOT_FOUND);
}

$response->dynamic($log, Response::MODEL_EXECUTION); //TODO: Change to model log, but model log already exists - decide what to do
}
}
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy