kuzzle-device-manager 0.4.8 → 0.4.9

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.
Files changed (61) hide show
  1. package/index.d.ts +4 -0
  2. package/index.js +17 -0
  3. package/lib/DeviceManagerPlugin.d.ts +100 -0
  4. package/lib/DeviceManagerPlugin.js +237 -0
  5. package/lib/controllers/AssetController.d.ts +7 -0
  6. package/lib/controllers/AssetController.js +53 -0
  7. package/lib/controllers/CRUDController.d.ts +34 -0
  8. package/lib/controllers/CRUDController.js +65 -0
  9. package/lib/controllers/DeviceController.d.ts +56 -0
  10. package/lib/controllers/DeviceController.js +218 -0
  11. package/lib/controllers/index.d.ts +3 -0
  12. package/lib/controllers/index.js +16 -0
  13. package/lib/core-classes/BatchProcessing/BatchController.d.ts +32 -0
  14. package/lib/core-classes/BatchProcessing/BatchController.js +86 -0
  15. package/lib/core-classes/BatchProcessing/BatchWriter.d.ts +110 -0
  16. package/lib/core-classes/BatchProcessing/BatchWriter.js +264 -0
  17. package/lib/core-classes/BatchProcessing/InstrumentablePromise.d.ts +6 -0
  18. package/lib/core-classes/BatchProcessing/InstrumentablePromise.js +13 -0
  19. package/lib/core-classes/BatchProcessing/index.d.ts +3 -0
  20. package/lib/core-classes/BatchProcessing/index.js +16 -0
  21. package/lib/core-classes/CustomMappings/AssetMappingsManager.d.ts +31 -0
  22. package/lib/core-classes/CustomMappings/AssetMappingsManager.js +79 -0
  23. package/lib/core-classes/CustomMappings/DeviceMappingsManager.d.ts +43 -0
  24. package/lib/core-classes/CustomMappings/DeviceMappingsManager.js +71 -0
  25. package/lib/core-classes/Decoder.d.ts +133 -0
  26. package/lib/core-classes/Decoder.js +166 -0
  27. package/lib/core-classes/DeviceManagerEngine.d.ts +21 -0
  28. package/lib/core-classes/DeviceManagerEngine.js +64 -0
  29. package/lib/core-classes/DeviceService.d.ts +41 -0
  30. package/lib/core-classes/DeviceService.js +264 -0
  31. package/lib/core-classes/MigrationService.d.ts +13 -0
  32. package/lib/core-classes/MigrationService.js +49 -0
  33. package/lib/core-classes/PayloadService.d.ts +43 -0
  34. package/lib/core-classes/PayloadService.js +191 -0
  35. package/lib/core-classes/index.d.ts +8 -0
  36. package/lib/core-classes/index.js +21 -0
  37. package/lib/models/BaseAsset.d.ts +56 -0
  38. package/lib/models/BaseAsset.js +58 -0
  39. package/lib/models/Catalog.d.ts +55 -0
  40. package/lib/models/Catalog.js +38 -0
  41. package/lib/models/Config.d.ts +33 -0
  42. package/lib/models/Config.js +26 -0
  43. package/lib/models/Device.d.ts +102 -0
  44. package/lib/models/Device.js +91 -0
  45. package/lib/models/index.d.ts +3 -0
  46. package/lib/models/index.js +16 -0
  47. package/lib/types/AssetsHistoryContent.d.ts +9 -0
  48. package/lib/types/AssetsHistoryContent.js +3 -0
  49. package/lib/types/BaseAssetContent.d.ts +8 -0
  50. package/lib/types/BaseAssetContent.js +3 -0
  51. package/lib/types/DeviceContent.d.ts +62 -0
  52. package/lib/types/DeviceContent.js +3 -0
  53. package/lib/types/Measure.d.ts +54 -0
  54. package/lib/types/Measure.js +3 -0
  55. package/lib/types/index.d.ts +3 -0
  56. package/lib/types/index.js +16 -0
  57. package/lib/utils/events.d.ts +8 -0
  58. package/lib/utils/events.js +17 -0
  59. package/lib/utils/index.d.ts +1 -0
  60. package/lib/utils/index.js +14 -0
  61. package/package.json +1 -1
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DeviceController = void 0;
7
+ const csvtojson_1 = __importDefault(require("csvtojson"));
8
+ const kuzzle_1 = require("kuzzle");
9
+ const CRUDController_1 = require("./CRUDController");
10
+ const models_1 = require("../models");
11
+ class DeviceController extends CRUDController_1.CRUDController {
12
+ constructor(plugin, deviceService) {
13
+ super(plugin, 'devices');
14
+ this.deviceService = deviceService;
15
+ this.definition = {
16
+ actions: {
17
+ update: {
18
+ handler: this.update.bind(this),
19
+ http: [{ verb: 'put', path: 'device-manager/:index/devices/:_id' }]
20
+ },
21
+ search: {
22
+ handler: this.search.bind(this),
23
+ http: [
24
+ { verb: 'post', path: 'device-manager/:index/devices/_search' },
25
+ { verb: 'get', path: 'device-manager/:index/devices/_search' }
26
+ ]
27
+ },
28
+ attachTenant: {
29
+ handler: this.attachTenant.bind(this),
30
+ http: [{ verb: 'put', path: 'device-manager/:index/devices/:_id/_attach' }]
31
+ },
32
+ mAttach: {
33
+ handler: this.mAttach.bind(this),
34
+ http: [{ verb: 'put', path: 'device-manager/devices/_mAttach' }]
35
+ },
36
+ detach: {
37
+ handler: this.detach.bind(this),
38
+ http: [{ verb: 'delete', path: 'device-manager/devices/:_id/_detach' }]
39
+ },
40
+ mDetach: {
41
+ handler: this.mDetach.bind(this),
42
+ http: [{ verb: 'put', path: 'device-manager/devices/_mDetach' }]
43
+ },
44
+ linkAsset: {
45
+ handler: this.linkAsset.bind(this),
46
+ http: [{ verb: 'put', path: 'device-manager/:index/devices/:_id/_link/:assetId' }]
47
+ },
48
+ mLink: {
49
+ handler: this.mLink.bind(this),
50
+ http: [{ verb: 'put', path: 'device-manager/devices/_mLink' }]
51
+ },
52
+ unlink: {
53
+ handler: this.unlink.bind(this),
54
+ http: [{ verb: 'delete', path: 'device-manager/:index/devices/:_id/_unlink' }]
55
+ },
56
+ mUnlink: {
57
+ handler: this.mUnlink.bind(this),
58
+ http: [{ verb: 'put', path: 'device-manager/devices/_mUnlink' }]
59
+ },
60
+ prunePayloads: {
61
+ handler: this.prunePayloads.bind(this),
62
+ http: [{ verb: 'delete', path: 'device-manager/devices/_prunePayloads' }]
63
+ },
64
+ }
65
+ };
66
+ }
67
+ get sdk() {
68
+ return this.context.accessors.sdk;
69
+ }
70
+ /**
71
+ * Attach a device to a tenant
72
+ */
73
+ async attachTenant(request) {
74
+ const tenantId = request.getIndex();
75
+ const deviceId = request.getId();
76
+ const document = { tenantId: tenantId, deviceId: deviceId };
77
+ const devices = await this.mGetDevice([document]);
78
+ await this.deviceService.mAttach(devices, [document], {
79
+ strict: true,
80
+ options: { ...request.input.args }
81
+ });
82
+ }
83
+ /**
84
+ * Attach multiple devices to multiple tenants
85
+ */
86
+ async mAttach(request) {
87
+ const { bulkData, strict } = await this.mParseRequest(request);
88
+ const devices = await this.mGetDevice(bulkData);
89
+ return this.deviceService.mAttach(devices, bulkData, {
90
+ strict,
91
+ options: { ...request.input.args }
92
+ });
93
+ }
94
+ /**
95
+ * Unattach a device from it's tenant
96
+ */
97
+ async detach(request) {
98
+ const deviceId = request.getId();
99
+ const document = { deviceId };
100
+ const devices = await this.mGetDevice([document]);
101
+ await this.deviceService.mDetach(devices, [document], {
102
+ strict: true,
103
+ options: { ...request.input.args }
104
+ });
105
+ }
106
+ /**
107
+ * Detach multiple devices from multiple tenants
108
+ */
109
+ async mDetach(request) {
110
+ const { bulkData, strict } = await this.mParseRequest(request);
111
+ const devices = await this.mGetDevice(bulkData);
112
+ return this.deviceService.mDetach(devices, bulkData, {
113
+ strict,
114
+ options: { ...request.input.args }
115
+ });
116
+ }
117
+ /**
118
+ * Link a device to an asset.
119
+ * @todo there is not restriction according to tenant index?
120
+ */
121
+ async linkAsset(request) {
122
+ const assetId = request.getString('assetId');
123
+ const deviceId = request.getId();
124
+ const document = { deviceId, assetId };
125
+ const devices = await this.mGetDevice([document]);
126
+ await this.deviceService.mLink(devices, [document], {
127
+ strict: true,
128
+ options: { ...request.input.args }
129
+ });
130
+ }
131
+ /**
132
+ * Link multiple devices to multiple assets.
133
+ */
134
+ async mLink(request) {
135
+ const { bulkData, strict } = await this.mParseRequest(request);
136
+ const devices = await this.mGetDevice(bulkData);
137
+ return this.deviceService.mLink(devices, bulkData, {
138
+ strict,
139
+ options: { ...request.input.args }
140
+ });
141
+ }
142
+ /**
143
+ * Unlink a device from an asset.
144
+ */
145
+ async unlink(request) {
146
+ const deviceId = request.getId();
147
+ const document = { deviceId };
148
+ const devices = await this.mGetDevice([document]);
149
+ await this.deviceService.mUnlink(devices, {
150
+ strict: true,
151
+ options: { ...request.input.args }
152
+ });
153
+ }
154
+ /**
155
+ * Unlink multiple device from multiple assets.
156
+ */
157
+ async mUnlink(request) {
158
+ const { bulkData, strict } = await this.mParseRequest(request);
159
+ const devices = await this.mGetDevice(bulkData);
160
+ return this.deviceService.mUnlink(devices, {
161
+ strict,
162
+ options: { ...request.input.args }
163
+ });
164
+ }
165
+ /**
166
+ * Clean payload collection for a time period
167
+ */
168
+ async prunePayloads(request) {
169
+ const body = request.getBody();
170
+ const date = new Date().setDate(new Date().getDate() - body.days || 7);
171
+ const filter = [];
172
+ filter.push({
173
+ range: {
174
+ '_kuzzle_info.createdAt': {
175
+ lt: date
176
+ }
177
+ }
178
+ });
179
+ if (body.deviceModel) {
180
+ filter.push({ term: { deviceModel: body.deviceModel } });
181
+ }
182
+ if (body.keepInvalid) {
183
+ filter.push({ term: { valid: true } });
184
+ }
185
+ return await this.as(request.context.user).bulk.deleteByQuery(this.config.adminIndex, 'payloads', { query: { bool: { filter } } });
186
+ }
187
+ async mGetDevice(devices) {
188
+ const deviceIds = devices.map(doc => doc.deviceId);
189
+ const result = await this.sdk.document.mGet(this.config.adminIndex, 'devices', deviceIds);
190
+ return result.successes.map((document) => new models_1.Device(document._source, document._id));
191
+ }
192
+ async mParseRequest(request) {
193
+ const body = request.input.body;
194
+ let bulkData;
195
+ if (body.csv) {
196
+ const lines = await (0, csvtojson_1.default)({ delimiter: 'auto' })
197
+ .fromString(body.csv);
198
+ bulkData = lines.map(({ tenantId, deviceId, assetId }) => ({
199
+ tenantId,
200
+ deviceId,
201
+ assetId
202
+ }));
203
+ }
204
+ else if (body.records) {
205
+ bulkData = body.records;
206
+ }
207
+ else if (body.deviceIds) {
208
+ bulkData = body.deviceIds.map((deviceId) => ({ deviceId }));
209
+ }
210
+ else {
211
+ throw new kuzzle_1.BadRequestError(`Malformed request missing property csv, records, deviceIds`);
212
+ }
213
+ const strict = request.getBoolean('strict');
214
+ return { strict, bulkData };
215
+ }
216
+ }
217
+ exports.DeviceController = DeviceController;
218
+ //# sourceMappingURL=DeviceController.js.map
@@ -0,0 +1,3 @@
1
+ export * from './AssetController';
2
+ export * from './CRUDController';
3
+ export * from './DeviceController';
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./AssetController"), exports);
14
+ __exportStar(require("./CRUDController"), exports);
15
+ __exportStar(require("./DeviceController"), exports);
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ import { DocumentController, EmbeddedSDK, JSONObject } from 'kuzzle';
2
+ import { BatchWriter } from './BatchWriter';
3
+ /**
4
+ * Overload of the document controller.
5
+ *
6
+ * This class replace the following methods and will execute them by batch using
7
+ * m* actions:
8
+ * - create
9
+ * - replace
10
+ * - createOrReplace
11
+ * - update
12
+ * - get
13
+ * - exists
14
+ * - delete
15
+ *
16
+ * The m* actions returns the successes in the same order as in the request so
17
+ * since we have the index of the single document inside the array of documents
18
+ * sent to the action, we can retrieve the corresponding result in the array of
19
+ * results.
20
+ *
21
+ */
22
+ export declare class BatchController extends DocumentController {
23
+ writer: BatchWriter;
24
+ constructor(sdk: EmbeddedSDK, writer: BatchWriter);
25
+ create(index: string, collection: string, content: JSONObject, _id?: string, options?: JSONObject): Promise<any>;
26
+ replace(index: string, collection: string, _id: string, content: JSONObject, options?: JSONObject): Promise<any>;
27
+ createOrReplace(index: string, collection: string, _id: string, content: JSONObject, options?: JSONObject): Promise<any>;
28
+ update(index: string, collection: string, _id: string, changes: JSONObject, options?: JSONObject): Promise<any>;
29
+ get(index: string, collection: string, id: string): Promise<any>;
30
+ exists(index: string, collection: string, id: string): Promise<any>;
31
+ delete(index: string, collection: string, id: string): Promise<any>;
32
+ }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BatchController = void 0;
4
+ const kuzzle_1 = require("kuzzle");
5
+ /**
6
+ * Overload of the document controller.
7
+ *
8
+ * This class replace the following methods and will execute them by batch using
9
+ * m* actions:
10
+ * - create
11
+ * - replace
12
+ * - createOrReplace
13
+ * - update
14
+ * - get
15
+ * - exists
16
+ * - delete
17
+ *
18
+ * The m* actions returns the successes in the same order as in the request so
19
+ * since we have the index of the single document inside the array of documents
20
+ * sent to the action, we can retrieve the corresponding result in the array of
21
+ * results.
22
+ *
23
+ */
24
+ class BatchController extends kuzzle_1.DocumentController {
25
+ constructor(sdk, writer) {
26
+ super(sdk);
27
+ this.writer = writer;
28
+ }
29
+ async create(index, collection, content, _id, options) {
30
+ const { idx, promise } = this.writer.addCreate(index, collection, content, _id, options);
31
+ const { successes } = await promise.promise;
32
+ return successes[idx];
33
+ }
34
+ async replace(index, collection, _id, content, options) {
35
+ const { idx, promise } = this.writer.addReplace(index, collection, content, _id, options);
36
+ const { successes, errors } = await promise.promise;
37
+ const error = errors.find(({ _id: id }) => id === _id);
38
+ if (error) {
39
+ throw new kuzzle_1.BadRequestError(`Cannot replace document "${_id}": ${error}`);
40
+ }
41
+ return successes[idx];
42
+ }
43
+ async createOrReplace(index, collection, _id, content, options) {
44
+ const { idx, promise } = this.writer.addCreateOrReplace(index, collection, content, _id, options);
45
+ const { successes, errors } = await promise.promise;
46
+ const error = errors.find(({ document }) => document._id === _id);
47
+ if (error) {
48
+ throw new kuzzle_1.BadRequestError(`Cannot create or replace document "${_id}": ${error}`);
49
+ }
50
+ return successes[idx];
51
+ }
52
+ async update(index, collection, _id, changes, options) {
53
+ const { idx, promise } = this.writer.addUpdate(index, collection, changes, _id, options);
54
+ const { successes, errors } = await promise.promise;
55
+ const error = errors.find(({ _id: id }) => id === _id);
56
+ if (error) {
57
+ throw new kuzzle_1.BadRequestError(`Cannot update document "${_id}": ${error}`);
58
+ }
59
+ return successes[idx];
60
+ }
61
+ async get(index, collection, id) {
62
+ const { promise } = this.writer.addGet(index, collection, undefined, id);
63
+ const { successes } = await promise.promise;
64
+ const document = successes.find(({ _id }) => _id === id);
65
+ if (!document) {
66
+ throw new kuzzle_1.NotFoundError(`Document ${id} not found`, 'services.storage.not_found');
67
+ }
68
+ return document;
69
+ }
70
+ async exists(index, collection, id) {
71
+ const { idx, promise } = this.writer.addExists(index, collection, undefined, id);
72
+ const { successes } = await promise.promise;
73
+ return successes[idx];
74
+ }
75
+ async delete(index, collection, id) {
76
+ const { idx, promise } = this.writer.addDelete(index, collection, undefined, id);
77
+ const { successes, errors } = await promise.promise;
78
+ const error = errors.find(({ _id }) => _id === id);
79
+ if (error) {
80
+ throw new kuzzle_1.NotFoundError(`Cannot delete document ${id}: ${error}`);
81
+ }
82
+ return successes[idx];
83
+ }
84
+ }
85
+ exports.BatchController = BatchController;
86
+ //# sourceMappingURL=BatchController.js.map
@@ -0,0 +1,110 @@
1
+ import { EmbeddedSDK, JSONObject } from 'kuzzle';
2
+ import { BatchController } from './BatchController';
3
+ import { InstrumentablePromise } from './InstrumentablePromise';
4
+ /**
5
+ * Map of index and collections with documents, options and associated promise
6
+ */
7
+ declare type IndexBuffer = {
8
+ [index: string]: {
9
+ [collection: string]: {
10
+ documents: Array<{
11
+ _id: string;
12
+ body: JSONObject;
13
+ }>;
14
+ promise: InstrumentablePromise;
15
+ options: JSONObject;
16
+ };
17
+ };
18
+ };
19
+ export declare class BatchBuffer {
20
+ indexes: IndexBuffer;
21
+ /**
22
+ * Add a document to the buffer of a specific collection
23
+ *
24
+ * @param index Index name
25
+ * @param collection Collection name
26
+ * @param body Document content
27
+ * @param _id Document ID
28
+ * @param options Option object passed to the m* action
29
+ *
30
+ * @returns An object containing the index of the array of results and a promise resolving to the array of results
31
+ */
32
+ add(index: string, collection: string, body: JSONObject, _id?: string, options?: JSONObject): {
33
+ idx: number;
34
+ promise: InstrumentablePromise;
35
+ };
36
+ }
37
+ /**
38
+ * This class handle buffers for every supported API action of the document controller:
39
+ * - create, update, createOrReplace, replace, get, exists, delete
40
+ *
41
+ * Each buffer is filled with documents to be write/get/delete into a collection.
42
+ *
43
+ * A timer will regularly execute the m* actions with the documents inside the buffers.
44
+ *
45
+ * If the interval is too big, buffers may contain too much documents for Kuzzle limits.
46
+ * (e.g. "limits.documentsWriteCount" is 200 by default)
47
+ */
48
+ export declare class BatchWriter {
49
+ private timer;
50
+ private sdk;
51
+ /**
52
+ * Timer interval to execute m* API actions
53
+ */
54
+ private interval;
55
+ /**
56
+ * Max write buffer size. (Should match "limits.documentsWriteCount")
57
+ */
58
+ private maxWriteBufferSize;
59
+ /**
60
+ * Max read buffer size. (Should match "limits.documentsReadCount")
61
+ */
62
+ private maxReadBufferSize;
63
+ private buffers;
64
+ /**
65
+ * Document Controller overload
66
+ */
67
+ document: BatchController;
68
+ get addCreate(): any;
69
+ get addUpdate(): any;
70
+ get addGet(): any;
71
+ get addExists(): any;
72
+ get addDelete(): any;
73
+ get addReplace(): any;
74
+ get addCreateOrReplace(): any;
75
+ /**
76
+ * @param sdk Connected SDK
77
+ * @param options.interval Timer interval in ms (50). Actions will be executed every {interval} ms
78
+ * @param options.maxWriteBufferSize Max write buffer size (200). (Should match "limits.documentsWriteCount")
79
+ * @param options.maxReadBufferSize Max read buffer size. (Should match "limits.documentsReadCount")
80
+ */
81
+ constructor(sdk: EmbeddedSDK, { interval, maxWriteBufferSize, maxReadBufferSize }?: {
82
+ interval?: number;
83
+ maxWriteBufferSize?: number;
84
+ maxReadBufferSize?: number;
85
+ });
86
+ /**
87
+ * Execute API actions with documents stored in the buffers.
88
+ */
89
+ execute(): Promise<void>;
90
+ /**
91
+ * Initialize the buffers and start the timer
92
+ */
93
+ begin(): void;
94
+ /**
95
+ * Execute pending actions from the buffers and stop the timer.
96
+ */
97
+ end(): Promise<void>;
98
+ /**
99
+ * Reset all the buffers
100
+ */
101
+ private prepareRound;
102
+ private sendCreateBuffer;
103
+ private sendUpdateBuffer;
104
+ private sendReplaceBuffer;
105
+ private sendCreateOrReplaceBuffer;
106
+ private sendGetBuffer;
107
+ private sendExistsBuffer;
108
+ private sendDeleteBuffer;
109
+ }
110
+ export {};