iobroker.digitalstrom 2.2.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -1
- package/README.md +809 -35
- package/admin/assets/index.js +682 -0
- package/admin/index.html +45 -0
- package/build/lib/activityCounter.js +82 -0
- package/build/lib/activityCounter.js.map +1 -0
- package/build/lib/configUtils.js +125 -0
- package/build/lib/configUtils.js.map +1 -0
- package/build/lib/constants.js +1285 -0
- package/build/lib/constants.js.map +1 -0
- package/build/lib/dss.js +877 -0
- package/build/lib/dss.js.map +1 -0
- package/build/lib/dssQueue.js +517 -0
- package/build/lib/dssQueue.js.map +1 -0
- package/build/lib/dssSmartHome.js +769 -0
- package/build/lib/dssSmartHome.js.map +1 -0
- package/build/lib/dssSmartHomeSync.js +601 -0
- package/build/lib/dssSmartHomeSync.js.map +1 -0
- package/build/lib/dssStructure.js +3390 -0
- package/build/lib/dssStructure.js.map +1 -0
- package/build/lib/websocket.js +386 -0
- package/build/lib/websocket.js.map +1 -0
- package/build/main.js +2203 -0
- package/build/main.js.map +1 -0
- package/io-package.json +262 -254
- package/package.json +67 -36
- package/admin/admin.d.ts +0 -1
- package/admin/index_m.html +0 -201
- package/admin/style.css +0 -10
- package/admin/words.js +0 -20
- package/img/dss-apartment.png +0 -0
- package/img/dss-devices.png +0 -0
- package/lib/adapter-config.d.ts +0 -16
- package/lib/constants.js +0 -1202
- package/lib/dss.js +0 -193
- package/lib/dssQueue.js +0 -268
- package/lib/dssStructure.js +0 -1650
- package/lib/tools.js +0 -91
- package/main.js +0 -713
package/build/lib/dss.js
ADDED
|
@@ -0,0 +1,877 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.DSS = exports.DSSError = void 0;
|
|
37
|
+
const node_events_1 = require("node:events");
|
|
38
|
+
const http = __importStar(require("node:http"));
|
|
39
|
+
const https = __importStar(require("node:https"));
|
|
40
|
+
const configUtils_1 = require("./configUtils");
|
|
41
|
+
const RETRYABLE_ERROR_CODES = ['ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'ECONNREFUSED'];
|
|
42
|
+
const DEFAULT_REQUEST_TIMEOUT = 30 * 1000;
|
|
43
|
+
const SESSION_MAX_AGE = 45 * 1000; // DSS invalidates sessions after 60s idle, renew a bit earlier
|
|
44
|
+
const DEFAULT_API_MAX_SOCKETS = 8;
|
|
45
|
+
// The adapter runs ONE long-poll (all events share a subscription id). The reserve keeps
|
|
46
|
+
// room for a re-subscribe running next to the poll and for additional channels.
|
|
47
|
+
const DEFAULT_EVENT_MAX_SOCKETS = 16;
|
|
48
|
+
const MAX_EVENT_ERRORS = 5;
|
|
49
|
+
const EVENT_RETRY_BASE_DELAY = 2000;
|
|
50
|
+
const EVENT_RETRY_MAX_DELAY = 60000;
|
|
51
|
+
/**
|
|
52
|
+
* Error of the DSS client.
|
|
53
|
+
*
|
|
54
|
+
* Besides the message it carries structured markers that the consumers evaluate instead
|
|
55
|
+
* of parsing the message text - see the AdapterError typedef in configUtils.
|
|
56
|
+
*/
|
|
57
|
+
class DSSError extends Error {
|
|
58
|
+
/** HTTP status code of the answer */
|
|
59
|
+
status;
|
|
60
|
+
/** backward compatible field name for status */
|
|
61
|
+
status_code;
|
|
62
|
+
/** node style error code, e.g. ETIMEDOUT */
|
|
63
|
+
code;
|
|
64
|
+
/** true for a request timeout of this client */
|
|
65
|
+
timeout;
|
|
66
|
+
/** true when the request was cancelled by stop() */
|
|
67
|
+
shutdown;
|
|
68
|
+
/**
|
|
69
|
+
* @param message error message
|
|
70
|
+
* @param [status] HTTP status code, if the DSS answered at all
|
|
71
|
+
* @param [options] standard error options, e.g. { cause }
|
|
72
|
+
*/
|
|
73
|
+
constructor(message, status, options) {
|
|
74
|
+
super(message, options);
|
|
75
|
+
this.name = 'DSSError';
|
|
76
|
+
this.status = status;
|
|
77
|
+
this.status_code = status;
|
|
78
|
+
this.code = undefined;
|
|
79
|
+
this.timeout = undefined;
|
|
80
|
+
this.shutdown = undefined;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
exports.DSSError = DSSError;
|
|
84
|
+
class DSS extends node_events_1.EventEmitter {
|
|
85
|
+
/**
|
|
86
|
+
* Allowlist of DSS endpoints that may be repeated once after a connection error.
|
|
87
|
+
*
|
|
88
|
+
* Deliberately a positive list: a newly used endpoint is not retried until its
|
|
89
|
+
* semantics have been checked. Every entry is a pure read whose repetition cannot
|
|
90
|
+
* change anything on the DSS or trigger an automation.
|
|
91
|
+
*/
|
|
92
|
+
static RETRYABLE_REQUESTS = new Set([
|
|
93
|
+
'apartment/getCircuits',
|
|
94
|
+
'apartment/getName',
|
|
95
|
+
// Pure read of the reachable groups of a zone, used once during startup.
|
|
96
|
+
// Repeating it changes nothing on the DSS (same semantics as zone/getReachableScenes).
|
|
97
|
+
'apartment/getReachableGroups',
|
|
98
|
+
'apartment/getSensorValues',
|
|
99
|
+
'apartment/getStructure',
|
|
100
|
+
'apartment/getTemperatureControlStatus',
|
|
101
|
+
// Pure read of the configured set points of one zone
|
|
102
|
+
'zone/getTemperatureControlValues',
|
|
103
|
+
'circuit/getConsumption',
|
|
104
|
+
'circuit/getEnergyMeterValue',
|
|
105
|
+
'device/getConfig',
|
|
106
|
+
'device/getConfigWord',
|
|
107
|
+
'device/getOutputChannelValue',
|
|
108
|
+
// The named channel read of vDC devices. Same pure read as the line above,
|
|
109
|
+
// and for a Sonos player it is the ONLY path to audioVolume and powerState.
|
|
110
|
+
'device/getOutputChannelValue2',
|
|
111
|
+
'device/getOutputValue',
|
|
112
|
+
'device/getSwitchThreshold',
|
|
113
|
+
// A subscription is a registration, not an action: subscribing the same id and name
|
|
114
|
+
// twice has no effect, so a lost answer during startup may be retried.
|
|
115
|
+
'event/subscribe',
|
|
116
|
+
'property/query',
|
|
117
|
+
// The same pure read as property/query, only with the answer keyed by node name.
|
|
118
|
+
// Used once at startup for the sensor states under /usr/addon-states.
|
|
119
|
+
'property/query2',
|
|
120
|
+
'system/version',
|
|
121
|
+
'zone/getLastCalledScene',
|
|
122
|
+
'zone/getReachableScenes',
|
|
123
|
+
]);
|
|
124
|
+
// DSSError hangs off the class so `DSS.DSSError` keeps working next to the named
|
|
125
|
+
// export of this module.
|
|
126
|
+
static DSSError = DSSError;
|
|
127
|
+
options;
|
|
128
|
+
host;
|
|
129
|
+
appToken;
|
|
130
|
+
subScriptionId;
|
|
131
|
+
subScriptionTimeout;
|
|
132
|
+
requestTimeout;
|
|
133
|
+
/**
|
|
134
|
+
* Optionaler Zaehl-Haken fuer die Aktivitaetsanzeige:
|
|
135
|
+
* ('request'|'eventPoll'|'event', pfadOderName). Darf nie werfen muessen -
|
|
136
|
+
* wird deshalb nur aufgerufen, nie awaited.
|
|
137
|
+
*/
|
|
138
|
+
onActivity;
|
|
139
|
+
baseUrl;
|
|
140
|
+
isSecure;
|
|
141
|
+
transport;
|
|
142
|
+
apiAgent;
|
|
143
|
+
eventAgent;
|
|
144
|
+
sessionToken;
|
|
145
|
+
sessionLastUsed;
|
|
146
|
+
sessionLoginPromise;
|
|
147
|
+
/** eventName -> { subscriptionId, timeout }: which names are registered */
|
|
148
|
+
subscriptions;
|
|
149
|
+
/** subscriptionId -> channel: exactly one long-poll per subscription id */
|
|
150
|
+
eventChannels;
|
|
151
|
+
activeRequests;
|
|
152
|
+
stopped;
|
|
153
|
+
constructor(options) {
|
|
154
|
+
super();
|
|
155
|
+
this.options = options || {
|
|
156
|
+
logger: console,
|
|
157
|
+
};
|
|
158
|
+
this.host = this.options.host;
|
|
159
|
+
this.appToken = this.options.appToken;
|
|
160
|
+
this.subScriptionId = this.options.subScriptionId || 42;
|
|
161
|
+
this.subScriptionTimeout = this.options.subScriptionTimeout || 40 * 1000;
|
|
162
|
+
this.requestTimeout = this.options.requestTimeout || DEFAULT_REQUEST_TIMEOUT;
|
|
163
|
+
this.onActivity = typeof this.options.onActivity === 'function' ? this.options.onActivity : null;
|
|
164
|
+
this.baseUrl = DSS.buildBaseUrl(this.host);
|
|
165
|
+
// The DSS uses https, but the configured scheme is respected (also keeps tests transport agnostic)
|
|
166
|
+
this.isSecure = this.baseUrl.startsWith('https:');
|
|
167
|
+
this.transport = this.isSecure ? https : http;
|
|
168
|
+
const agentOptions = {
|
|
169
|
+
// No keep-alive on purpose: the DSS closes idle connections, and a pooled socket
|
|
170
|
+
// that was closed in the meantime results in "socket hang up" on the next request.
|
|
171
|
+
// The request rate is limited by the queue anyway, so pooling would gain very little.
|
|
172
|
+
keepAlive: false,
|
|
173
|
+
// The DSS uses a self-signed certificate, so validation must be opt-in.
|
|
174
|
+
// Normalized here as well because the token dialog builds a client directly
|
|
175
|
+
// from the raw configuration.
|
|
176
|
+
rejectUnauthorized: (0, configUtils_1.normalizeBoolean)(this.options.validateCertificate, false),
|
|
177
|
+
};
|
|
178
|
+
// Event long-polls occupy their socket for the whole polling timeout. They get their
|
|
179
|
+
// own agent so that normal API calls (scene calls, login, ...) are never queued behind them.
|
|
180
|
+
this.apiAgent = new this.transport.Agent({
|
|
181
|
+
...agentOptions,
|
|
182
|
+
maxSockets: this.options.apiMaxSockets || DEFAULT_API_MAX_SOCKETS,
|
|
183
|
+
});
|
|
184
|
+
this.eventAgent = new this.transport.Agent({
|
|
185
|
+
...agentOptions,
|
|
186
|
+
maxSockets: this.options.eventMaxSockets || DEFAULT_EVENT_MAX_SOCKETS,
|
|
187
|
+
});
|
|
188
|
+
this.sessionToken = null;
|
|
189
|
+
this.sessionLastUsed = 0;
|
|
190
|
+
this.sessionLoginPromise = null;
|
|
191
|
+
// eventName -> { subscriptionId, timeout }: which names are registered
|
|
192
|
+
this.subscriptions = {};
|
|
193
|
+
// subscriptionId -> channel: exactly one long-poll per subscription id
|
|
194
|
+
this.eventChannels = {};
|
|
195
|
+
this.activeRequests = new Set();
|
|
196
|
+
this.stopped = false;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Normalizes a configured host into a base url.
|
|
200
|
+
* Accepts "1.2.3.4", "1.2.3.4:8080", "https://host:8080", "[::1]:8080" and DNS names.
|
|
201
|
+
*
|
|
202
|
+
* @param host configured host value
|
|
203
|
+
* @returns normalized base url without trailing slash
|
|
204
|
+
*/
|
|
205
|
+
static buildBaseUrl(host) {
|
|
206
|
+
if (typeof host !== 'string' || !host.trim()) {
|
|
207
|
+
throw new DSSError('No DSS host configured');
|
|
208
|
+
}
|
|
209
|
+
let raw = host.trim();
|
|
210
|
+
const schemeMatch = raw.match(/^([a-z][a-z0-9+.-]*):\/\//i);
|
|
211
|
+
if (schemeMatch) {
|
|
212
|
+
const scheme = schemeMatch[1].toLowerCase();
|
|
213
|
+
if (scheme !== 'https' && scheme !== 'http') {
|
|
214
|
+
throw new DSSError(`Invalid DSS host "${host}": only https and http are supported`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
raw = `https://${raw}`;
|
|
219
|
+
}
|
|
220
|
+
// Split into scheme, authority and everything behind it. Only the authority decides
|
|
221
|
+
// about brackets and the port - a trailing slash must not influence that.
|
|
222
|
+
const schemeEnd = raw.indexOf('://') + 3;
|
|
223
|
+
const scheme = raw.slice(0, schemeEnd);
|
|
224
|
+
const rest = raw.slice(schemeEnd);
|
|
225
|
+
const authorityEnd = rest.search(/[/?#]/);
|
|
226
|
+
let authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
|
|
227
|
+
const trailer = authorityEnd === -1 ? '' : rest.slice(authorityEnd);
|
|
228
|
+
// Bare IPv6 addresses need brackets to be parseable ("::1" -> "[::1]")
|
|
229
|
+
if (!authority.startsWith('[') && (authority.match(/:/g) || []).length > 1) {
|
|
230
|
+
authority = `[${authority}]`;
|
|
231
|
+
}
|
|
232
|
+
raw = scheme + authority + trailer;
|
|
233
|
+
let url;
|
|
234
|
+
try {
|
|
235
|
+
url = new URL(raw);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
throw new DSSError(`Invalid DSS host "${host}"`);
|
|
239
|
+
}
|
|
240
|
+
if (url.username || url.password) {
|
|
241
|
+
throw new DSSError('The DSS host must not contain credentials');
|
|
242
|
+
}
|
|
243
|
+
if (url.search || url.hash || (url.pathname && url.pathname !== '/')) {
|
|
244
|
+
throw new DSSError(`Invalid DSS host "${host}": only host and port are allowed`);
|
|
245
|
+
}
|
|
246
|
+
if (!url.hostname) {
|
|
247
|
+
throw new DSSError(`Invalid DSS host "${host}"`);
|
|
248
|
+
}
|
|
249
|
+
// The URL API drops a port that is the default of the scheme (443/80), so the
|
|
250
|
+
// raw authority decides whether the DSS default port 8080 has to be added.
|
|
251
|
+
const hasExplicitPort = authority.includes(']') ? /]:\d+$/.test(authority) : /:\d+$/.test(authority);
|
|
252
|
+
let port = url.port;
|
|
253
|
+
if (!port) {
|
|
254
|
+
port = hasExplicitPort ? (url.protocol === 'https:' ? '443' : '80') : '8080';
|
|
255
|
+
}
|
|
256
|
+
return `${url.protocol}//${url.hostname}:${port}`;
|
|
257
|
+
}
|
|
258
|
+
stop() {
|
|
259
|
+
this.stopped = true;
|
|
260
|
+
Object.keys(this.eventChannels).forEach(key => this.clearEventRetry(this.eventChannels[key].subscriptionId));
|
|
261
|
+
// Abort in-flight requests (especially the long running event polls)
|
|
262
|
+
this.activeRequests.forEach(req => req.destroy());
|
|
263
|
+
this.activeRequests.clear();
|
|
264
|
+
this.apiAgent.destroy();
|
|
265
|
+
this.eventAgent.destroy();
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Low level HTTPS GET against the DSS JSON API
|
|
269
|
+
*
|
|
270
|
+
* @param path e.g. /json/system/login
|
|
271
|
+
* @param [query] query parameters
|
|
272
|
+
* @param [timeout] timeout in ms for this request
|
|
273
|
+
* @param [isEventPoll] use the separate event agent for long-polls
|
|
274
|
+
* @returns parsed JSON body
|
|
275
|
+
*/
|
|
276
|
+
httpRequest(path, query, timeout, isEventPoll) {
|
|
277
|
+
return new Promise((resolve, reject) => {
|
|
278
|
+
if (this.stopped) {
|
|
279
|
+
// Hard barrier: after stop() the agents are destroyed and no new socket
|
|
280
|
+
// may be opened, no matter which late callback ends up here.
|
|
281
|
+
const stoppedErr = new DSSError(`Client is stopped, not requesting ${path}`);
|
|
282
|
+
stoppedErr.shutdown = true;
|
|
283
|
+
return void reject(stoppedErr);
|
|
284
|
+
}
|
|
285
|
+
const search = query ? `?${new URLSearchParams(query).toString()}` : '';
|
|
286
|
+
const url = this.baseUrl + path + search;
|
|
287
|
+
const effectiveTimeout = timeout || this.requestTimeout;
|
|
288
|
+
let req = undefined;
|
|
289
|
+
const done = (err, body) => {
|
|
290
|
+
if (req) {
|
|
291
|
+
this.activeRequests.delete(req);
|
|
292
|
+
}
|
|
293
|
+
if (err) {
|
|
294
|
+
reject(err);
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
resolve(body);
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
// Fuer die Aktivitaetsanzeige des Status-Tabs: was geht ueber diesen Weg
|
|
301
|
+
this.onActivity && this.onActivity(isEventPoll ? 'eventPoll' : 'request', path);
|
|
302
|
+
req = this.transport.get(url, {
|
|
303
|
+
agent: isEventPoll ? this.eventAgent : this.apiAgent,
|
|
304
|
+
timeout: effectiveTimeout,
|
|
305
|
+
}, res => {
|
|
306
|
+
let data = '';
|
|
307
|
+
res.setEncoding('utf8');
|
|
308
|
+
res.on('data', (chunk) => (data += chunk));
|
|
309
|
+
res.on('end', () => {
|
|
310
|
+
if (res.statusCode !== 200) {
|
|
311
|
+
return done(new DSSError(`HTTP ${res.statusCode} for ${path}`, res.statusCode));
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
done(null, JSON.parse(data));
|
|
315
|
+
}
|
|
316
|
+
catch (err) {
|
|
317
|
+
done(new DSSError(`Invalid JSON response for ${path}: ${(0, configUtils_1.errorMessage)(err)}`, undefined, {
|
|
318
|
+
cause: err,
|
|
319
|
+
}));
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
res.on('error', err => done(new DSSError(`Response error for ${path}: ${err.message}`, undefined, { cause: err })));
|
|
323
|
+
});
|
|
324
|
+
const request = req;
|
|
325
|
+
this.activeRequests.add(request);
|
|
326
|
+
request.on('timeout', () => {
|
|
327
|
+
// destroy() triggers the 'error' handler with our timeout error.
|
|
328
|
+
// The error carries the structured markers of a real socket timeout so that
|
|
329
|
+
// isRetryableConnectionError() does not have to parse the message text.
|
|
330
|
+
const timeoutError = new DSSError(`Timeout after ${effectiveTimeout}ms for ${path}`);
|
|
331
|
+
timeoutError.code = 'ETIMEDOUT';
|
|
332
|
+
timeoutError.timeout = true;
|
|
333
|
+
request.destroy(timeoutError);
|
|
334
|
+
});
|
|
335
|
+
request.on('error', err => done(err instanceof DSSError
|
|
336
|
+
? err
|
|
337
|
+
: new DSSError(`Request error for ${path}: ${err.message}`, undefined, { cause: err })));
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Returns a valid session token, renews it via loginApplication when needed.
|
|
342
|
+
* Parallel callers share one login request.
|
|
343
|
+
*/
|
|
344
|
+
async getSessionToken() {
|
|
345
|
+
if (this.sessionToken && Date.now() - this.sessionLastUsed < SESSION_MAX_AGE) {
|
|
346
|
+
return this.sessionToken;
|
|
347
|
+
}
|
|
348
|
+
if (!this.sessionLoginPromise) {
|
|
349
|
+
this.sessionLoginPromise = this.httpRequest('/json/system/loginApplication', {
|
|
350
|
+
loginToken: this.appToken,
|
|
351
|
+
}).then(body => {
|
|
352
|
+
this.sessionLoginPromise = null;
|
|
353
|
+
if (!body || body.ok !== true || !body.result || !body.result.token) {
|
|
354
|
+
throw new DSSError(`Login failed: ${(body && body.message) || 'unknown error'}`);
|
|
355
|
+
}
|
|
356
|
+
this.sessionToken = body.result.token;
|
|
357
|
+
this.sessionLastUsed = Date.now();
|
|
358
|
+
return this.sessionToken;
|
|
359
|
+
}, err => {
|
|
360
|
+
this.sessionLoginPromise = null;
|
|
361
|
+
throw err;
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return this.sessionLoginPromise;
|
|
365
|
+
}
|
|
366
|
+
invalidateSession() {
|
|
367
|
+
this.sessionToken = null;
|
|
368
|
+
this.sessionLastUsed = 0;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* True for connection level errors where the request was never answered.
|
|
372
|
+
* Typical case: the DSS closed a pooled keep-alive socket while it was idle
|
|
373
|
+
* and Node picked exactly that socket for the next request ("socket hang up").
|
|
374
|
+
*
|
|
375
|
+
* @param err thrown value
|
|
376
|
+
*/
|
|
377
|
+
static isRetryableConnectionError(err) {
|
|
378
|
+
const error = (0, configUtils_1.asError)(err);
|
|
379
|
+
if (!error) {
|
|
380
|
+
return false;
|
|
381
|
+
}
|
|
382
|
+
const cause = (0, configUtils_1.asError)(error.cause);
|
|
383
|
+
// Structured marker of our own request timeout, see httpRequest()
|
|
384
|
+
if (error.timeout === true || (cause && cause.timeout === true)) {
|
|
385
|
+
return true;
|
|
386
|
+
}
|
|
387
|
+
const code = error.code || (cause && cause.code);
|
|
388
|
+
if (code && RETRYABLE_ERROR_CODES.includes(code)) {
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
return /socket hang up|ECONNRESET|EPIPE/i.test(error.message || '');
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Decides whether a request may be sent a second time after a connection error.
|
|
395
|
+
*
|
|
396
|
+
* A connection error does not tell whether the DSS already processed the request -
|
|
397
|
+
* only the answer is known to be missing. Repeating is therefore only allowed for
|
|
398
|
+
* pure reads, where a second execution has no effect at all.
|
|
399
|
+
*
|
|
400
|
+
* Explicitly NOT retryable:
|
|
401
|
+
* - callScene / undoScene: would run the scene twice and can trigger dS automations
|
|
402
|
+
* - event/raise: would raise the event twice
|
|
403
|
+
* - state/set, pushSensorValue, setValue, setConfig: change data other systems react on
|
|
404
|
+
* - event/get: a read, but it consumes the pending events - a repeat would lose them
|
|
405
|
+
*
|
|
406
|
+
* @returns true if a single automatic retry is safe
|
|
407
|
+
*/
|
|
408
|
+
static isRetryableRequest(dssClass, dssFunction) {
|
|
409
|
+
return DSS.RETRYABLE_REQUESTS.has(`${dssClass}/${dssFunction}`);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Do Request to DSS. Resolves only with an "ok" response, rejects otherwise.
|
|
413
|
+
*
|
|
414
|
+
* @param dssClass class of the DSS JSON API, e.g. apartment
|
|
415
|
+
* @param dssFunction function of that class, e.g. getStructure
|
|
416
|
+
* @param [params] parameters of the request
|
|
417
|
+
* @param [options] options object, or a timeout in ms for the legacy signature
|
|
418
|
+
* @param [legacyIsEventPoll] only used together with the legacy signature
|
|
419
|
+
* @returns Promise resolving with the JSON body (body.ok === true)
|
|
420
|
+
*/
|
|
421
|
+
async requestAsync(dssClass, dssFunction, params, options, legacyIsEventPoll) {
|
|
422
|
+
if (this.stopped) {
|
|
423
|
+
// A callback that was already running when stop() was called must not be able to
|
|
424
|
+
// open a new connection afterwards. Rejecting with the shutdown marker keeps the
|
|
425
|
+
// consumers on their expected-error path instead of producing warnings.
|
|
426
|
+
const err = new DSSError(`Client is stopped, not sending ${dssClass}/${dssFunction}`);
|
|
427
|
+
err.shutdown = true;
|
|
428
|
+
throw err;
|
|
429
|
+
}
|
|
430
|
+
if (!this.appToken) {
|
|
431
|
+
throw new DSSError('You need to provide an appToken or do a login');
|
|
432
|
+
}
|
|
433
|
+
if (typeof options !== 'object' || options === null) {
|
|
434
|
+
// Legacy signature (dssClass, dssFunction, params, timeout, isEventPoll)
|
|
435
|
+
options = { timeout: options, eventPoll: legacyIsEventPoll };
|
|
436
|
+
}
|
|
437
|
+
const timeout = options.timeout;
|
|
438
|
+
const isEventPoll = !!options.eventPoll;
|
|
439
|
+
const mayRetry = options.retryOnConnectionError === undefined
|
|
440
|
+
? DSS.isRetryableRequest(dssClass, dssFunction)
|
|
441
|
+
: !!options.retryOnConnectionError;
|
|
442
|
+
const path = `/json/${dssClass}/${dssFunction}`;
|
|
443
|
+
let retriedAuth = false;
|
|
444
|
+
let retriedConnection = false;
|
|
445
|
+
for (;;) {
|
|
446
|
+
const token = await this.getSessionToken();
|
|
447
|
+
let body;
|
|
448
|
+
try {
|
|
449
|
+
body = await this.httpRequest(path, { ...params, token }, timeout, isEventPoll);
|
|
450
|
+
}
|
|
451
|
+
catch (err) {
|
|
452
|
+
// Only repeated when a second execution is known to be without effect
|
|
453
|
+
if (mayRetry && !retriedConnection && !this.stopped && DSS.isRetryableConnectionError(err)) {
|
|
454
|
+
retriedConnection = true;
|
|
455
|
+
this.options.logger &&
|
|
456
|
+
this.options.logger.debug(`Connection lost for ${path}, retrying once: ${(0, configUtils_1.errorMessage)(err)}`);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (this.stopped) {
|
|
460
|
+
// stop() aborts the running requests on purpose - consumers use this flag
|
|
461
|
+
// to not report the expected shutdown errors as warnings.
|
|
462
|
+
(0, configUtils_1.markShutdown)(err);
|
|
463
|
+
}
|
|
464
|
+
throw err;
|
|
465
|
+
}
|
|
466
|
+
this.sessionLastUsed = Date.now();
|
|
467
|
+
if (body && body.ok === true) {
|
|
468
|
+
return body;
|
|
469
|
+
}
|
|
470
|
+
const message = (body && body.message) || 'unknown error';
|
|
471
|
+
// Session might have been invalidated server side (e.g. DSS restart) - retry once with a fresh login
|
|
472
|
+
if (!retriedAuth && /not logged in|authentication|login/i.test(message)) {
|
|
473
|
+
retriedAuth = true;
|
|
474
|
+
this.invalidateSession();
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
throw new DSSError(`Error response for ${path}: ${message}`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async createAppTokenAsync(username, password, readableName) {
|
|
481
|
+
readableName = readableName || 'ioBroker';
|
|
482
|
+
if (typeof username !== 'string' || !username) {
|
|
483
|
+
throw new DSSError('No username provided');
|
|
484
|
+
}
|
|
485
|
+
if (typeof password !== 'string' || !password) {
|
|
486
|
+
throw new DSSError('No password provided');
|
|
487
|
+
}
|
|
488
|
+
const tokenRes = await this.httpRequest('/json/system/requestApplicationToken', {
|
|
489
|
+
applicationName: readableName,
|
|
490
|
+
});
|
|
491
|
+
if (!tokenRes || tokenRes.ok !== true || !tokenRes.result || !tokenRes.result.applicationToken) {
|
|
492
|
+
throw new DSSError(`Could not request application token: ${(tokenRes && tokenRes.message) || 'unknown error'}`);
|
|
493
|
+
}
|
|
494
|
+
const appToken = tokenRes.result.applicationToken;
|
|
495
|
+
const loginRes = await this.httpRequest('/json/system/login', { user: username, password });
|
|
496
|
+
if (!loginRes || loginRes.ok !== true || !loginRes.result || !loginRes.result.token) {
|
|
497
|
+
throw new DSSError(`Login failed - please check username and password: ${(loginRes && loginRes.message) || 'unknown error'}`);
|
|
498
|
+
}
|
|
499
|
+
const enableRes = await this.httpRequest('/json/system/enableToken', {
|
|
500
|
+
applicationToken: appToken,
|
|
501
|
+
token: loginRes.result.token,
|
|
502
|
+
});
|
|
503
|
+
if (!enableRes || enableRes.ok !== true) {
|
|
504
|
+
throw new DSSError(`Could not enable application token: ${(enableRes && enableRes.message) || 'unknown error'}`);
|
|
505
|
+
}
|
|
506
|
+
this.appToken = appToken;
|
|
507
|
+
return appToken;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Normalizes a single event from the DSS so that consumers can rely on
|
|
511
|
+
* source/properties being objects. Returns null for unusable entries.
|
|
512
|
+
*
|
|
513
|
+
* @param event raw event as delivered by the DSS - deliberately any, this is
|
|
514
|
+
* unvalidated input and validating it is exactly what this function is for
|
|
515
|
+
* @returns normalized event
|
|
516
|
+
*/
|
|
517
|
+
static normalizeEvent(event) {
|
|
518
|
+
if (!event || typeof event !== 'object' || typeof event.name !== 'string' || !event.name) {
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
const source = event.source && typeof event.source === 'object' ? event.source : {};
|
|
522
|
+
const properties = event.properties && typeof event.properties === 'object' ? event.properties : {};
|
|
523
|
+
// TempFix: dSID ist eigentlich eine dSUID
|
|
524
|
+
if (source.dsid !== undefined && source.dSUID === undefined) {
|
|
525
|
+
source.dSUID = source.dsid;
|
|
526
|
+
}
|
|
527
|
+
// TempFix: Schreibfehler
|
|
528
|
+
if (properties.sceneId !== undefined && properties.sceneID === undefined) {
|
|
529
|
+
properties.sceneID = properties.sceneId;
|
|
530
|
+
}
|
|
531
|
+
// The guard above proved event.name is a non-empty string, but the spread widens
|
|
532
|
+
// it back to any - name it explicitly so the returned shape really is a DssEvent
|
|
533
|
+
return { ...event, name: event.name, source, properties };
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Returns the channel of a subscription id, creating it on demand.
|
|
537
|
+
*
|
|
538
|
+
* All event names of a channel share ONE subscription id and therefore ONE long-poll:
|
|
539
|
+
* the DSS delivers every event of a subscription id through the same event/get.
|
|
540
|
+
* That keeps exactly one open connection to the DSS instead of one per event name.
|
|
541
|
+
*
|
|
542
|
+
* @param subscriptionId subscription id of the channel
|
|
543
|
+
* @param [timeout] long-poll timeout in ms
|
|
544
|
+
* @returns the channel record
|
|
545
|
+
*/
|
|
546
|
+
ensureChannel(subscriptionId, timeout) {
|
|
547
|
+
const key = String(subscriptionId);
|
|
548
|
+
if (!this.eventChannels[key]) {
|
|
549
|
+
this.eventChannels[key] = {
|
|
550
|
+
subscriptionId,
|
|
551
|
+
timeout: timeout || this.subScriptionTimeout,
|
|
552
|
+
// errorCount belongs to the channel: a failing event/get concerns every
|
|
553
|
+
// event name on it, so counting it once is what the limit is about.
|
|
554
|
+
errorCount: 0,
|
|
555
|
+
retryTimer: null,
|
|
556
|
+
polling: false,
|
|
557
|
+
lastPollTime: 0,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
else if (timeout) {
|
|
561
|
+
this.eventChannels[key].timeout = timeout;
|
|
562
|
+
}
|
|
563
|
+
return this.eventChannels[key];
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* @returns the channel or null if it does not exist
|
|
567
|
+
*/
|
|
568
|
+
getChannel(subscriptionId) {
|
|
569
|
+
return this.eventChannels[String(subscriptionId)] || null;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* All event names that are currently registered on one subscription id.
|
|
573
|
+
*
|
|
574
|
+
* @returns event names
|
|
575
|
+
*/
|
|
576
|
+
channelEventNames(subscriptionId) {
|
|
577
|
+
return Object.keys(this.subscriptions).filter(eventName => this.subscriptions[eventName].subscriptionId === subscriptionId);
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Readable name of a channel for log messages and the eventError event.
|
|
581
|
+
*/
|
|
582
|
+
channelLabel(subscriptionId) {
|
|
583
|
+
const eventNames = this.channelEventNames(subscriptionId);
|
|
584
|
+
return eventNames.length ? eventNames.join(', ') : `subscription ${subscriptionId}`;
|
|
585
|
+
}
|
|
586
|
+
clearEventRetry(subscriptionId) {
|
|
587
|
+
const channel = this.getChannel(subscriptionId);
|
|
588
|
+
if (channel && channel.retryTimer) {
|
|
589
|
+
clearTimeout(channel.retryTimer);
|
|
590
|
+
channel.retryTimer = null;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Schedules exactly one retry timer per channel using a bounded exponential backoff.
|
|
595
|
+
*/
|
|
596
|
+
scheduleEventRetry(subscriptionId, action) {
|
|
597
|
+
const channel = this.getChannel(subscriptionId);
|
|
598
|
+
if (!channel || this.stopped) {
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
this.clearEventRetry(subscriptionId);
|
|
602
|
+
const delay = Math.min(EVENT_RETRY_BASE_DELAY * 2 ** Math.max(0, channel.errorCount - 1), EVENT_RETRY_MAX_DELAY);
|
|
603
|
+
channel.retryTimer = setTimeout(() => {
|
|
604
|
+
const current = this.getChannel(subscriptionId);
|
|
605
|
+
if (current) {
|
|
606
|
+
current.retryTimer = null;
|
|
607
|
+
}
|
|
608
|
+
if (!current || this.stopped) {
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
action();
|
|
612
|
+
}, delay);
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Handles a polling or re-subscribe failure of one channel: counts the error,
|
|
616
|
+
* emits eventError once the limit is reached, otherwise schedules a retry.
|
|
617
|
+
*
|
|
618
|
+
* @param subscriptionId subscription id of the channel
|
|
619
|
+
* @param err error of the failed request
|
|
620
|
+
* @param context short description used for logging
|
|
621
|
+
*/
|
|
622
|
+
handleEventFailure(subscriptionId, err, context) {
|
|
623
|
+
const channel = this.getChannel(subscriptionId);
|
|
624
|
+
if (!channel || this.stopped) {
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
channel.errorCount = (channel.errorCount || 0) + 1;
|
|
628
|
+
const message = (0, configUtils_1.errorMessage)(err);
|
|
629
|
+
const label = this.channelLabel(subscriptionId);
|
|
630
|
+
this.options.logger &&
|
|
631
|
+
this.options.logger.warn(`Error on ${context} for events ${label} (${channel.errorCount}): ${message}`);
|
|
632
|
+
if (channel.errorCount > MAX_EVENT_ERRORS) {
|
|
633
|
+
this.clearEventRetry(subscriptionId);
|
|
634
|
+
return void this.emit('eventError', label, channel.errorCount, `Too many errors on ${context} for ${label}: ${message}`);
|
|
635
|
+
}
|
|
636
|
+
// A lost subscription (e.g. after a DSS restart) needs a re-subscribe before polling makes sense again
|
|
637
|
+
const needsResubscribe = channel.errorCount >= 2 || err.status === 500;
|
|
638
|
+
this.scheduleEventRetry(subscriptionId, () => {
|
|
639
|
+
if (needsResubscribe) {
|
|
640
|
+
// Every name of the channel has to be registered again: the DSS loses the
|
|
641
|
+
// whole subscription id, not just the name whose poll happened to fail.
|
|
642
|
+
this.resubscribeChannel(subscriptionId, subErr => {
|
|
643
|
+
if (subErr) {
|
|
644
|
+
this.handleEventFailure(subscriptionId, subErr, 're-subscribing');
|
|
645
|
+
}
|
|
646
|
+
else {
|
|
647
|
+
this.options.logger && this.options.logger.info(`Successfully resubscribed to ${label}`);
|
|
648
|
+
this.pollChannel(subscriptionId);
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
this.pollChannel(subscriptionId);
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Subscribes every event name of a channel again, e.g. after the DSS dropped the
|
|
659
|
+
* subscription. Does not start the poll - the caller decides.
|
|
660
|
+
*
|
|
661
|
+
* @param subscriptionId subscription id of the channel
|
|
662
|
+
* @param [callback] called with the first error, if any
|
|
663
|
+
*/
|
|
664
|
+
resubscribeChannel(subscriptionId, callback) {
|
|
665
|
+
const eventNames = this.channelEventNames(subscriptionId);
|
|
666
|
+
if (!eventNames.length) {
|
|
667
|
+
return void (callback && setImmediate(() => callback(null)));
|
|
668
|
+
}
|
|
669
|
+
let open = eventNames.length;
|
|
670
|
+
const errs = [];
|
|
671
|
+
const finish = (err) => {
|
|
672
|
+
if (err) {
|
|
673
|
+
errs.push(err);
|
|
674
|
+
}
|
|
675
|
+
if (!--open) {
|
|
676
|
+
callback && callback(errs.length ? errs[0] : null);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
eventNames.forEach(eventName => this.requestAsync('event', 'subscribe', { subscriptionID: subscriptionId, name: eventName }).then(() => finish(null), err => finish(err)));
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* The long-poll of one channel. Delivers the events of every subscribed name.
|
|
683
|
+
*/
|
|
684
|
+
pollChannel(subscriptionId) {
|
|
685
|
+
const channel = this.getChannel(subscriptionId);
|
|
686
|
+
if (!channel || this.stopped || channel.polling) {
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
channel.polling = true;
|
|
690
|
+
channel.lastPollTime = Date.now();
|
|
691
|
+
// HTTP timeout needs to be longer than the long-polling timeout of the DSS
|
|
692
|
+
this.requestAsync('event', 'get', { subscriptionID: channel.subscriptionId, timeout: channel.timeout },
|
|
693
|
+
// No retry: event/get consumes the pending events on the DSS, repeating it
|
|
694
|
+
// after a lost answer would drop them. Failures go through the backoff below.
|
|
695
|
+
{ timeout: channel.timeout + 15000, eventPoll: true, retryOnConnectionError: false }).then(events => {
|
|
696
|
+
const current = this.getChannel(subscriptionId);
|
|
697
|
+
if (current) {
|
|
698
|
+
current.polling = false;
|
|
699
|
+
}
|
|
700
|
+
if (!current || this.stopped) {
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
current.errorCount = 0;
|
|
704
|
+
const rawEvents = (events && events.result && events.result.events) || [];
|
|
705
|
+
if (Array.isArray(rawEvents)) {
|
|
706
|
+
rawEvents.forEach((rawEvent) => {
|
|
707
|
+
// One broken event must not prevent the remaining events of this response
|
|
708
|
+
try {
|
|
709
|
+
const event = DSS.normalizeEvent(rawEvent);
|
|
710
|
+
if (!event) {
|
|
711
|
+
this.options.logger &&
|
|
712
|
+
this.options.logger.debug(`Ignoring unusable event on subscription ${subscriptionId}: ${JSON.stringify(rawEvent)}`);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (this.getChannel(subscriptionId)) {
|
|
716
|
+
this.onActivity && this.onActivity('event', event.name);
|
|
717
|
+
this.emit(event.name, event);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
catch (err) {
|
|
721
|
+
this.options.logger &&
|
|
722
|
+
this.options.logger.warn(`Error while handling event on subscription ${subscriptionId}: ${(0, configUtils_1.errorMessage)(err)}`);
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
setImmediate(() => this.pollChannel(subscriptionId));
|
|
727
|
+
}, err => {
|
|
728
|
+
const current = this.getChannel(subscriptionId);
|
|
729
|
+
if (current) {
|
|
730
|
+
current.polling = false;
|
|
731
|
+
}
|
|
732
|
+
this.handleEventFailure(subscriptionId, err, 'polling');
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Registers one event name on the DSS without starting the poll.
|
|
737
|
+
*/
|
|
738
|
+
registerEventSubscription(eventName, subscriptionId, timeout) {
|
|
739
|
+
return this.requestAsync('event', 'subscribe', { subscriptionID: subscriptionId, name: eventName }).then(() => {
|
|
740
|
+
if (this.stopped) {
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
this.subscriptions[eventName] = { subscriptionId, timeout };
|
|
744
|
+
// The channel keeps its errorCount on purpose. A successful event/subscribe
|
|
745
|
+
// says nothing about event/get: if subscribing works but polling keeps
|
|
746
|
+
// failing (e.g. HTTP 500 on every event/get), resetting here would keep the
|
|
747
|
+
// counter below the limit forever - the adapter would stay green while
|
|
748
|
+
// re-subscribing every few seconds and never processing an event again.
|
|
749
|
+
// Only a successful event/get clears the counter, see pollChannel().
|
|
750
|
+
this.ensureChannel(subscriptionId, timeout);
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
subscribeEvent(eventName, subscriptionId, timeout, callback) {
|
|
754
|
+
this.registerEventSubscription(eventName, subscriptionId, timeout).then(() => {
|
|
755
|
+
if (!this.stopped) {
|
|
756
|
+
this.pollChannel(subscriptionId);
|
|
757
|
+
}
|
|
758
|
+
callback && callback(null);
|
|
759
|
+
}, err => {
|
|
760
|
+
callback && callback(err);
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Subscribes all given event names on ONE subscription id and then starts the single
|
|
765
|
+
* long-poll of that channel.
|
|
766
|
+
*
|
|
767
|
+
* Polling deliberately starts only after the last subscription: a poll that is already
|
|
768
|
+
* running when a name is added would not have to deliver its events.
|
|
769
|
+
*
|
|
770
|
+
* @param eventNames one or more names of DSS events
|
|
771
|
+
* @param [subscriptionId] subscription id for all names, default subScriptionId
|
|
772
|
+
* @param [timeout] long-poll timeout in ms
|
|
773
|
+
* @param [callback] called when done
|
|
774
|
+
*/
|
|
775
|
+
subscribeEvents(eventNames, subscriptionId, timeout, callback) {
|
|
776
|
+
// Legacy signatures: the callback may take the place of the id or of the timeout
|
|
777
|
+
let done = callback;
|
|
778
|
+
if (typeof subscriptionId === 'function') {
|
|
779
|
+
done = subscriptionId;
|
|
780
|
+
subscriptionId = undefined;
|
|
781
|
+
timeout = undefined;
|
|
782
|
+
}
|
|
783
|
+
if (typeof timeout === 'function') {
|
|
784
|
+
done = timeout;
|
|
785
|
+
timeout = undefined;
|
|
786
|
+
}
|
|
787
|
+
const finalCallback = done;
|
|
788
|
+
const pollTimeout = typeof timeout === 'number' ? timeout : this.subScriptionTimeout;
|
|
789
|
+
const channelId = typeof subscriptionId === 'number' ? subscriptionId : this.subScriptionId;
|
|
790
|
+
const names = Array.isArray(eventNames) ? eventNames : [eventNames];
|
|
791
|
+
if (!names.length) {
|
|
792
|
+
return void (finalCallback && setImmediate(() => finalCallback(null)));
|
|
793
|
+
}
|
|
794
|
+
let toSubscribe = names.length;
|
|
795
|
+
const errs = [];
|
|
796
|
+
const finish = (err) => {
|
|
797
|
+
if (err) {
|
|
798
|
+
errs.push(err);
|
|
799
|
+
}
|
|
800
|
+
if (!--toSubscribe) {
|
|
801
|
+
// Not a single name got through: without a channel there is nothing to poll
|
|
802
|
+
if (!this.stopped && this.getChannel(channelId)) {
|
|
803
|
+
this.pollChannel(channelId);
|
|
804
|
+
}
|
|
805
|
+
finalCallback && finalCallback(errs.length ? errs : null);
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
names.forEach(eventName => this.registerEventSubscription(eventName, channelId, pollTimeout).then(() => finish(null), err => finish(err)));
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Unsubscribes the channel an event name belongs to.
|
|
812
|
+
*
|
|
813
|
+
* The DSS does not remove a single name: event/unsubscribe drops the whole
|
|
814
|
+
* subscription id. The local registration therefore follows the DSS and removes every
|
|
815
|
+
* name of that channel instead of pretending the remaining ones were still delivered.
|
|
816
|
+
*
|
|
817
|
+
* Measured against a dSS20 1.19.13 instead of assumed, because everything the unload
|
|
818
|
+
* does rests on it: two names were subscribed to one id, one of them unsubscribed, and
|
|
819
|
+
* the id was gone. The dSS says so itself - the next event/get answered "Event
|
|
820
|
+
* subscription token not found ... token:4711 m_subscriptions.size():0". So the single
|
|
821
|
+
* request unsubscribeAllEvents() sends really does release all nine event names.
|
|
822
|
+
*/
|
|
823
|
+
unsubscribeEvent(eventName, callback) {
|
|
824
|
+
const sub = this.subscriptions[eventName];
|
|
825
|
+
if (!sub) {
|
|
826
|
+
return void (callback && callback(null));
|
|
827
|
+
}
|
|
828
|
+
const subscriptionId = sub.subscriptionId;
|
|
829
|
+
this.clearEventRetry(subscriptionId);
|
|
830
|
+
this.channelEventNames(subscriptionId).forEach(name => delete this.subscriptions[name]);
|
|
831
|
+
delete this.eventChannels[String(subscriptionId)];
|
|
832
|
+
this.requestAsync('event', 'unsubscribe', { subscriptionID: subscriptionId, name: eventName }).then(() => {
|
|
833
|
+
callback && callback(null);
|
|
834
|
+
}, err => {
|
|
835
|
+
callback && callback(err);
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Unsubscribes every channel - one request per subscription id, not per event name.
|
|
840
|
+
*
|
|
841
|
+
* @param [callback] gets the time the last long-poll runs until
|
|
842
|
+
*/
|
|
843
|
+
unsubscribeAllEvents(callback) {
|
|
844
|
+
let lastPollEnd = 0;
|
|
845
|
+
const channels = Object.keys(this.eventChannels).map(key => this.eventChannels[key]);
|
|
846
|
+
let openChannels = channels.length;
|
|
847
|
+
if (!openChannels) {
|
|
848
|
+
this.subscriptions = {};
|
|
849
|
+
this.eventChannels = {};
|
|
850
|
+
return void (callback && callback(0));
|
|
851
|
+
}
|
|
852
|
+
const finish = () => {
|
|
853
|
+
if (!--openChannels) {
|
|
854
|
+
this.subscriptions = {};
|
|
855
|
+
this.eventChannels = {};
|
|
856
|
+
callback && callback(lastPollEnd);
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
channels.forEach(channel => {
|
|
860
|
+
const pollEnd = (channel.lastPollTime || 0) + channel.timeout;
|
|
861
|
+
if (pollEnd > lastPollEnd) {
|
|
862
|
+
lastPollEnd = pollEnd;
|
|
863
|
+
}
|
|
864
|
+
this.clearEventRetry(channel.subscriptionId);
|
|
865
|
+
const [eventName] = this.channelEventNames(channel.subscriptionId);
|
|
866
|
+
if (!eventName) {
|
|
867
|
+
return void setImmediate(finish);
|
|
868
|
+
}
|
|
869
|
+
this.requestAsync('event', 'unsubscribe', {
|
|
870
|
+
subscriptionID: channel.subscriptionId,
|
|
871
|
+
name: eventName,
|
|
872
|
+
}).then(finish, finish);
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
exports.DSS = DSS;
|
|
877
|
+
//# sourceMappingURL=dss.js.map
|