"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RefreshPublicTripCacheTask = void 0;
const VPContainerToken_1 = require("../../../ioc/VPContainerToken");
const const_1 = require("../../../../../schema-definitions/vehicle-positions/redis/const");
const IoRedisConnector_1 = require("@golemio/core/dist/helpers/data-access/redis/IoRedisConnector");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const integration_engine_1 = require("@golemio/core/dist/integration-engine");
const pubsub_1 = require("@golemio/core/dist/integration-engine/data-access/pubsub");
const ioc_1 = require("@golemio/core/dist/integration-engine/ioc");
const workers_1 = require("@golemio/core/dist/integration-engine/workers");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const redis_semaphore_1 = require("@golemio/core/dist/shared/redis-semaphore");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const promises_1 = require("node:timers/promises");
const constants_1 = require("../constants");
const TripsRepository_1 = require("../data-access/TripsRepository");
const PublicApiCacheRepository_1 = require("../data-access/cache/PublicApiCacheRepository");
const PublicApiTripTransformation_1 = require("../transformations/PublicApiTripTransformation");
const PublicCacheTripsFilter_1 = require("../helpers/public-api/PublicCacheTripsFilter");
let RefreshPublicTripCacheTask = class RefreshPublicTripCacheTask extends workers_1.AbstractEmptyTask {
    constructor(config, logger, redisClient, publicApiCacheRepository, publicApiTripTransformation) {
        super(constants_1.WORKER_NAME);
        this.logger = logger;
        this.redisClient = redisClient;
        this.publicApiCacheRepository = publicApiCacheRepository;
        this.publicApiTripTransformation = publicApiTripTransformation;
        this.queueName = "refreshPublicTripCache";
        this.queueTtl = 10000; // 10s
        this.lockTimeout = config.getValue("old.datasources.pid.vehicle-positions.publicCache.mutexLockTimeout", 3000); // default 3s
        this.refreshInterval = this.lockTimeout * constants_1.LOCK_REFRESH_INTERVAL_RATIO;
        this.tripRepository = new TripsRepository_1.TripsRepository();
        this.redisChannel = new pubsub_1.RedisPubSubChannel(const_1.PUBLIC_CACHE_NAMESPACE_PREFIX);
    }
    async execute() {
        const startDateTime = new Date();
        const mutex = this.createMutex();
        const lockAcquired = await mutex.tryAcquire();
        if (!lockAcquired) {
            this.logger.info(`${this.constructor.name}: mutex lock was not acquired`);
            return;
        }
        try {
            const trips = await this.tripRepository.findAllForPublicCache(startDateTime);
            if (trips.length === 0) {
                return;
            }
            let ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
            this.logger.info(`${this.constructor.name}: fetched ${trips.length} trips in ${ellapsedTimeInMs}ms`);
            const { filteredTrips, futureTrips, canceledTrips } = PublicCacheTripsFilter_1.PublicCacheTripsFilter.getDistinctLatestTrips(trips);
            const transformedTrips = this.publicApiTripTransformation.transformArray(filteredTrips);
            const transformedFutureTrips = this.publicApiTripTransformation.transformArray(futureTrips);
            const transformedCanceledTrips = this.publicApiTripTransformation.transformArray(canceledTrips);
            ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
            this.logger.info(`${this.constructor.name}: transformed all trips in ${ellapsedTimeInMs}ms`);
            // this operation can block redis connection, which may cause the mutex lock to expire
            const newSetKey = await this.publicApiCacheRepository.geoadd(transformedTrips, transformedFutureTrips, transformedCanceledTrips);
            ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
            this.logger.info(`${this.constructor.name}: saved all trips to cache in ${ellapsedTimeInMs}ms`);
            // this operation can block redis connection, which may cause the mutex lock to expire
            await this.redisChannel.publishMessage(newSetKey);
        }
        catch (err) {
            if (err instanceof golemio_errors_1.AbstractGolemioError) {
                throw err;
            }
            throw new golemio_errors_1.GeneralError(`${this.constructor.name}: error while refreshing public trip cache`, this.constructor.name, err);
        }
        finally {
            await mutex.release();
        }
        const ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
        this.logger.info(`${this.constructor.name}: finished in ${ellapsedTimeInMs}ms`);
        if (ellapsedTimeInMs < this.refreshInterval) {
            await (0, promises_1.setTimeout)(this.refreshInterval - ellapsedTimeInMs);
        }
        integration_engine_1.QueueManager.sendMessageToExchange(this.queuePrefix, this.queueName, {});
    }
    createMutex() {
        return new redis_semaphore_1.Mutex(this.redisClient.getConnection(), this.queueName, {
            acquireAttemptsLimit: 1,
            lockTimeout: this.lockTimeout,
            refreshInterval: this.refreshInterval,
            onLockLost: (err) => {
                this.logger.error(err, `${this.constructor.name}: mutex lock was lost`);
            },
        });
    }
};
exports.RefreshPublicTripCacheTask = RefreshPublicTripCacheTask;
exports.RefreshPublicTripCacheTask = RefreshPublicTripCacheTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.SimpleConfig)),
    __param(1, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __param(2, (0, tsyringe_1.inject)(ioc_1.ContainerToken.RedisConnector)),
    __param(3, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.PublicApiCacheRepository)),
    __param(4, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.PublicApiTripTransformation)),
    __metadata("design:paramtypes", [Object, Object, IoRedisConnector_1.IoRedisConnector,
        PublicApiCacheRepository_1.PublicApiCacheRepository,
        PublicApiTripTransformation_1.PublicApiTripTransformation])
], RefreshPublicTripCacheTask);
//# sourceMappingURL=RefreshPublicTripCacheTask.js.map