"use strict";
/**
 * 装饰器模块
 * @date 2022-03
 * @author 何华东
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sync = exports.Retryable = exports.CronJob = void 0;
var typescript_ioc_1 = require("typescript-ioc");
var mslib_1 = require("mslib");
var PromiseUtils_1 = require("./PromiseUtils");
var schedule = require("node-schedule");
var Contants_1 = require("./Contants");
/**
 * Cron任务装饰器
 *
 * 自动添加任务到node-schedule任务计划中
 * @type { IService } 被装饰的类需实现该接口
 * @param cronExpression cron表达式
 * @param description 任务描述
 * @returns
 */
function CronJob(cronExpression, description) {
    return function (target) {
        var _this = this;
        mslib_1.logger.info(Contants_1.default.SS_SERVICE_BASE_URL + "/" + process.env["KT_PID"] + "." + target.name + "/1.0", description);
        //本地调试环境不加入
        if (Contants_1.default.IS_LOCAL_DEBUG)
            return;
        schedule.scheduleJob(cronExpression, function () { return __awaiter(_this, void 0, void 0, function () {
            var error_1;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, ((_a = typescript_ioc_1.Container.get(target)) === null || _a === void 0 ? void 0 : _a.doService())];
                    case 1:
                        _b.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _b.sent();
                        mslib_1.logger.error("" + target.name, error_1);
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); });
    };
}
exports.CronJob = CronJob;
/**
 * 重试函数
 *
 * 立刻执行传入的目标方法，如果目标方法执行出现异常将自动异步重试
 * @param func 目标方法
 * @param retryCount 重试次数
 * @param errorHandler 异常处理
 * @param delayMs 每次重试延迟毫秒数
 * @returns 目标方法至少执行成功一次才会正确返回，否则返回空
 */
function retry(func, retryCount, errorHandler, delayMs) {
    var _this = this;
    return new Promise(function (resolve, reject) {
        func()
            .then(function (res) { resolve(res); })
            .catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                errorHandler(error);
                setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
                    var i, res, error_2;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                i = retryCount;
                                _a.label = 1;
                            case 1:
                                if (!(i > 0)) return [3 /*break*/, 7];
                                if (!delayMs) return [3 /*break*/, 3];
                                return [4 /*yield*/, PromiseUtils_1.delay(delayMs)];
                            case 2:
                                _a.sent();
                                _a.label = 3;
                            case 3:
                                _a.trys.push([3, 5, , 6]);
                                return [4 /*yield*/, func()];
                            case 4:
                                res = _a.sent();
                                resolve(res);
                                return [3 /*break*/, 7];
                            case 5:
                                error_2 = _a.sent();
                                errorHandler(error_2, retryCount - i + 1);
                                return [3 /*break*/, 6];
                            case 6:
                                i--;
                                return [3 /*break*/, 1];
                            case 7:
                                reject();
                                return [2 /*return*/];
                        }
                    });
                }); });
                return [2 /*return*/];
            });
        }); });
    });
}
/**
 * 重试装饰器
 *
 * 如果被装饰的方法执行出现异常，将自动异步重试
 * @param retryCount 重试次数，默认一次
 * @param ms 每次重试延迟毫秒数，默认1分钟
 * @returns 被装饰的方法至少执行成功一次才会正确返回，否则返回空
 */
function Retryable(retryCount, ms) {
    retryCount = retryCount || 1;
    ms = ms || 1000 * 60;
    return function (target, key, descriptor) {
        var method = descriptor.value;
        descriptor.value = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                var result, _a;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, retry(function () { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0: return [4 /*yield*/, method.apply(this, args)];
                                            case 1: return [2 /*return*/, _a.sent()];
                                        }
                                    });
                                }); }, retryCount, function (error, retryIndex) {
                                    mslib_1.logger.error(target.constructor.name + "/" + key + "\uFF0C\u5DF2\u91CD\u8BD5" + (retryIndex || 0) + "\u6B21\uFF0Cargs:" + JSON.stringify(args) + " ", error);
                                }, ms)];
                        case 1:
                            result = _b.sent();
                            return [2 /*return*/, result];
                        case 2:
                            _a = _b.sent();
                            mslib_1.logger.error(target.constructor.name + "/" + key + "\u91CD\u8BD5\u5931\u8D25,args:" + JSON.stringify(args));
                            return [2 /*return*/];
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
    };
}
exports.Retryable = Retryable;
/**
 * 同步锁
 */
var AsyncLock = /** @class */ (function () {
    function AsyncLock() {
        this.promise = Promise.resolve();
    }
    /**
     * 启用锁
     */
    AsyncLock.prototype.enable = function () {
        var _this = this;
        this.promise = new Promise(function (resolve) { return _this.disable = resolve; });
    };
    return AsyncLock;
}());
/**
 * 同步装饰器
 *
 * 被装饰的方法将同步执行
 */
function Sync() {
    return function (target, key, descriptor) {
        var method = descriptor.value;
        var lock = new AsyncLock();
        descriptor.value = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, lock.promise];
                        case 1:
                            _a.sent();
                            lock.enable();
                            try {
                                return [2 /*return*/, method.apply(this, args)];
                            }
                            catch (error) {
                                throw error;
                            }
                            finally {
                                lock.disable();
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
    };
}
exports.Sync = Sync;
//# sourceMappingURL=Decorators.js.map