"use strict";
(() => {
var exports = {};
exports.id = 398;
exports.ids = [398];
exports.modules = {

/***/ 2748:
/***/ ((module) => {

module.exports = require("luxon");

/***/ }),

/***/ 1185:
/***/ ((module) => {

module.exports = require("mongoose");

/***/ }),

/***/ 9456:
/***/ ((module) => {

module.exports = require("phin");

/***/ }),

/***/ 7773:
/***/ ((module) => {

module.exports = require("winston");

/***/ }),

/***/ 7564:
/***/ ((module) => {

module.exports = import("chalk");;

/***/ }),

/***/ 8518:
/***/ ((module) => {

module.exports = import("serialize-error");;

/***/ }),

/***/ 6555:
/***/ ((module) => {

module.exports = import("uuid");;

/***/ }),

/***/ 837:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var worker_loop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5290);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([worker_loop__WEBPACK_IMPORTED_MODULE_0__]);
worker_loop__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];

/** Stats a worker cron that polls and manages events in development */ async function handler(req, res) {
    (0,worker_loop__WEBPACK_IMPORTED_MODULE_0__/* .watch */ .Y)();
    return res.status(200).json({
        watch: true
    });
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 5290:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Y": () => (/* binding */ watch)
/* harmony export */ });
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2748);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(luxon__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var winston_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(674);
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9456);
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(phin__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var mongo_db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9306);
/* harmony import */ var _scheduler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7979);
/* harmony import */ var serialize_error__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8518);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([winston_logger__WEBPACK_IMPORTED_MODULE_1__, mongo_db__WEBPACK_IMPORTED_MODULE_3__, serialize_error__WEBPACK_IMPORTED_MODULE_5__]);
([winston_logger__WEBPACK_IMPORTED_MODULE_1__, mongo_db__WEBPACK_IMPORTED_MODULE_3__, serialize_error__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);






const watch = ()=>{
    const crond = global.cron();
    crond.register("worker", "* * * * * *", async ()=>{
        try {
            let jobs = [];
            while(jobs.length < MAX_JOB_CHUNK){
                const next = await mongo_db__WEBPACK_IMPORTED_MODULE_3__/* .Job.findOneAndUpdate */ .oI.findOneAndUpdate({
                    "schedule.next": {
                        $lt: new Date()
                    }
                }, {
                    $set: {
                        schedule: null
                    }
                }, {
                    new: true
                }).exec();
                if (!next) {
                    break;
                }
                jobs.push(next);
            }
            if (jobs.length === 0) {
                // nothing to do
                return;
            }
            log.debug(`Found ${jobs.length} item(s)`);
            await Promise.allSettled(jobs.filter(isMongoJob).map((job)=>handle(job)
            ));
        } catch (e) {
            log.error(e);
        }
    });
};
const MAX_JOB_CHUNK = 10;
/** Simple typeguard to discard null results */ function isMongoJob(v) {
    return v !== null;
}
const log = winston_logger__WEBPACK_IMPORTED_MODULE_1__/* .logger.child */ .k.child({
    label: "worker/loop.ts"
});
/** Handle a single instance of a job */ const handle = async (job)=>{
    log.info("Handling Jobs");
    if (job.enabled === false) {
        // disabled
        return;
    }
    const now = luxon__WEBPACK_IMPORTED_MODULE_0__.DateTime.now();
    const l = log.child({
        job: job.name
    });
    l.info("Handler invoked");
    let retry = false;
    const entry = new mongo_db__WEBPACK_IMPORTED_MODULE_3__/* .Log */ .Zb({
        isNew: true,
        job: job._id,
        jobId: job.v5id
    });
    const jjson = job.toJSON();
    const headers = {
        ...jjson.headers ?? {},
        "user-agent": "Taskless DevServer Worker",
        "content-type": "application/json"
    };
    const request = {
        url: job.endpoint,
        method: "POST",
        headers,
        // attach data if set
        ...job.body ? {
            data: job.body
        } : {},
        followRedirects: true,
        timeout: 15000
    };
    l.debug(`Phin Request: \n${JSON.stringify(request)}`);
    try {
        l.info("Making Request");
        const resp = await phin__WEBPACK_IMPORTED_MODULE_2___default()({
            ...request,
            parse: "json"
        });
        entry.status = `${resp.statusCode}`.indexOf("2") === 0 ? "COMPLETED" : "FAILED";
        entry.statusCode = resp.statusCode ?? 200;
        entry.output = JSON.stringify(resp.body);
        if (`${resp.statusCode}`.indexOf("2") !== 0) {
            l.warn(`Non-2xx received from url: ${job.endpoint}`);
            retry = (job.schedule.attempt ?? 0) < (job.retries ?? 0) - 1;
        }
    } catch (e) {
        var ref;
        const ser = (0,serialize_error__WEBPACK_IMPORTED_MODULE_5__.serializeError)(e);
        const msg = typeof e === "string" ? e : e instanceof Error ? e.message : `${e}`;
        l.error(`Error received: ${msg}`);
        retry = (((ref = job.schedule) === null || ref === void 0 ? void 0 : ref.attempt) ?? 0) < (job.retries ?? 0) - 1;
        entry.status = "FAILED";
        entry.statusCode = 500;
        entry.output = JSON.stringify({
            "@taskless/dev": true,
            error: ser
        });
    }
    log.info("Recording results");
    if (!job.logs) {
        job.logs = [];
    }
    job.logs.push(entry);
    await entry.save();
    // next scheduling
    if (retry) {
        l.info("Linear rescheduling of job");
        job.schedule = new mongo_db__WEBPACK_IMPORTED_MODULE_3__/* .Schedule */ .Pf({
            next: now.plus({
                seconds: 3
            }).toJSDate(),
            attempt: (job.schedule.attempt ?? 0) + 1
        });
    }
    if (!retry && job.runEvery) {
        l.info("Scheduling next occurence");
        const runAt = luxon__WEBPACK_IMPORTED_MODULE_0__.DateTime.fromISO(job.runAt);
        const interval = luxon__WEBPACK_IMPORTED_MODULE_0__.Duration.fromISO(job.runEvery);
        const nextRun = (0,_scheduler__WEBPACK_IMPORTED_MODULE_4__/* .findNextTime */ .h)(runAt, interval, now);
        job.schedule = new mongo_db__WEBPACK_IMPORTED_MODULE_3__/* .Schedule */ .Pf({
            next: nextRun.toJSDate(),
            attempt: 0
        });
    }
    await job.save();
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 7979:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "h": () => (/* binding */ findNextTime)
/* harmony export */ });
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2748);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(luxon__WEBPACK_IMPORTED_MODULE_0__);

const findNextTime = (start, interval, until)=>{
    const sm = start.toMillis();
    const um = until.toMillis();
    const im = interval.toMillis();
    const passed = Math.floor((um - sm) / im);
    const closestStart = luxon__WEBPACK_IMPORTED_MODULE_0__.DateTime.fromMillis(sm + im * passed);
    return closestStart.plus(interval);
};


/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [306,674], () => (__webpack_exec__(837)));
module.exports = __webpack_exports__;

})();