-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
object.go
737 lines (598 loc) · 18.2 KB
/
object.go
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
package core
import (
"errors"
"fmt"
"slices"
"sort"
"github.com/inoxlang/inox/internal/commonfmt"
permkind "github.com/inoxlang/inox/internal/core/permkind"
"github.com/inoxlang/inox/internal/inoxconsts"
"github.com/inoxlang/inox/internal/utils"
)
// Object implements Value.
type Object struct {
keys []string
values []Serializable
//TODO: Refactor to use a single []objectEntry slice if possible: this would reduce unsafe.Sizeof(Object) from 56 to 24.
// This would also make sortProps faster because a single slice would be modified.
//Additional fields that are allocated if the object becomes more 'complex' or is watched.
//Note: additionalObjectFields should never be set back to nil.
*additionalObjectFields
}
type additionalObjectFields struct {
url URL //can be empty
sysgraph SystemGraphPointer
constraintId ConstraintId
visibilityId VisibilityId
jobs *ValueLifetimeJobs //can be nil
//Locking and transaction related fields
lock SmartLock
//pendingChanges []pendingObjectEntryChange //only visible by the current read-write tx
//TODO: make sure the .IsEmpty and .Contains methods use them.
txIsolator StrongTransactionIsolator //TODO: replace with LiteTransactionIsolator
//Watching related fields
watchers *ValueWatchers
mutationCallbacks *MutationCallbacks
messageHandlers *SynchronousMessageHandlers
watchingDepth WatchingDepth
propMutationCallbacks []CallbackHandle
}
// NewObject creates an empty object.
func NewObject() *Object {
return &Object{}
}
// helper function to create an object, lifetime jobs are initialized.
func NewObjectFromMap(valMap ValMap, ctx *Context) *Object {
obj := objFrom(valMap)
obj.addMessageHandlers(ctx) // add handlers before because jobs can mutate the object
obj.instantiateLifetimeJobs(ctx)
return obj
}
// helper function to create an object, lifetime jobs are not initialized.
func NewObjectFromMapNoInit(valMap ValMap) *Object {
obj := objFrom(valMap)
return obj
}
func newUnitializedObjectWithPropCount(count int) *Object {
return &Object{
keys: make([]string, count),
values: make([]Serializable, count),
}
}
type ValMap map[string]Serializable
// helper function to create an object, lifetime jobs and system parts are NOT initialized
func objFrom(entryMap ValMap) *Object {
keys := make([]string, len(entryMap))
values := make([]Serializable, len(entryMap))
i := 0
for k, v := range entryMap {
keys[i] = k
values[i] = v
i++
}
obj := &Object{keys: keys, values: values}
obj.sortProps()
// NOTE: jobs not started
return obj
}
func objFromLists(keys []string, values []Serializable) *Object {
//handle index keys ? or ignore
obj := &Object{keys: keys, values: values}
obj.sortProps()
return obj
}
func (obj *Object) ensureAdditionalFields() {
if obj.additionalObjectFields == nil {
obj.additionalObjectFields = &additionalObjectFields{}
}
}
func (obj *Object) hasAdditionalFields() bool {
return obj.additionalObjectFields != nil
}
func (obj *Object) hasWatchersOrMutationCallbacks() bool {
return obj.additionalObjectFields != nil && (obj.mutationCallbacks != nil || obj.watchers != nil && len(obj.watchers.watchers) > 0)
}
func (obj *Object) hasPropMutationCallbacks() bool {
return obj.additionalObjectFields != nil && obj.propMutationCallbacks != nil
}
func (obj *Object) sortProps() {
if obj.hasPropMutationCallbacks() {
for len(obj.propMutationCallbacks) < len(obj.keys) {
obj.propMutationCallbacks = append(obj.propMutationCallbacks, FIRST_VALID_CALLBACK_HANDLE-1)
}
}
keys, values, newIndexes := sortProps(obj.keys, obj.values)
obj.keys, obj.values = keys, values
if obj.hasPropMutationCallbacks() {
newPropMutationCallbacks := make([]CallbackHandle, len(obj.propMutationCallbacks))
for i, newIndex := range newIndexes {
newPropMutationCallbacks[newIndex] = obj.propMutationCallbacks[i]
}
}
}
func (obj *Object) indexOfKey(k string) int {
for i, key := range obj.keys {
if key == k {
return i
}
}
panic(fmt.Errorf("unknown key %s", k))
}
// this function is called during object creation
func (obj *Object) instantiateLifetimeJobs(ctx *Context) error {
var jobs []*LifetimeJob
state := ctx.GetClosestState()
for keyIndex, key := range obj.keys {
if key != inoxconsts.IMPLICIT_PROP_NAME {
continue
}
list := obj.values[keyIndex].(*List)
for elemIndex := 0; elemIndex < list.Len(); elemIndex++ {
if job, ok := list.At(ctx, elemIndex).(*LifetimeJob); ok && job.subjectPattern == nil {
jobs = append(jobs, job)
}
}
}
if len(jobs) != 0 {
obj.Share(state)
obj.ensureAdditionalFields()
jobs := NewValueLifetimeJobs(ctx, obj, jobs)
if err := jobs.InstantiateJobs(ctx); err != nil {
return err
}
obj.jobs = jobs
}
return nil
}
// this function is called during object creation
func (obj *Object) addMessageHandlers(ctx *Context) error {
var handlers []*SynchronousMessageHandler
for keyIndex, key := range obj.keys {
if key != inoxconsts.IMPLICIT_PROP_NAME {
continue
}
list, ok := obj.values[keyIndex].(*List)
if !ok {
return nil
}
for elemIndex := 0; elemIndex < list.Len(); elemIndex++ {
if handler, ok := list.At(ctx, elemIndex).(*SynchronousMessageHandler); ok {
handlers = append(handlers, handler)
}
}
}
if len(handlers) != 0 {
obj.ensureAdditionalFields()
obj.messageHandlers = NewSynchronousMessageHandlers(handlers...)
}
return nil
}
// LifetimeJobs returns the lifetime jobs bound to the object, the returned pointer can be nil.
func (obj *Object) LifetimeJobs() *ValueLifetimeJobs {
if obj.hasAdditionalFields() {
return nil
}
return obj.jobs
}
func (obj *Object) IsSharable(originState *GlobalState) (bool, string) {
if obj.hasAdditionalFields() && obj.lock.IsValueShared() {
return true, ""
}
for i, v := range obj.values {
k := obj.keys[i]
if ok, expl := IsSharableOrClonable(v, originState); !ok {
return false, commonfmt.FmtNotSharableBecausePropertyNotSharable(k, expl)
}
}
return true, ""
}
func (obj *Object) Share(originState *GlobalState) {
obj.ensureAdditionalFields()
obj.lock.Share(originState, func() {
for i, v := range obj.values {
obj.values[i] = utils.Must(ShareOrClone(v, originState)).(Serializable)
}
//Allocating the additional fields enables transaction isolation.
obj.ensureAdditionalFields()
})
}
func (obj *Object) IsShared() bool {
if !obj.hasAdditionalFields() {
return false
}
return obj.lock.IsValueShared()
}
func (obj *Object) _lock(state *GlobalState) {
if obj.additionalObjectFields == nil { //not shared.
return
}
obj.lock.Lock(state, obj)
}
func (obj *Object) _unlock(state *GlobalState) {
if obj.additionalObjectFields == nil { //not shared.
return
}
obj.lock.Unlock(state, obj)
}
func (obj *Object) SmartLock(state *GlobalState) {
obj.ensureAdditionalFields()
obj.lock.Lock(state, obj, true)
}
func (obj *Object) SmartUnlock(state *GlobalState) {
if obj.additionalObjectFields == nil {
panic(errors.New("unexpected Object.SmartUnlock call: object is not locked because it does not have additional fields"))
}
obj.lock.Unlock(state, obj, true)
}
func (obj *Object) jobInstances() []*LifetimeJobInstance {
if !obj.hasAdditionalFields() {
return nil
}
return obj.jobs.Instances()
}
func (obj *Object) waitForOtherTxsToTerminate(ctx *Context, requiredRunningTx bool) (currentTx *Transaction) {
if !obj.hasAdditionalFields() {
return
}
tx, err := obj.txIsolator.WaitForOtherTxsToTerminate(ctx, requiredRunningTx)
if err != nil {
panic(err)
}
return tx
}
func (obj *Object) Prop(ctx *Context, name string) Value {
return obj.prop(ctx, name, true)
}
func (obj *Object) PropNotStored(ctx *Context, name string) Value {
return obj.prop(ctx, name, false)
}
func (obj *Object) prop(ctx *Context, name string, stored bool) (returnedValue Value) {
obj.waitForOtherTxsToTerminate(ctx, !stored)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
if obj.hasAdditionalFields() {
if obj.url != "" {
perm := DatabasePermission{
Kind_: permkind.Read,
Entity: obj.url.ToDirURL().AppendRelativePath("./" + Path(name)),
}
if err := ctx.CheckHasPermission(perm); err != nil {
panic(err)
}
}
// //If the current transaction is read-write we look at the pending changes
// //before checking the actual entries.
// if tx != nil && !tx.IsReadonly() {
// for _, change := range obj.pendingChanges {
// if change.key != name {
// continue
// }
// if change.isDeletion {
// panic(FormatErrPropertyDoesNotExist(name, obj))
// }
// returnedValue = change.value
// break
// }
// }
}
//Iterate over entries.
if returnedValue == nil {
for i, key := range obj.keys {
if key == name {
returnedValue = obj.values[i]
break
}
}
}
if returnedValue == nil {
panic(FormatErrPropertyDoesNotExist(name, obj))
}
if obj.IsShared() && stored {
//We use ShareOrClone and not CheckSharedOrClone because a not-yet-shared value (at any depth) may have been added
//during a previous PropNotStored call.
returnedValue = utils.Must(ShareOrClone(returnedValue, closestState)).(Serializable)
}
return
}
func (obj *Object) SetProp(ctx *Context, name string, value Value) error {
serializableVal, ok := value.(Serializable)
if !ok {
return fmt.Errorf("value is not serializable")
}
tx := obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
if obj.IsShared() {
newVal, err := ShareOrClone(value, closestState)
if err != nil {
return fmt.Errorf("failed to share/clone value when setting property %s: %w", name, err)
}
serializableVal = newVal.(Serializable)
}
unlock := true
obj._lock(closestState)
defer func() {
if unlock {
obj._unlock(closestState)
}
}()
var constraint Pattern
if obj.hasAdditionalFields() && obj.constraintId.HasConstraint() {
constraint, _ = GetConstraint(obj.constraintId)
}
if obj.hasAdditionalFields() && obj.url != "" {
perm := DatabasePermission{
Kind_: permkind.Write,
Entity: obj.url.ToDirURL().AppendRelativePath("./" + Path(name)),
}
if err := ctx.CheckHasPermission(perm); err != nil {
return err
}
}
//If the object is an entity and we are in a transaction we update the pending changes instead of directly mutating the entries.
//If there is already a change for the entry we update it, else we add a new change.
if tx != nil && obj.hasURL() {
if tx.IsReadonly() {
//TODO: also prevent deep mutation
panic(fmt.Errorf("cannot mutate object (entity): %w", ErrEffectsNotAllowedInReadonlyTransaction))
}
// obj.ensureAdditionalFields()
// needToAddChange := true
// for i, change := range obj.pendingChanges {
// if change.key != name {
// continue
// }
// needToAddChange = false
// if change.isDeletion {
// obj.pendingChanges[i].isDeletion = false
// obj.pendingChanges[i].value = serializableVal
// } else {
// obj.pendingChanges[i].value = serializableVal
// }
// break
// }
// if needToAddChange {
// obj.pendingChanges = append(obj.pendingChanges, pendingObjectEntryChange{
// key: name,
// value: serializableVal,
// })
// }
//TODO: on transaction rollback: remove all pending changes.
//TODO: on transaction validation (if constraints): apply changes, check constraints.
//If fail: reverse changes
//If success: inform watchers and call mutation callbacks
//if no constraints: apply changes on commit
//return nil
}
for i, key := range obj.keys {
if key == name { // property is already present
prevValue := obj.values[i]
obj.values[i] = serializableVal
// check constraints
if constraint != nil && !constraint.(*ObjectPattern).Test(ctx, obj) {
obj.values[i] = prevValue
return ErrConstraintViolation
}
// update object
obj.sortProps()
if !obj.hasAdditionalFields() {
return nil
}
obj.sysgraph.AddEvent(ctx, "prop updated: "+name, obj)
if obj.hasPropMutationCallbacks() {
//Remove the mutation callback of the previous value and a mutation callback
//for the new value.
index := obj.indexOfKey(name)
obj.removePropMutationCallbackNoLock(ctx, index, prevValue)
if err := obj.addPropMutationCallbackNoLock(ctx, index, serializableVal); err != nil {
return fmt.Errorf("failed to add mutation callback for updated object property %s: %w", name, err)
}
}
if obj.hasWatchersOrMutationCallbacks() {
//Create mutation and inform watchers about it.
mutation := NewUpdatePropMutation(ctx, name, serializableVal, ShallowWatching, Path("/"+name))
obj.watchers.InformAboutAsync(ctx, mutation, mutation.Depth, true)
if obj.mutationCallbacks != nil {
unlock = false
obj._unlock(closestState)
obj.mutationCallbacks.CallMicrotasks(ctx, mutation)
}
}
return nil
}
}
// add new property
obj.keys = append(obj.keys, name)
obj.values = append(obj.values, serializableVal)
//check constraint
if constraint != nil && !constraint.(*ObjectPattern).Test(ctx, obj) {
obj.keys = obj.keys[:len(obj.keys)-1]
obj.values = obj.values[:len(obj.values)-1]
return ErrConstraintViolation
}
obj.sortProps()
if !obj.hasAdditionalFields() {
return nil
}
//---------------------------------------
if obj.hasPropMutationCallbacks() {
if err := obj.addPropMutationCallbackNoLock(ctx, len(obj.keys)-1, serializableVal); err != nil {
return fmt.Errorf("failed to add mutation callback for new object property %s: %w", name, err)
}
}
obj.sysgraph.AddEvent(ctx, "new prop: "+name, obj)
if obj.hasWatchersOrMutationCallbacks() {
//Inform watchers & microtasks about the update.
mutation := NewAddPropMutation(ctx, name, serializableVal, ShallowWatching, Path("/"+name))
obj.sysgraph.AddEvent(ctx, "new prop: "+name, obj)
obj.watchers.InformAboutAsync(ctx, mutation, mutation.Depth, true)
if obj.mutationCallbacks != nil {
unlock = false
obj._unlock(closestState)
obj.mutationCallbacks.CallMicrotasks(ctx, mutation)
}
}
return nil
}
func (obj *Object) PropertyNames(ctx *Context) []string {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
return obj.keys
}
func (obj *Object) HasProp(ctx *Context, name string) bool {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
for _, k := range obj.keys {
if k == name {
return true
}
}
return false
}
func (obj *Object) HasPropValue(ctx *Context, value Value) bool {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
for _, v := range obj.values {
if v.Equal(ctx, value, map[uintptr]uintptr{}, 0) {
return true
}
}
return false
}
func (obj *Object) EntryMap(ctx *Context) map[string]Serializable {
if obj == nil {
return nil
}
if ctx != nil {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
} else if obj.IsShared() {
panic(errors.New("nil context"))
}
isShared := obj.IsShared()
map_ := map[string]Serializable{}
for i, v := range obj.values {
if isShared {
v = utils.Must(CheckSharedOrClone(v, map[uintptr]Clonable{}, 0)).(Serializable)
}
map_[obj.keys[i]] = v
}
return map_
}
func (obj *Object) ValueEntryMap(ctx *Context) map[string]Value {
if obj == nil {
return nil
}
if ctx != nil {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
} else if obj.IsShared() {
panic(errors.New("nil context"))
}
isShared := obj.IsShared()
map_ := map[string]Value{}
for i, v := range obj.values {
if isShared {
v = utils.Must(CheckSharedOrClone(v, map[uintptr]Clonable{}, 0)).(Serializable)
}
map_[obj.keys[i]] = v
}
return map_
}
func (obj *Object) ForEachEntry(fn func(k string, v Serializable) error) error {
if obj.IsShared() {
panic(errors.New("Object.ForEachEntry() can only be called on objects that are not shared"))
}
for i, v := range obj.values {
if err := fn(obj.keys[i], v); err != nil {
return err
}
}
return nil
}
// ForEachElement iterates over the elements in the empty "" property, if the property's value is not a list
// the function does nothing.
func (obj *Object) ForEachElement(ctx *Context, fn func(index int, v Serializable) error) error {
if obj.IsShared() {
panic(errors.New("Object.ForEachElement() can only be called on objects that are not shared"))
}
for i, v := range obj.values {
key := obj.keys[i]
if key != inoxconsts.IMPLICIT_PROP_NAME {
continue
}
list, ok := v.(*List)
if !ok {
return nil
}
for elemIndex := 0; elemIndex < list.Len(); elemIndex++ {
if err := fn(elemIndex, list.At(ctx, elemIndex).(Serializable)); err != nil {
return err
}
}
}
return nil
}
func (obj *Object) URL() (URL, bool) {
if !obj.hasAdditionalFields() {
return "", false
}
if obj.url != "" {
return obj.url, true
}
return "", false
}
func (obj *Object) hasURL() bool {
_, ok := obj.URL()
return ok
}
func (obj *Object) SetURLOnce(ctx *Context, u URL) error {
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
obj.ensureAdditionalFields()
if obj.url != "" {
return ErrURLAlreadySet
}
obj.url = u
return nil
}
func (obj *Object) Keys(ctx *Context) []string {
obj.waitForOtherTxsToTerminate(ctx, false)
closestState := ctx.GetClosestState()
obj._lock(closestState)
defer obj._unlock(closestState)
return obj.keys
}
func sortProps[V Value](keys []string, values []V) ([]string, []V, []int) {
if len(keys) == 0 {
return nil, nil, nil
}
newKeys := slices.Clone(keys)
sort.Strings(newKeys)
newValues := make([]V, len(values))
newIndexes := make([]int, len(values))
for i := 0; i < len(keys); i++ {
newIndex := sort.SearchStrings(newKeys, keys[i])
newValues[newIndex] = values[i]
newIndexes[i] = newIndex
}
return newKeys, newValues, newIndexes
}
// A pendingObjectEntryChange represents a change for a shared object's entry,
// it is an update or a deletion.
type pendingObjectEntryChange struct {
isDeletion bool //update if false
key string
value Serializable //nil if deletion
}