@filemap/events-sdk
Version:
SDK for Filemap events. Desktop client for Filemap dev server.
141 lines • 6.3 kB
JavaScript
;
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.KeyFetcher = void 0;
const tsyringe_1 = require("tsyringe");
const logger_service_1 = require("./logger.service");
const key_manager_service_1 = require("./key-manager.service");
let KeyFetcher = class KeyFetcher {
logger;
keyManager;
pendingFetches = new Map();
RETRY_INTERVAL = 5000;
constructor(logger, keyManager) {
this.logger = logger;
this.keyManager = keyManager;
}
async startFetching(uuid, referrer, expirationTime) {
this.logger.debug(`Starting key fetch for UUID: ${uuid} from ${referrer}`);
const existing = this.pendingFetches.get(referrer);
if (existing) {
this.logger.debug(`Canceling fetch for old UUID: ${existing.uuid} from ${referrer}`);
this.stopFetchingForReferrer(referrer);
}
const pendingFetch = {
uuid,
referrer,
retryTimer: null
};
this.pendingFetches.set(referrer, pendingFetch);
const expiry = new Date(expirationTime);
if (expiry <= new Date()) {
this.logger.debug(`UUID ${uuid} from ${referrer} is already expired, not fetching`);
this.pendingFetches.delete(referrer);
return;
}
await this.attemptFetch(referrer);
}
cleanup() {
for (const referrer of this.pendingFetches.keys()) {
this.stopFetchingForReferrer(referrer);
}
this.pendingFetches.clear();
}
async attemptFetch(referrer) {
const pendingFetch = this.pendingFetches.get(referrer);
if (!pendingFetch)
return;
const { uuid } = pendingFetch;
try {
this.logger.debug(`Attempting to fetch key for UUID: ${uuid} from ${referrer}`);
const backendUrl = this.getBackendUrl();
const response = await fetch(`${backendUrl}/api/fetch-key/${uuid}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
const currentFetch = this.pendingFetches.get(referrer);
if (!currentFetch || currentFetch.uuid !== uuid) {
this.logger.debug(`Ignoring response for old UUID: ${uuid} from ${referrer}`);
return;
}
if (!response.ok) {
if (response.status === 500) {
this.logger.debug(`Server down for UUID: ${uuid} from ${referrer}, will retry`);
this.scheduleRetry(referrer);
return;
}
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
const keyData = await response.json();
const expirationTime = new Date(keyData.expirationTime);
const now = new Date();
if (expirationTime <= now) {
this.logger.debug(`Received expired key for UUID: ${uuid} from ${referrer}, stopping fetch`);
this.stopFetchingForReferrer(referrer);
return;
}
const keyDataWithUuid = { ...keyData, uuid };
const success = this.keyManager.setKey(referrer, keyDataWithUuid);
if (success) {
this.logger.debug(`Successfully fetched and set key for UUID: ${uuid} from ${referrer}`);
this.stopFetchingForReferrer(referrer);
}
else {
this.logger.error(`Failed to set key for UUID: ${uuid} from ${referrer}`);
this.stopFetchingForReferrer(referrer);
}
}
catch (err) {
const currentFetch = this.pendingFetches.get(referrer);
if (currentFetch && currentFetch.uuid === uuid) {
const msg = err instanceof Error ? err.message : 'Unknown error';
this.logger.error(`Failed to fetch key for UUID: ${uuid} from ${referrer}: ${msg}`);
this.scheduleRetry(referrer);
}
}
}
scheduleRetry(referrer) {
const pendingFetch = this.pendingFetches.get(referrer);
if (!pendingFetch)
return;
this.logger.debug(`Scheduling retry for ${referrer} in ${this.RETRY_INTERVAL / 1000} seconds`);
pendingFetch.retryTimer = setTimeout(() => {
this.attemptFetch(referrer);
}, this.RETRY_INTERVAL);
}
stopFetchingForReferrer(referrer) {
const pendingFetch = this.pendingFetches.get(referrer);
if (!pendingFetch)
return;
if (pendingFetch.retryTimer) {
clearTimeout(pendingFetch.retryTimer);
pendingFetch.retryTimer = null;
}
this.pendingFetches.delete(referrer);
}
getBackendUrl() {
return 'https://filemap.ai';
}
};
exports.KeyFetcher = KeyFetcher;
exports.KeyFetcher = KeyFetcher = __decorate([
(0, tsyringe_1.singleton)(),
(0, tsyringe_1.injectable)(),
__param(0, (0, tsyringe_1.inject)(logger_service_1.Logger)),
__param(1, (0, tsyringe_1.inject)(key_manager_service_1.KeyManager)),
__metadata("design:paramtypes", [logger_service_1.Logger,
key_manager_service_1.KeyManager])
], KeyFetcher);
//# sourceMappingURL=key-fetcher.service.js.map