UNPKG

diffusion

Version:

Diffusion JavaScript client

346 lines (345 loc) 15 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.InternalSessionWebworkerProxy = void 0; var errors_1 = require("./../../../errors/errors"); var internal_session_1 = require("./../../client/internal-session"); var service_adapter_1 = require("./../../client/service-adapter"); var service_locator_1 = require("./../../client/service-locator"); var session_context_impl_1 = require("./../../client/session-context-impl"); var conversation_id_1 = require("./../../conversation/conversation-id"); var emitter_1 = require("./../../events/emitter"); var stream_1 = require("./../../events/stream"); var buffer_input_stream_1 = require("./../../io/buffer-input-stream"); var buffer_output_stream_1 = require("./../../io/buffer-output-stream"); var buffer_serialiser_1 = require("./../../serialisers/buffer-serialiser"); var command_header_1 = require("./../../services/command-header"); var command_header_serialiser_1 = require("./../../services/command-header-serialiser"); var options_impl_1 = require("./../../session/options-impl"); var session_id_1 = require("./../../session/session-id"); var logger = require("./../../util/logger"); var uint8array_1 = require("./../../util/uint8array"); var message_1 = require("./../../v4-stack/message"); var internal_session_locks_proxy_1 = require("./../../webworker/client/internal-session-locks-proxy"); var stream_registry_web_worker_proxy_1 = require("./../../webworker/client/stream-registry-web-worker-proxy"); var worker_command_1 = require("./../../webworker/worker-command"); var close_reason_1 = require("../../../client/close-reason"); var log = logger.create('InternalSessionWebworkerProxy'); var SHARED_WORKER_CONNECT_TIMEOUT = 1000; /** * Internal session implementation */ var InternalSessionWebworkerProxy = /** @class */ (function (_super) { __extends(InternalSessionWebworkerProxy, _super); /** * Create a new InternalSessionWebworkerProxy instance * * @param serviceRegistry the service registry * @param connectionFactory a factory for creating the connection * @param opts the session options */ function InternalSessionWebworkerProxy(conversationSetFactory, serviceRegistry, connector, opts) { var _this = this; var factory = emitter_1.Emitter.create(); _this = _super.call(this, factory) || this; _this.emitter = factory.emitter(_this); _this.connector = connector; _this.opts = opts; _this.connected = false; _this.state = internal_session_1.InternalSessionState.INITIALISING; _this.connector.on({ // eslint-disable-next-line @typescript-eslint/naming-convention connect_event: function (connectArgs) { var _a = __read(connectArgs, 3), sessionID = _a[0], options = _a[1], serverMaximumMessageSize = _a[2]; try { _this.serverMaximumMessageSize = parseInt(serverMaximumMessageSize, 10); _this.opts = JSON.parse(options); _this.sessionID = session_id_1.SessionId.fromString(sessionID); _this.connected = true; _this.emitter.emit('connect', _this.sessionID, new options_impl_1.OptionsImpl(_this.opts)); } catch (err) { log.error('Unable to parse options from shared session', err); _this.emitter.emit('error', new Error('Unable to parse options from shared session')); } }, // eslint-disable-next-line @typescript-eslint/naming-convention connect_error: function (error) { _this.connector.disconnect(); _this.emitter.emit('error', close_reason_1.CloseReasonEnum[error] || new Error(error)); }, // eslint-disable-next-line @typescript-eslint/naming-convention reconnect_event: function () { _this.connected = true; _this.emitter.emit('reconnect'); }, // eslint-disable-next-line @typescript-eslint/naming-convention disconnect_event: function (reason) { _this.connected = false; var reasonKey = close_reason_1.CloseReasonEnum[reason]; _this.emitter.emit('disconnect', close_reason_1.CloseReasonEnum[reasonKey]); }, // eslint-disable-next-line @typescript-eslint/naming-convention close_event: function (reason) { _this.connector.disconnect(); _this.connected = false; var reasonKey = close_reason_1.CloseReasonEnum[reason]; _this.emitter.close(close_reason_1.CloseReasonEnum[reasonKey]); }, // eslint-disable-next-line @typescript-eslint/naming-convention error_event: function (err) { _this.connector.disconnect(); _this.connected = false; _this.emitter.emit('error', new Error(err)); }, // eslint-disable-next-line @typescript-eslint/naming-convention command_response: function (responseArgs) { var _a = __read(responseArgs, 2), cidStr = _a[0], inputStr = _a[1]; var cid = conversation_id_1.ConversationId.fromString(cidStr); var input = new buffer_input_stream_1.BufferInputStream(uint8array_1.uint8FromBase64(inputStr)); _this.conversationSet.respondIfPresent(cid, input); }, // eslint-disable-next-line @typescript-eslint/naming-convention command_error: function (responseArgs) { var _a = __read(responseArgs, 2), cidStr = _a[0], errorStr = _a[1]; var cid = conversation_id_1.ConversationId.fromString(cidStr); var error; try { error = JSON.parse(errorStr); } catch (err) { error = new Error('Could not parse error response'); } _this.conversationSet.discard(cid, error); }, // eslint-disable-next-line @typescript-eslint/naming-convention service_request: function (requestArgs) { var _a = __read(requestArgs, 3), serviceIdStr = _a[0], ridStr = _a[1], inputStr = _a[2]; var rid = conversation_id_1.ConversationId.fromString(ridStr); var bos = new buffer_output_stream_1.BufferOutputStream(); command_header_serialiser_1.CommandHeaderSerialiser.write(bos, new command_header_1.CommandHeader(parseInt(serviceIdStr, 10), rid)); buffer_serialiser_1.BufferSerialiser.write(bos, uint8array_1.uint8FromBase64(inputStr)); var input = new buffer_input_stream_1.BufferInputStream(bos.getBuffer()); _this.serviceAdapter.onMessage(message_1.types.SERVICE_REQUEST, input); }, // eslint-disable-next-line @typescript-eslint/naming-convention state_change: function (newState) { _this.state = newState; } }); _this.serviceAdapter = new service_adapter_1.ServiceAdapter(_this, function (msg) { _this.connector.sendMessage(msg); }); _this.serviceLocator = new service_locator_1.ServiceLocatorImpl(_this, _this.serviceAdapter); _this.serviceRegistry = serviceRegistry; _this.serviceRegistry.addListener(_this.serviceAdapter.addService.bind(_this.serviceAdapter)); _this.serviceRegistry.addListener(function (definition) { _this.connector.send(worker_command_1.WorkerCommand.SERVICE, JSON.stringify({ action: 'add', serviceId: definition.id })); }); _this.topicStreamRegistry = new stream_registry_web_worker_proxy_1.StreamRegistryWebworkerProxy(_this.connector); _this.conversationSet = conversationSetFactory(); _this.sessionLocks = new internal_session_locks_proxy_1.InternalSessionLocksProxy(_this.connector); return _this; } /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.connect = function () { var _this = this; if (this.opts) { var _a = this.opts, credentials = _a.credentials, reconnect = _a.reconnect, opts = __rest(_a, ["credentials", "reconnect"]); var isCredentialsBuffer = credentials instanceof Uint8Array; var credentialsStr = isCredentialsBuffer ? uint8array_1.uint8ToBase64(credentials) : credentials; opts.reconnect = reconnect.timeout; this.connector.send(worker_command_1.WorkerCommand.CONNECT, JSON.stringify([opts, isCredentialsBuffer, credentialsStr])); } else { this.connector.send(worker_command_1.WorkerCommand.CONNECT_EXISTING); } var connectAckReceived = false; this.connector.on('connect_ack', function () { connectAckReceived = true; }); setTimeout(function () { if (!connectAckReceived) { _this.emitter.emit('error', new Error('Unable to connect to shared worker')); _this.connector.close(); } }, SHARED_WORKER_CONNECT_TIMEOUT); }; InternalSessionWebworkerProxy.prototype.close = function () { if (this.state !== internal_session_1.InternalSessionState.CLOSED) { this.connector.send(worker_command_1.WorkerCommand.CLOSE); } return this; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.isConnected = function () { return this.connected; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.checkConnected = function (reject) { if (this.isConnected()) { return true; } else { reject(new Error('The session is not connected. Operations are not possible at this time.')); return false; } }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getSessionId = function () { return this.sessionID; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getPrincipal = function () { if (this.opts === undefined) { throw new errors_1.IllegalStateError('Shared session is not connected'); } return this.opts.principal || ''; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.setPrincipal = function (newPrincipal) { if (this.opts === undefined) { throw new errors_1.IllegalStateError('Shared session is not connected'); } this.opts.principal = newPrincipal; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getOptions = function () { if (this.opts === undefined) { throw new errors_1.IllegalStateError('Shared session is not connected'); } return this.opts; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getState = function () { return this.state; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getServerMaximumMessageSize = function () { return this.serverMaximumMessageSize; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.lock = function (lockName, scope) { return this.sessionLocks.lock(lockName, scope); }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.onSystemPing = function () { throw new errors_1.InternalError('Method not implemented.'); }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getStreamRegistry = function () { return this.topicStreamRegistry; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getServiceRegistry = function () { return this.serviceRegistry; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getRouting = function () { throw new errors_1.InternalError('Method not implemented.'); }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getServiceLocator = function () { return this.serviceLocator; }; /** * Get the conversation set * * @return a reference to the conversation set */ InternalSessionWebworkerProxy.prototype.getConversationSet = function () { return this.conversationSet; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.isShared = function () { return true; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.getContext = function () { return session_context_impl_1.sessionContext; }; /** * @inheritdoc */ InternalSessionWebworkerProxy.prototype.updateFeatures = function () { // no-op }; return InternalSessionWebworkerProxy; }(stream_1.StreamImpl)); exports.InternalSessionWebworkerProxy = InternalSessionWebworkerProxy;