import Env from '@ioc:Adonis/Core/Env' ; import Redis from '@ioc:Adonis/Addons/Redis' ; import { schema , rules , validator , ValidationException } from '@ioc:Adonis/Core/Validator' ; import DomainSetupResponse from '../models/transient/DomainSetupResponse' ; export default class SetupService { private static CACHE_QUEUE_KEY = 'domain-queue' ; private static CACHE_RESULT_PREFIX = 'domain-result-' ; public static async queueDomainSetup ( domain ) { let errors = [ ] ; let domainsInQueue = 0 ; try { if ( domain === undefined ) { throw new Error ( 'Domain is undefined' ) ; } domain = domain . replace ( /(^\w+:|^)\/\// , '' ) ; domain = domain . split ( '/' ) . shift ( ) ; await validator . validate ( { schema : schema . create ( { domain : schema . string ( { } , [ rules . url ( ) ] ) , } ) , data : { domain : domain , } , } ) ; await Redis . sadd ( this . CACHE_QUEUE_KEY , domain ) ; domainsInQueue = await this . getDomainQueueCount ( ) ; } catch ( e ) { if ( e instanceof ValidationException ) { errors = e . messages . domain ; } else { errors = [ `Unknown exception: ${ e }` ] ; } } return new DomainSetupResponse ( domain , domainsInQueue , errors ) ; } public static async getDomainQueueCount ( ) { return await Redis . scard ( this . CACHE_QUEUE_KEY ) ; } public static async getDomainFromQueue ( ) { return await Redis . spop ( this . CACHE_QUEUE_KEY ) ; } public static async processDomainSetup ( domain ) { const { execSync } = require ( 'child_process' ) ; execSync ( `certbot --nginx -d ${ domain } -n` , ( error , stdout , stderr ) => { if ( error ) { Redis . setex ( `${ this . CACHE_RESULT_PREFIX }${ domain }` , Env . get ( 'RESULT_CACHE_SECONDS' ) , error ) ; return ; } if ( stderr ) { Redis . setex ( `${ this . CACHE_RESULT_PREFIX }${ domain }` , Env . get ( 'RESULT_CACHE_SECONDS' ) , stderr ) ; return ; } Redis . setex ( `${ this . CACHE_RESULT_PREFIX }${ domain }` , Env . get ( 'RESULT_CACHE_SECONDS' ) , stdout ) ; } ) ; } }