forked from openiap/opencore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.ts
More file actions
3807 lines (3692 loc) · 210 KB
/
Copy pathDatabaseConnection.ts
File metadata and controls
3807 lines (3692 loc) · 210 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { MongoClient, ObjectID, Db, Binary, InsertOneWriteOpResult, MapReduceOptions, CollectionInsertOneOptions, GridFSBucket, ChangeStream, CollectionAggregationOptions, MongoClientOptions, ReplaceOneOptions } from "mongodb";
import { Crypt } from "./Crypt";
import { Config } from "./Config";
import { TokenUser, Base, WellknownIds, Rights, NoderedUtil, mapFunc, finalizeFunc, reduceFunc, Ace, UpdateOneMessage, UpdateManyMessage, InsertOrUpdateOneMessage, Role, Rolemember, User, Customer, WatchEventMessage, Workitem, WorkitemQueue, QueryOptions } from "@openiap/openflow-api";
import { OAuthProvider } from "./OAuthProvider";
import { ValueRecorder } from "@opentelemetry/api-metrics"
import { Span } from "@opentelemetry/api";
import { Logger } from "./Logger";
const { JSONPath } = require('jsonpath-plus');
import events = require("events");
import { amqpwrapper } from "./amqpwrapper";
import { WebSocketServer } from "./WebSocketServer";
import { clsstream } from "./WebSocketServerClient";
import { SocketMessage } from "./SocketMessage";
import { LoginProvider } from "./LoginProvider";
import { WebServer } from "./WebServer";
// tslint:disable-next-line: typedef
const safeObjectID = (s: string | number | ObjectID) => ObjectID.isValid(s) ? new ObjectID(s) : null;
const isoDatePattern = new RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);
const jsondiffpatch = require('jsondiffpatch').create({
objectHash: function (obj, index) {
// try to find an id property, otherwise just use the index in the array
return obj.name || obj.id || obj._id || '$$index:' + index;
}
});
export type GetDocumentVersionOptions = {
collectionname: string,
id: string,
version: number,
jwt?: string,
decrypt?: boolean,
}
export type GetLatestDocumentVersionOptions = {
collectionname: string,
id: string,
jwt?: string,
decrypt?: boolean,
}
export class DatabaseConnection extends events.EventEmitter {
private mongodburl: string;
private cli: MongoClient;
public db: Db;
private _dbname: string;
// public static ot_mongodb_query_count: Counter;
public static mongodb_query: ValueRecorder;
public static mongodb_aggregate: ValueRecorder;
public static mongodb_insert: ValueRecorder;
public static mongodb_insertmany: ValueRecorder;
public static mongodb_update: ValueRecorder;
public static mongodb_updatemany: ValueRecorder;
public static mongodb_replace: ValueRecorder;
public static mongodb_delete: ValueRecorder;
public static mongodb_deletemany: ValueRecorder;
// public static semaphore = Auth.Semaphore(1);
public registerGlobalWatches: boolean = true;
public queuemonitoringhandle: NodeJS.Timeout = null;
public queuemonitoringpaused: boolean = false;
public queuemonitoringlastrun: Date = new Date();
constructor(mongodburl: string, dbname: string, registerGlobalWatches: boolean) {
super();
this._dbname = dbname;
this.mongodburl = mongodburl;
if (!NoderedUtil.IsNullEmpty(registerGlobalWatches)) this.registerGlobalWatches = registerGlobalWatches;
if (!NoderedUtil.IsNullUndefinded(Logger.otel) && !NoderedUtil.IsNullUndefinded(Logger.otel.meter)) {
DatabaseConnection.mongodb_query = Logger.otel.meter.createValueRecorder('openflow_mongodb_query_seconds', {
description: 'Duration for mongodb queries',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_aggregate = Logger.otel.meter.createValueRecorder('openflow_mongodb_aggregate_seconds', {
description: 'Duration for mongodb aggregates',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_insert = Logger.otel.meter.createValueRecorder('openflow_mongodb_insert_seconds', {
description: 'Duration for mongodb inserts',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_insertmany = Logger.otel.meter.createValueRecorder('openflow_mongodb_insertmany_seconds', {
description: 'Duration for mongodb insert many',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_update = Logger.otel.meter.createValueRecorder('openflow_mongodb_update_seconds', {
description: 'Duration for mongodb updates',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_updatemany = Logger.otel.meter.createValueRecorder('openflow_mongodb_updatemany_seconds', {
description: 'Duration for mongodb update many',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_replace = Logger.otel.meter.createValueRecorder('openflow_mongodb_replace_seconds', {
description: 'Duration for mongodb replaces',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_delete = Logger.otel.meter.createValueRecorder('openflow_mongodb_delete_seconds', {
description: 'Duration for mongodb deletes',
boundaries: Logger.otel.default_boundaries
});
DatabaseConnection.mongodb_deletemany = Logger.otel.meter.createValueRecorder('openflow_mongodb_deletemany_seconds', {
description: 'Duration for mongodb deletemanys',
boundaries: Logger.otel.default_boundaries
});
}
}
static toArray(iterator): Promise<any[]> {
return new Promise((resolve, reject) => {
iterator.toArray((err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
public isConnected: boolean = false;
async shutdown() {
try {
if (!NoderedUtil.IsNullUndefinded(this.queuemonitoringhandle)) {
clearTimeout(this.queuemonitoringhandle);
}
if (this.cli) {
this.cli.removeAllListeners();
await this.cli.close(true);
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "shutdown", error);
}
}
public replicat: string = null;
public streams: clsstream[] = [];
/**
* Connect to MongoDB
* @returns Promise<void>
*/
async connect(parent: Span = undefined): Promise<void> {
if (this.cli !== null && this.cli !== undefined && this.isConnected) {
return;
}
const span: Span = Logger.otel.startSubSpan("db.connect", parent);
this.streams = [];
span?.addEvent("connecting to mongodb");
Logger.instanse.info("DatabaseConnection", "connect", "Connecting to mongodb");
const options: MongoClientOptions = { minPoolSize: Config.mongodb_minpoolsize, autoReconnect: false, useNewUrlParser: true, useUnifiedTopology: true };
this.cli = await MongoClient.connect(this.mongodburl, options);
Logger.instanse.info("DatabaseConnection", "connect", "Connected to mongodb");
span?.addEvent("Connected to mongodb");
Logger.instanse.silly("DatabaseConnection", "connect", "Really connected to mongodb");
const errEvent = (error) => {
this.isConnected = false;
Logger.instanse.error("DatabaseConnection", "connect", error);
this.emit("disconnected");
}
const closeEvent = () => {
this.isConnected = false;
Logger.instanse.silly("DatabaseConnection", "connect", "Disconnected from mongodb");
this.emit("disconnected");
}
this.cli
.on('error', errEvent)
.on('parseError', errEvent)
.on('timeout', errEvent)
.on('close', closeEvent);
this.db = this.cli.db(this._dbname);
try {
var topology = (this.cli as any).topology;
if (topology.s.description.type == "Single" || topology.s.description.type == "single") {
Config.supports_watch = false;
} else {
Config.supports_watch = true;
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "connect", error);
}
Logger.instanse.debug("DatabaseConnection", "connect", "supports_watch: " + Config.supports_watch);
if (Config.supports_watch) {
let collections = await DatabaseConnection.toArray(this.db.listCollections());
collections = collections.filter(x => x.name.indexOf("system.") === -1);
if (this.registerGlobalWatches) {
for (var c = 0; c < collections.length; c++) {
if (collections[c].type != "collection") continue;
if (collections[c].name == "fs.files" || collections[c].name == "fs.chunks") continue;
this.registerGlobalWatch(collections[c].name, span);
}
}
}
// if (this.queuemonitoringhandle == null && Config.workitem_queue_monitoring_enabled) {
// this.queuemonitoringpaused = false;
// this.queuemonitoringhandle = setTimeout(this.queuemonitoring.bind(this), Config.workitem_queue_monitoring_interval);
// }
this.isConnected = true;
Logger.otel.endSpan(span);
this.emit("connected");
}
async queuemonitoring() {
try {
if (!this.isConnected == true) return;
if (this.queuemonitoringpaused) return;
const jwt = Crypt.rootToken();
var pipeline: any[] = [];
pipeline.push({ "$match": { state: "new", "_type": "workitem", "nextrun": { "$lte": new Date(new Date().toISOString()) } } });
pipeline.push({ "$group": { _id: "$wiq", "count": { "$sum": 1 } } });
pipeline.push({
"$graphLookup":
{
from: 'mq',
startWith: '$_id',
connectFromField: '_id',
connectToField: 'name',
as: 'queue',
maxDepth: 1,
restrictSearchWithMatch: {
"$or": [
{ robotqueue: { "$exists": true, $ne: null } },
{ amqpqueue: { "$exists": true, $ne: null } }
]
}
}
});
pipeline.push({ "$match": { "queue": { $size: 1 } } });
var results: any[] = await this.aggregate(pipeline, "workitems", jwt, null, null);
this.queuemonitoringlastrun = new Date();
if (results.length > 0) Logger.instanse.verbose("DatabaseConnection", "queuemonitoring", "[workitems] found " + results.length + " queues with pending workitems");
for (var i = 0; i < results.length; i++) {
if (results[i].count > 0 && results[i].queue.length > 0) {
const wiq: WorkitemQueue = results[i].queue[0];
const payload = {
command: "invoke",
workflowid: wiq.workflowid,
data: { payload: {} }
}
if ("(Empty)")
if (!NoderedUtil.IsNullEmpty(wiq.robotqueue) && !NoderedUtil.IsNullEmpty(wiq.workflowid)) {
if (wiq.robotqueue.toLowerCase() != "(empty)" && wiq.workflowid.toLowerCase() != "(empty)") {
Logger.instanse.verbose("DatabaseConnection", "queuemonitoring", "[workitems] Send invoke message to robot queue " + wiq.workflowid);
let expiration = (Config.amqp_requeue_time / 2, 10) | 0;
if (expiration < 500) expiration = 500;
await amqpwrapper.Instance().send(null, wiq.robotqueue, payload, expiration, null, null, 2);
}
}
if (!NoderedUtil.IsNullEmpty(wiq.amqpqueue)) {
if (wiq.amqpqueue.toLowerCase() != "(empty)") {
Logger.instanse.verbose("DatabaseConnection", "queuemonitoring", "[workitems] Send invoke message to amqp queue " + wiq.amqpqueue);
let expiration = (Config.amqp_requeue_time / 2, 10) | 0;
if (expiration < 500) expiration = 500;
await amqpwrapper.Instance().send(null, wiq.amqpqueue, payload, expiration, null, null, 2);
}
}
}
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "queuemonitoring", error);
}
finally {
this.queuemonitoringhandle = setTimeout(this.queuemonitoring.bind(this), Config.workitem_queue_monitoring_interval);
}
}
registerGlobalWatch(collectionname: string, parent: Span) {
if (!this.registerGlobalWatches) return;
const span: Span = Logger.otel.startSubSpan("registerGlobalWatch", parent);
try {
span?.setAttribute("collectionname", collectionname);
var exists = this.streams.filter(x => x.collectionname == collectionname);
if (exists.length > 0) return;
if (collectionname.endsWith("_hist")) return;
// if (collectionname == "users") return;
if (collectionname == "dbusage") return;
if (collectionname == "audit") return;
Logger.instanse.verbose("DatabaseConnection", "registerGlobalWatch", "register global watch for " + collectionname + " collection");
var stream = new clsstream();
stream.collectionname = collectionname;
stream.stream = this.db.collection(collectionname).watch([], { fullDocument: 'updateLookup' });
(stream.stream as any).on("error", err => {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", err);
});
(stream.stream as any).on("change", async (next) => {
try {
var _id = next.documentKey._id;
if (next.operationType == 'update' && collectionname == "users") {
if (next.updateDescription.updatedFields.hasOwnProperty("_heartbeat")) return;
if (next.updateDescription.updatedFields.hasOwnProperty("lastseen")) return;
if (next.updateDescription.updatedFields.hasOwnProperty("_rpaheartbeat")) return;
if (next.updateDescription.updatedFields.hasOwnProperty("_webheartbeat")) return;
if (next.updateDescription.updatedFields.hasOwnProperty("_noderedheartbeat")) return;
if (next.updateDescription.updatedFields.hasOwnProperty("_powershellheartbeat")) return;
}
var item = next.fullDocument;
var _type = "";
if (collectionname == "config" && NoderedUtil.IsNullUndefinded(item)) {
item = await this.GetLatestDocumentVersion({ collectionname, id: _id, jwt: Crypt.rootToken() }, null);
}
if (!NoderedUtil.IsNullUndefinded(item)) {
_type = item._type;
if (collectionname == "mq") {
// DBHelper.clearCache("watch detected change in " + collectionname + " collection for a " + _type + " " + item.name);
await Logger.DBHelper.memoryCache.del("mq" + item._id);
if (_type == "exchange") await Logger.DBHelper.memoryCache.del("exchangename_" + item.name);
if (_type == "queue") await Logger.DBHelper.memoryCache.del("queuename_" + item.name);
}
if (collectionname == "users" && (_type == "user" || _type == "role" || _type == "customer")) {
Logger.DBHelper.clearCache("watch detected change in " + collectionname + " collection for a " + _type + " " + item.name);
// await DBHelper.memoryCache.del("users" + item._id);
// if (_type == "role") {
// var role: Role = item as Role;
// await DBHelper.memoryCache.del("rolename_" + item.name);
// // this.WellknownIdsArray.indexOf(item._id) == -1
// if (!NoderedUtil.IsNullUndefinded(role.members) && role.members.length > 0 && item._id != WellknownIds.users) {
// for (let i = 0; i < role.members.length; i++) {
// let member = role.members[i];
// await DBHelper.memoryCache.del("users" + member._id);
// await DBHelper.memoryCache.del("username_" + member.name);
// await DBHelper.memoryCache.del("rolename_" + member.name);
// }
// }
// } else {
// await DBHelper.memoryCache.del("username_" + item.name);
// }
}
if (collectionname == "config" && (_type == "restriction" || _type == "resource")) {
Logger.DBHelper.clearCache("watch detected change in " + collectionname + " collection for a " + _type + " " + item.name);
}
if (collectionname == "config" && _type == "provider") {
await Logger.DBHelper.ClearProviders();
await LoginProvider.RegisterProviders(WebServer.app, Config.baseurl());
}
if (collectionname === "config" && _type === "oauthclient") {
setTimeout(() => OAuthProvider.LoadClients(), 1000);
}
}
let doContinue: boolean = false;
if (WebSocketServer._clients)
for (let i = 0; i < WebSocketServer._clients.length; i++) {
let client = WebSocketServer._clients[i];
if (NoderedUtil.IsNullUndefinded(client.user)) continue;
let ids = Object.keys(client.watches);
for (let y = 0; y < ids.length; y++) {
var stream = client.watches[ids[y]];
if (stream.collectionname != collectionname) continue;
doContinue = true;
break;
}
if (doContinue == true) break;
}
if (!doContinue) return;
if (NoderedUtil.IsNullEmpty(item)) item = await this.GetLatestDocumentVersion({ collectionname, id: _id, jwt: Crypt.rootToken() }, null);
if (NoderedUtil.IsNullEmpty(item)) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", "Missing fullDocument and could not find historic version for " + _id + " in " + collectionname);
return;
} else {
Logger.instanse.verbose("DatabaseConnection", "registerGlobalWatch", "[" + collectionname + "][" + next.operationType + "] " + _id + " " + item.name);
}
try {
for (var i = 0; i < WebSocketServer._clients.length; i++) {
var client = WebSocketServer._clients[i];
if (NoderedUtil.IsNullUndefinded(client.user)) continue;
const tuser: TokenUser = TokenUser.From(client.user);
try {
if (DatabaseConnection.hasAuthorization(tuser, item, Rights.read)) {
try {
var ids = Object.keys(client.watches);
for (var y = 0; y < ids.length; y++) {
let notify: boolean = false;
var stream = client.watches[ids[y]];
if (stream.collectionname != collectionname) {
} else if (NoderedUtil.IsNullUndefinded(stream.aggregates)) {
notify = true;
} else if (stream.aggregates.length == 0) {
notify = true;
} else if (typeof stream.aggregates[0] === 'object') {
// This is fucking ugly, but need something to be backward compatible with older version of OpenRPA and Nodered Nodes
var match = stream.aggregates[0]["$match"];
if (NoderedUtil.IsNullUndefinded(match)) { continue; }
var keys = Object.keys(match);
var ismatch = true;
keys.forEach(key => {
var targetkey = key.replace("fullDocument.", "");
var value = match[key];
if (value = "{'$exists': true}") {
if (!item.hasOwnProperty(targetkey)) ismatch = false;
} else {
if (item[targetkey] != value) ismatch = false;
}
});
if (ismatch) notify = true;
} else {
if (Array.isArray(stream.aggregates)) {
for (let p = 0; p < stream.aggregates.length; p++) {
let path = stream.aggregates[p];
if (!NoderedUtil.IsNullEmpty(path)) {
try {
const result = JSONPath({ path, json: { a: item } });
if (result && result.length > 0) notify = true;
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
}
}
} else {
if (!NoderedUtil.IsNullEmpty(stream.aggregates)) {
try {
let path = stream.aggregates;
const result = JSONPath({ path, json: { a: item } });
if (result && result.length > 0) notify = true;
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
}
}
// Watch all
if (stream.aggregates.length == 0) {
notify = true;
}
}
if (notify) {
Logger.instanse.verbose("DatabaseConnection", "registerGlobalWatch", "Notify " + tuser.username + " of " + next.operationType + " " + item.name);
// Logger.instanse.info("Watch: " + JSON.stringify(next.documentKey));
const msg: SocketMessage = SocketMessage.fromcommand("watchevent");
const q = new WatchEventMessage();
q.id = ids[y];
q.result = next;
if (q.result && !q.result.fullDocument) q.result.fullDocument = item;
if (q.result && q.result.fullDocument) {
q.result.fullDocument = Config.db.decryptentity(q.result.fullDocument);
}
msg.data = JSON.stringify(q);
client._socketObject.send(msg.tojson(), (err) => {
if (err) Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", err);
});
}
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
} catch (error) {
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
}
});
this.streams.push(stream);
} catch (error) {
span?.recordException(error);
Logger.instanse.error("DatabaseConnection", "registerGlobalWatch", error);
return false;
} finally {
Logger.otel.endSpan(span);
}
}
async ListCollections(jwt: string): Promise<any[]> {
let result = await DatabaseConnection.toArray(this.db.listCollections());
result = result.filter(x => x.name.indexOf("system.") === -1);
result.sort((a, b) => a.name.localeCompare(b.name, undefined, {sensitivity: 'base'}))
await Crypt.verityToken(jwt);
return result;
}
async DropCollection(collectionname: string, jwt: string, parent: Span): Promise<void> {
const span: Span = Logger.otel.startSubSpan("db.DropCollection", parent);
try {
const user: TokenUser = await Crypt.verityToken(jwt);
span?.setAttribute("collection", collectionname);
span?.setAttribute("username", user.username);
if (!user.HasRoleName("admins")) throw new Error("Access denied, droppping collection " + collectionname);
if (["workflow", "entities", "config", "audit", "jslog", "openrpa", "nodered", "openrpa_instances", "forms", "workflow_instances", "users"].indexOf(collectionname) > -1) throw new Error("Access denied, dropping reserved collection " + collectionname);
const mongodbspan: Span = Logger.otel.startSubSpan("mongodb.dropCollection", span);
await this.db.dropCollection(collectionname);
Logger.otel.endSpan(mongodbspan);
} catch (error) {
span?.recordException(error);
throw error;
} finally {
Logger.otel.endSpan(span);
}
}
WellknownIdsArray: string[] = [
WellknownIds.root,
WellknownIds.admins,
WellknownIds.users,
WellknownIds.robots,
WellknownIds.nodered_users,
WellknownIds.nodered_admins,
WellknownIds.nodered_api_users,
WellknownIds.filestore_users,
WellknownIds.filestore_admins,
WellknownIds.robot_users,
WellknownIds.robot_admins,
WellknownIds.personal_nodered_users,
WellknownIds.robot_agent_users,
WellknownIds.customer_admins,
WellknownIds.resellers
]
WellknownNamesArray: string[] = [
"root",
"admins",
"users",
"user",
"admin",
"nodered",
"administrator",
"robots",
"robot",
"nodered_users",
"nodered_admins",
"nodered_api_users",
"filestore_users",
"filestore_admins",
"robot_users",
"robot_admins",
"personal_nodered_users",
"robot_agent_users",
"customer_admins",
"nodered users",
"nodered admins",
"nodered api_users",
"filestore users",
"filestore admins",
"robot users",
"robot admins",
"personal nodered users",
"robot agent users",
"customer admins",
"reseller", "resellers"
]
async CleanACL<T extends Base>(item: T, user: TokenUser, collection: string, parent: Span): Promise<T> {
const span: Span = Logger.otel.startSubSpan("db.CleanACL", parent);
try {
if (item._acl.length > Config.max_ace_count) {
// remove excesive acls
const newacl = item._acl.slice(0, Config.max_ace_count);
item._acl = newacl;
}
for (let i = item._acl.length - 1; i >= 0; i--) {
{
const ace = item._acl[i];
if (typeof ace.rights === "string") {
const b = new Binary(Buffer.from(ace.rights, "base64"), 0);
(ace.rights as any) = b;
}
if (this.WellknownIdsArray.indexOf(ace._id) === -1) {
let _user = await Logger.DBHelper.FindById(ace._id, null, span);
if (NoderedUtil.IsNullUndefinded(_user)) {
const ot_end = Logger.otel.startTimer();
const mongodbspan: Span = Logger.otel.startSubSpan("mongodb.find", span);
mongodbspan?.setAttribute("collection", "users");
if (Config.otel_trace_include_query) mongodbspan?.setAttribute("query", JSON.stringify({ _id: ace._id }));
const arr = await this.db.collection("users").find({ _id: ace._id }).project({ name: 1 }).limit(1).toArray();
mongodbspan?.setAttribute("results", arr.length);
Logger.otel.endSpan(mongodbspan);
Logger.otel.endTimer(ot_end, DatabaseConnection.mongodb_query, { collection: "users" });
// if (arr.length > 0) {
// _user = arr[0];
// await Auth.AddUser(_user, ace._id, "cleanacl");
// }
}
if (NoderedUtil.IsNullUndefinded(_user)) {
item._acl.splice(i, 1);
} else { ace.name = _user.name; }
}
}
}
let addself: boolean = true;
item._acl.forEach(ace => {
if (ace._id === user._id) addself = false;
if (addself) {
user.roles.forEach(role => {
if (ace._id === role._id) addself = false;
});
}
})
if (addself) {
Base.addRight(item, user._id, user.name, [Rights.full_control], false);
}
item = this.ensureResource(item, collection);
} catch (error) {
span?.recordException(error);
}
Logger.otel.endSpan(span);
return item;
}
async Cleanmembers<T extends Role>(item: T, original: T): Promise<T> {
const removed: Rolemember[] = [];
if (NoderedUtil.IsNullUndefinded(item.members)) item.members = [];
if (original != null && Config.update_acl_based_on_groups === true) {
for (let i = original.members.length - 1; i >= 0; i--) {
const ace = original.members[i];
const exists = item.members.filter(x => x._id === ace._id);
if (exists.length === 0) removed.push(ace);
}
}
let doadd: boolean = true;
if ((item as any).hidemembers == true) {
doadd = false;
for (let i = item.members.length - 1; i >= 0; i--) {
const ace = item.members[i];
removed.push(ace);
}
}
const multi_tenant_skip: string[] = [WellknownIds.users, WellknownIds.filestore_users,
WellknownIds.nodered_api_users, WellknownIds.nodered_users, WellknownIds.personal_nodered_users,
WellknownIds.robot_users, WellknownIds.robots, WellknownIds.customer_admins, WellknownIds.resellers];
if (item._id === WellknownIds.users && Config.multi_tenant) {
doadd = false;
}
if (doadd) {
for (let i = item.members.length - 1; i >= 0; i--) {
{
const ace = item.members[i];
const exists = item.members.filter(x => x._id === ace._id);
if (exists.length > 1) {
item.members.splice(i, 1);
} else {
const ot_end = Logger.otel.startTimer();
const arr = await this.db.collection("users").find({ _id: ace._id }).project({ name: 1, _acl: 1, _type: 1 }).limit(1).toArray();
Logger.otel.endTimer(ot_end, DatabaseConnection.mongodb_query, { collection: "users" });
if (arr.length === 0) {
item.members.splice(i, 1);
}
else if (Config.update_acl_based_on_groups === true) {
ace.name = arr[0].name;
if (Config.multi_tenant && multi_tenant_skip.indexOf(item._id) > -1) {
// when multi tenant don't allow members of common user groups to see each other
Logger.instanse.silly("DatabaseConnection", "Cleanmembers", "Running in multi tenant mode, skip adding permissions for " + item.name);
} else if (arr[0]._type === "user") {
let u: User = User.assign(arr[0]);
if (!Base.hasRight(u, item._id, Rights.read)) {
Logger.instanse.silly("DatabaseConnection", "Cleanmembers", "Assigning " + item.name + " read permission to " + u.name);
Base.addRight(u, item._id, item.name, [Rights.read], false);
u = this.ensureResource(u, "users");
const _ot_end1 = Logger.otel.startTimer();
await this.db.collection("users").updateOne({ _id: u._id }, { $set: { _acl: u._acl } });
Logger.otel.endTimer(_ot_end1, DatabaseConnection.mongodb_update, { collection: "users" });
} else if (u._id != item._id) {
Logger.instanse.silly("DatabaseConnection", "Cleanmembers", item.name + " allready exists on " + u.name);
}
} else if (arr[0]._type === "role") {
let r: Role = Role.assign(arr[0]);
if (r._id !== WellknownIds.admins && r._id !== WellknownIds.users && !Base.hasRight(r, item._id, Rights.read)) {
Logger.instanse.silly("DatabaseConnection", "Cleanmembers", "Assigning " + item.name + " read permission to " + r.name);
Base.addRight(r, item._id, item.name, [Rights.read], false);
r = this.ensureResource(r, "users");
const _ot_end2 = Logger.otel.startTimer();
await this.db.collection("users").updateOne({ _id: r._id }, { $set: { _acl: r._acl } });
Logger.otel.endTimer(_ot_end2, DatabaseConnection.mongodb_update, { collection: "users" });
} else if (r._id != item._id) {
Logger.instanse.silly("DatabaseConnection", "Cleanmembers", item.name + " allready exists on " + r.name);
}
}
}
}
}
}
}
if (Config.update_acl_based_on_groups) {
for (let i = removed.length - 1; i >= 0; i--) {
const ace = removed[i];
if (NoderedUtil.IsNullUndefinded(ace)) continue;
const ot_end = Logger.otel.startTimer();
const arr = await this.db.collection("users").find({ _id: ace._id }).project({ name: 1, _acl: 1, _type: 1 }).limit(1).toArray();
Logger.otel.endTimer(ot_end, DatabaseConnection.mongodb_query, { collection: "users" });
if (arr.length === 1 && item._id != WellknownIds.admins && item._id != WellknownIds.root) {
if (Config.multi_tenant && multi_tenant_skip.indexOf(item._id) > -1 && !((item as any).hidemembers == true)) {
// when multi tenant don't allow members of common user groups to see each other
Logger.instanse.verbose("DatabaseConnection", "Cleanmembers", "Running in multi tenant mode, skip removing permissions for " + item.name);
} else if (arr[0]._type === "user") {
let u: User = User.assign(arr[0]);
if (Base.hasRight(u, item._id, Rights.read)) {
Base.removeRight(u, item._id, [Rights.read]);
// was read the only right ? then remove it
const right = Base.getRight(u, item._id, false);
if (NoderedUtil.IsNullUndefinded(right) || (!Ace.isBitSet(right, 3) && !Ace.isBitSet(right, 4) && !Ace.isBitSet(right, 5))) {
Base.removeRight(u, item._id, [Rights.full_control]);
u = this.ensureResource(u, "users");
Logger.instanse.debug("DatabaseConnection", "Cleanmembers", "Removing " + item.name + " read permissions from " + u.name);
const _ot_end1 = Logger.otel.startTimer();
await this.db.collection("users").updateOne({ _id: u._id }, { $set: { _acl: u._acl } });
Logger.otel.endTimer(_ot_end1, DatabaseConnection.mongodb_update, { collection: "users" });
}
} else {
Logger.instanse.debug("DatabaseConnection", "Cleanmembers", "No need to remove " + item.name + " read permissions from " + u.name);
}
} else if (arr[0]._type === "role") {
let r: Role = Role.assign(arr[0]);
if (Base.hasRight(r, item._id, Rights.read)) {
Base.removeRight(r, item._id, [Rights.read]);
// was read the only right ? then remove it
const right = Base.getRight(r, item._id, false);
if (NoderedUtil.IsNullUndefinded(right) || (!Ace.isBitSet(right, 3) && !Ace.isBitSet(right, 4) && !Ace.isBitSet(right, 5))) {
Base.removeRight(r, item._id, [Rights.full_control]);
r = this.ensureResource(r, "users");
Logger.instanse.debug("DatabaseConnection", "Cleanmembers", "Removing " + item.name + " read permissions from " + r.name);
const _ot_end2 = Logger.otel.startTimer();
await this.db.collection("users").updateOne({ _id: r._id }, { $set: { _acl: r._acl } });
Logger.otel.endTimer(_ot_end2, DatabaseConnection.mongodb_update, { collection: "users" });
}
} else {
Logger.instanse.debug("DatabaseConnection", "Cleanmembers", "No need to remove " + item.name + " read permissions from " + r.name);
}
}
}
}
}
return item;
}
/**
* Send a query to the database.
* @param {any} query MongoDB Query
* @param {Object} projection MongoDB projection
* @param {number} top Limit result to X number of results
* @param {number} skip Skip a number of records (Paging)
* @param {Object|string} orderby MongoDB orderby, or string with name of a single field to orderby
* @param {string} collectionname What collection to query
* @param {string} jwt JWT of user who is making the query, to limit results based on permissions
* @param {boolean} decrypt Decrypt encrypted data, default: true
* @returns Promise<T[]> Array of results
*/
// tslint:disable-next-line: max-line-length
async query<T extends Base>(options: QueryOptions, parent: Span): Promise<T[]> {
let { query, projection, top, skip, orderby, collectionname, jwt, queryas, hint, decrypt } = Object.assign({
top: 100,
skip: 0,
decrypt: true
}, options);
const span: Span = Logger.otel.startSubSpan("db.query", parent);
let _query: Object = {};
try {
await this.connect(span);
let mysort: Object = {};
if (orderby) {
span?.addEvent("parse orderby");
if (typeof orderby === "string" || orderby instanceof String) {
let neworderby = null;
try {
if (orderby.indexOf("{") > -1) {
neworderby = JSON.parse((orderby as string));
mysort = neworderby;
}
} catch (error) {
span?.addEvent("Parsing order by failed");
span?.recordException(error);
span?.setAttribute("failedorderby", orderby as string);
Logger.instanse.error("DatabaseConnection", "query", error);
}
if (NoderedUtil.IsNullUndefinded(neworderby)) mysort[(orderby as string)] = 1;
} else {
mysort = orderby;
}
span?.setAttribute("orderby", JSON.stringify(mysort));
}
let myhint: Object = {};
if (hint) {
span?.addEvent("parse hint");
if (typeof hint === "string" || hint instanceof String) {
let newhint = null;
try {
if (hint.indexOf("{") > -1) {
newhint = JSON.parse((hint as string));
myhint = newhint;
}
} catch (error) {
span?.addEvent("Parsing hint by failed");
span?.recordException(error);
span?.setAttribute("failedhint", hint as string);
Logger.instanse.error("DatabaseConnection", "query", error);
}
if (NoderedUtil.IsNullUndefinded(newhint)) myhint[(hint as string)] = 1;
} else {
myhint = hint;
}
span?.setAttribute("hint", JSON.stringify(myhint));
}
if (projection) {
span?.addEvent("parse projection");
if (typeof projection === "string" || projection instanceof String) {
projection = JSON.parse((projection as string));
}
span?.setAttribute("projection", JSON.stringify(projection));
}
if (query !== null && query !== undefined) {
span?.addEvent("parse query");
let json: any = query;
if (typeof json !== 'string' && !(json instanceof String)) {
json = JSON.stringify(json, (key, value) => {
if (value instanceof RegExp)
return ("__REGEXP " + value.toString());
else
return value;
});
}
query = JSON.parse(json, (key, value) => {
if (typeof value === 'string' && value.match(isoDatePattern)) {
return new Date(value); // isostring, so cast to js date
} else if (value != null && value != undefined && value.toString().indexOf("__REGEXP ") === 0) {
const m = value.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/);
return new RegExp(m[1], m[2] || "");
} else
return value; // leave any other value as-is
});
if (Config.otel_trace_include_query) span?.setAttribute("query", JSON.stringify(query));
}
if (NoderedUtil.IsNullUndefinded(query)) {
throw new Error("Query is mandatory");
}
const keys: string[] = Object.keys(query);
for (let key of keys) {
if (key === "_id") {
const id: string = query._id;
const safeid = safeObjectID(id);
if (safeid !== null && safeid !== undefined) {
delete query._id;
query.$or = [{ _id: id }, { _id: safeObjectID(id) }];
}
}
}
span?.addEvent("verityToken");
const user: TokenUser = await Crypt.verityToken(jwt);
span?.addEvent("getbasequery");
if (collectionname === "files") { collectionname = "fs.files"; }
if (DatabaseConnection.usemetadata(collectionname)) {
let impersonationquery;
if (!NoderedUtil.IsNullEmpty(queryas)) impersonationquery = await this.getbasequeryuserid(user, queryas, "metadata._acl", [Rights.read], span);
if (!NoderedUtil.IsNullEmpty(queryas) && !NoderedUtil.IsNullUndefinded(impersonationquery)) {
_query = { $and: [query, this.getbasequery(user, "metadata._acl", [Rights.read]), impersonationquery] };
} else {
_query = { $and: [query, this.getbasequery(user, "metadata._acl", [Rights.read])] };
}
projection = null;
} else {
let impersonationquery: any;
if (!NoderedUtil.IsNullEmpty(queryas)) impersonationquery = await this.getbasequeryuserid(user, queryas, "_acl", [Rights.read], span)
if (!NoderedUtil.IsNullEmpty(queryas) && !NoderedUtil.IsNullUndefinded(impersonationquery)) {
_query = { $and: [query, this.getbasequery(user, "_acl", [Rights.read]), impersonationquery] };
} else {
_query = { $and: [query, this.getbasequery(user, "_acl", [Rights.read])] };
}
}
if (!top) { top = 500; }
if (!skip) { skip = 0; }
span?.setAttribute("collection", collectionname);
span?.setAttribute("username", user.username);
span?.setAttribute("top", top);
span?.setAttribute("skip", skip);
let arr: T[] = [];
const ot_end = Logger.otel.startTimer();
const mongodbspan: Span = Logger.otel.startSubSpan("mongodb.find", span);
let _pipe = this.db.collection(collectionname).find(_query);
if (projection != null) {
_pipe = _pipe.project(projection);
}
_pipe = _pipe.sort(mysort as any).limit(top).skip(skip);
if (hint) {
_pipe = _pipe.hint(myhint);
}
arr = await _pipe.toArray();
mongodbspan?.setAttribute("results", arr.length);
Logger.otel.endSpan(mongodbspan);
Logger.otel.endTimer(ot_end, DatabaseConnection.mongodb_query, { collection: collectionname });
if (decrypt) for (let i: number = 0; i < arr.length; i++) { arr[i] = this.decryptentity(arr[i]); }
DatabaseConnection.traversejsondecode(arr);
Logger.instanse.debug("DatabaseConnection", "query", "[" + user.username + "][" + collectionname + "] query gave " + arr.length + " results ");
return arr;
} catch (error) {
Logger.instanse.error("DatabaseConnection", "query", "[" + collectionname + "] query error " + (error.message ? error.message : error));
span?.recordException(error);
throw error;
} finally {
Logger.otel.endSpan(span);
}
}
async GetLatestDocumentVersion<T extends Base>(options: GetLatestDocumentVersionOptions, parent: Span): Promise<T> {
let { collectionname, id, jwt, decrypt } = Object.assign({
decrypt: true
}, options);
let result: T = await this.getbyid<T>(id, collectionname, jwt, true, parent);
if (result) return result;
const basehist = await this.query<any>({ query: { id: id }, projection: { _version: 1 }, top: 1, orderby: { _version: -1 }, collectionname: collectionname + "_hist", jwt: Crypt.rootToken(), decrypt }, parent);
if (basehist.length > 0) {
let result: T = null;
try {
result = await this.GetDocumentVersion({ collectionname, id, version: basehist[0]._version, jwt: Crypt.rootToken(), decrypt }, parent)
return result;
} catch (error) {
}
}
return null;
}
async GetDocumentVersion<T extends Base>(options: GetDocumentVersionOptions, parent: Span): Promise<T> {
let { collectionname, id, version, jwt, decrypt } = Object.assign({
decrypt: true
}, options);
const span: Span = Logger.otel.startSubSpan("db.GetDocumentVersion", parent);
try {
let result: T = await this.getbyid<T>(id, collectionname, jwt, false, span);
if (NoderedUtil.IsNullUndefinded(result)) {
const subbasehist = await this.query<any>({ query: { id: id, item: { $exists: true, $ne: null } }, top: 1, orderby: { _version: -1 }, collectionname: collectionname + "_hist", decrypt: false, jwt }, span);
if (subbasehist.length === 0) return null;
result = subbasehist[0];
result._version = version + 1;
}
if (result._version > version) {
const rootjwt = Crypt.rootToken()
const basehist = await this.query<any>(
{
query: { id: id, item: { $exists: true, $ne: null }, "_version": { $lte: version } },
top: null, orderby: { _version: -1 }, collectionname: collectionname + "_hist", jwt: rootjwt,
decrypt: false
}, span);
result = basehist[0].item;
const baseversion = basehist[0]._version;
const history = await this.query<T>({
query: { id: id, "_version": { $gt: baseversion, $lte: version } },
top: Config.history_delta_count, orderby: { _version: 1 }, collectionname: collectionname + "_hist", jwt: rootjwt,
decrypt: false
}, span);
for (let delta of history) {
if (delta != null && (delta as any).delta != null) {
result = jsondiffpatch.patch(result, (delta as any).delta);
}
}
}
if (decrypt && !NoderedUtil.IsNullUndefinded(result)) result = this.decryptentity(result);
return result;
} catch (error) {
Logger.instanse.error("DatabaseConnection", "GetDocumentVersion", error);
span?.recordException(error);
throw error;
} finally {
Logger.otel.endSpan(span);
}
}
/**
* Get a single item based on id
* @param {string} id Id to search for
* @param {string} collectionname Collection to search
* @param {string} jwt JWT of user who is making the query, to limit results based on permissions
* @returns Promise<T>
*/
async GetOne<T extends Base>(options: { query?: object, collectionname: string, orderby?: object, jwt?: string, decrypt?: boolean }, parent: Span): Promise<T> {
const span: Span = Logger.otel.startSubSpan("db.GetOne", parent);
if (NoderedUtil.IsNullUndefinded(options.jwt)) options.jwt = Crypt.rootToken();
if (NoderedUtil.IsNullUndefinded(options.decrypt)) options.decrypt = true;
if (NoderedUtil.IsNullUndefinded(options.query)) options.query = {};
const { query, collectionname, orderby, jwt, decrypt } = options;
try {
const arr: T[] = await this.query<T>({ query, collectionname, orderby, jwt, decrypt }, span);
if (arr === null || arr.length === 0) { return null; }
return arr[0];
} catch (error) {
span?.recordException(error);
throw error;
} finally {
Logger.otel.endSpan(span);
}
}
/**
* Get a single item based on id
* @param {string} id Id to search for
* @param {string} collectionname Collection to search
* @param {string} jwt JWT of user who is making the query, to limit results based on permissions
* @returns Promise<T>
*/
async getbyid<T extends Base>(id: string, collectionname: string, jwt: string, decrypt: boolean, parent: Span): Promise<T> {
const span: Span = Logger.otel.startSubSpan("db.getbyid", parent);
try {
if (id === null || id === undefined || id === "") { throw Error("Id cannot be null"); }
const query = { _id: id };
return this.GetOne({ query, collectionname, jwt, decrypt }, span)
} catch (error) {
span?.recordException(error);
throw error;