@pureweb/platform-streaming-agent
Version:
The PureWeb platform streaming agent enables your game to communicate and stream through the PureWeb Platform
63 lines (62 loc) • 3.11 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LeasingExtension = void 0;
const Log_1 = __importDefault(require("../../Log"));
const IExtension_1 = require("../../IExtension");
const ConnectionStates_1 = require("../../ConnectionStates");
class LeaseResponse {
}
class LeasingExtension extends IExtension_1.AbstractExtension {
constructor() {
super();
this.stopRequested = false;
this.start = async () => {
this.leaseUrl = this.config.leaseUrl;
this.connectionStateChange?.(ConnectionStates_1.ConnectionStates.LEASE_REQUESTING);
this.lease();
return Promise.resolve(true);
};
this.stop = () => {
clearTimeout(this.timeout);
this.stopRequested = true;
this.connectionStateChange?.(ConnectionStates_1.ConnectionStates.LEASE_STOPPED);
return Promise.resolve(true);
};
this.lease = async () => {
try {
const res = await fetch(this.leaseUrl);
const response = await res.json();
if (response.leased && !this.stopRequested) {
const nextLease = response.expire - Date.now() - LeasingExtension.LEASE_REQUEST_WINDOW_MS;
// setTimeout defaults to 0 on negative values, so if for some reason our window is greater then the time left for the lease to expire,
// setTimeout will schedule to call lease as soon as possible.
this.timeout = setTimeout(this.lease, nextLease);
// A warning message seems apropriate though since this might indicate a bug somewhere,
// specially in case for some reason the lease has actually already expired.
if (nextLease <= 0) {
Log_1.default.warn('Lease request window is too big or the lease has already expired:\n' +
` Next lease request in: ${nextLease}ms\n` +
` Window size: ${LeasingExtension.LEASE_REQUEST_WINDOW_MS}ms`);
}
}
else {
Log_1.default.info('Service Manager refused to lease more time. No more lease requests will be made.');
this.connectionStateChange?.(ConnectionStates_1.ConnectionStates.LEASE_DENIED);
}
}
catch (e) {
Log_1.default.error(`Error requesting Service Manager lease: ${e}`);
this.timeout = setTimeout(this.lease, 1000);
}
};
}
onStateChanged(handler) {
this.connectionStateChange = handler;
}
}
exports.LeasingExtension = LeasingExtension;
// TODO: this should probably come from the launch request
LeasingExtension.LEASE_REQUEST_WINDOW_MS = 15000; // How many milliseconds before expiring should the leasing service request a new lease.