This repository has been archived by the owner on Aug 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_module.py
1490 lines (1418 loc) Β· 42.7 KB
/
base_module.py
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
from config import Config
from enums import Event, DELETE_STRATEGY
from data import Data
from utils import (
validate_doc,
InvalidAttrException,
MissingAttrException,
ConvertAttrException,
update_attr_values,
)
from classes import (
DictObj,
BaseModel,
Query,
InvalidAttrTypeException,
InvalidAttrTypeArgException,
LIMP_EVENTS,
LIMP_ENV,
Query,
LIMP_QUERY,
LIMP_DOC,
ATTR,
PERM,
EXTN,
ATTR_MOD,
CACHE,
CACHED_QUERY,
ANALYTIC
)
from base_method import BaseMethod
from typing import List, Dict, Union, Tuple, Callable, Any, TypedDict
from PIL import Image
from bson import ObjectId
import traceback, logging, datetime, re, sys, io, copy, asyncio
logger = logging.getLogger('limp')
class BaseModule:
collection: Union[str, bool]
proxy: str
attrs: Dict[str, ATTR]
diff: Union[bool, ATTR_MOD]
defaults: Dict[str, Any]
unique_attrs: List[str]
extns: Dict[str, EXTN]
privileges: List[str]
methods: TypedDict(
'METHODS',
permissions=List[PERM],
query_args=Dict[str, Union[ATTR, ATTR_MOD]],
doc_args=Dict[str, Union[ATTR, ATTR_MOD]],
get_method=bool,
post_method=bool,
watch_method=bool
)
cache: List[CACHE]
analytics: List[ANALYTIC]
package_name: str
module_name: str
def __init__(self):
if not getattr(self, 'collection', None):
self.collection = False
if not getattr(self, 'proxy', None):
self.proxy = False
if not getattr(self, 'attrs', None):
self.attrs = {}
if not getattr(self, 'diff', None):
self.diff = False
if not getattr(self, 'defaults', None):
self.defaults = {}
if not getattr(self, 'unique_attrs', None):
self.unique_attrs = []
if not getattr(self, 'extns', None):
self.extns = {}
if not getattr(self, 'privileges', None):
self.privileges = ['read', 'create', 'update', 'delete', 'admin']
if not getattr(self, 'methods', None):
self.methods = {}
if not getattr(self, 'cache', None):
self.cache = []
if not getattr(self, 'analytics', None):
self.analytics = []
Config.modules = {}
# [DOC] Populate package and module names for in-context use.
self.package_name = (
self.__module__.replace('modules.', '').upper().split('.')[0]
)
self.module_name = re.sub(
r'([A-Z])',
r'_\1',
self.__class__.__name__[0].lower() + self.__class__.__name__[1:],
).lower()
def _initialise(self) -> None:
# [DOC] Check for proxy
if self.proxy:
logger.debug(f'Module \'{self.module_name}\' is a proxy module. Updating.')
# [DOC] Copy regular attrs
self.collection = Config.modules[self.proxy].collection
self.attrs = copy.deepcopy(Config.modules[self.proxy].attrs)
self.diff = Config.modules[self.proxy].diff
self.defaults = copy.deepcopy(Config.modules[self.proxy].defaults)
self.unique_attrs = copy.deepcopy(Config.modules[self.proxy].unique_attrs)
self.extns = copy.deepcopy(Config.modules[self.proxy].extns)
self.privileges = copy.deepcopy(Config.modules[self.proxy].privileges)
# [DOC] Update methods from original module
for method in Config.modules[self.proxy].methods.keys():
# [DOC] Copy method attrs if not present in proxy
if method not in self.methods.keys():
if type(Config.modules[self.proxy].methods[method]) == dict:
self.methods[method] = copy.deepcopy(
Config.modules[self.proxy].methods[method]
)
elif type(Config.modules[self.proxy].methods[method]) == BaseMethod:
self.methods[method] = {
'permissions': copy.deepcopy(
Config.modules[self.proxy].methods[method].permissions
),
'query_args': copy.deepcopy(
Config.modules[self.proxy].methods[method].query_args
),
'doc_args': copy.deepcopy(
Config.modules[self.proxy].methods[method].doc_args
),
'get_method': Config.modules[self.proxy]
.methods[method]
.get_method,
}
# [DOC] Create methods functions in proxy module if not present
if not getattr(self, method, None):
setattr(
self,
method,
lambda self=self, skip_events=[], env={}, query=[], doc={}: getattr(
Config.modules[self.proxy], method
)(
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload={},
),
)
# [DOC] Check attrs for any invalid type
for attr in self.attrs.keys():
try:
logger.debug(
f'Attempting to validate Attr Type for \'{attr}\' of module \'{self.module_name}\'.'
)
ATTR.validate_type(attr_type=self.attrs[attr])
except InvalidAttrTypeException as e:
logger.error(
f'Invalid Attr Type for \'{attr}\' of module \'{self.module_name}\'. Original validation error: {str(e)}. Exiting.'
)
exit()
except InvalidAttrTypeArgException as e:
logger.error(
f'Invalid Attr Type Arg for \'{attr}\' of module \'{self.module_name}\'. Original validation error: {str(e)}. Exiting.'
)
exit()
# [DOC] Update default value
for default in self.defaults.keys():
if (
default == attr
or default.startswith(f'{attr}.')
or default.startswith(f'{attr}:')
):
logger.debug(
f'Updating default value for attr \'{attr}\' to: \'{self.defaults[default]}\''
)
update_attr_values(
attr=ATTR.DICT(dict=self.attrs),
value='default',
value_path=default,
value_val=self.defaults[default],
)
# [DOC] Update extn value
for extn in self.extns.keys():
if (
extn == attr
or extn.startswith(f'{attr}.')
or extn.startswith(f'{attr}:')
):
logger.debug(
f'Updating extn value for attr \'{extn}\' to: \'{self.extns[extn]}\''
)
update_attr_values(
attr=ATTR.DICT(dict=self.attrs),
value='extn',
value_path=extn,
value_val=self.extns[extn],
)
# [DOC] Abstract methods as BaseMethod objects
for method in self.methods.keys():
# [DOC] Check for existence of at least single permissions set per method
if not len(self.methods[method]['permissions']):
logger.error(
f'No permissions sets for method \'{method}\' of module \'{self.module_name}\'. Exiting.'
)
exit()
# [DOC] Check method query_args attr, set it or update it if required.
if 'query_args' not in self.methods[method].keys():
if method == 'create_file':
self.methods[method]['query_args'] = [
{'_id': ATTR.ID(), 'attr': ATTR.STR()}
]
elif method == 'delete_file':
self.methods[method]['query_args'] = [
{
'_id': ATTR.ID(),
'attr': ATTR.STR(),
'index': ATTR.INT(),
'name': ATTR.STR(),
}
]
else:
self.methods[method]['query_args'] = False
elif type(self.methods[method]['query_args']) == dict:
self.methods[method]['query_args'] = [
self.methods[method]['query_args']
]
# [DOC] Check method doc_args attr, set it or update it if required.
if 'doc_args' not in self.methods[method].keys():
if method == 'create_file':
self.methods[method]['doc_args'] = [{'file': ATTR.FILE()}]
else:
self.methods[method]['doc_args'] = False
elif type(self.methods[method]['doc_args']) == dict:
self.methods[method]['doc_args'] = [self.methods[method]['doc_args']]
# [DOC] Check method watch_method attr, set it or update it if required.
if (
'watch_method' not in self.methods[method].keys()
or self.methods[method]['watch_method'] == False
):
self.methods[method]['watch_method'] = False
# [DOC] Check method get_method attr, set it or update it if required.
if 'get_method' not in self.methods[method].keys():
self.methods[method]['get_method'] = False
elif self.methods[method]['get_method'] == True:
if not self.methods[method]['query_args']:
if method == 'retrieve_file':
self.methods[method]['query_args'] = [
{
'_id': ATTR.ID(),
'attr': ATTR.STR(),
'filename': ATTR.STR(),
},
{
'_id': ATTR.ID(),
'attr': ATTR.STR(),
'thumb': ATTR.STR(pattern=r'[0-9]+x[0-9]+'),
'filename': ATTR.STR(),
},
]
else:
self.methods[method]['query_args'] = [{}]
# [DOC] Check method post_method attr, set it or update it if required.
if 'post_method' not in self.methods[method].keys():
self.methods[method]['post_method'] = False
elif self.methods[method]['post_method'] == True:
if not self.methods[method]['query_args']:
self.methods[method]['query_args'] = [{}]
# [DOC] Check permissions sets for any invalid set
for permissions_set in self.methods[method]['permissions']:
if type(permissions_set) != PERM:
logger.error(
f'Invalid permissions set \'{permissions_set}\' of method \'{method}\' of module \'{self.module_name}\'. Exiting.'
)
exit()
# [DOC] Add default Doc Modifiers to prevent sys attrs from being modified
if method == 'update':
for attr in ['user', 'create_time']:
if attr not in permissions_set.doc_mod.keys():
permissions_set.doc_mod[attr] = None
elif permissions_set.doc_mod[attr] == True:
del permissions_set.doc_mod[attr]
# [DOC] Check invalid query_args, doc_args types
for arg_set in ['query', 'doc']:
if self.methods[method][f'{arg_set}_args']:
for args_set in self.methods[method][f'{arg_set}_args']:
for attr in args_set.keys():
try:
ATTR.validate_type(attr_type=args_set[attr])
except:
logger.error(
f'Invalid \'{arg_set}_args\' attr type for \'{attr}\' of set \'{args_set}\' of method \'{method}\' of module \'{self.module_name}\'. Exiting.'
)
exit()
# [DOC] Initlise method as BaseMethod
self.methods[method] = BaseMethod(
module=self,
method=method,
permissions=self.methods[method]['permissions'],
query_args=self.methods[method]['query_args'],
doc_args=self.methods[method]['doc_args'],
watch_method=self.methods[method]['watch_method'],
get_method=self.methods[method]['get_method'],
post_method=self.methods[method]['post_method'],
)
# [DOC] Check extns for invalid extnded attrs
for attr in self.extns.keys():
if type(self.extns[attr]) not in [EXTN, ATTR_MOD]:
logger.error(
f'Invalid extns attr \'{attr}\' of module \'{self.module_name}\'. Exiting.'
)
exit()
logger.debug(f'Initialised module {self.module_name}')
def status(
self, *, status: int, msg: str, args: Dict[str, Any] = None
) -> Dict[str, Any]:
status_dict = {'status': status, 'msg': msg, 'args': {}}
if args:
status_dict['args'] = args
if 'code' in status_dict['args'].keys():
status_dict['args'][
'code'
] = f'{self.package_name.upper()}_{self.module_name.upper()}_{status_dict["args"]["code"]}'
return status_dict
def __getattribute__(self, attr):
# [DOC] Module is not yet initialised, skip to return exact attr
try:
object.__getattribute__(self, 'methods')
except AttributeError:
return object.__getattribute__(self, attr)
# [DOC] Module is initialised attempt to check for methods
if attr in object.__getattribute__(self, 'methods').keys():
return object.__getattribute__(self, 'methods')[attr]
elif attr.startswith('_method_'):
return object.__getattribute__(self, attr.replace('_method_', ''))
else:
return object.__getattribute__(self, attr)
async def pre_read(
self,
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
LIMP_EVENTS, LIMP_ENV, Union[LIMP_QUERY, Query], LIMP_DOC, Dict[str, Any]
]:
return (skip_events, env, query, doc, payload)
async def on_read(
self,
results: Dict[str, Any],
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
Dict[str, Any],
LIMP_EVENTS,
LIMP_ENV,
Union[LIMP_QUERY, Query],
LIMP_DOC,
Dict[str, Any],
]:
return (results, skip_events, env, query, doc, payload)
async def read(
self,
skip_events: LIMP_EVENTS = [],
env: LIMP_ENV = {},
query: Union[LIMP_QUERY, Query] = [],
doc: LIMP_DOC = {},
) -> DictObj:
if Event.PRE not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module pre_read
pre_read = await Config.modules[self.proxy].pre_read(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_read) in [DictObj, dict]:
return pre_read
skip_events, env, query, doc, payload = pre_read
pre_read = await self.pre_read(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_read) in [DictObj, dict]:
return pre_read
skip_events, env, query, doc, payload = pre_read
else: payload = {}
# [DOC] Check for cache workflow instructins
if self.cache:
results = False
for cache_set in self.cache:
if (
cache_set.condition(skip_events=skip_events, env=env, query=query)
== True
):
cache_key = f'{str(query._query)}____{str(query._special)}'
if cache_key in cache_set.queries.keys():
if cache_set.period:
if (
cache_set.queries[cache_key].query_time
+ datetime.timedelta(seconds=cache_set.period)
) < datetime.datetime.utcnow():
if not results:
results = await Data.read(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
)
cache_set.queries[cache_key] = CACHED_QUERY(
results=results
)
else:
results = cache_set.queries[cache_key].results
results['cache'] = cache_set.queries[
cache_key
].query_time.isoformat()
else:
results = cache_set.queries[cache_key].results
results['cache'] = cache_set.queries[
cache_key
].query_time.isoformat()
else:
if not results:
results = await Data.read(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
)
cache_set.queries[cache_key] = CACHED_QUERY(results=results)
if not results:
results = await Data.read(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
skip_extn='$extn' in query or Event.EXTN in skip_events,
)
else:
results = await Data.read(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
skip_extn='$extn' in query or Event.EXTN in skip_events,
)
if Event.ON not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module on_read
on_read = await Config.modules[self.proxy].on_read(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_read) in [DictObj, dict]:
return on_read
results, skip_events, env, query, doc, payload = on_read
on_read = await self.on_read(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_read) in [DictObj, dict]:
return on_read
results, skip_events, env, query, doc, payload = on_read
# [DOC] if $attrs query arg is present return only required keys.
if '$attrs' in query:
query['$attrs'].insert(0, '_id')
for i in range(len(results['docs'])):
results['docs'][i] = BaseModel(
{
attr: results['docs'][i][attr]
for attr in query['$attrs']
if attr in results['docs'][i]._attrs()
}
)
return self.status(
status=200, msg=f'Found {results["count"]} docs.', args=results
)
async def pre_watch(
self,
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
LIMP_EVENTS, LIMP_ENV, Union[LIMP_QUERY, Query], LIMP_DOC, Dict[str, Any]
]:
return (skip_events, env, query, doc, payload)
async def on_watch(
self,
results: Dict[str, Any],
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
Dict[str, Any],
LIMP_EVENTS,
LIMP_ENV,
Union[LIMP_QUERY, Query],
LIMP_DOC,
Dict[str, Any],
]:
return (results, skip_events, env, query, doc, payload)
async def watch(
self,
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> DictObj:
if Event.PRE not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module pre_watch
pre_watch = await Config.modules[self.proxy].pre_watch(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_watch) in [DictObj, dict]:
yield pre_watch
skip_events, env, query, doc, payload = pre_watch
pre_watch = await self.pre_watch(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_watch) in [DictObj, dict]:
yield pre_watch
skip_events, env, query, doc, payload = pre_watch
else: payload = {}
logger.debug('Preparing async loop at BaseModule')
async for results in Data.watch(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
skip_extn='$extn' in query or Event.EXTN in skip_events,
):
logger.debug(f'Received watch results at BaseModule: {results}')
if 'stream' in results.keys():
yield results
continue
if Event.ON not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module on_watch
on_watch = await Config.modules[self.proxy].on_watch(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_watch) in [DictObj, dict]:
yield on_watch
results, skip_events, env, query, doc, payload = on_watch
on_watch = await self.on_watch(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_watch) in [DictObj, dict]:
yield on_watch
results, skip_events, env, query, doc, payload = on_watch
# [DOC] if $attrs query arg is present return only required keys.
if '$attrs' in query:
query['$attrs'].insert(0, '_id')
for i in range(len(results['docs'])):
results['docs'][i] = BaseModel(
{
attr: results['docs'][i][attr]
for attr in query['$attrs']
if attr in results['docs'][i]._attrs()
}
)
yield self.status(
status=200, msg=f'Detected {results["count"]} docs.', args=results
)
logger.debug('Generator ended at BaseModule.')
async def pre_create(
self,
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
LIMP_EVENTS, LIMP_ENV, Union[LIMP_QUERY, Query], LIMP_DOC, Dict[str, Any]
]:
return (skip_events, env, query, doc, payload)
async def on_create(
self,
results: Dict[str, Any],
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
Dict[str, Any],
LIMP_EVENTS,
LIMP_ENV,
Union[LIMP_QUERY, Query],
LIMP_DOC,
Dict[str, Any],
]:
return (results, skip_events, env, query, doc, payload)
async def create(
self,
skip_events: LIMP_EVENTS = [],
env: LIMP_ENV = {},
query: Union[LIMP_QUERY, Query] = [],
doc: LIMP_DOC = {},
) -> DictObj:
if Event.PRE not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module pre_create
pre_create = await Config.modules[self.proxy].pre_create(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_create) in [DictObj, dict]:
return pre_create
skip_events, env, query, doc, payload = pre_create
pre_create = await self.pre_create(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_create) in [DictObj, dict]:
return pre_create
skip_events, env, query, doc, payload = pre_create
else: payload = {}
# [DOC] Deleted all extra doc args
doc = {
attr: doc[attr]
for attr in ['_id', *self.attrs.keys()]
if attr in doc.keys() and doc[attr] != None
}
# [DOC] Append host_add, user_agent, create_time, diff if it's present in attrs.
if (
'user' in self.attrs.keys()
and 'host_add' not in doc.keys()
and env['session']
and Event.ARGS not in skip_events
):
doc['user'] = env['session'].user._id
if 'create_time' in self.attrs.keys():
doc['create_time'] = datetime.datetime.utcnow().isoformat()
if 'host_add' in self.attrs.keys() and 'host_add' not in doc.keys():
doc['host_add'] = env['REMOTE_ADDR']
if 'user_agent' in self.attrs.keys() and 'user_agent' not in doc.keys():
doc['user_agent'] = env['HTTP_USER_AGENT']
if Event.ARGS not in skip_events:
# [DOC] Check presence and validate all attrs in doc args
try:
validate_doc(
doc=doc,
attrs=self.attrs,
skip_events=skip_events,
env=env,
query=query,
)
except MissingAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'create\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'MISSING_ATTR'},
)
except InvalidAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'create\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'INVALID_ATTR'},
)
except ConvertAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'create\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'CONVERT_INVALID_ATTR'},
)
# [DOC] Check unique_attrs
if self.unique_attrs:
unique_attrs_query = [[]]
for attr in self.unique_attrs:
if type(attr) == str:
unique_attrs_query[0].append({attr: doc[attr]})
elif type(attr) == tuple:
unique_attrs_query[0].append(
{child_attr: doc[child_attr] for child_attr in attr}
)
unique_attrs_query.append({'$limit': 1})
unique_results = await self.read(
skip_events=[Event.PERM], env=env, query=unique_attrs_query
)
if unique_results.args.count: # pylint: disable=no-member
unique_attrs_str = ', '.join(
map(
lambda _: ('(' + ', '.join(_) + ')')
if type(_) == tuple
else _,
self.unique_attrs,
)
)
return self.status(
status=400,
msg=f'A doc with the same \'{unique_attrs_str}\' already exists.',
args={'code': 'DUPLICATE_DOC'},
)
# [DOC] Execute Data driver create
results = await Data.create(
env=env, collection=self.collection, attrs=self.attrs, doc=doc
)
if Event.ON not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module on_create
on_create = await Config.modules[self.proxy].on_create(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_create) in [DictObj, dict]:
return on_create
results, skip_events, env, query, doc, payload = on_create
on_create = await self.on_create(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_create) in [DictObj, dict]:
return on_create
results, skip_events, env, query, doc, payload = on_create
# [DOC] create soft action is to only retrurn the new created doc _id.
if Event.SOFT in skip_events:
results = await self.methods['read'](
skip_events=[Event.PERM], env=env, query=[[{'_id': results['docs'][0]}]]
)
results = results['args']
# [DOC] Module collection is updated, update_cache
asyncio.create_task(self.update_cache(env=env))
return self.status(
status=200, msg=f'Created {results["count"]} docs.', args=results
)
async def pre_update(
self,
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
LIMP_EVENTS, LIMP_ENV, Union[LIMP_QUERY, Query], LIMP_DOC, Dict[str, Any]
]:
return (skip_events, env, query, doc, payload)
async def on_update(
self,
results: Dict[str, Any],
skip_events: LIMP_EVENTS,
env: LIMP_ENV,
query: Union[LIMP_QUERY, Query],
doc: LIMP_DOC,
payload: Dict[str, Any],
) -> Tuple[
Dict[str, Any],
LIMP_EVENTS,
LIMP_ENV,
Union[LIMP_QUERY, Query],
LIMP_DOC,
Dict[str, Any],
]:
return (results, skip_events, env, query, doc, payload)
async def update(
self,
skip_events: LIMP_EVENTS = [],
env: LIMP_ENV = {},
query: Union[LIMP_QUERY, Query] = [],
doc: LIMP_DOC = {},
) -> DictObj:
if Event.PRE not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module pre_update
pre_update = await Config.modules[self.proxy].pre_update(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_update) in [DictObj, dict]:
return pre_update
skip_events, env, query, doc, payload = pre_update
pre_update = await self.pre_update(
skip_events=skip_events, env=env, query=query, doc=doc, payload={}
)
if type(pre_update) in [DictObj, dict]:
return pre_update
skip_events, env, query, doc, payload = pre_update
else: payload = {}
# [DOC] Check presence and validate all attrs in doc args
try:
validate_doc(
doc=doc,
attrs=self.attrs,
allow_opers=True,
allow_none=True,
skip_events=skip_events,
env=env,
query=query,
)
except MissingAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'update\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'MISSING_ATTR'},
)
except InvalidAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'update\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'INVALID_ATTR'},
)
except ConvertAttrException as e:
return self.status(
status=400,
msg=f'{str(e)} for \'update\' request on module \'{self.package_name.upper()}_{self.module_name.upper()}\'.',
args={'code': 'CONVERT_INVALID_ATTR'},
)
# [DOC] Delete all attrs not belonging to the doc, checking against top level attrs only
doc = {
attr: doc[attr]
for attr in ['_id', *doc.keys()]
if attr.split('.')[0] in self.attrs.keys() and doc[attr] != None
}
# [DOC] Check if there is anything yet to update
if not len(doc.keys()):
return self.status(status=200, msg='Nothing to update.', args={})
# [DOC] Find which docs are to be updated
docs_results = await Data.read(
env=env,
collection=self.collection,
attrs=self.attrs,
query=query,
skip_process=True,
)
# [DOC] Check unique_attrs
if self.unique_attrs:
# [DOC] If any of the unique_attrs is present in doc, and docs_results is > 1, we have duplication
if len(docs_results['docs']) > 1:
unique_attrs_check = True
for attr in self.unique_attrs:
if type(attr) == str and attr in doc.keys():
unique_attrs_check = False
break
elif type(attr) == tuple:
for child_attr in attr:
if not unique_attrs_check:
break
if child_attr in doc.keys():
unique_attrs_check = False
break
if not unique_attrs_check:
return self.status(
status=400,
msg='Update call query has more than one doc as results. This would result in duplication.',
args={'code': 'MULTI_DUPLICATE'},
)
# [DOC] Check if any of the unique_attrs are present in doc
if sum(1 for attr in doc.keys() if attr in self.unique_attrs) > 0:
# [DOC] Check if the doc would result in duplication after update
unique_attrs_query = [[]]
for attr in self.unique_attrs:
if type(attr) == str:
if attr in doc.keys():
unique_attrs_query[0].append({attr: doc[attr]})
elif type(attr) == tuple:
unique_attrs_query[0].append(
{
child_attr: doc[child_attr]
for child_attr in attr
if attr in doc.keys()
}
)
unique_attrs_query.append(
{'_id': {'$nin': [doc._id for doc in docs_results['docs']]}}
)
unique_attrs_query.append({'$limit': 1})
unique_results = await self.read(
skip_events=[Event.PERM], env=env, query=unique_attrs_query
)
if unique_results.args.count: # pylint: disable=no-member
unique_attrs_str = ', '.join(
map(
lambda _: ('(' + ', '.join(_) + ')')
if type(_) == tuple
else _,
self.unique_attrs,
)
)
return self.status(
status=400,
msg=f'A doc with the same \'{unique_attrs_str}\' already exists.',
args={'code': 'DUPLICATE_DOC'},
)
results = await Data.update(
env=env,
collection=self.collection,
attrs=self.attrs,
docs=[doc._id for doc in docs_results['docs']],
doc=doc,
)
if Event.ON not in skip_events:
# [DOC] Check proxy module
if self.proxy:
# [DOC] Call original module on_update
on_update = await Config.modules[self.proxy].on_update(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_update) in [DictObj, dict]:
return on_update
results, skip_events, env, query, doc, payload = on_update
on_update = await self.on_update(
results=results,
skip_events=skip_events,
env=env,
query=query,
doc=doc,
payload=payload,
)
if type(on_update) in [DictObj, dict]:
return on_update
results, skip_events, env, query, doc, payload = on_update
# [DOC] If at least one doc updated, and module has diff enabled, and __DIFF__ not skippend:
if results['count'] and self.diff and Event.DIFF not in skip_events:
# [DOC] If diff is a ATTR_MOD, Check condition for valid diff case
if type(self.diff) == ATTR_MOD:
self.diff: ATTR_MOD
if self.diff.condition(skip_events=skip_events, env=env, query=query, doc=doc):
# [DOC] if condition passed, create Diff doc with default callable
diff_vars = doc
if self.diff.default and callable(self.diff.default):
diff_vars = self.diff.default(
skip_events=skip_events, env=env, query=query, doc=doc
)
diff_results = await Config.modules['diff'].methods['create'](
skip_events=[Event.PERM],
env=env,
query=query,
doc={'module': self.module_name, 'vars': diff_vars},
)
if diff_results.status != 200:
logger.error(f'Failed to create Diff doc, results: {diff_results}')
else:
logger.debug(f'Skipped Diff Workflow due to failed condition.')