-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlib.coffee
1539 lines (1196 loc) · 56.5 KB
/
lib.coffee
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 util from 'util'
globals = @
RESERVED_FIELDS = ['document', 'parent', 'schema', 'migrations']
INVALID_TARGET = "Invalid target document"
MAX_RETRIES = 1000
# From Meteor's random/random.js
share.UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz'
# TODO: Support also other types of _id generation (like ObjectID)
# TODO: We could do also a hash of an ID and then split, this would also prevent any DOS attacks by forcing IDs of a particular form
PREFIX = share.UNMISTAKABLE_CHARS.split ''
class codeMinimizedTest
@CODE_MINIMIZED = codeMinimizedTest.name and codeMinimizedTest.name isnt 'codeMinimizedTest'
isPlainObject = (obj) ->
if not _.isObject(obj) or _.isArray(obj) or _.isFunction(obj)
return false
if obj.constructor isnt Object
return false
return true
deepExtend = (obj, args...) ->
_.each args, (source) ->
_.each source, (value, key) ->
if obj[key] and value and isPlainObject(obj[key]) and isPlainObject(value)
obj[key] = deepExtend obj[key], value
else
obj[key] = value
obj
setPath = (object, path, value) ->
outputObject = object
segments = path.split '.'
for segment, i in segments
if _.isObject object
if i is segments.length - 1
object[segment] = value
break
else if segment not of object
object[segment] = {}
object = object[segment]
else
throw new Error "Path '#{path}' crosses a non-object."
outputObject
removeUndefined = (obj) ->
assert isPlainObject obj
res = {}
for key, value of obj
if _.isUndefined value
continue
else if isPlainObject value
res[key] = removeUndefined value
else
res[key] = value
res
startsWith = (string, start) ->
string.lastIndexOf(start, 0) is 0
removePrefix = (string, prefix) ->
string.substring prefix.length
getCollection = (name, document, replaceParent) ->
transform = (doc) -> new document doc
if _.isString(name)
if Document._collections[name]
methodHandlers = Document._collections[name]._connection.method_handlers or Document._collections[name]._connection._methodHandlers
for method of methodHandlers
if startsWith method, Document._collections[name]._prefix
if replaceParent
delete methodHandlers[method]
else
throw new Error "Reuse of a collection without replaceParent set"
if Document._collections[name]._connection.registerStore
if replaceParent
delete Document._collections[name]._connection._stores[name]
else
throw new Error "Reuse of a collection without replaceParent set"
collection = new Mongo.Collection name, transform: transform
Document._collections[name] = collection
else if name is null
collection = new Mongo.Collection name, transform: transform
else
collection = name
if collection._peerdb and not replaceParent
throw new Error "Reuse of a collection without replaceParent set"
collection._transform = LocalCollection.wrapTransform transform
collection._peerdb = true
collection
fieldsToProjection = (fields) ->
projection =
_id: 1 # In the case we want only id, that is, detect deletions
if _.isArray fields
for field in fields
if _.isString field
projection[field] = 1
else
_.extend projection, field
else if _.isObject fields
_.extend projection, fields
else
throw new Error "Invalid fields: #{ fields }"
projection
extractValue = (obj, path) ->
while path.length
obj = obj[path[0]]
path = path[1..]
obj
isModifiableCollection = (collection) ->
if Meteor.isClient
collection._connection is null
else
collection._connection in [null, Meteor.server]
isServerCollection = (collection) ->
Meteor.isServer and collection._connection is Meteor.server
# We augment the cursor so that it matches our extra method in documents manager.
LocalCollection.Cursor::exists = ->
# We just have to limit the query temporary. For limited and unsorted queries
# there is already a fast path in _getRawObjects. Same for single ID queries.
# We cannot do much if it is a sorted query (Minimongo does not have indexes).
# The only combination we could optimize further is an unsorted query with skip
# and instead of generating a set of all documents and then doing a slice, we
# could traverse at most skip number of documents.
originalLimit = @limit
@limit = 1
try
return !!@count()
finally
@limit = originalLimit
class globals.Document
# TODO: When we will require all fields to be specified and have validator support to validate new objects, we can also run validation here and check all data, reference fields and others
@objectify: (parent, ancestorArray, obj, fields) ->
throw new Error "Document does not match schema, not a plain object" unless isPlainObject obj
for name, field of fields
# Not all fields are necessary provided
continue unless obj[name]
path = if parent then "#{ parent }.#{ name }" else name
if field instanceof globals.Document._ReferenceField
throw new Error "Document does not match schema, sourcePath does not match: #{ field.sourcePath } vs. #{ path }" if field.sourcePath isnt path
if field.isArray
throw new Error "Document does not match schema, not an array" unless _.isArray obj[name]
obj[name] = _.map obj[name], (o) => new field.targetDocument o
else
throw new Error "Document does not match schema, ancestorArray does not match: #{ field.ancestorArray } vs. #{ ancestorArray }" if field.ancestorArray isnt ancestorArray
throw new Error "Document does not match schema, not a plain object" unless isPlainObject obj[name]
obj[name] = new field.targetDocument obj[name]
else if isPlainObject field
if _.isArray obj[name]
throw new Error "Document does not match schema, an unexpected array" unless _.some field, (f) => f.ancestorArray is path
throw new Error "Document does not match schema, nested arrays are not supported" if ancestorArray
obj[name] = _.map obj[name], (o) => @objectify path, path, o, field
else
throw new Error "Document does not match schema, expected an array" if _.some field, (f) => f.ancestorArray is path
obj[name] = @objectify path, ancestorArray, obj[name], field
obj
constructor: (doc) ->
_.extend @, @constructor.objectify '', null, (doc or {}), (@constructor?.Meta?.fields or {})
@_setDelayedCheck: ->
return unless globals.Document._delayed.length
@_clearDelayedCheck()
globals.Document._delayedCheckTimeout = Meteor.setTimeout ->
if globals.Document._delayed.length
delayed = [] # Display friendly list of delayed documents
for document in globals.Document._delayed
delayed.push "#{ document.Meta._name } from #{ document.Meta._location }"
Log.error "Not all delayed document definitions were successfully retried:\n#{ delayed.join('\n') }"
, 1000 # ms
@_clearDelayedCheck: ->
Meteor.clearTimeout globals.Document._delayedCheckTimeout if globals.Document._delayedCheckTimeout
@_processTriggers: (triggers) ->
assert triggers
assert isPlainObject triggers
for name, trigger of triggers
throw new Error "Trigger names cannot contain '.' (for #{ name } trigger from #{ @Meta._location })" if name.indexOf('.') isnt -1
if trigger instanceof globals.Document._Trigger
trigger.contributeToClass @, name
else
throw new Error "Invalid value for trigger (for #{ name } trigger from #{ @Meta._location })"
triggers
@_processFieldsOrGenerators: (isGenerator, fields, parent, ancestorArray) ->
assert fields
assert isPlainObject fields
ancestorArray = ancestorArray or null
if isGenerator
resourceName = "Generator"
lowerCaseResourceName = "generator"
else
resourceName = "Field"
lowerCaseResourceName = "field"
res = {}
for name, field of fields
throw new Error "#{ resourceName } names cannot contain '.' (for #{ name } from #{ @Meta._location })" if name.indexOf('.') isnt -1
path = if parent then "#{ parent }.#{ name }" else name
array = ancestorArray
if _.isArray field
throw new Error "Array #{ lowerCaseResourceName } has to contain exactly one element, not #{ field.length } (for #{ path } from #{ @Meta._location })" if field.length isnt 1
field = field[0]
if array
# TODO: Support nested arrays
# See: https://jira.mongodb.org/browse/SERVER-831
throw new Error "#{ resourceName } cannot be in a nested array (for #{ path } from #{ @Meta._location })"
array = path
if field instanceof globals.Document._Field
throw new Error "Not a generated field among generators (for #{ name } from #{ @Meta._location })" if isGenerator and not field instanceof globals.Document._GeneratedField
field.contributeToClass @, path, array
res[name] = field
else if _.isObject field
res[name] = @_processFieldsOrGenerators isGenerator, field, path, array
else
throw new Error "Invalid value for #{ lowerCaseResourceName } (for #{ path } from #{ @Meta._location })"
res
@_processFields: (fields, parent, ancestorArray) ->
@_processFieldsOrGenerators false, fields, parent, ancestorArray
@_processGenerators: (generators, parent, ancestorArray) ->
@_processFieldsOrGenerators true, generators, parent, ancestorArray
@_fieldsUseDocument: (fields, document) ->
assert fields
assert isPlainObject fields
for name, field of fields
if field instanceof globals.Document._TargetedFieldsObservingField
return true if field.sourceDocument is document
return true if field.targetDocument is document
else if field instanceof globals.Document._Field
return true if field.sourceDocument is document
else
assert isPlainObject field
return true if @_fieldsUseDocument field, document
false
@_retryAllUsing: (document) ->
documents = globals.Document.list
globals.Document.list = []
for doc in documents
if @_fieldsUseDocument doc.Meta.fields, document
delete doc.Meta._replaced
delete doc.Meta._listIndex
@_addDelayed doc
else if @_fieldsUseDocument doc.Meta.generators, document
delete doc.Meta._replaced
delete doc.Meta._listIndex
@_addDelayed doc
else
globals.Document.list.push doc
doc.Meta._listIndex = globals.Document.list.length - 1
@_retryDelayed: (throwErrors) ->
@_clearDelayedCheck()
# We store the delayed list away, so that we can iterate over it
delayed = globals.Document._delayed
# And set it back to the empty list, we will add to it again as necessary
globals.Document._delayed = []
for document in delayed
delete document.Meta._delayIndex
processedCount = 0
for document in delayed
assert not document.Meta._listIndex?
if document.Meta._replaced
continue
try
triggers = document.Meta._triggers.call document, {}
if triggers and isPlainObject triggers
document.Meta.triggers = document._processTriggers triggers
catch e
if not throwErrors and (e.message is INVALID_TARGET or e instanceof ReferenceError)
@_addDelayed document
continue
else
throw new Error "Invalid triggers (from #{ document.Meta._location }): #{ e.stringOf?() or e }\n---#{ if e.stack then "#{ e.stack }\n---" else '' }"
throw new Error "No triggers returned (from #{ document.Meta._location })" unless triggers
throw new Error "Returned triggers should be a plain object (from #{ document.Meta._location })" unless isPlainObject triggers
try
generators = document.Meta._generators.call document, {}
if generators and isPlainObject generators
document.Meta.generators = document._processGenerators generators
catch e
if not throwErrors and (e.message is INVALID_TARGET or e instanceof ReferenceError)
@_addDelayed document
continue
else
throw new Error "Invalid generators (from #{ document.Meta._location }): #{ e.stringOf?() or e }\n---#{ if e.stack then "#{ e.stack }\n---" else '' }"
throw new Error "No generators returned (from #{ document.Meta._location })" unless generators
throw new Error "Returned generators should be a plain object (from #{ document.Meta._location })" unless isPlainObject generators
try
fields = document.Meta._fields.call document, {}
if fields and isPlainObject fields
# We run _processFields first, so that _reverseFields for this document is populated as well
document._processFields fields
reverseFields = {}
for reverse in document.Meta._reverseFields
setPath reverseFields, reverse.reverseName, [globals.Document.ReferenceField reverse.sourceDocument, reverse.reverseFields]
# And now we run _processFields for real on all fields
document.Meta.fields = document._processFields deepExtend fields, reverseFields
catch e
if not throwErrors and (e.message is INVALID_TARGET or e instanceof ReferenceError)
@_addDelayed document
continue
else
throw new Error "Invalid fields (from #{ document.Meta._location }): #{ e.stringOf?() or e }\n---#{ if e.stack then "#{ e.stack }\n---" else '' }"
throw new Error "No fields returned (from #{ document.Meta._location })" unless fields
throw new Error "Returned fields should be a plain object (from #{ document.Meta._location })" unless isPlainObject fields
# Local documents cannot have replaceParent set.
if document.Meta.replaceParent and not document.Meta.parent?._replaced
throw new Error "Replace parent set, but no parent known (from #{ document.Meta._location })" unless document.Meta.parent
document.Meta.parent._replaced = true
if document.Meta.parent._listIndex?
globals.Document.list.splice document.Meta.parent._listIndex, 1
delete document.Meta.parent._listIndex
# Renumber documents
for doc, i in globals.Document.list
doc.Meta._listIndex = i
else if document.Meta.parent._delayIndex?
globals.Document._delayed.splice document.Meta.parent._delayIndex, 1
delete document.Meta.parent._delayIndex
# Renumber documents
for doc, i in globals.Document._delayed
doc.Meta._delayIndex = i
@_retryAllUsing document.Meta.parent.document
unless document.Meta.local
globals.Document.list.push document
document.Meta._listIndex = globals.Document.list.length - 1
delete document.Meta._delayIndex
assert not document.Meta._replaced
unless document.Meta.local
# If a document is defined after PeerDB has started we have to setup observers for it.
globals.Document._setupObservers() if globals.Document.hasStarted()
processedCount++
@_setDelayedCheck()
processedCount
@_addDelayed: (document) ->
@_clearDelayedCheck()
assert not document.Meta._replaced
assert not document.Meta._listIndex?
globals.Document._delayed.push document
document.Meta._delayIndex = globals.Document._delayed.length - 1
@_setDelayedCheck()
@_validateTriggers: (document) ->
for name, trigger of document.Meta.triggers
if trigger instanceof globals.Document._Trigger
trigger.validate()
else
throw new Error "Invalid trigger (for #{ name } trigger from #{ document.Meta._location })"
@_validateFieldsOrGenerators: (obj) ->
for name, field of obj
if field instanceof globals.Document._Field
field.validate()
else
@_validateFieldsOrGenerators field
@Meta: (meta) ->
for field in RESERVED_FIELDS or startsWith field, '_'
throw "Reserved meta field name: #{ field }" if field of meta
if meta.abstract
throw new Error "name cannot be set in abstract document" if meta.name
throw new Error "replaceParent cannot be set in abstract document" if meta.replaceParent
throw new Error "Abstract document with a parent" if @Meta._name
else
throw new Error "Missing document name" unless meta.name
throw new Error "replaceParent set without a parent" if meta.replaceParent and not @Meta._name
if meta.local
throw new Error "replaceParent cannot be set when local is set" if meta.replaceParent
name = meta.name
currentTriggers = meta.triggers or (ts) -> ts
currentGenerators = meta.generators or (gs) -> gs
currentFields = meta.fields or (fs) -> fs
meta = _.omit meta, 'name', 'triggers', 'generators', 'fields'
parentMeta = @Meta
if parentMeta._triggers
triggers = (ts) ->
newTs = parentMeta._triggers.call @, ts
removeUndefined _.extend ts, newTs, currentTriggers.call @, newTs
else
triggers = currentTriggers
meta._triggers = triggers # Triggers function
if parentMeta._generators
generators = (gs) ->
newGs = parentMeta._generators.call @, gs
removeUndefined deepExtend gs, newGs, currentGenerators.call @, newGs
else
generators = currentGenerators
meta._generators = generators # Generators function
if parentMeta._fields
fields = (fs) ->
newFs = parentMeta._fields.call @, fs
removeUndefined deepExtend fs, newFs, currentFields.call @, newFs
else
fields = currentFields
meta._fields = fields # Fields function
if not meta.abstract
meta._name = name # "name" is a reserved property name on functions in some environments (eg. node.js), so we use "_name"
# For easier debugging and better error messages
if CODE_MINIMIZED
meta._location = '<code_minimized>'
else
if Meteor.isServer
meta._location = Promise.await(StackTrace.getCaller())?.toString() or '<unknown>'
else
meta._location = '<unknown>'
# We ignore potential errors and assign the location asynchronously.
StackTrace.getCaller().then (caller) =>
meta._location = caller?.toString() or '<unknown>'
meta.document = @
if meta.collection is null or meta.collection
meta.collection = getCollection meta.collection, @, meta.replaceParent
else if parentMeta.collection?._peerdb
meta.collection = getCollection parentMeta.collection, @, meta.replaceParent
else
meta.collection = getCollection "#{ name }s", @, meta.replaceParent
if @Meta._name
meta.parent = parentMeta
if not meta.replaceParent
# If we are not replacing the parent, we override _reverseFields with an empty set
# because we want reverse fields only on exact target document and not its children.
meta._reverseFields = []
else
meta._reverseFields = _.clone parentMeta._reverseFields
if not meta.replaceParent
# If we are not replacing the parent, we create a new list of migrations
meta.migrations = []
clonedParentMeta = -> parentMeta.apply @, arguments
filteredParentMeta = _.omit parentMeta, '_listIndex', '_delayIndex', '_replaced', '_observersSetup', 'parent', 'replaceParent', 'abstract', 'local'
@Meta = _.extend clonedParentMeta, filteredParentMeta, meta
if not meta.abstract
assert @Meta._reverseFields
@documents = new @_Manager @Meta
@_addDelayed @
@_retryDelayed()
@list: []
@_delayed: []
@_delayedCheckTimeout: null
@_collections: {}
@validateAll: ->
for document in globals.Document.list
throw new Error "Missing fields (from #{ document.Meta._location })" unless document.Meta.fields
@_validateTriggers document
@_validateFieldsOrGenerators document.Meta.generators
@_validateFieldsOrGenerators document.Meta.fields
@defineAll: (dontThrowDelayedErrors) ->
for i in [0..MAX_RETRIES]
if i is MAX_RETRIES
throw new Error "Possible infinite loop" unless dontThrowDelayedErrors
break
globals.Document._retryDelayed not dontThrowDelayedErrors
break unless globals.Document._delayed.length
globals.Document.validateAll()
assert dontThrowDelayedErrors or globals.Document._delayed.length is 0
prepared = false
prepareList = []
started = false
startList = []
@prepare: (f) ->
if prepared
f()
else
prepareList.push f
@runPrepare: ->
assert not prepared
prepared = true
prepare() for prepare in prepareList
return
@startup: (f) ->
if started
f()
else
startList.push f
@runStartup: ->
assert not started
started = true
start() for start in startList
return
@hasStarted: ->
started
# TODO: Should we add retry?
@_observerCallback: (limitToPrefix, f) ->
return (obj, args...) ->
try
if limitToPrefix
# We call f only if the first character of id is in share.PREFIX. By that we allow each instance to
# operate only on a subset of documents, allowing simple coordination while scaling.
id = if _.isObject obj then obj._id else obj
f obj, args... if id[0] in PREFIX
else
f obj, args...
catch e
Log.error "PeerDB exception: #{ e }: #{ util.inspect args, depth: 10 }"
Log.error e.stack
@_sourceFieldProcessDeleted: (field, id, ancestorSegments, pathSegments, value) ->
if ancestorSegments.length
assert ancestorSegments[0] is pathSegments[0]
@_sourceFieldProcessDeleted field, id, ancestorSegments[1..], pathSegments[1..], value[ancestorSegments[0]]
else
value = [value] unless _.isArray value
ids = (extractValue(v, pathSegments)._id for v in value when extractValue(v, pathSegments)?._id)
assert field.reverseName
query =
_id:
$nin: ids
query["#{ field.reverseName }._id"] = id
update = {}
update[field.reverseName] =
_id: id
field.targetCollection.update query, {$pull: update}, multi: true
@_sourceFieldUpdated: (isGenerator, id, name, value, field, originalValue) ->
# TODO: Should we check if field still exists but just value is undefined, so that it is the same as null? Or can this happen only when removing the field?
if _.isUndefined value
if field and field.reverseName and isModifiableCollection field.targetCollection
@_sourceFieldProcessDeleted field, id, [], name.split('.')[1..], originalValue
return
if isGenerator
field = field or @Meta.generators[name]
else
field = field or @Meta.fields[name]
# We should be subscribed only to those updates which are defined in @Meta.generators or @Meta.fields
assert field
originalValue = originalValue or value
if field instanceof globals.Document._ObservingField
if field.ancestorArray and name is field.ancestorArray
unless _.isArray value
Log.error "Document '#{ @Meta._name }' '#{ id }' field '#{ name }' was updated with a non-array value: #{ util.inspect value }"
return
else
value = [value]
for v in value
field.updatedWithValue id, v
if field.reverseName and isModifiableCollection field.targetCollection
# In updatedWithValue we added possible new entry/ies to reverse fields, but here
# we have also to remove those which were maybe removed from the value and are
# not referencing anymore a document which got added the entry to its reverse
# field in the past. So we make sure that only those documents which are still in
# the value have the entry in their reverse fields by creating a query which pulls
# the entry from all other.
pathSegments = name.split('.')
if field.ancestorArray
ancestorSegments = field.ancestorArray.split('.')
assert ancestorSegments[0] is pathSegments[0]
@_sourceFieldProcessDeleted field, id, ancestorSegments[1..], pathSegments[1..], originalValue
else
@_sourceFieldProcessDeleted field, id, [], pathSegments[1..], originalValue
else if field not instanceof globals.Document._Field
value = [value] unless _.isArray value
# A trick to get reverse fields correctly cleaned up when the last element is removed from the
# array of reference fields which have a reverse field defined. If the array is empty, the loop
# below would not run, so we change it to an array with an empty object, which runs the loop
# for one iteration, but makes all values (v[n]) undefined, which means that the first condition
# of this method is met, and if field has reverseName defined, then _sourceFieldProcessDeleted
# is called, correctly cleaning up the reverse field.
value = [{}] unless value.length
# If value is an array but it should not be, we cannot do much else.
# Same goes if the value does not match structurally fields.
for v in value
for n, f of field
# TODO: Should we skip calling @_sourceFieldUpdated if we already called it with exactly the same parameters this run?
@_sourceFieldUpdated isGenerator, id, "#{ name }.#{ n }", v[n], f, originalValue
@_sourceUpdated: (isGenerator, id, fields) ->
for name, value of fields
@_sourceFieldUpdated isGenerator, id, name, value
@_setupSourceObservers: (updateAll) ->
for [fields, isGenerator] in [[@Meta.fields, false], [@Meta.generators, true]]
do (fields, isGenerator) =>
return if _.isEmpty fields
indexes = []
sourceFields = {}
sourceFieldsLimitedToPrefix = {}
# We use isModifiableCollection to optimize so that we do not even setup observers
# for fields which deal with unmodifiable collections.
sourceFieldsWalker = (obj) ->
for name, field of obj
if field instanceof globals.Document._ObservingField
if field instanceof globals.Document._ReferenceField
if field.reverseName
if isModifiableCollection(field.sourceCollection) or isModifiableCollection(field.targetCollection)
# Limit to PREFIX only when both collections are server side. Otherwise there is a collection
# which is local only to this instance and we want to process all documents for it. Alternatively,
# there is a collection through a connection, in which case we are conservative and also process
# all documents for it. We do not necessary know if connections are shared between instances.
if isServerCollection(field.sourceCollection) and isServerCollection(field.targetCollection)
sourceFieldsLimitedToPrefix[field.sourcePath] = 1
else
sourceFields[field.sourcePath] = 1
index = {}
index["#{ field.sourcePath }._id"] = 1
indexes.push index
else
if isModifiableCollection field.sourceCollection
if isServerCollection field.sourceCollection
sourceFieldsLimitedToPrefix[field.sourcePath] = 1
else
sourceFields[field.sourcePath] = 1
index = {}
index["#{ field.sourcePath }._id"] = 1
indexes.push index
else
if isModifiableCollection field.sourceCollection
if isServerCollection field.sourceCollection
sourceFieldsLimitedToPrefix[field.sourcePath] = 1
else
sourceFields[field.sourcePath] = 1
else if field not instanceof globals.Document._Field
sourceFieldsWalker field
sourceFieldsWalker fields
unless updateAll
for index in indexes
@Meta.collection._ensureIndex index if Meteor.isServer and @Meta.collection._connection is Meteor.server
# Source or target collections are modifiable collections.
unless _.isEmpty sourceFields
initializing = true
observers =
added: globals.Document._observerCallback false, (id, fields) =>
@_sourceUpdated isGenerator, id, fields if updateAll or not initializing
unless updateAll
observers.changed = globals.Document._observerCallback false, (id, fields) =>
@_sourceUpdated isGenerator, id, fields
handle = @Meta.collection.find({}, fields: sourceFields).observeChanges observers
initializing = false
handle.stop() if updateAll
# Source or target collections are modifiable collections.
unless _.isEmpty sourceFieldsLimitedToPrefix
initializingLimitedToPrefix = true
observers =
added: globals.Document._observerCallback true, (id, fields) =>
@_sourceUpdated isGenerator, id, fields if updateAll or not initializingLimitedToPrefix
unless updateAll
observers.changed = globals.Document._observerCallback true, (id, fields) =>
@_sourceUpdated isGenerator, id, fields
handle = @Meta.collection.find({}, fields: sourceFieldsLimitedToPrefix).observeChanges observers
initializingLimitedToPrefix = false
handle.stop() if updateAll
@_updateAll: ->
# It is only reasonable to run anything if this instance
# is not disabled. Otherwise we would still go over all
# documents, just we would not process any.
return if globals.Document.instanceDisabled
Log.info "Updating all references..."
@_setupObservers true
Log.info "Done"
@_setupObservers: (updateAll) ->
setupTriggerObserves = (triggers) =>
for name, trigger of triggers
trigger._setupObservers()
setupTargetObservers = (fields) =>
for name, field of fields
# There are no arrays anymore here, just objects (for subdocuments) or fields
if field instanceof @_TargetedFieldsObservingField
field._setupTargetObservers updateAll
else if field not instanceof @_Field
setupTargetObservers field
for document in @list
if updateAll
# For fields we pass updateAll on.
setupTargetObservers document.Meta.fields
setupTargetObservers document.Meta.generators
document._setupSourceObservers true
else
# For each document we should setup observers only once.
continue if document.Meta._observersSetup
document.Meta._observersSetup = true
# We setup triggers only when we are not updating all.
setupTriggerObserves document.Meta.triggers
setupTargetObservers document.Meta.fields
setupTargetObservers document.Meta.generators
document._setupSourceObservers false
return
@Trigger: (args...) ->
new @_Trigger args...
@ReferenceField: (args...) ->
new @_ReferenceField args...
@GeneratedField: (args...) ->
new @_GeneratedField args...
@usedBy: ->
fields = []
fieldsWalker = (document, obj) =>
for name, field of obj
if field instanceof globals.Document._ReferenceField
if field.targetDocument is @
assert field.sourceDocument is document
fields.push
field: field
document: field.sourceDocument
path: field.sourcePath
else if field not instanceof globals.Document._Field
fieldsWalker document, field
for document in @list
fieldsWalker document, document.Meta.fields
return fields
class globals.Document._Trigger
# Arguments:
# fields
# fields, trigger, triggerOnUnmodifiable
constructor: (@fields, @trigger, @triggerOnUnmodifiable) ->
@fields ?= []
contributeToClass: (@document, @name) =>
@_metaLocation = @document.Meta._location
@collection = @document.Meta.collection
validate: =>
# TODO: Should these be simply asserts?
throw new Error "Missing meta location" unless @_metaLocation
throw new Error "Missing name (from #{ @_metaLocation })" unless @name
throw new Error "Missing document (for #{ @name} trigger from #{ @_metaLocation })" unless @document
throw new Error "Missing collection (for #{ @name} trigger from #{ @_metaLocation })" unless @collection
throw new Error "Document not defined (for #{ @name} trigger from #{ @_metaLocation })" unless @document.Meta._listIndex?
assert not @document.Meta._replaced
assert not @document.Meta._delayIndex?
assert.equal @document.Meta.document, @document
assert.equal @document.Meta.document.Meta, @document.Meta
_setupObservers: =>
return unless isModifiableCollection(@collection) or @triggerOnUnmodifiable
initializing = true
limitToPrefix = isServerCollection @collection
queryFields = fieldsToProjection @fields
@collection.find({}, fields: queryFields).observe
added: globals.Document._observerCallback limitToPrefix, (document) =>
@trigger document, null unless initializing
changed: globals.Document._observerCallback limitToPrefix, (newDocument, oldDocument) =>
@trigger newDocument, oldDocument
removed: globals.Document._observerCallback limitToPrefix, (oldDocument) =>
@trigger null, oldDocument
initializing = false
class globals.Document._Field
contributeToClass: (@sourceDocument, @sourcePath, @ancestorArray) =>
@_metaLocation = @sourceDocument.Meta._location
@sourceCollection = @sourceDocument.Meta.collection
validate: =>
# TODO: Should these be simply asserts?
throw new Error "Missing meta location" unless @_metaLocation
throw new Error "Missing source path (from #{ @_metaLocation })" unless @sourcePath
throw new Error "Missing source document (for #{ @sourcePath } from #{ @_metaLocation })" unless @sourceDocument
throw new Error "Missing source collection (for #{ @sourcePath } from #{ @_metaLocation })" unless @sourceCollection
throw new Error "Source document not defined (for #{ @sourcePath } from #{ @_metaLocation })" unless @sourceDocument.Meta._listIndex?
assert not @sourceDocument.Meta._replaced
assert not @sourceDocument.Meta._delayIndex?
assert.equal @sourceDocument.Meta.document, @sourceDocument
assert.equal @sourceDocument.Meta.document.Meta, @sourceDocument.Meta
class globals.Document._ObservingField extends globals.Document._Field
class globals.Document._TargetedFieldsObservingField extends globals.Document._ObservingField
# Arguments:
# targetDocument, fields
constructor: (targetDocument, @fields) ->
super()
@fields ?= []
if targetDocument is 'self'
@targetDocument = 'self'
@targetCollection = null
else if _.isFunction(targetDocument) and targetDocument.prototype instanceof globals.Document
@targetDocument = targetDocument
@targetCollection = targetDocument.Meta.collection
else
throw new Error INVALID_TARGET
contributeToClass: (sourceDocument, sourcePath, ancestorArray) =>
super sourceDocument, sourcePath, ancestorArray
if @targetDocument is 'self'
@targetDocument = @sourceDocument
@targetCollection = @sourceCollection
# Helpful values to know where and what the field is
@inArray = @ancestorArray and startsWith @sourcePath, @ancestorArray
@isArray = @ancestorArray and @sourcePath is @ancestorArray
@arraySuffix = removePrefix @sourcePath, @ancestorArray if @inArray
validate: =>
super()
throw new Error "Missing target document (for #{ @sourcePath } from #{ @_metaLocation })" unless @targetDocument
throw new Error "Missing target collection (for #{ @sourcePath } from #{ @_metaLocation })" unless @targetCollection
throw new Error "Target document not defined (for #{ @sourcePath } from #{ @_metaLocation })" unless @targetDocument.Meta._listIndex?
assert not @targetDocument.Meta._replaced
assert not @targetDocument.Meta._delayIndex?
assert.equal @targetDocument.Meta.document, @targetDocument
assert.equal @targetDocument.Meta.document.Meta, @targetDocument.Meta
_setupTargetObservers: (updateAll) =>
return unless isModifiableCollection @sourceCollection
initializing = true
# Limit to PREFIX only when both collections are server side. Otherwise there is a collection
# which is local only to this instance and we want to process all documents for it. Alternatively,
# there is a collection through a connection, in which case we are conservative and also process
# all documents for it. We do not necessary know if connections are shared between instances.
limitToPrefix = isServerCollection(@targetCollection) and isServerCollection(@sourceCollection)
observers =
added: globals.Document._observerCallback limitToPrefix, (id, fields) =>
@updateSource id, fields if updateAll or not initializing
unless updateAll
observers.changed = globals.Document._observerCallback limitToPrefix, (id, fields) =>
@updateSource id, fields
observers.removed = globals.Document._observerCallback limitToPrefix, (id) =>
@removeSource id
referenceFields = fieldsToProjection @fields
handle = @targetCollection.find({}, fields: referenceFields).observeChanges observers
initializing = false
handle.stop() if updateAll
class globals.Document._ReferenceField extends globals.Document._TargetedFieldsObservingField
# Arguments:
# targetDocument, fields
# targetDocument, fields, required
# targetDocument, fields, required, reverseName
# targetDocument, fields, required, reverseName, reverseFields
constructor: (targetDocument, fields, @required, @reverseName, @reverseFields) ->
super targetDocument, fields