@@ -21,6 +21,7 @@ import { WizardTaskService } from 'omniboxd/tasks/wizard-task.service';
2121import { Image , ProcessedImage } from 'omniboxd/wizard/types/wizard.types' ;
2222import { InternalTaskDto } from 'omniboxd/tasks/dto/task.dto' ;
2323import { isEmpty } from 'omniboxd/utils/is-empty' ;
24+ import { FetchTaskRequest } from 'omniboxd/wizard/dto/fetch-task-request.dto' ;
2425
2526@Injectable ( )
2627export class WizardService {
@@ -241,30 +242,45 @@ export class WizardService {
241242 task . output . images = processedImages ;
242243 }
243244
244- async fetchTask ( ) : Promise < InternalTaskDto | null > {
245+ async fetchTask ( query : FetchTaskRequest ) : Promise < InternalTaskDto | null > {
246+ const andConditions : string [ ] = [ ] ;
247+ if ( query . namespace_id ) {
248+ andConditions . push ( `tasks.namespace_id = '${ query . namespace_id } '` ) ;
249+ }
250+ if ( query . function ) {
251+ andConditions . push ( `tasks.function = '${ query . function } '` ) ;
252+ }
253+ const andCondition : string = andConditions . map ( ( x ) => `AND ${ x } ` ) . join ( ' ' ) ;
245254 const rawQuery = `
246- WITH running_tasks_sub_query AS (SELECT namespace_id,
247- COUNT(id) AS running_count
248- FROM tasks
249- WHERE started_at IS NOT NULL
250- AND ended_at IS NULL
251- AND canceled_at IS NULL
252- AND deleted_at IS NULL
253- GROUP BY namespace_id),
254- id_subquery AS (SELECT tasks.id
255- FROM tasks
256- LEFT OUTER JOIN running_tasks_sub_query
257- ON tasks.namespace_id = running_tasks_sub_query.namespace_id
258- LEFT OUTER JOIN namespaces
259- ON tasks.namespace_id = namespaces.id
260- WHERE tasks.started_at IS NULL
261- AND tasks.canceled_at IS NULL
262- AND tasks.deleted_at IS NULL
263- AND COALESCE(running_tasks_sub_query.running_count, 0) <
264- COALESCE(namespaces.max_running_tasks, 0)
265- ORDER BY priority DESC,
266- tasks.created_at
267- LIMIT 1)
255+ WITH
256+ running_tasks_sub_query AS (
257+ SELECT
258+ namespace_id,
259+ COUNT(id) AS running_count
260+ FROM tasks
261+ WHERE started_at IS NOT NULL
262+ AND ended_at IS NULL
263+ AND canceled_at IS NULL
264+ AND deleted_at IS NULL
265+ GROUP BY namespace_id
266+ ),
267+ id_subquery AS (
268+ SELECT tasks.id
269+ FROM tasks
270+ LEFT OUTER JOIN running_tasks_sub_query
271+ ON tasks.namespace_id = running_tasks_sub_query.namespace_id
272+ LEFT OUTER JOIN namespaces
273+ ON tasks.namespace_id = namespaces.id
274+ WHERE tasks.started_at IS NULL
275+ AND tasks.canceled_at IS NULL
276+ AND tasks.deleted_at IS NULL
277+ AND COALESCE(running_tasks_sub_query.running_count, 0) < COALESCE(namespaces.max_running_tasks, 0)
278+ ${ andCondition }
279+ ORDER BY
280+ priority DESC,
281+ tasks.created_at
282+ LIMIT 1
283+ )
268284 SELECT *
269285 FROM tasks
270286 WHERE id IN (SELECT id FROM id_subquery)
0 commit comments