@vtex/diagnostics-nodejs
Version:
Diagnostics library for Node.js applications
78 lines • 2.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.S3ConfigProvider = void 0;
const client_s3_1 = require("@aws-sdk/client-s3");
class S3ConfigProvider {
constructor(bucket, key, region = 'us-east-1', intervalMs = 30000 // 30s polling
) {
this.bucket = bucket;
this.key = key;
this.region = region;
this.intervalMs = intervalMs;
this.callbacks = [];
this.pollingInterval = null;
this.s3Client = new client_s3_1.S3Client({ region: this.region });
}
async load() {
try {
const command = new client_s3_1.GetObjectCommand({
Bucket: this.bucket,
Key: this.key
});
const response = await this.s3Client.send(command);
if (!response.Body)
return this.lastConfig;
const content = await response.Body.transformToString();
const config = JSON.parse(content);
this.lastConfig = config;
return config;
}
catch (error) {
console.warn(`Could not load config from S3 ${this.bucket}/${this.key}:`, error);
return this.lastConfig;
}
}
onChange(callback) {
this.callbacks.push(callback);
if (!this.pollingInterval) {
this.startPolling();
}
}
startPolling() {
this.pollingInterval = setInterval(async () => {
try {
const head = await this.s3Client.send(new client_s3_1.HeadObjectCommand({
Bucket: this.bucket,
Key: this.key
}));
const etag = head.ETag;
if (etag && etag !== this.lastEtag) {
this.lastEtag = etag;
const config = await this.load();
if (config) {
this.callbacks.forEach(cb => {
try {
cb(config);
}
catch (error) {
console.error('Error in S3 config change callback:', error);
}
});
}
}
}
catch (error) {
console.warn(`Error checking S3 config ${this.bucket}/${this.key}:`, error);
}
}, this.intervalMs);
}
dispose() {
if (this.pollingInterval) {
clearInterval(this.pollingInterval);
this.pollingInterval = null;
}
this.callbacks = [];
}
}
exports.S3ConfigProvider = S3ConfigProvider;
//# sourceMappingURL=s3.js.map