|
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var crypto = require("crypto");
- var fs = require("fs");
- var os = require("os");
- var path = require("path");
- var OperationCanceledException_1 = require("./OperationCanceledException");
- var CancellationToken = /** @class */ (function () {
- function CancellationToken(cancellationFileName, isCancelled) {
- this.isCancelled = !!isCancelled;
- this.cancellationFileName =
- cancellationFileName || crypto.randomBytes(64).toString('hex');
- this.lastCancellationCheckTime = 0;
- }
- CancellationToken.createFromJSON = function (json) {
- return new CancellationToken(json.cancellationFileName, json.isCancelled);
- };
- CancellationToken.prototype.toJSON = function () {
- return {
- cancellationFileName: this.cancellationFileName,
- isCancelled: this.isCancelled
- };
- };
- CancellationToken.prototype.getCancellationFilePath = function () {
- return path.join(os.tmpdir(), this.cancellationFileName);
- };
- CancellationToken.prototype.isCancellationRequested = function () {
- if (this.isCancelled) {
- return true;
- }
- var time = Date.now();
- var duration = Math.abs(time - this.lastCancellationCheckTime);
- if (duration > 10) {
- // check no more than once every 10ms
- this.lastCancellationCheckTime = time;
- this.isCancelled = fs.existsSync(this.getCancellationFilePath());
- }
- return this.isCancelled;
- };
- CancellationToken.prototype.throwIfCancellationRequested = function () {
- if (this.isCancellationRequested()) {
- throw new OperationCanceledException_1.OperationCanceledException();
- }
- };
- CancellationToken.prototype.requestCancellation = function () {
- fs.writeFileSync(this.getCancellationFilePath(), '');
- this.isCancelled = true;
- };
- CancellationToken.prototype.cleanupCancellation = function () {
- if (this.isCancelled && fs.existsSync(this.getCancellationFilePath())) {
- fs.unlinkSync(this.getCancellationFilePath());
- this.isCancelled = false;
- }
- };
- return CancellationToken;
- }());
- exports.CancellationToken = CancellationToken;
|