import * as Redis from "ioredis" ; import * as urllib from "url" ; import { CeleryBackend } from "." ; private constant type { string } const keyPrefix = "celery-task-meta-" ; private param { string } urlString function redisOptsFromUrl ( urlString ) { const redisOpts = { } as Redis . RedisOptions ; try { const redisUrl = urllib . parse ( urlString ) ; redisOpts . port = + redisUrl . port || 6379 ; redisOpts . host = redisUrl . hostname ; redisOpts . db = redisUrl . pathname ? + redisUrl . pathname . split ( "/" ) [ 1 ] : 0 ; if ( redisUrl . auth ) { [ , redisOpts . password ] = redisUrl . auth . split ( ":" ) ; } } catch ( e ) { throw new Error ( e . message ) ; } return redisOpts ; } exports export default class RedisBackend implements CeleryBackend { redis : Redis . Redis ; constructor param { string } url param { object } opts constructor ( url , opts ) { this . redis = new Redis ( { ... redisOptsFromUrl ( url ) , ... opts } ) ; } method returns { Promise } public isReady ( ) { return new Promise ( ( resolve , reject ) => { if ( this . redis . status === "ready" ) { resolve ( ) ; } else { let handleError ; const handleReady = ( ) => { this . redis . removeListener ( "error" , handleError ) ; resolve ( ) ; } ; handleError = err => { this . redis . removeListener ( "ready" , handleReady ) ; reject ( err ) ; } ; this . redis . once ( "ready" , handleReady ) ; this . redis . once ( "error" , handleError ) ; } } ) ; } method returns { Promise } public disconnect ( ) { return this . redis . quit ( ) ; } method param { string } taskId param { * } result param { string } state public storeResult ( taskId , result , state ) { return this . set ( `${ keyPrefix }${ taskId }` , JSON . stringify ( { status : state , result : state == 'FAILURE' ? null : result , traceback : result , children : [ ] , task_id : taskId , date_done : new Date ( ) . toISOString ( ) } ) ) ; } method param { string } taskId returns { Promise } public getTaskMeta ( taskId ) { return this . get ( `${ keyPrefix }${ taskId }` ) . then ( msg => JSON . parse ( msg ) ) ; } method private param { String } key param { String } value returns { Promise } private set ( key , value ) { return Promise . all ( [ this . redis . setex ( key , 86400 , value ) , this . redis . publish ( key , value ) ] ) ; } method private param { string } key return { Promise } private get ( key ) { return this . redis . get ( key ) ; } }