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CAE/B,MADY,IAAI,mBAAmB,gBAAgB,KAAK,0CAE5D,CAIA,OAFA,EAAY,OAAO,KAAK,WAClB,EAAY,UACX,CACX,CACA,MAAO,GACH,GAAI,aAAa,mBACb,MAAM,EAEV,MAAM,EAAM,EAIZ,OAHA,EAAI,QAAU,8BAA8B,KAAK,WAAW,EAAI,UAChE,YAAY,OAAO,MAAM,SACnB,EAAY,YACX,CACX,CACJ,CAIA,UAAM,GACF,MAAM,SAAgB,KAAK,UAAU,IAAI,KAAK,MAAM,GACpD,SAAI,aAAuC,EAAS,EAAO,UAC/C,UAAU,EAG1B,EAMJ,SAAS,yBAAyB,GAC9B,OAAO,IAAI,cAAc,EAAQ,OAAQ,EAAQ,OAAQ,EAAQ,WAAY,EAAQ,mBACzF,CASA,eAAe,kBAAkB,EAAS,GACtC,MAAM,EAAO,yBAAyB,GAEtC,UADuB,EAAK,UAGxB,MAAM,IAAI,MAAM,6BAA6B,EAAQ,4BAA4B,EAAQ,WAE7F,IACI,aAAa,GACjB,CACA,QACI,EAAK,SACT,CACJ,CA5BA,QAAQ,cAAgB,cAOxB,QAAQ,yBAA2B,yBAsBnC,QAAQ,kBAAoB","file":"/npm/@google-automations/datastore-lock@7.1.2/build/src/datastore-lock.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@google-automations/datastore-lock@7.1.2/build/src/datastore-lock.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.withDatastoreLock = exports.datastoreLockFromDetails = exports.DatastoreLock = exports.DatastoreLockError = void 0;\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst uuid_1 = require(\"uuid\");\nconst datastore_1 = require(\"@google-cloud/datastore\");\nconst gcf_utils_1 = require(\"gcf-utils\");\nconst DEFAULT_LOCK_EXPIRY = 20 * 1000; // 20 seconds\nconst MAX_LOCK_EXPIRY = 60 * 1000; // 60 seconds\nconst DEFAULT_LOCK_ACQUIRE_TIMEOUT = 120 * 1000; // 120 seconds\nconst BACKOFF_INITIAL_DELAY = 2 * 1000; // 1 seconds\nconst BACKOFF_MAX_DELAY = 10 * 1000; // 10 seconds\nlet cachedClient;\nvar AcquireResult;\n(function (AcquireResult) {\n    AcquireResult[AcquireResult[\"Success\"] = 1] = \"Success\";\n    AcquireResult[AcquireResult[\"Failure\"] = 2] = \"Failure\";\n    AcquireResult[AcquireResult[\"LockActive\"] = 3] = \"LockActive\";\n})(AcquireResult || (AcquireResult = {}));\nconst sleep = (ms) => {\n    return new Promise(r => setTimeout(r, ms));\n};\nfunction isExpired(entity) {\n    return Date.now() > entity.expiry;\n}\nconst DATASTORE_LOCK_ERROR_NAME = 'DatastoreLockError';\nclass DatastoreLockError extends Error {\n    constructor(msg) {\n        super(msg);\n        this.name = DATASTORE_LOCK_ERROR_NAME;\n    }\n}\nexports.DatastoreLockError = DatastoreLockError;\n/**\n * A simple lock backed by Cloud Datastore\n */\nclass DatastoreLock {\n    constructor(lockId, target, lockExpiry = DEFAULT_LOCK_EXPIRY, lockAcquireTimeout = DEFAULT_LOCK_ACQUIRE_TIMEOUT) {\n        if (lockExpiry > MAX_LOCK_EXPIRY) {\n            throw new Error(`lockExpiry is too long, max is ${MAX_LOCK_EXPIRY}, ` +\n                `given ${lockExpiry}`);\n        }\n        // It reduces memory overhead on Cloud Function if we\n        // only instantiate GRPC client once:\n        if (!cachedClient) {\n            cachedClient = new datastore_1.Datastore();\n        }\n        this.datastore = cachedClient;\n        this.kind = `ds-lock-${lockId}`;\n        this.target = target;\n        const hash = crypto_1.default.createHash('sha1');\n        hash.update(this.target);\n        this.key = this.datastore.key([this.kind, hash.digest('hex')]);\n        this.uniqueId = (0, uuid_1.v4)();\n        this.lockExpiry = lockExpiry;\n        this.lockAcquireTimeout = lockAcquireTimeout;\n    }\n    /**\n     * Acquire the lock.\n     */\n    async acquire() {\n        const startTime = Date.now();\n        // Avoid multiple clients waiting for the same period of time.\n        let waitTime = BACKOFF_INITIAL_DELAY + Math.floor(Math.random() * 1000);\n        const maxDelay = BACKOFF_MAX_DELAY + Math.floor(Math.random() * 1000);\n        while (Date.now() - startTime < this.lockAcquireTimeout) {\n            const result = await this._acquire();\n            if (result === AcquireResult.Success) {\n                return true;\n            }\n            if (result === AcquireResult.Failure) {\n                gcf_utils_1.logger.debug(`Failed to acquire the lock, retrying after ${waitTime} miliseconds`);\n            }\n            if (result === AcquireResult.LockActive) {\n                // The lock is active, wait and retry.\n                gcf_utils_1.logger.debug(`The lock is active, retrying after ${waitTime} miliseconds`);\n            }\n            await sleep(waitTime);\n            waitTime = Math.min(maxDelay, waitTime + Math.floor(Math.random() * 2000));\n        }\n        // Timeout\n        return false;\n    }\n    async _acquire() {\n        const transaction = this.datastore.transaction();\n        try {\n            await transaction.run();\n            // First get the entity\n            const entity = (await transaction.get(this.key))[0];\n            gcf_utils_1.logger.debug(entity);\n            if (entity === undefined || isExpired(entity)) {\n                const entity = {\n                    key: this.key,\n                    data: {\n                        expiry: Date.now() + this.lockExpiry,\n                        uuid: this.uniqueId,\n                    },\n                };\n                transaction.save(entity);\n                gcf_utils_1.logger.debug(entity);\n                await transaction.commit();\n                return AcquireResult.Success;\n            }\n            else {\n                // The lock is active.\n                await transaction.rollback();\n                return AcquireResult.LockActive;\n            }\n        }\n        catch (e) {\n            const err = e;\n            err.message = `Error acquiring a lock for ${this.target}: ${err.message}`;\n            gcf_utils_1.logger.error(err);\n            await transaction.rollback();\n            return AcquireResult.Failure;\n        }\n    }\n    /**\n     * Release the lock.\n     *\n     * @throws {DATASTORE_LOCK_ERROR_NAME}\n     */\n    async release() {\n        const transaction = this.datastore.transaction();\n        try {\n            await transaction.run();\n            const [entity] = await transaction.get(this.key);\n            if (entity === undefined) {\n                await transaction.rollback();\n                return true;\n            }\n            if (entity.uuid !== this.uniqueId) {\n                const err = new DatastoreLockError(`The lock for ${this.target} was acquired by another process.`);\n                throw err;\n            }\n            // The lock is created by myself.\n            transaction.delete(this.key);\n            await transaction.commit();\n            return true;\n        }\n        catch (e) {\n            if (e instanceof DatastoreLockError) {\n                throw e;\n            }\n            const err = e;\n            err.message = `Error releasing a lock for ${this.target}: ${err.message}`;\n            gcf_utils_1.logger.error(err);\n            await transaction.rollback();\n            return false;\n        }\n    }\n    /**\n     * Check whether or not a lock currently exists for a key.\n     */\n    async peek() {\n        const entity = (await this.datastore.get(this.key))[0];\n        if (entity === null || entity === void 0 ? void 0 : entity.expiry)\n            return !isExpired(entity);\n        else\n            return false;\n    }\n}\nexports.DatastoreLock = DatastoreLock;\n/**\n * Construct a new DatastoreLock.\n */\nfunction datastoreLockFromDetails(details) {\n    return new DatastoreLock(details.lockId, details.target, details.lockExpiry, details.lockAcquireTimeout);\n}\nexports.datastoreLockFromDetails = datastoreLockFromDetails;\n/**\n * Execute a function while holding a lock.\n *\n * @param details The Datastore lock's details.\n * @param f The function to execute while holding the lock.\n * @returns the value returned by f().\n */\nasync function withDatastoreLock(details, f) {\n    const lock = datastoreLockFromDetails(details);\n    const acquired = await lock.acquire();\n    if (!acquired) {\n        // throw an error and expect gcf-utils infrastructure to retry\n        throw new Error(`Failed to acquire lock in ${details.lockAcquireTimeout}ms for ${details.target}.`);\n    }\n    try {\n        return await f();\n    }\n    finally {\n        lock.release();\n    }\n}\nexports.withDatastoreLock = withDatastoreLock;\n"]}