2020-05-04 14:35:01 +00:00
< ? php
2021-03-10 17:48:05 +00:00
use Ahc\Jwt\JWT ;
use Appwrite\Auth\Auth ;
2022-04-19 13:13:55 +00:00
use Appwrite\Event\Build ;
2022-05-24 14:28:27 +00:00
use Appwrite\Event\Delete ;
use Appwrite\Event\Event ;
2022-04-17 20:34:32 +00:00
use Appwrite\Event\Func ;
2022-04-13 12:39:31 +00:00
use Appwrite\Event\Validator\Event as ValidatorEvent ;
2022-02-18 12:36:24 +00:00
use Appwrite\Extend\Exception ;
2022-01-18 11:05:04 +00:00
use Appwrite\Utopia\Database\Validator\CustomId ;
2022-12-14 15:42:25 +00:00
use Utopia\Database\Helpers\ID ;
2022-12-14 16:04:06 +00:00
use Utopia\Database\Helpers\Permission ;
use Utopia\Database\Helpers\Role ;
2021-07-25 14:47:18 +00:00
use Utopia\Database\Validator\UID ;
2022-08-09 06:28:38 +00:00
use Appwrite\Usage\Stats ;
2022-05-24 14:28:27 +00:00
use Utopia\Storage\Device ;
2021-01-22 08:28:33 +00:00
use Utopia\Storage\Validator\File ;
2021-01-27 13:15:44 +00:00
use Utopia\Storage\Validator\FileExt ;
2021-01-22 08:28:33 +00:00
use Utopia\Storage\Validator\FileSize ;
use Utopia\Storage\Validator\Upload ;
2020-10-30 19:53:27 +00:00
use Appwrite\Utopia\Response ;
2022-05-24 14:28:27 +00:00
use Utopia\Swoole\Request ;
2020-05-05 17:30:12 +00:00
use Appwrite\Task\Validator\Cron ;
2022-08-23 09:12:48 +00:00
use Appwrite\Utopia\Database\Validator\Queries\Deployments ;
2022-08-23 09:26:34 +00:00
use Appwrite\Utopia\Database\Validator\Queries\Executions ;
2022-08-23 09:02:06 +00:00
use Appwrite\Utopia\Database\Validator\Queries\Functions ;
2022-08-26 13:38:39 +00:00
use Appwrite\Utopia\Database\Validator\Queries\Variables ;
2020-07-12 21:18:52 +00:00
use Utopia\App ;
2021-06-12 14:33:23 +00:00
use Utopia\Database\Database ;
2021-05-04 21:25:17 +00:00
use Utopia\Database\Document ;
2022-07-12 13:32:39 +00:00
use Utopia\Database\DateTime ;
2021-05-04 21:25:17 +00:00
use Utopia\Database\Query ;
use Utopia\Database\Validator\Authorization ;
2020-05-05 17:30:12 +00:00
use Utopia\Validator\ArrayList ;
use Utopia\Validator\Assoc ;
2020-05-04 14:35:01 +00:00
use Utopia\Validator\Text ;
use Utopia\Validator\Range ;
2020-05-05 17:30:12 +00:00
use Utopia\Validator\WhiteList ;
2020-07-14 16:13:18 +00:00
use Utopia\Config\Config ;
2020-05-12 22:00:48 +00:00
use Cron\CronExpression ;
2022-02-05 10:08:05 +00:00
use Executor\Executor ;
2021-10-14 09:37:00 +00:00
use Utopia\CLI\Console ;
2022-08-12 12:23:58 +00:00
use Utopia\Database\Validator\Roles ;
2021-12-06 15:04:00 +00:00
use Utopia\Validator\Boolean ;
2022-08-02 16:11:15 +00:00
use Utopia\Database\Exception\Duplicate as DuplicateException ;
2020-05-04 14:35:01 +00:00
include_once __DIR__ . '/../shared/api.php' ;
2020-07-12 21:18:52 +00:00
App :: post ( '/v1/functions' )
-> groups ([ 'api' , 'functions' ])
2020-05-04 14:35:01 +00:00
-> desc ( 'Create Function' )
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].create' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'function.create' )
2022-08-09 14:38:54 +00:00
-> label ( 'audits.resource' , 'function/{response.$id}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-04 14:35:01 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'create' )
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/create-function.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_FUNCTION )
2023-01-20 22:22:16 +00:00
-> param ( 'functionId' , '' , new CustomId (), 'Function ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2020-09-10 14:40:14 +00:00
-> param ( 'name' , '' , new Text ( 128 ), 'Function name. Max length: 128 chars.' )
2022-08-27 03:19:00 +00:00
-> param ( 'execute' , [], new Roles ( APP_LIMIT_ARRAY_PARAMS_SIZE ), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.' )
2021-06-22 10:18:26 +00:00
-> param ( 'runtime' , '' , new WhiteList ( array_keys ( Config :: getParam ( 'runtimes' )), true ), 'Execution runtime.' )
2022-05-12 18:41:04 +00:00
-> param ( 'events' , [], new ArrayList ( new ValidatorEvent (), APP_LIMIT_ARRAY_PARAMS_SIZE ), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.' , true )
2020-09-10 14:40:14 +00:00
-> param ( 'schedule' , '' , new Cron (), 'Schedule CRON syntax.' , true )
2022-01-21 08:05:41 +00:00
-> param ( 'timeout' , 15 , new Range ( 1 , ( int ) App :: getEnv ( '_APP_FUNCTIONS_TIMEOUT' , 900 )), 'Function maximum execution time in seconds.' , true )
2022-09-12 09:02:14 +00:00
-> param ( 'enabled' , true , new Boolean (), 'Is function enabled?' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-09-23 06:12:17 +00:00
-> inject ( 'project' )
-> inject ( 'user' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2022-09-23 06:12:17 +00:00
-> action ( function ( string $functionId , string $name , array $execute , string $runtime , array $events , string $schedule , int $timeout , bool $enabled , Response $response , Database $dbForProject , Document $project , Document $user , Event $eventsInstance ) {
$cron = ! empty ( $schedule ) ? new CronExpression ( $schedule ) : null ;
$next = ! empty ( $schedule ) ? DateTime :: format ( $cron -> getNextRunDate ()) : null ;
2021-01-16 23:38:13 +00:00
2022-08-14 14:22:38 +00:00
$functionId = ( $functionId == 'unique()' ) ? ID :: unique () : $functionId ;
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> createDocument ( 'functions' , new Document ([
2021-08-14 18:56:28 +00:00
'$id' => $functionId ,
2021-05-04 21:25:17 +00:00
'execute' => $execute ,
2022-09-12 09:02:14 +00:00
'enabled' => $enabled ,
2020-07-12 21:18:52 +00:00
'name' => $name ,
2021-06-21 14:42:39 +00:00
'runtime' => $runtime ,
2022-01-24 22:59:02 +00:00
'deployment' => '' ,
2020-07-12 21:18:52 +00:00
'events' => $events ,
'schedule' => $schedule ,
2022-09-11 12:20:26 +00:00
'scheduleUpdatedAt' => DateTime :: now (),
2022-07-07 09:26:30 +00:00
'schedulePrevious' => null ,
2022-09-23 06:12:17 +00:00
'scheduleNext' => $next ,
2020-07-12 21:18:52 +00:00
'timeout' => $timeout ,
2022-08-30 12:30:52 +00:00
'search' => implode ( ' ' , [ $functionId , $name , $runtime ])
2021-05-04 21:25:17 +00:00
]));
2020-05-05 17:30:12 +00:00
2022-09-23 06:12:17 +00:00
if ( $next ) {
// Async task reschedule
$functionEvent = new Func ();
$functionEvent
-> setFunction ( $function )
-> setType ( 'schedule' )
-> setUser ( $user )
-> setProject ( $project )
-> schedule ( new \DateTime ( $next ));
}
2022-04-13 12:39:31 +00:00
$eventsInstance -> setParam ( 'functionId' , $function -> getId ());
2022-09-07 11:02:36 +00:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $function , Response :: MODEL_FUNCTION );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
App :: get ( '/v1/functions' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'List Functions' )
-> label ( 'scope' , 'functions.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'list' )
-> label ( 'sdk.description' , '/docs/references/functions/list-functions.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_FUNCTION_LIST )
2022-08-23 09:02:06 +00:00
-> param ( 'queries' , [], new Functions (), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). 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 ( ', ' , Functions :: ALLOWED_ATTRIBUTES ), true )
2020-09-10 14:40:14 +00:00
-> param ( 'search' , '' , new Text ( 256 ), 'Search term to filter your list results. Max length: 256 chars.' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-08-23 09:02:06 +00:00
-> action ( function ( array $queries , string $search , Response $response , Database $dbForProject ) {
2020-07-12 21:18:52 +00:00
2022-08-23 09:02:06 +00:00
$queries = Query :: parseQueries ( $queries );
2021-08-06 12:36:05 +00:00
2022-08-11 23:53:52 +00:00
if ( ! empty ( $search )) {
2022-08-23 09:02:06 +00:00
$queries [] = Query :: search ( 'search' , $search );
2021-08-06 12:36:05 +00:00
}
2022-08-23 09:02:06 +00:00
// Get cursor document if there was a cursor query
2022-08-30 23:31:43 +00:00
$cursor = Query :: getByType ( $queries , Query :: TYPE_CURSORAFTER , Query :: TYPE_CURSORBEFORE );
$cursor = reset ( $cursor );
2022-08-30 11:55:23 +00:00
if ( $cursor ) {
2022-08-23 09:02:06 +00:00
/** @var Query $cursor */
$functionId = $cursor -> getValue ();
$cursorDocument = $dbForProject -> getDocument ( 'functions' , $functionId );
2021-08-18 13:42:03 +00:00
2022-08-11 23:53:52 +00:00
if ( $cursorDocument -> isEmpty ()) {
2022-08-23 09:02:06 +00:00
throw new Exception ( Exception :: GENERAL_CURSOR_NOT_FOUND , " Function ' { $functionId } ' for the 'cursor' value not found. " );
2022-08-11 23:53:52 +00:00
}
2022-08-23 09:02:06 +00:00
$cursor -> setValue ( $cursorDocument );
2021-08-18 13:42:03 +00:00
}
2020-07-12 21:18:52 +00:00
2022-08-23 09:02:06 +00:00
$filterQueries = Query :: groupByType ( $queries )[ 'filters' ];
2020-10-30 19:53:27 +00:00
$response -> dynamic ( new Document ([
2022-08-23 09:02:06 +00:00
'functions' => $dbForProject -> find ( 'functions' , $queries ),
2022-08-11 23:53:52 +00:00
'total' => $dbForProject -> count ( 'functions' , $filterQueries , APP_LIMIT_COUNT ),
2020-10-30 19:53:27 +00:00
]), Response :: MODEL_FUNCTION_LIST );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2021-12-09 13:02:12 +00:00
App :: get ( '/v1/functions/runtimes' )
-> groups ([ 'api' , 'functions' ])
2022-03-02 12:21:03 +00:00
-> desc ( 'List runtimes' )
2021-12-09 13:02:12 +00:00
-> label ( 'scope' , 'functions.read' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'listRuntimes' )
-> label ( 'sdk.description' , '/docs/references/functions/list-runtimes.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_RUNTIME_LIST )
-> inject ( 'response' )
2022-05-24 14:28:27 +00:00
-> action ( function ( Response $response ) {
2021-12-09 13:02:12 +00:00
$runtimes = Config :: getParam ( 'runtimes' );
$runtimes = array_map ( function ( $key ) use ( $runtimes ) {
$runtimes [ $key ][ '$id' ] = $key ;
return $runtimes [ $key ];
}, array_keys ( $runtimes ));
2022-04-13 12:39:31 +00:00
$response -> dynamic ( new Document ([
2022-02-27 09:57:09 +00:00
'total' => count ( $runtimes ),
2021-12-09 13:02:12 +00:00
'runtimes' => $runtimes
]), Response :: MODEL_RUNTIME_LIST );
});
2020-07-12 21:18:52 +00:00
App :: get ( '/v1/functions/:functionId' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'Get Function' )
-> label ( 'scope' , 'functions.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'get' )
-> label ( 'sdk.description' , '/docs/references/functions/get-function.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_FUNCTION )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-05-24 14:28:27 +00:00
-> action ( function ( string $functionId , Response $response , Database $dbForProject ) {
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-05-05 17:30:12 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-05-05 17:30:12 +00:00
}
2020-10-30 19:53:27 +00:00
$response -> dynamic ( $function , Response :: MODEL_FUNCTION );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2020-10-30 19:53:27 +00:00
App :: get ( '/v1/functions/:functionId/usage' )
-> desc ( 'Get Function Usage' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_ADMIN ])
2020-10-30 19:53:27 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-07-17 10:30:58 +00:00
-> label ( 'sdk.method' , 'getFunctionUsage' )
2021-08-26 19:12:36 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2021-08-27 17:34:43 +00:00
-> label ( 'sdk.response.model' , Response :: MODEL_USAGE_FUNCTIONS )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2020-10-30 19:53:27 +00:00
-> param ( 'range' , '30d' , new WhiteList ([ '24h' , '7d' , '30d' , '90d' ]), 'Date range.' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-05-24 14:28:27 +00:00
-> action ( function ( string $functionId , string $range , Response $response , Database $dbForProject ) {
2020-10-30 19:53:27 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-10-30 19:53:27 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-10-30 19:53:27 +00:00
}
2022-04-13 12:39:31 +00:00
2021-08-26 19:12:36 +00:00
$usage = [];
2022-04-13 12:39:31 +00:00
if ( App :: getEnv ( '_APP_USAGE_STATS' , 'enabled' ) == 'enabled' ) {
2021-10-27 22:17:15 +00:00
$periods = [
2021-01-13 01:10:52 +00:00
'24h' => [
2022-10-21 05:45:25 +00:00
'period' => '1h' ,
'limit' => 24 ,
2021-01-13 01:10:52 +00:00
],
'7d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 7 ,
2021-01-13 01:10:52 +00:00
],
'30d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 30 ,
2021-01-13 01:10:52 +00:00
],
'90d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 90 ,
2021-01-13 01:10:52 +00:00
],
];
2022-04-13 12:39:31 +00:00
2021-08-26 19:12:36 +00:00
$metrics = [
2022-08-11 05:25:39 +00:00
" executions. $functionId .compute.total " ,
" executions. $functionId .compute.success " ,
" executions. $functionId .compute.failure " ,
" executions. $functionId .compute.time " ,
" builds. $functionId .compute.total " ,
" builds. $functionId .compute.success " ,
" builds. $functionId .compute.failure " ,
" builds. $functionId .compute.time " ,
2021-08-26 19:12:36 +00:00
];
$stats = [];
2021-08-20 10:04:57 +00:00
2022-04-13 12:39:31 +00:00
Authorization :: skip ( function () use ( $dbForProject , $periods , $range , $metrics , & $stats ) {
2021-08-28 16:25:48 +00:00
foreach ( $metrics as $metric ) {
2021-10-27 22:17:15 +00:00
$limit = $periods [ $range ][ 'limit' ];
$period = $periods [ $range ][ 'period' ];
2021-10-27 19:57:20 +00:00
2021-12-27 12:45:23 +00:00
$requestDocs = $dbForProject -> find ( 'stats' , [
2022-08-11 23:53:52 +00:00
Query :: equal ( 'period' , [ $period ]),
Query :: equal ( 'metric' , [ $metric ]),
Query :: limit ( $limit ),
Query :: orderDesc ( 'time' ),
]);
2022-04-13 12:39:31 +00:00
2021-08-28 16:25:48 +00:00
$stats [ $metric ] = [];
foreach ( $requestDocs as $requestDoc ) {
$stats [ $metric ][] = [
'value' => $requestDoc -> getAttribute ( 'value' ),
'date' => $requestDoc -> getAttribute ( 'time' ),
];
}
2021-10-27 19:57:20 +00:00
// backfill metrics with empty values for graphs
$backfill = $limit - \count ( $requestDocs );
while ( $backfill > 0 ) {
$last = $limit - $backfill - 1 ; // array index of last added metric
2022-04-13 12:39:31 +00:00
$diff = match ( $period ) { // convert period to seconds for unix timestamp math
2022-10-21 05:45:25 +00:00
'1h' => 3600 ,
2021-10-27 19:57:20 +00:00
'1d' => 86400 ,
};
$stats [ $metric ][] = [
'value' => 0 ,
2022-09-15 23:48:09 +00:00
'date' => DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime ( $stats [ $metric ][ $last ][ 'date' ] ? ? null ), - 1 * $diff )),
2021-10-27 19:57:20 +00:00
];
$backfill -- ;
}
2021-08-28 16:25:48 +00:00
$stats [ $metric ] = array_reverse ( $stats [ $metric ]);
2022-04-13 12:39:31 +00:00
}
2021-08-28 16:25:48 +00:00
});
2021-08-20 08:24:45 +00:00
2021-08-26 19:12:36 +00:00
$usage = new Document ([
2021-01-13 01:10:52 +00:00
'range' => $range ,
2022-08-20 11:20:31 +00:00
'executionsTotal' => $stats [ " executions. $functionId .compute.total " ] ? ? [],
'executionsFailure' => $stats [ " executions. $functionId .compute.failure " ] ? ? [],
'executionsSuccesse' => $stats [ " executions. $functionId .compute.success " ] ? ? [],
'executionsTime' => $stats [ " executions. $functionId .compute.time " ] ? ? [],
'buildsTotal' => $stats [ " builds. $functionId .compute.total " ] ? ? [],
'buildsFailure' => $stats [ " builds. $functionId .compute.failure " ] ? ? [],
'buildsSuccess' => $stats [ " builds. $functionId .compute.success " ] ? ? [],
'buildsTime' => $stats [ " builds. $functionId .compute.time " ? ? []]
2021-01-13 01:10:52 +00:00
]);
2020-10-30 19:53:27 +00:00
}
2022-04-13 12:39:31 +00:00
2022-07-17 10:30:58 +00:00
$response -> dynamic ( $usage , Response :: MODEL_USAGE_FUNCTION );
});
App :: get ( '/v1/functions/usage' )
2022-07-28 06:55:14 +00:00
-> desc ( 'Get Functions Usage' )
2022-07-17 10:30:58 +00:00
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.read' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_ADMIN ])
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'getUsage' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_USAGE_FUNCTIONS )
-> param ( 'range' , '30d' , new WhiteList ([ '24h' , '7d' , '30d' , '90d' ]), 'Date range.' , true )
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-07-17 10:39:44 +00:00
-> action ( function ( string $range , Response $response , Database $dbForProject ) {
2022-07-17 10:30:58 +00:00
2021-08-26 19:12:36 +00:00
$usage = [];
2022-04-13 12:39:31 +00:00
if ( App :: getEnv ( '_APP_USAGE_STATS' , 'enabled' ) == 'enabled' ) {
2021-10-27 22:17:15 +00:00
$periods = [
2021-01-13 01:10:52 +00:00
'24h' => [
2022-10-21 05:45:25 +00:00
'period' => '1h' ,
'limit' => 24 ,
2021-01-13 01:10:52 +00:00
],
'7d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 7 ,
2021-01-13 01:10:52 +00:00
],
'30d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 30 ,
2021-01-13 01:10:52 +00:00
],
'90d' => [
2021-08-20 08:24:45 +00:00
'period' => '1d' ,
'limit' => 90 ,
2021-01-13 01:10:52 +00:00
],
];
2022-04-13 12:39:31 +00:00
2021-08-26 19:12:36 +00:00
$metrics = [
2022-08-11 05:25:39 +00:00
'executions.$all.compute.total' ,
'executions.$all.compute.failure' ,
'executions.$all.compute.success' ,
'executions.$all.compute.time' ,
'builds.$all.compute.total' ,
'builds.$all.compute.failure' ,
'builds.$all.compute.success' ,
'builds.$all.compute.time' ,
2021-08-26 19:12:36 +00:00
];
$stats = [];
2021-08-20 10:04:57 +00:00
2022-04-13 12:39:31 +00:00
Authorization :: skip ( function () use ( $dbForProject , $periods , $range , $metrics , & $stats ) {
2021-08-28 16:25:48 +00:00
foreach ( $metrics as $metric ) {
2021-10-27 22:17:15 +00:00
$limit = $periods [ $range ][ 'limit' ];
$period = $periods [ $range ][ 'period' ];
2021-10-27 19:57:20 +00:00
2021-12-27 12:45:23 +00:00
$requestDocs = $dbForProject -> find ( 'stats' , [
2022-08-25 14:56:15 +00:00
Query :: equal ( 'period' , [ $period ]),
Query :: equal ( 'metric' , [ $metric ]),
2022-09-02 14:19:36 +00:00
Query :: limit ( $limit ),
Query :: orderDesc ( 'time' ),
]);
2022-04-13 12:39:31 +00:00
2021-08-28 16:25:48 +00:00
$stats [ $metric ] = [];
foreach ( $requestDocs as $requestDoc ) {
$stats [ $metric ][] = [
'value' => $requestDoc -> getAttribute ( 'value' ),
'date' => $requestDoc -> getAttribute ( 'time' ),
];
}
2021-10-27 19:57:20 +00:00
// backfill metrics with empty values for graphs
$backfill = $limit - \count ( $requestDocs );
while ( $backfill > 0 ) {
$last = $limit - $backfill - 1 ; // array index of last added metric
2022-04-13 12:39:31 +00:00
$diff = match ( $period ) { // convert period to seconds for unix timestamp math
2022-10-21 05:45:25 +00:00
'1h' => 3600 ,
2021-10-27 19:57:20 +00:00
'1d' => 86400 ,
};
$stats [ $metric ][] = [
'value' => 0 ,
2022-09-15 23:48:09 +00:00
'date' => DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime ( $stats [ $metric ][ $last ][ 'date' ] ? ? null ), - 1 * $diff )),
2021-10-27 19:57:20 +00:00
];
$backfill -- ;
}
2021-08-28 16:25:48 +00:00
$stats [ $metric ] = array_reverse ( $stats [ $metric ]);
2022-04-13 12:39:31 +00:00
}
2021-08-28 16:25:48 +00:00
});
2021-08-20 08:24:45 +00:00
2021-08-26 19:12:36 +00:00
$usage = new Document ([
2021-01-13 01:10:52 +00:00
'range' => $range ,
2022-08-20 11:20:31 +00:00
'executionsTotal' => $stats [ $metrics [ 0 ]] ? ? [],
'executionsFailure' => $stats [ $metrics [ 1 ]] ? ? [],
'executionsSuccess' => $stats [ $metrics [ 2 ]] ? ? [],
'executionsTime' => $stats [ $metrics [ 3 ]] ? ? [],
'buildsTotal' => $stats [ $metrics [ 4 ]] ? ? [],
'buildsFailure' => $stats [ $metrics [ 5 ]] ? ? [],
'buildsSuccess' => $stats [ $metrics [ 6 ]] ? ? [],
'buildsTime' => $stats [ $metrics [ 7 ]] ? ? [],
2021-01-13 01:10:52 +00:00
]);
2020-10-30 19:53:27 +00:00
}
2021-08-26 19:12:36 +00:00
2021-08-27 17:34:43 +00:00
$response -> dynamic ( $usage , Response :: MODEL_USAGE_FUNCTIONS );
2020-12-26 15:20:08 +00:00
});
2020-10-30 19:53:27 +00:00
2020-07-12 21:18:52 +00:00
App :: put ( '/v1/functions/:functionId' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'Update Function' )
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].update' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'function.update' )
2022-08-09 14:38:54 +00:00
-> label ( 'audits.resource' , 'function/{response.$id}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'update' )
-> label ( 'sdk.description' , '/docs/references/functions/update-function.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_FUNCTION )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2020-09-10 14:40:14 +00:00
-> param ( 'name' , '' , new Text ( 128 ), 'Function name. Max length: 128 chars.' )
2022-08-27 03:19:00 +00:00
-> param ( 'execute' , [], new Roles ( APP_LIMIT_ARRAY_PARAMS_SIZE ), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.' )
2022-05-12 18:41:04 +00:00
-> param ( 'events' , [], new ArrayList ( new ValidatorEvent (), APP_LIMIT_ARRAY_PARAMS_SIZE ), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.' , true )
2020-09-10 14:40:14 +00:00
-> param ( 'schedule' , '' , new Cron (), 'Schedule CRON syntax.' , true )
2022-01-21 08:05:41 +00:00
-> param ( 'timeout' , 15 , new Range ( 1 , ( int ) App :: getEnv ( '_APP_FUNCTIONS_TIMEOUT' , 900 )), 'Maximum execution time in seconds.' , true )
2022-09-12 09:02:14 +00:00
-> param ( 'enabled' , true , new Boolean (), 'Is function enabled?' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2021-01-16 23:38:13 +00:00
-> inject ( 'project' )
2021-12-07 10:42:33 +00:00
-> inject ( 'user' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2022-09-09 08:49:18 +00:00
-> action ( function ( string $functionId , string $name , array $execute , array $events , string $schedule , int $timeout , bool $enabled , Response $response , Database $dbForProject , Document $project , Document $user , Event $eventsInstance ) {
2021-01-16 23:38:13 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-07-12 21:18:52 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2022-09-23 06:12:17 +00:00
$cron = ! empty ( $schedule ) ? new CronExpression ( $schedule ) : null ;
$next = ! empty ( $schedule ) ? DateTime :: format ( $cron -> getNextRunDate ()) : null ;
2020-07-12 21:18:52 +00:00
2022-09-09 08:49:18 +00:00
$enabled ? ? = $function -> getAttribute ( 'enabled' , true );
2022-09-11 12:20:26 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> updateDocument ( 'functions' , $function -> getId (), new Document ( array_merge ( $function -> getArrayCopy (), [
2021-05-04 21:25:17 +00:00
'execute' => $execute ,
2020-07-12 21:18:52 +00:00
'name' => $name ,
'events' => $events ,
'schedule' => $schedule ,
2022-09-23 06:12:17 +00:00
'scheduleUpdatedAt' => DateTime :: now (),
2022-07-07 09:26:30 +00:00
'scheduleNext' => $next ,
2021-01-16 23:38:13 +00:00
'timeout' => $timeout ,
2022-09-09 08:49:18 +00:00
'enabled' => $enabled ,
2021-08-14 18:56:28 +00:00
'search' => implode ( ' ' , [ $functionId , $name , $function -> getAttribute ( 'runtime' )]),
2021-05-04 21:25:17 +00:00
])));
2020-05-05 17:30:12 +00:00
2022-09-23 06:12:17 +00:00
if ( $next ) {
2022-04-19 13:13:55 +00:00
// Async task reschedule
$functionEvent = new Func ();
$functionEvent
-> setFunction ( $function )
-> setType ( 'schedule' )
-> setUser ( $user )
2022-07-07 09:54:46 +00:00
-> setProject ( $project )
2022-07-12 13:32:39 +00:00
-> schedule ( new \DateTime ( $next ));
2021-01-16 23:38:13 +00:00
}
2022-04-13 12:39:31 +00:00
$eventsInstance -> setParam ( 'functionId' , $function -> getId ());
2020-10-30 19:53:27 +00:00
$response -> dynamic ( $function , Response :: MODEL_FUNCTION );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-02-15 09:16:32 +00:00
App :: patch ( '/v1/functions/:functionId/deployments/:deploymentId' )
2020-07-12 21:18:52 +00:00
-> groups ([ 'api' , 'functions' ])
2022-01-24 22:59:02 +00:00
-> desc ( 'Update Function Deployment' )
2020-05-06 17:35:56 +00:00
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].deployments.[deploymentId].update' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'deployment.update' )
2022-08-13 07:34:03 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-06 17:35:56 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-01-24 22:59:02 +00:00
-> label ( 'sdk.method' , 'updateDeployment' )
-> label ( 'sdk.description' , '/docs/references/functions/update-function-deployment.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_FUNCTION )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2022-02-15 09:16:32 +00:00
-> param ( 'deploymentId' , '' , new UID (), 'Deployment ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2021-01-16 23:38:13 +00:00
-> inject ( 'project' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2022-05-24 14:28:27 +00:00
-> action ( function ( string $functionId , string $deploymentId , Response $response , Database $dbForProject , Document $project , Event $events ) {
2021-01-16 23:38:13 +00:00
2022-01-06 09:45:56 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2022-02-15 09:16:32 +00:00
$deployment = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
2022-01-26 23:19:02 +00:00
$build = $dbForProject -> getDocument ( 'builds' , $deployment -> getAttribute ( 'buildId' , '' ));
2021-09-06 00:37:20 +00:00
2021-12-08 15:08:53 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2021-12-08 15:08:53 +00:00
}
2021-01-16 23:38:13 +00:00
2022-01-24 22:59:02 +00:00
if ( $deployment -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
2021-12-08 15:08:53 +00:00
}
2021-09-06 00:37:20 +00:00
2021-12-08 15:08:53 +00:00
if ( $build -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: BUILD_NOT_FOUND );
2020-05-06 17:35:56 +00:00
}
2021-12-08 15:08:53 +00:00
if ( $build -> getAttribute ( 'status' ) !== 'ready' ) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: BUILD_NOT_READY );
2021-09-06 00:37:20 +00:00
}
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> updateDocument ( 'functions' , $function -> getId (), new Document ( array_merge ( $function -> getArrayCopy (), [
2022-09-23 06:12:17 +00:00
'deployment' => $deployment -> getId ()
2021-12-08 15:08:53 +00:00
])));
2022-04-13 12:39:31 +00:00
$events
-> setParam ( 'functionId' , $function -> getId ())
-> setParam ( 'deploymentId' , $deployment -> getId ());
2021-12-08 15:08:53 +00:00
$response -> dynamic ( $function , Response :: MODEL_FUNCTION );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
App :: delete ( '/v1/functions/:functionId' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'Delete Function' )
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].delete' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'function.delete' )
2022-08-09 14:38:54 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'delete' )
-> label ( 'sdk.description' , '/docs/references/functions/delete-function.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2020-12-26 15:20:08 +00:00
-> inject ( 'deletes' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2022-05-24 14:28:27 +00:00
-> action ( function ( string $functionId , Response $response , Database $dbForProject , Delete $deletes , Event $events ) {
2020-10-30 19:53:27 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-05-05 17:30:12 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2020-05-06 12:12:52 +00:00
2021-12-27 12:45:23 +00:00
if ( ! $dbForProject -> deleteDocument ( 'functions' , $function -> getId ())) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: GENERAL_SERVER_ERROR , 'Failed to remove function from DB' );
2020-05-04 14:35:01 +00:00
}
2020-05-05 17:30:12 +00:00
2020-10-30 19:53:27 +00:00
$deletes
2022-04-17 20:34:32 +00:00
-> setType ( DELETE_TYPE_DOCUMENT )
-> setDocument ( $function );
2022-04-13 12:39:31 +00:00
$events -> setParam ( 'functionId' , $function -> getId ());
2020-10-30 19:53:27 +00:00
2020-07-12 21:18:52 +00:00
$response -> noContent ();
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-01-24 23:05:17 +00:00
App :: post ( '/v1/functions/:functionId/deployments' )
2020-07-12 21:18:52 +00:00
-> groups ([ 'api' , 'functions' ])
2022-01-24 23:05:17 +00:00
-> desc ( 'Create Deployment' )
2020-05-05 17:30:12 +00:00
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].deployments.[deploymentId].create' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'deployment.create' )
2022-08-13 07:34:03 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-01-24 23:05:17 +00:00
-> label ( 'sdk.method' , 'createDeployment' )
-> label ( 'sdk.description' , '/docs/references/functions/create-deployment.md' )
2021-01-29 14:29:53 +00:00
-> label ( 'sdk.packaging' , true )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.request.type' , 'multipart/form-data' )
2022-07-18 09:43:51 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_ACCEPTED )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2022-01-24 23:05:17 +00:00
-> label ( 'sdk.response.model' , Response :: MODEL_DEPLOYMENT )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2021-09-01 09:48:56 +00:00
-> param ( 'entrypoint' , '' , new Text ( '1028' ), 'Entrypoint File.' )
2021-03-22 16:19:05 +00:00
-> param ( 'code' , [], new File (), 'Gzip file with your code package. When used with the Appwrite CLI, pass the path to your code directory, and the CLI will automatically package your code. Use a path that is within the current directory.' , false )
2022-02-15 08:46:21 +00:00
-> param ( 'activate' , false , new Boolean ( true ), 'Automatically activate the deployment when it is finished building.' , false )
2020-12-26 15:20:08 +00:00
-> inject ( 'request' )
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2021-12-08 15:08:53 +00:00
-> inject ( 'project' )
2021-12-13 08:08:36 +00:00
-> inject ( 'deviceFunctions' )
-> inject ( 'deviceLocal' )
2022-08-11 05:25:39 +00:00
-> action ( function ( string $functionId , string $entrypoint , mixed $code , bool $activate , Request $request , Response $response , Database $dbForProject , Event $events , Document $project , Device $deviceFunctions , Device $deviceLocal ) {
2021-01-16 23:38:13 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-07-12 21:18:52 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2020-07-14 20:33:52 +00:00
2021-01-31 19:11:03 +00:00
$file = $request -> getFiles ( 'code' );
2022-12-13 06:49:20 +00:00
// GraphQL multipart spec adds files with index keys
if ( empty ( $file )) {
$file = $request -> getFiles ( 0 );
}
2020-07-14 20:33:52 +00:00
if ( empty ( $file )) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: STORAGE_FILE_EMPTY , 'No file sent' );
2020-07-14 20:33:52 +00:00
}
2022-12-13 06:49:20 +00:00
$fileExt = new FileExt ([ FileExt :: TYPE_GZIP ]);
$fileSizeValidator = new FileSize ( App :: getEnv ( '_APP_FUNCTIONS_SIZE_LIMIT' , 0 ));
$upload = new Upload ();
2020-07-14 20:33:52 +00:00
// Make sure we handle a single file and multiple files the same way
2021-09-27 07:01:04 +00:00
$fileName = ( \is_array ( $file [ 'name' ]) && isset ( $file [ 'name' ][ 0 ])) ? $file [ 'name' ][ 0 ] : $file [ 'name' ];
$fileTmpName = ( \is_array ( $file [ 'tmp_name' ]) && isset ( $file [ 'tmp_name' ][ 0 ])) ? $file [ 'tmp_name' ][ 0 ] : $file [ 'tmp_name' ];
2021-11-30 08:06:54 +00:00
$fileSize = ( \is_array ( $file [ 'size' ]) && isset ( $file [ 'size' ][ 0 ])) ? $file [ 'size' ][ 0 ] : $file [ 'size' ];
2020-07-14 20:33:52 +00:00
2021-01-27 18:08:46 +00:00
if ( ! $fileExt -> isValid ( $file [ 'name' ])) { // Check if file type is allowed
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: STORAGE_FILE_TYPE_UNSUPPORTED );
2021-01-26 22:15:20 +00:00
}
2020-07-14 20:33:52 +00:00
2021-09-27 07:01:04 +00:00
$contentRange = $request -> getHeader ( 'content-range' );
2022-08-14 14:22:38 +00:00
$deploymentId = ID :: unique ();
2021-09-27 07:01:04 +00:00
$chunk = 1 ;
$chunks = 1 ;
if ( ! empty ( $contentRange )) {
$start = $request -> getContentRangeStart ();
$end = $request -> getContentRangeEnd ();
2021-11-30 08:06:54 +00:00
$fileSize = $request -> getContentRangeSize ();
2022-02-17 08:26:24 +00:00
$deploymentId = $request -> getHeader ( 'x-appwrite-id' , $deploymentId );
2022-04-13 12:39:31 +00:00
if ( is_null ( $start ) || is_null ( $end ) || is_null ( $fileSize )) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: STORAGE_INVALID_CONTENT_RANGE );
2021-09-27 07:01:04 +00:00
}
2022-01-16 07:16:06 +00:00
if ( $end === $fileSize ) {
2021-09-27 07:01:04 +00:00
//if it's a last chunks the chunk size might differ, so we set the $chunks and $chunk to notify it's last chunk
$chunks = $chunk = - 1 ;
} else {
// Calculate total number of chunks based on the chunk size i.e ($rangeEnd - $rangeStart)
2021-11-30 08:06:54 +00:00
$chunks = ( int ) ceil ( $fileSize / ( $end + 1 - $start ));
2021-11-30 08:01:47 +00:00
$chunk = ( int ) ( $start / ( $end + 1 - $start )) + 1 ;
2021-09-27 07:01:04 +00:00
}
}
2021-11-30 08:06:54 +00:00
if ( ! $fileSizeValidator -> isValid ( $fileSize )) { // Check if file size is exceeding allowed limit
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: STORAGE_INVALID_FILE_SIZE );
2020-07-14 20:33:52 +00:00
}
2021-09-27 07:01:04 +00:00
if ( ! $upload -> isValid ( $fileTmpName )) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: STORAGE_INVALID_FILE );
2020-07-14 20:33:52 +00:00
}
// Save to storage
2021-12-13 08:08:36 +00:00
$fileSize ? ? = $deviceLocal -> getFileSize ( $fileTmpName );
2022-04-13 12:39:31 +00:00
$path = $deviceFunctions -> getPath ( $deploymentId . '.' . \pathinfo ( $fileName , PATHINFO_EXTENSION ));
2022-02-17 08:26:24 +00:00
$deployment = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
2021-09-27 07:01:04 +00:00
2022-02-17 12:47:26 +00:00
$metadata = [ 'content_type' => $deviceLocal -> getFileMimeType ( $fileTmpName )];
if ( ! $deployment -> isEmpty ()) {
2022-02-17 08:26:24 +00:00
$chunks = $deployment -> getAttribute ( 'chunksTotal' , 1 );
2022-02-17 12:47:26 +00:00
$metadata = $deployment -> getAttribute ( 'metadata' , []);
if ( $chunk === - 1 ) {
2021-11-30 08:40:21 +00:00
$chunk = $chunks ;
2021-09-27 07:01:04 +00:00
}
}
2022-02-17 12:47:26 +00:00
$chunksUploaded = $deviceFunctions -> upload ( $fileTmpName , $path , $chunk , $chunks , $metadata );
2021-09-27 07:01:04 +00:00
if ( empty ( $chunksUploaded )) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: GENERAL_SERVER_ERROR , 'Failed moving file' );
2020-07-14 20:33:52 +00:00
}
2021-12-08 15:08:53 +00:00
2022-03-01 15:09:21 +00:00
$activate = ( bool ) filter_var ( $activate , FILTER_VALIDATE_BOOLEAN );
2022-02-25 14:27:50 +00:00
2022-04-13 12:39:31 +00:00
if ( $chunksUploaded === $chunks ) {
2022-02-25 14:27:50 +00:00
if ( $activate ) {
// Remove deploy for all other deployments.
$activeDeployments = $dbForProject -> find ( 'deployments' , [
2022-08-11 23:53:52 +00:00
Query :: equal ( 'activate' , [ true ]),
Query :: equal ( 'resourceId' , [ $functionId ]),
Query :: equal ( 'resourceType' , [ 'functions' ])
2022-02-25 14:27:50 +00:00
]);
foreach ( $activeDeployments as $activeDeployment ) {
$activeDeployment -> setAttribute ( 'activate' , false );
$dbForProject -> updateDocument ( 'deployments' , $activeDeployment -> getId (), $activeDeployment );
}
}
2022-04-13 12:39:31 +00:00
2021-12-13 08:08:36 +00:00
$fileSize = $deviceFunctions -> getFileSize ( $path );
2021-09-27 07:01:04 +00:00
2022-02-17 08:26:24 +00:00
if ( $deployment -> isEmpty ()) {
$deployment = $dbForProject -> createDocument ( 'deployments' , new Document ([
'$id' => $deploymentId ,
2022-08-02 09:21:53 +00:00
'$permissions' => [
2022-08-14 05:21:11 +00:00
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: any ()),
Permission :: delete ( Role :: any ()),
2022-08-02 09:21:53 +00:00
],
2022-02-17 08:26:24 +00:00
'resourceId' => $function -> getId (),
2022-02-18 15:38:48 +00:00
'resourceType' => 'functions' ,
2022-02-17 08:26:24 +00:00
'entrypoint' => $entrypoint ,
2021-09-27 07:01:04 +00:00
'path' => $path ,
2021-11-30 08:06:54 +00:00
'size' => $fileSize ,
2022-02-17 08:26:24 +00:00
'search' => implode ( ' ' , [ $deploymentId , $entrypoint ]),
2022-02-22 12:27:18 +00:00
'activate' => $activate ,
2022-02-17 12:47:26 +00:00
'metadata' => $metadata ,
2021-09-27 07:01:04 +00:00
]));
} else {
2022-02-17 12:47:26 +00:00
$deployment = $dbForProject -> updateDocument ( 'deployments' , $deploymentId , $deployment -> setAttribute ( 'size' , $fileSize ) -> setAttribute ( 'metadata' , $metadata ));
2021-09-27 07:01:04 +00:00
}
2022-02-25 11:06:58 +00:00
2022-04-19 13:13:55 +00:00
// Start the build
$buildEvent = new Build ();
$buildEvent
-> setType ( BUILD_TYPE_DEPLOYMENT )
-> setResource ( $function )
-> setDeployment ( $deployment )
-> setProject ( $project )
-> trigger ();
2021-09-27 07:01:04 +00:00
} else {
2022-04-13 12:39:31 +00:00
if ( $deployment -> isEmpty ()) {
2022-02-17 08:26:24 +00:00
$deployment = $dbForProject -> createDocument ( 'deployments' , new Document ([
'$id' => $deploymentId ,
2022-08-02 09:21:53 +00:00
'$permissions' => [
2022-08-14 05:21:11 +00:00
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: any ()),
Permission :: delete ( Role :: any ()),
2022-08-02 09:21:53 +00:00
],
2022-02-17 08:26:24 +00:00
'resourceId' => $function -> getId (),
2022-02-18 15:38:48 +00:00
'resourceType' => 'functions' ,
2022-02-17 08:26:24 +00:00
'entrypoint' => $entrypoint ,
2021-09-27 07:01:04 +00:00
'path' => $path ,
2022-02-22 12:31:04 +00:00
'size' => $fileSize ,
2021-09-27 07:01:04 +00:00
'chunksTotal' => $chunks ,
'chunksUploaded' => $chunksUploaded ,
2022-02-17 08:26:24 +00:00
'search' => implode ( ' ' , [ $deploymentId , $entrypoint ]),
2022-02-22 12:27:13 +00:00
'activate' => $activate ,
2022-02-17 12:47:26 +00:00
'metadata' => $metadata ,
2021-09-27 07:01:04 +00:00
]));
} else {
2022-02-17 12:47:26 +00:00
$deployment = $dbForProject -> updateDocument ( 'deployments' , $deploymentId , $deployment -> setAttribute ( 'chunksUploaded' , $chunksUploaded ) -> setAttribute ( 'metadata' , $metadata ));
2021-09-27 07:01:04 +00:00
}
}
2020-05-05 17:30:12 +00:00
2022-02-17 12:47:26 +00:00
$metadata = null ;
2021-12-08 15:08:53 +00:00
2022-04-13 12:39:31 +00:00
$events
-> setParam ( 'functionId' , $function -> getId ())
-> setParam ( 'deploymentId' , $deployment -> getId ());
2022-09-07 11:02:36 +00:00
$response
-> setStatusCode ( Response :: STATUS_CODE_ACCEPTED )
-> dynamic ( $deployment , Response :: MODEL_DEPLOYMENT );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-01-24 23:09:24 +00:00
App :: get ( '/v1/functions/:functionId/deployments' )
2020-07-12 21:18:52 +00:00
-> groups ([ 'api' , 'functions' ])
2022-01-24 23:09:24 +00:00
-> desc ( 'List Deployments' )
2020-05-05 17:30:12 +00:00
-> label ( 'scope' , 'functions.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-01-24 23:09:24 +00:00
-> label ( 'sdk.method' , 'listDeployments' )
-> label ( 'sdk.description' , '/docs/references/functions/list-deployments.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2022-01-24 23:09:24 +00:00
-> label ( 'sdk.response.model' , Response :: MODEL_DEPLOYMENT_LIST )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2022-08-23 09:12:48 +00:00
-> param ( 'queries' , [], new Deployments (), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). 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 ( ', ' , Deployments :: ALLOWED_ATTRIBUTES ), true )
2020-09-10 14:40:14 +00:00
-> param ( 'search' , '' , new Text ( 256 ), 'Search term to filter your list results. Max length: 256 chars.' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-08-23 09:12:48 +00:00
-> action ( function ( string $functionId , array $queries , string $search , Response $response , Database $dbForProject ) {
2021-01-16 23:38:13 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-05-05 17:30:12 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2021-05-27 10:09:14 +00:00
2022-08-23 09:12:48 +00:00
$queries = Query :: parseQueries ( $queries );
2021-08-06 12:36:05 +00:00
2022-08-11 23:53:52 +00:00
if ( ! empty ( $search )) {
2022-08-23 09:12:48 +00:00
$queries [] = Query :: search ( 'search' , $search );
2021-08-06 12:36:05 +00:00
}
2022-08-23 09:12:48 +00:00
// Set resource queries
$queries [] = Query :: equal ( 'resourceId' , [ $function -> getId ()]);
$queries [] = Query :: equal ( 'resourceType' , [ 'functions' ]);
2021-08-18 13:42:03 +00:00
2022-08-23 09:12:48 +00:00
// Get cursor document if there was a cursor query
2022-08-30 23:31:43 +00:00
$cursor = Query :: getByType ( $queries , Query :: TYPE_CURSORAFTER , Query :: TYPE_CURSORBEFORE );
$cursor = reset ( $cursor );
2022-08-30 11:55:23 +00:00
if ( $cursor ) {
2022-08-23 09:12:48 +00:00
/** @var Query $cursor */
$deploymentId = $cursor -> getValue ();
$cursorDocument = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
2021-08-18 13:42:03 +00:00
2022-08-11 23:53:52 +00:00
if ( $cursorDocument -> isEmpty ()) {
2022-08-23 09:12:48 +00:00
throw new Exception ( Exception :: GENERAL_CURSOR_NOT_FOUND , " Deployment ' { $deploymentId } ' for the 'cursor' value not found. " );
2022-08-11 23:53:52 +00:00
}
2021-08-18 13:42:03 +00:00
2022-08-23 09:12:48 +00:00
$cursor -> setValue ( $cursorDocument );
2021-08-18 13:42:03 +00:00
}
2022-08-23 09:12:48 +00:00
$filterQueries = Query :: groupByType ( $queries )[ 'filters' ];
2021-08-18 13:42:03 +00:00
2022-08-23 09:12:48 +00:00
$results = $dbForProject -> find ( 'deployments' , $queries );
2022-08-11 23:53:52 +00:00
$total = $dbForProject -> count ( 'deployments' , $filterQueries , APP_LIMIT_COUNT );
2020-07-12 21:18:52 +00:00
2022-01-31 11:29:31 +00:00
foreach ( $results as $result ) {
2022-02-16 11:43:21 +00:00
$build = $dbForProject -> getDocument ( 'builds' , $result -> getAttribute ( 'buildId' , '' ));
2022-02-16 16:00:45 +00:00
$result -> setAttribute ( 'status' , $build -> getAttribute ( 'status' , 'processing' ));
2022-01-31 11:29:31 +00:00
$result -> setAttribute ( 'buildStderr' , $build -> getAttribute ( 'stderr' , '' ));
$result -> setAttribute ( 'buildStdout' , $build -> getAttribute ( 'stdout' , '' ));
2022-10-10 15:24:40 +00:00
$result -> setAttribute ( 'buildTime' , $build -> getAttribute ( 'duration' , 0 ));
2021-12-06 14:12:41 +00:00
}
2020-10-30 19:53:27 +00:00
$response -> dynamic ( new Document ([
2022-01-24 23:09:24 +00:00
'deployments' => $results ,
2022-02-27 09:57:09 +00:00
'total' => $total ,
2022-01-24 23:09:24 +00:00
]), Response :: MODEL_DEPLOYMENT_LIST );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-01-24 23:11:33 +00:00
App :: get ( '/v1/functions/:functionId/deployments/:deploymentId' )
2020-07-12 21:18:52 +00:00
-> groups ([ 'api' , 'functions' ])
2022-01-24 23:11:33 +00:00
-> desc ( 'Get Deployment' )
2020-05-05 17:30:12 +00:00
-> label ( 'scope' , 'functions.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-01-24 23:11:33 +00:00
-> label ( 'sdk.method' , 'getDeployment' )
-> label ( 'sdk.description' , '/docs/references/functions/get-deployment.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2022-07-07 04:49:44 +00:00
-> label ( 'sdk.response.model' , Response :: MODEL_DEPLOYMENT )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2022-01-24 23:11:33 +00:00
-> param ( 'deploymentId' , '' , new UID (), 'Deployment ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-05-24 14:28:27 +00:00
-> action ( function ( string $functionId , string $deploymentId , Response $response , Database $dbForProject ) {
2021-01-16 23:38:13 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2020-05-05 17:30:12 +00:00
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2020-05-05 17:30:12 +00:00
2022-01-24 23:11:33 +00:00
$deployment = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
2020-05-05 17:30:12 +00:00
2022-01-25 16:51:05 +00:00
if ( $deployment -> getAttribute ( 'resourceId' ) !== $function -> getId ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2020-05-05 17:30:12 +00:00
2022-01-24 23:11:33 +00:00
if ( $deployment -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
2020-05-05 17:30:12 +00:00
}
2022-10-31 05:11:55 +00:00
$build = $dbForProject -> getDocument ( 'builds' , $deployment -> getAttribute ( 'buildId' , '' ));
$deployment -> setAttribute ( 'status' , $build -> getAttribute ( 'status' , 'processing' ));
$deployment -> setAttribute ( 'buildStderr' , $build -> getAttribute ( 'stderr' , '' ));
$deployment -> setAttribute ( 'buildStdout' , $build -> getAttribute ( 'stdout' , '' ));
2022-01-24 23:11:33 +00:00
$response -> dynamic ( $deployment , Response :: MODEL_DEPLOYMENT );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-01-24 23:14:21 +00:00
App :: delete ( '/v1/functions/:functionId/deployments/:deploymentId' )
2020-07-12 21:18:52 +00:00
-> groups ([ 'api' , 'functions' ])
2022-01-24 23:14:21 +00:00
-> desc ( 'Delete Deployment' )
2020-05-05 17:30:12 +00:00
-> label ( 'scope' , 'functions.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].deployments.[deploymentId].delete' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'deployment.delete' )
2022-08-13 07:34:03 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
2022-01-24 23:14:21 +00:00
-> label ( 'sdk.method' , 'deleteDeployment' )
-> label ( 'sdk.description' , '/docs/references/functions/delete-deployment.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2022-01-24 23:14:21 +00:00
-> param ( 'deploymentId' , '' , new UID (), 'Deployment ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-01-28 01:29:20 +00:00
-> inject ( 'deletes' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2021-12-13 08:08:36 +00:00
-> inject ( 'deviceFunctions' )
2022-08-11 05:25:39 +00:00
-> action ( function ( string $functionId , string $deploymentId , Response $response , Database $dbForProject , Delete $deletes , Event $events , Device $deviceFunctions ) {
2021-01-16 23:38:13 +00:00
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
2021-06-20 13:59:36 +00:00
if ( $function -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2022-04-13 12:39:31 +00:00
2022-01-24 23:14:21 +00:00
$deployment = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
if ( $deployment -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
2021-09-13 10:50:45 +00:00
}
2022-01-31 23:44:55 +00:00
if ( $deployment -> getAttribute ( 'resourceId' ) !== $function -> getId ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
2021-09-13 10:50:45 +00:00
}
2022-02-17 08:26:24 +00:00
if ( $deviceFunctions -> delete ( $deployment -> getAttribute ( 'path' , '' ))) {
if ( ! $dbForProject -> deleteDocument ( 'deployments' , $deployment -> getId ())) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: GENERAL_SERVER_ERROR , 'Failed to remove deployment from DB' );
2020-07-18 21:48:28 +00:00
}
2020-05-05 17:30:12 +00:00
}
2022-04-13 12:39:31 +00:00
if ( $function -> getAttribute ( 'deployment' ) === $deployment -> getId ()) { // Reset function deployment
2021-12-27 12:45:23 +00:00
$function = $dbForProject -> updateDocument ( 'functions' , $function -> getId (), new Document ( array_merge ( $function -> getArrayCopy (), [
2022-01-24 23:14:21 +00:00
'deployment' => '' ,
2021-05-04 21:25:17 +00:00
])));
2020-10-30 19:53:27 +00:00
}
2022-04-13 12:39:31 +00:00
$events
-> setParam ( 'functionId' , $function -> getId ())
-> setParam ( 'deploymentId' , $deployment -> getId ());
2020-07-18 21:48:28 +00:00
2022-01-28 01:29:20 +00:00
$deletes
2022-04-17 20:34:32 +00:00
-> setType ( DELETE_TYPE_DOCUMENT )
-> setDocument ( $deployment );
2022-01-28 01:29:20 +00:00
2020-07-12 21:18:52 +00:00
$response -> noContent ();
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
2022-09-29 08:42:46 +00:00
App :: post ( '/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId' )
-> groups ([ 'api' , 'functions' ])
-> desc ( 'Create Build' )
-> label ( 'scope' , 'functions.write' )
-> label ( 'event' , 'functions.[functionId].deployments.[deploymentId].update' )
-> label ( 'audits.event' , 'deployment.update' )
-> label ( 'audits.resource' , 'function/{request.functionId}' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'createBuild' )
-> label ( 'sdk.description' , '/docs/references/functions/create-build.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
-> param ( 'deploymentId' , '' , new UID (), 'Deployment ID.' )
-> param ( 'buildId' , '' , new UID (), 'Build unique ID.' )
-> inject ( 'response' )
-> inject ( 'dbForProject' )
-> inject ( 'project' )
-> inject ( 'events' )
-> action ( function ( string $functionId , string $deploymentId , string $buildId , Response $response , Database $dbForProject , Document $project , Event $events ) {
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
$deployment = $dbForProject -> getDocument ( 'deployments' , $deploymentId );
if ( $function -> isEmpty ()) {
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
}
if ( $deployment -> isEmpty ()) {
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND );
}
$build = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'builds' , $buildId ));
if ( $build -> isEmpty ()) {
throw new Exception ( Exception :: BUILD_NOT_FOUND );
}
if ( $build -> getAttribute ( 'status' ) !== 'failed' ) {
throw new Exception ( Exception :: BUILD_IN_PROGRESS , 'Build not failed' );
}
$events
-> setParam ( 'functionId' , $function -> getId ())
-> setParam ( 'deploymentId' , $deployment -> getId ());
// Retry the build
$buildEvent = new Build ();
$buildEvent
-> setType ( BUILD_TYPE_RETRY )
-> setResource ( $function )
-> setDeployment ( $deployment )
-> setProject ( $project )
-> trigger ();
$response -> noContent ();
});
2020-07-12 21:18:52 +00:00
App :: post ( '/v1/functions/:functionId/executions' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'Create Execution' )
2020-12-30 07:26:01 +00:00
-> label ( 'scope' , 'execution.write' )
2022-04-13 12:39:31 +00:00
-> label ( 'event' , 'functions.[functionId].executions.[executionId].create' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_KEY , APP_AUTH_TYPE_JWT ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'createExecution' )
-> label ( 'sdk.description' , '/docs/references/functions/create-execution.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_EXECUTION )
2022-08-30 23:33:19 +00:00
-> label ( 'abuse-key' , 'ip:{ip},userId:{userId}' )
2022-08-30 23:34:17 +00:00
-> label ( 'abuse-limit' , APP_LIMIT_WRITE_RATE_DEFAULT )
-> label ( 'abuse-time' , APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2021-03-09 19:58:03 +00:00
-> param ( 'data' , '' , new Text ( 8192 ), 'String of custom data to send to function.' , true )
2022-09-07 08:24:49 +00:00
-> param ( 'async' , false , new Boolean (), 'Execute code in the background. Default value is false.' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
-> inject ( 'project' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2021-03-10 16:58:46 +00:00
-> inject ( 'user' )
2022-04-13 12:39:31 +00:00
-> inject ( 'events' )
2022-07-13 08:57:57 +00:00
-> inject ( 'usage' )
2022-09-09 08:49:18 +00:00
-> inject ( 'mode' )
-> action ( function ( string $functionId , string $data , bool $async , Response $response , Document $project , Database $dbForProject , Document $user , Event $events , Stats $usage , string $mode ) {
2020-07-16 21:50:37 +00:00
2022-04-13 12:39:31 +00:00
$function = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'functions' , $functionId ));
2020-07-12 21:18:52 +00:00
2022-09-09 08:49:18 +00:00
if ( $function -> isEmpty () || ! $function -> getAttribute ( 'enabled' )) {
if ( ! ( $mode === APP_MODE_ADMIN && Auth :: isPrivilegedUser ( Authorization :: getRoles ()))) {
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
}
2020-07-12 21:18:52 +00:00
}
2020-07-16 21:50:37 +00:00
2022-02-04 01:29:40 +00:00
$runtimes = Config :: getParam ( 'runtimes' , []);
2022-02-05 19:49:57 +00:00
$runtime = ( isset ( $runtimes [ $function -> getAttribute ( 'runtime' , '' )])) ? $runtimes [ $function -> getAttribute ( 'runtime' , '' )] : null ;
2022-02-04 01:29:40 +00:00
if ( \is_null ( $runtime )) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: FUNCTION_RUNTIME_UNSUPPORTED , 'Runtime "' . $function -> getAttribute ( 'runtime' , '' ) . '" is not supported' );
2022-02-04 01:29:40 +00:00
}
2022-04-13 12:39:31 +00:00
$deployment = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'deployments' , $function -> getAttribute ( 'deployment' , '' )));
2020-07-16 21:50:37 +00:00
2022-01-25 16:51:05 +00:00
if ( $deployment -> getAttribute ( 'resourceId' ) !== $function -> getId ()) {
2022-08-14 06:56:12 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND , 'Deployment not found. Create a deployment before trying to execute a function' );
2020-07-16 21:50:37 +00:00
}
2022-01-24 23:16:53 +00:00
if ( $deployment -> isEmpty ()) {
2022-08-14 06:56:12 +00:00
throw new Exception ( Exception :: DEPLOYMENT_NOT_FOUND , 'Deployment not found. Create a deployment before trying to execute a function' );
2020-07-16 21:50:37 +00:00
}
2020-12-29 23:00:44 +00:00
2022-02-03 00:05:03 +00:00
/** Check if build has completed */
2022-04-13 12:39:31 +00:00
$build = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'builds' , $deployment -> getAttribute ( 'buildId' , '' )));
2022-02-03 00:05:03 +00:00
if ( $build -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: BUILD_NOT_FOUND );
2022-02-03 00:05:03 +00:00
}
if ( $build -> getAttribute ( 'status' ) !== 'ready' ) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: BUILD_NOT_READY );
2022-02-03 00:05:03 +00:00
}
2022-01-18 06:38:10 +00:00
$validator = new Authorization ( 'execute' );
2020-12-29 23:00:44 +00:00
2021-05-04 21:25:17 +00:00
if ( ! $validator -> isValid ( $function -> getAttribute ( 'execute' ))) { // Check if user has write access to execute function
2022-07-26 14:56:59 +00:00
throw new Exception ( Exception :: USER_UNAUTHORIZED , $validator -> getDescription ());
2020-12-29 23:00:44 +00:00
}
2022-08-14 14:22:38 +00:00
$executionId = ID :: unique ();
2021-09-27 10:12:42 +00:00
2022-06-15 12:46:52 +00:00
/** @var Document $execution */
2022-04-13 12:39:31 +00:00
$execution = Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'executions' , new Document ([
2021-09-27 10:12:42 +00:00
'$id' => $executionId ,
2022-08-15 11:24:31 +00:00
'$permissions' => ! $user -> isEmpty () ? [ Permission :: read ( Role :: user ( $user -> getId ()))] : [],
2020-07-12 21:18:52 +00:00
'functionId' => $function -> getId (),
2022-01-24 23:16:53 +00:00
'deploymentId' => $deployment -> getId (),
2020-10-30 19:53:27 +00:00
'trigger' => 'http' , // http / schedule / event
2022-11-21 11:43:20 +00:00
'status' => $async ? 'waiting' : 'processing' , // waiting / processing / completed / failed
2021-12-10 10:43:56 +00:00
'statusCode' => 0 ,
2022-04-25 09:12:58 +00:00
'response' => '' ,
2020-07-12 21:18:52 +00:00
'stderr' => '' ,
2022-09-09 12:02:04 +00:00
'duration' => 0.0 ,
2021-09-27 10:12:42 +00:00
'search' => implode ( ' ' , [ $functionId , $executionId ]),
2021-12-17 15:25:05 +00:00
])));
2020-12-29 23:00:44 +00:00
2021-03-10 20:25:54 +00:00
$jwt = '' ; // initialize
2021-06-20 13:59:36 +00:00
if ( ! $user -> isEmpty ()) { // If userId exists, generate a JWT for function
2021-07-22 14:49:52 +00:00
$sessions = $user -> getAttribute ( 'sessions' , []);
$current = new Document ();
2021-03-10 16:58:46 +00:00
2022-04-13 12:39:31 +00:00
foreach ( $sessions as $session ) {
/** @var Utopia\Database\Document $session */
2021-07-22 14:49:52 +00:00
if ( $session -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) { // If current session delete the cookies too
$current = $session ;
2021-03-10 16:58:46 +00:00
}
}
2022-04-13 12:39:31 +00:00
if ( ! $current -> isEmpty ()) {
2021-03-10 20:25:54 +00:00
$jwtObj = new JWT ( App :: getEnv ( '_APP_OPENSSL_KEY_V1' ), 'HS256' , 900 , 10 ); // Instantiate with key, algo, maxAge and leeway.
$jwt = $jwtObj -> encode ([
2021-03-10 17:48:05 +00:00
'userId' => $user -> getId (),
2021-07-22 14:49:52 +00:00
'sessionId' => $current -> getId (),
2021-03-10 17:48:05 +00:00
]);
2021-03-10 16:58:46 +00:00
}
}
2022-04-13 12:39:31 +00:00
$events
-> setParam ( 'functionId' , $function -> getId ())
-> setParam ( 'executionId' , $execution -> getId ())
2022-06-22 10:51:49 +00:00
-> setContext ( 'function' , $function );
2022-04-13 12:39:31 +00:00
2021-08-24 09:32:27 +00:00
if ( $async ) {
2022-04-17 20:34:32 +00:00
$event = new Func ();
2022-04-13 12:39:31 +00:00
$event
2022-04-17 20:34:32 +00:00
-> setType ( 'http' )
-> setExecution ( $execution )
-> setFunction ( $function )
-> setData ( $data )
-> setJWT ( $jwt )
2022-04-13 12:39:31 +00:00
-> setProject ( $project )
2022-04-17 20:34:32 +00:00
-> setUser ( $user );
2022-04-13 12:39:31 +00:00
2022-04-17 20:34:32 +00:00
$event -> trigger ();
2020-07-12 21:18:52 +00:00
2022-09-07 11:02:36 +00:00
return $response
-> setStatusCode ( Response :: STATUS_CODE_ACCEPTED )
-> dynamic ( $execution , Response :: MODEL_EXECUTION );
2021-08-24 09:32:27 +00:00
}
2022-01-10 14:18:33 +00:00
2022-08-30 12:30:52 +00:00
$vars = array_reduce ( $function [ 'vars' ] ? ? [], function ( array $carry , Document $var ) {
2022-09-19 11:58:41 +00:00
$carry [ $var -> getAttribute ( 'key' )] = $var -> getAttribute ( 'value' ) ? ? '' ;
2022-08-30 12:30:52 +00:00
return $carry ;
}, []);
2022-08-10 13:43:05 +00:00
$vars = \array_merge ( $vars , [
2022-02-04 01:29:40 +00:00
'APPWRITE_FUNCTION_ID' => $function -> getId (),
2022-09-30 09:52:35 +00:00
'APPWRITE_FUNCTION_NAME' => $function -> getAttribute ( 'name' ),
2022-02-04 01:29:40 +00:00
'APPWRITE_FUNCTION_DEPLOYMENT' => $deployment -> getId (),
2022-02-05 10:08:05 +00:00
'APPWRITE_FUNCTION_PROJECT_ID' => $project -> getId (),
2022-02-04 01:29:40 +00:00
'APPWRITE_FUNCTION_TRIGGER' => 'http' ,
2022-09-19 11:58:41 +00:00
'APPWRITE_FUNCTION_RUNTIME_NAME' => $runtime [ 'name' ] ? ? '' ,
'APPWRITE_FUNCTION_RUNTIME_VERSION' => $runtime [ 'version' ] ? ? '' ,
'APPWRITE_FUNCTION_DATA' => $data ? ? '' ,
'APPWRITE_FUNCTION_USER_ID' => $user -> getId () ? ? '' ,
'APPWRITE_FUNCTION_JWT' => $jwt ? ? '' ,
2022-02-04 01:29:40 +00:00
]);
2022-02-03 00:05:03 +00:00
2022-02-05 19:49:57 +00:00
/** Execute function */
2022-04-13 16:15:25 +00:00
$executor = new Executor ( App :: getEnv ( '_APP_EXECUTOR_HOST' ));
2022-02-15 17:39:03 +00:00
try {
$executionResponse = $executor -> createExecution (
projectId : $project -> getId (),
deploymentId : $deployment -> getId (),
path : $build -> getAttribute ( 'outputPath' , '' ),
vars : $vars ,
data : $data ,
entrypoint : $deployment -> getAttribute ( 'entrypoint' , '' ),
runtime : $function -> getAttribute ( 'runtime' , '' ),
timeout : $function -> getAttribute ( 'timeout' , 0 ),
baseImage : $runtime [ 'image' ]
);
/** Update execution status */
$execution -> setAttribute ( 'status' , $executionResponse [ 'status' ]);
$execution -> setAttribute ( 'statusCode' , $executionResponse [ 'statusCode' ]);
2022-04-25 09:12:58 +00:00
$execution -> setAttribute ( 'response' , $executionResponse [ 'response' ]);
2022-08-10 07:19:07 +00:00
$execution -> setAttribute ( 'stdout' , $executionResponse [ 'stdout' ]);
2022-02-15 17:39:03 +00:00
$execution -> setAttribute ( 'stderr' , $executionResponse [ 'stderr' ]);
2022-09-09 12:02:04 +00:00
$execution -> setAttribute ( 'duration' , $executionResponse [ 'duration' ]);
2022-02-15 17:39:03 +00:00
} catch ( \Throwable $th ) {
2022-07-12 13:32:39 +00:00
$interval = ( new \DateTime ()) -> diff ( new \DateTime ( $execution -> getCreatedAt ()));
2022-07-02 14:25:44 +00:00
$execution
2022-09-09 12:02:04 +00:00
-> setAttribute ( 'duration' , ( float ) $interval -> format ( '%s.%f' ))
2022-07-02 14:25:44 +00:00
-> setAttribute ( 'status' , 'failed' )
-> setAttribute ( 'statusCode' , $th -> getCode ())
-> setAttribute ( 'stderr' , $th -> getMessage ());
2022-02-15 17:39:03 +00:00
Console :: error ( $th -> getMessage ());
}
2022-02-04 01:29:40 +00:00
2022-04-13 12:39:31 +00:00
Authorization :: skip ( fn () => $dbForProject -> updateDocument ( 'executions' , $executionId , $execution ));
2022-02-24 12:58:10 +00:00
2022-08-11 06:49:20 +00:00
// TODO revise this later using route label
2022-07-13 08:57:57 +00:00
$usage
2022-08-11 06:49:20 +00:00
-> setParam ( 'functionId' , $function -> getId ())
2022-08-17 10:13:50 +00:00
-> setParam ( 'executions.{scope}.compute' , 1 )
-> setParam ( 'executionStatus' , $execution -> getAttribute ( 'status' , '' ))
2022-09-09 12:02:04 +00:00
-> setParam ( 'executionTime' , $execution -> getAttribute ( 'duration' )); // ms
2022-07-13 08:57:57 +00:00
2022-08-14 08:44:17 +00:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2022-09-06 00:28:57 +00:00
2022-08-16 05:23:51 +00:00
if ( ! $isPrivilegedUser && ! $isAppUser ) {
2022-08-16 04:34:49 +00:00
$execution -> setAttribute ( 'stdout' , '' );
$execution -> setAttribute ( 'stderr' , '' );
}
2022-07-13 08:57:57 +00:00
2022-01-10 14:18:33 +00:00
$response
2022-01-26 23:19:02 +00:00
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2022-02-24 13:22:20 +00:00
-> dynamic ( $execution , Response :: MODEL_EXECUTION );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
App :: get ( '/v1/functions/:functionId/executions' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'List Executions' )
2020-12-30 07:26:01 +00:00
-> label ( 'scope' , 'execution.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_KEY , APP_AUTH_TYPE_JWT ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'listExecutions' )
-> label ( 'sdk.description' , '/docs/references/functions/list-executions.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_EXECUTION_LIST )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
2022-08-23 09:26:34 +00:00
-> param ( 'queries' , [], new Executions (), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). 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 ( ', ' , Executions :: ALLOWED_ATTRIBUTES ), true )
2021-09-27 10:12:42 +00:00
-> param ( 'search' , '' , new Text ( 256 ), 'Search term to filter your list results. Max length: 256 chars.' , true )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-09-09 08:49:18 +00:00
-> inject ( 'mode' )
-> action ( function ( string $functionId , array $queries , string $search , Response $response , Database $dbForProject , string $mode ) {
2020-05-05 17:30:12 +00:00
2022-04-13 12:39:31 +00:00
$function = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'functions' , $functionId ));
2020-05-05 17:30:12 +00:00
2022-09-09 08:49:18 +00:00
if ( $function -> isEmpty () || ! $function -> getAttribute ( 'enabled' )) {
if ( ! ( $mode === APP_MODE_ADMIN && Auth :: isPrivilegedUser ( Authorization :: getRoles ()))) {
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
}
2020-07-12 21:18:52 +00:00
}
2021-05-27 10:09:14 +00:00
2022-08-23 09:26:34 +00:00
$queries = Query :: parseQueries ( $queries );
2021-08-06 12:36:05 +00:00
2022-08-11 23:53:52 +00:00
if ( ! empty ( $search )) {
2022-08-23 09:26:34 +00:00
$queries [] = Query :: search ( 'search' , $search );
2021-08-06 12:36:05 +00:00
}
2022-08-23 09:26:34 +00:00
// Set internal queries
$queries [] = Query :: equal ( 'functionId' , [ $function -> getId ()]);
2021-09-27 10:12:42 +00:00
2022-08-23 09:26:34 +00:00
// Get cursor document if there was a cursor query
2022-08-30 23:31:43 +00:00
$cursor = Query :: getByType ( $queries , Query :: TYPE_CURSORAFTER , Query :: TYPE_CURSORBEFORE );
$cursor = reset ( $cursor );
2022-08-30 11:55:23 +00:00
if ( $cursor ) {
2022-08-23 09:26:34 +00:00
/** @var Query $cursor */
$executionId = $cursor -> getValue ();
$cursorDocument = $dbForProject -> getDocument ( 'executions' , $executionId );
2021-08-06 12:36:05 +00:00
2022-08-11 23:53:52 +00:00
if ( $cursorDocument -> isEmpty ()) {
2022-08-23 09:26:34 +00:00
throw new Exception ( Exception :: GENERAL_CURSOR_NOT_FOUND , " Execution ' { $executionId } ' for the 'cursor' value not found. " );
2021-08-06 12:36:05 +00:00
}
2022-08-23 09:26:34 +00:00
$cursor -> setValue ( $cursorDocument );
2021-09-27 10:12:42 +00:00
}
2022-08-23 09:26:34 +00:00
$filterQueries = Query :: groupByType ( $queries )[ 'filters' ];
$results = $dbForProject -> find ( 'executions' , $queries );
2022-08-11 23:53:52 +00:00
$total = $dbForProject -> count ( 'executions' , $filterQueries , APP_LIMIT_COUNT );
2020-07-12 21:18:52 +00:00
2022-08-14 08:54:11 +00:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2022-08-16 04:34:49 +00:00
if ( ! $isPrivilegedUser && ! $isAppUser ) {
2022-08-14 08:54:11 +00:00
$results = array_map ( function ( $execution ) {
$execution -> setAttribute ( 'stdout' , '' );
$execution -> setAttribute ( 'stderr' , '' );
2022-08-14 09:23:41 +00:00
return $execution ;
2022-08-14 08:54:11 +00:00
}, $results );
}
2020-07-12 21:18:52 +00:00
2020-10-30 19:53:27 +00:00
$response -> dynamic ( new Document ([
2021-05-27 10:09:14 +00:00
'executions' => $results ,
2022-02-27 09:57:09 +00:00
'total' => $total ,
2020-10-30 19:53:27 +00:00
]), Response :: MODEL_EXECUTION_LIST );
2020-12-26 15:20:08 +00:00
});
2020-07-12 21:18:52 +00:00
App :: get ( '/v1/functions/:functionId/executions/:executionId' )
-> groups ([ 'api' , 'functions' ])
2020-05-05 17:30:12 +00:00
-> desc ( 'Get Execution' )
2020-12-30 07:26:01 +00:00
-> label ( 'scope' , 'execution.read' )
2021-04-16 07:22:17 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_KEY , APP_AUTH_TYPE_JWT ])
2020-05-05 17:30:12 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'getExecution' )
-> label ( 'sdk.description' , '/docs/references/functions/get-execution.md' )
2020-11-11 21:02:24 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_EXECUTION )
2021-12-10 12:27:11 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function ID.' )
-> param ( 'executionId' , '' , new UID (), 'Execution ID.' )
2020-12-26 15:20:08 +00:00
-> inject ( 'response' )
2021-12-27 12:45:23 +00:00
-> inject ( 'dbForProject' )
2022-09-09 08:49:18 +00:00
-> inject ( 'mode' )
-> action ( function ( string $functionId , string $executionId , Response $response , Database $dbForProject , string $mode ) {
2021-12-17 15:25:05 +00:00
2022-04-13 12:39:31 +00:00
$function = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'functions' , $functionId ));
2020-05-05 17:30:12 +00:00
2022-09-09 08:49:18 +00:00
if ( $function -> isEmpty () || ! $function -> getAttribute ( 'enabled' )) {
if ( ! ( $mode === APP_MODE_ADMIN && Auth :: isPrivilegedUser ( Authorization :: getRoles ()))) {
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
}
2020-07-12 21:18:52 +00:00
}
2020-05-05 17:30:12 +00:00
2021-12-27 12:45:23 +00:00
$execution = $dbForProject -> getDocument ( 'executions' , $executionId );
2020-05-05 17:30:12 +00:00
2020-10-27 19:46:15 +00:00
if ( $execution -> getAttribute ( 'functionId' ) !== $function -> getId ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: EXECUTION_NOT_FOUND );
2020-07-12 21:18:52 +00:00
}
2020-05-05 17:30:12 +00:00
2021-06-20 13:59:36 +00:00
if ( $execution -> isEmpty ()) {
2022-07-26 14:24:32 +00:00
throw new Exception ( Exception :: EXECUTION_NOT_FOUND );
2020-05-05 17:30:12 +00:00
}
2020-07-12 21:18:52 +00:00
2022-08-14 08:44:17 +00:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2022-08-16 05:23:51 +00:00
if ( ! $isPrivilegedUser && ! $isAppUser ) {
2022-08-16 04:34:49 +00:00
$execution -> setAttribute ( 'stdout' , '' );
$execution -> setAttribute ( 'stderr' , '' );
2020-05-05 17:30:12 +00:00
}
2020-07-12 21:18:52 +00:00
2020-10-30 19:53:27 +00:00
$response -> dynamic ( $execution , Response :: MODEL_EXECUTION );
2020-12-26 15:20:08 +00:00
});
2021-12-06 14:12:41 +00:00
2022-08-01 15:13:47 +00:00
// Variables
2022-08-09 15:29:24 +00:00
App :: post ( '/v1/functions/:functionId/variables' )
2022-08-01 15:13:47 +00:00
-> desc ( 'Create Variable' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.write' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'variable.create' )
2022-09-04 08:13:44 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2022-08-03 13:32:50 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'createVariable' )
2022-08-09 12:11:50 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/create-variable.md' )
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_VARIABLE )
2022-09-19 10:05:42 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function unique ID.' , false )
2022-08-30 07:27:44 +00:00
-> param ( 'key' , null , new Text ( Database :: LENGTH_KEY ), 'Variable key. Max length: ' . Database :: LENGTH_KEY . ' chars.' , false )
2022-08-30 07:53:16 +00:00
-> param ( 'value' , null , new Text ( 8192 ), 'Variable value. Max length: 8192 chars.' , false )
2022-08-01 15:13:47 +00:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-08-02 10:05:58 +00:00
-> action ( function ( string $functionId , string $key , string $value , Response $response , Database $dbForProject ) {
2022-08-01 15:13:47 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
if ( $function -> isEmpty ()) {
2022-08-30 07:27:54 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
2022-08-26 13:38:39 +00:00
$variableId = ID :: unique ();
2022-08-01 15:13:47 +00:00
$variable = new Document ([
2022-08-26 13:38:39 +00:00
'$id' => $variableId ,
2022-08-24 15:07:18 +00:00
'$permissions' => [
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: any ()),
Permission :: delete ( Role :: any ()),
],
2022-08-01 15:13:47 +00:00
'functionInternalId' => $function -> getInternalId (),
'functionId' => $function -> getId (),
'key' => $key ,
2022-08-26 13:38:39 +00:00
'value' => $value ,
'search' => implode ( ' ' , [ $variableId , $function -> getId (), $key ]),
2022-08-01 15:13:47 +00:00
]);
try {
$variable = $dbForProject -> createDocument ( 'variables' , $variable );
} catch ( DuplicateException $th ) {
2022-08-30 07:28:01 +00:00
throw new Exception ( Exception :: VARIABLE_ALREADY_EXISTS );
2022-08-01 15:13:47 +00:00
}
$dbForProject -> deleteCachedDocument ( 'functions' , $function -> getId ());
2022-09-07 11:11:10 +00:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $variable , Response :: MODEL_VARIABLE );
2022-08-01 15:13:47 +00:00
});
2022-08-09 15:29:24 +00:00
App :: get ( '/v1/functions/:functionId/variables' )
2022-08-01 15:13:47 +00:00
-> desc ( 'List Variables' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.read' )
2022-08-03 13:32:50 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'listVariables' )
2022-08-09 12:11:50 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/list-variables.md' )
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_VARIABLE_LIST )
2022-09-19 10:05:42 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function unique ID.' , false )
2022-08-01 15:13:47 +00:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-09-12 09:02:14 +00:00
-> action ( function ( string $functionId , Response $response , Database $dbForProject ) {
2022-08-01 15:13:47 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
if ( $function -> isEmpty ()) {
2022-08-30 07:28:48 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$response -> dynamic ( new Document ([
2022-09-12 09:02:14 +00:00
'variables' => $function -> getAttribute ( 'vars' ),
'total' => \count ( $function -> getAttribute ( 'vars' )),
2022-08-01 15:13:47 +00:00
]), Response :: MODEL_VARIABLE_LIST );
});
2022-08-09 15:29:24 +00:00
App :: get ( '/v1/functions/:functionId/variables/:variableId' )
2022-08-01 15:13:47 +00:00
-> desc ( 'Get Variable' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.read' )
2022-08-03 13:32:50 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'getVariable' )
2022-08-09 12:11:50 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/get-variable.md' )
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_VARIABLE )
2022-09-19 10:05:42 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function unique ID.' , false )
-> param ( 'variableId' , '' , new UID (), 'Variable unique ID.' , false )
2022-08-01 15:13:47 +00:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-08-02 10:05:58 +00:00
-> action ( function ( string $functionId , string $variableId , Response $response , Database $dbForProject ) {
2022-08-01 15:13:47 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
if ( $function -> isEmpty ()) {
2022-08-30 07:28:37 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$variable = $dbForProject -> findOne ( 'variables' , [
2022-08-30 12:30:52 +00:00
Query :: equal ( '$id' , [ $variableId ]),
2022-08-24 14:10:56 +00:00
Query :: equal ( 'functionInternalId' , [ $function -> getInternalId ()]),
2022-08-01 15:13:47 +00:00
]);
if ( $variable === false || $variable -> isEmpty ()) {
2022-08-30 07:29:09 +00:00
throw new Exception ( Exception :: VARIABLE_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$response -> dynamic ( $variable , Response :: MODEL_VARIABLE );
});
2022-08-09 15:29:24 +00:00
App :: put ( '/v1/functions/:functionId/variables/:variableId' )
2022-08-01 15:13:47 +00:00
-> desc ( 'Update Variable' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.write' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'variable.update' )
2022-09-04 08:13:44 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2022-08-03 13:32:50 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'updateVariable' )
2022-08-09 12:11:50 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/update-variable.md' )
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_VARIABLE )
2022-09-19 10:05:42 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function unique ID.' , false )
-> param ( 'variableId' , '' , new UID (), 'Variable unique ID.' , false )
2022-08-31 07:33:43 +00:00
-> param ( 'key' , null , new Text ( 255 ), 'Variable key. Max length: 255 chars.' , false )
2022-08-30 07:53:16 +00:00
-> param ( 'value' , null , new Text ( 8192 ), 'Variable value. Max length: 8192 chars.' , true )
2022-08-01 15:13:47 +00:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-08-31 07:33:43 +00:00
-> action ( function ( string $functionId , string $variableId , string $key , ? string $value , Response $response , Database $dbForProject ) {
2022-08-01 15:13:47 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
if ( $function -> isEmpty ()) {
2022-08-30 07:29:20 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$variable = $dbForProject -> findOne ( 'variables' , [
2022-08-30 12:30:52 +00:00
Query :: equal ( '$id' , [ $variableId ]),
2022-08-24 14:10:56 +00:00
Query :: equal ( 'functionInternalId' , [ $function -> getInternalId ()]),
2022-08-01 15:13:47 +00:00
]);
if ( $variable === false || $variable -> isEmpty ()) {
2022-08-30 07:29:30 +00:00
throw new Exception ( Exception :: VARIABLE_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$variable
2022-08-31 07:33:43 +00:00
-> setAttribute ( 'key' , $key )
2022-08-01 15:13:47 +00:00
-> setAttribute ( 'value' , $value ? ? $variable -> getAttribute ( 'value' ))
2022-08-26 13:38:39 +00:00
-> setAttribute ( 'search' , implode ( ' ' , [ $variableId , $function -> getId (), $key ]))
2022-08-01 15:13:47 +00:00
;
try {
$dbForProject -> updateDocument ( 'variables' , $variable -> getId (), $variable );
} catch ( DuplicateException $th ) {
2022-08-30 07:28:09 +00:00
throw new Exception ( Exception :: VARIABLE_ALREADY_EXISTS );
2022-08-01 15:13:47 +00:00
}
$dbForProject -> deleteCachedDocument ( 'functions' , $function -> getId ());
$response -> dynamic ( $variable , Response :: MODEL_VARIABLE );
});
2022-08-09 15:29:24 +00:00
App :: delete ( '/v1/functions/:functionId/variables/:variableId' )
2022-08-01 15:13:47 +00:00
-> desc ( 'Delete Variable' )
-> groups ([ 'api' , 'functions' ])
-> label ( 'scope' , 'functions.write' )
2022-09-05 08:00:08 +00:00
-> label ( 'audits.event' , 'variable.delete' )
2022-09-04 08:13:44 +00:00
-> label ( 'audits.resource' , 'function/{request.functionId}' )
2022-08-03 13:32:50 +00:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_KEY ])
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.namespace' , 'functions' )
-> label ( 'sdk.method' , 'deleteVariable' )
2022-08-09 12:11:50 +00:00
-> label ( 'sdk.description' , '/docs/references/functions/delete-variable.md' )
2022-08-01 15:13:47 +00:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2022-09-19 10:05:42 +00:00
-> param ( 'functionId' , '' , new UID (), 'Function unique ID.' , false )
-> param ( 'variableId' , '' , new UID (), 'Variable unique ID.' , false )
2022-08-01 15:13:47 +00:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2022-08-02 10:05:58 +00:00
-> action ( function ( string $functionId , string $variableId , Response $response , Database $dbForProject ) {
2022-08-01 15:13:47 +00:00
$function = $dbForProject -> getDocument ( 'functions' , $functionId );
if ( $function -> isEmpty ()) {
2022-08-30 07:28:20 +00:00
throw new Exception ( Exception :: FUNCTION_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$variable = $dbForProject -> findOne ( 'variables' , [
2022-08-30 12:30:52 +00:00
Query :: equal ( '$id' , [ $variableId ]),
2022-08-24 14:10:56 +00:00
Query :: equal ( 'functionInternalId' , [ $function -> getInternalId ()]),
2022-08-01 15:13:47 +00:00
]);
if ( $variable === false || $variable -> isEmpty ()) {
2022-08-30 07:28:27 +00:00
throw new Exception ( Exception :: VARIABLE_NOT_FOUND );
2022-08-01 15:13:47 +00:00
}
$dbForProject -> deleteDocument ( 'variables' , $variable -> getId ());
$dbForProject -> deleteCachedDocument ( 'functions' , $function -> getId ());
$response -> noContent ();
});