-
Notifications
You must be signed in to change notification settings - Fork 16
/
document_store.go
599 lines (497 loc) · 15.8 KB
/
document_store.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
package ravendb
import (
"crypto/tls"
"crypto/x509"
"strings"
"sync"
"time"
)
// Note: Java's IDocumentStore is DocumentStore
// Note: Java's DocumentStoreBase is folded into DocumentStore
// DocumentStore represents a database
type DocumentStore struct {
// from DocumentStoreBase
onBeforeStore []func(*BeforeStoreEventArgs)
onAfterSaveChanges []func(*AfterSaveChangesEventArgs)
onBeforeDelete []func(*BeforeDeleteEventArgs)
onBeforeQuery []func(*BeforeQueryEventArgs)
// TODO: there's no way to register for this event
onSessionCreated []func(*SessionCreatedEventArgs)
subscriptions *DocumentSubscriptions
disposed bool
conventions *DocumentConventions
urls []string // urls for HTTP endopoints of server nodes
initialized bool
Certificate *tls.Certificate
TrustStore *x509.Certificate
database string // name of the database
// maps database name to DatabaseChanges. Must be protected with mutex
databaseChanges map[string]*DatabaseChanges
// Note: access must be protected with mu
// Lazy.Value is **EvictItemsFromCacheBasedOnChanges
aggressiveCacheChanges map[string]*evictItemsFromCacheBasedOnChanges
// maps database name to its RequestsExecutor
// access must be protected with mu
// TODO: in Java is ConcurrentMap<String, RequestExecutor> requestExecutors
// so must protect access with mutex and use case-insensitive lookup
requestsExecutors map[string]*RequestExecutor
multiDbHiLo *MultiDatabaseHiLoIDGenerator
maintenanceOperationExecutor *MaintenanceOperationExecutor
operationExecutor *OperationExecutor
identifier string
aggressiveCachingUsed bool
afterClose []func(*DocumentStore)
beforeClose []func(*DocumentStore)
mu sync.Mutex
}
// methods from DocumentStoreBase
// GetConventions returns DocumentConventions
func (s *DocumentStore) GetConventions() *DocumentConventions {
if s.conventions == nil {
s.conventions = NewDocumentConventions()
}
return s.conventions
}
// SetConventions sets DocumentConventions
func (s *DocumentStore) SetConventions(conventions *DocumentConventions) {
s.assertNotInitialized("conventions")
s.conventions = conventions
}
// Subscriptions returns DocumentSubscriptions which allows subscribing to changes in store
func (s *DocumentStore) Subscriptions() *DocumentSubscriptions {
return s.subscriptions
}
// GetUrls returns urls of all RavenDB nodes
func (s *DocumentStore) GetUrls() []string {
return s.urls
}
// SetUrls sets initial urls of RavenDB nodes
func (s *DocumentStore) SetUrls(urls []string) {
panicIf(len(urls) == 0, "urls is empty")
s.assertNotInitialized("urls")
for i, s := range urls {
urls[i] = strings.TrimSuffix(s, "/")
}
s.urls = urls
}
func (s *DocumentStore) ensureNotClosed() error {
if s.disposed {
return newIllegalStateError("The document store has already been disposed and cannot be used")
}
return nil
}
// AddBeforeStoreStoreListener registers a function that will be called before storing ab entity.
// It'll be registered with every new session.
// Returns listener id that can be passed to RemoveBeforeStoreListener to unregister
// the listener.
func (s *DocumentStore) AddBeforeStoreListener(handler func(*BeforeStoreEventArgs)) int {
id := len(s.onBeforeStore)
s.onBeforeStore = append(s.onBeforeStore, handler)
return id
}
// RemoveBeforeStoreListener removes a listener given id returned by AddBeforeStoreListener
func (s *DocumentStore) RemoveBeforeStoreListener(handlerID int) {
s.onBeforeStore[handlerID] = nil
}
// AddAfterSaveChangesListener registers a function that will be called before saving changes.
// It'll be registered with every new session.
// Returns listener id that can be passed to RemoveAfterSaveChangesListener to unregister
// the listener.
func (s *DocumentStore) AddAfterSaveChangesListener(handler func(*AfterSaveChangesEventArgs)) int {
s.onAfterSaveChanges = append(s.onAfterSaveChanges, handler)
return len(s.onAfterSaveChanges) - 1
}
// RemoveAfterSaveChangesListener removes a listener given id returned by AddAfterSaveChangesListener
func (s *DocumentStore) RemoveAfterSaveChangesListener(handlerID int) {
s.onAfterSaveChanges[handlerID] = nil
}
// AddBeforeDeleteListener registers a function that will be called before deleting an entity.
// It'll be registered with every new session.
// Returns listener id that can be passed to RemoveBeforeDeleteListener to unregister
// the listener.
func (s *DocumentStore) AddBeforeDeleteListener(handler func(*BeforeDeleteEventArgs)) int {
s.onBeforeDelete = append(s.onBeforeDelete, handler)
return len(s.onBeforeDelete) - 1
}
// RemoveBeforeDeleteListener removes a listener given id returned by AddBeforeDeleteListener
func (s *DocumentStore) RemoveBeforeDeleteListener(handlerID int) {
s.onBeforeDelete[handlerID] = nil
}
// AddBeforeQueryListener registers a function that will be called before running a query.
// It allows customizing query via DocumentQueryCustomization.
// It'll be registered with every new session.
// Returns listener id that can be passed to RemoveBeforeQueryListener to unregister
// the listener.
func (s *DocumentStore) AddBeforeQueryListener(handler func(*BeforeQueryEventArgs)) int {
s.onBeforeQuery = append(s.onBeforeQuery, handler)
return len(s.onBeforeQuery) - 1
}
// RemoveBeforeQueryListener removes a listener given id returned by AddBeforeQueryListener
func (s *DocumentStore) RemoveBeforeQueryListener(handlerID int) {
s.onBeforeQuery[handlerID] = nil
}
func (s *DocumentStore) registerEvents(session *InMemoryDocumentSessionOperations) {
// TODO: unregister those events?
for _, handler := range s.onBeforeStore {
if handler != nil {
session.AddBeforeStoreListener(handler)
}
}
for _, handler := range s.onAfterSaveChanges {
if handler != nil {
session.AddAfterSaveChangesListener(handler)
}
}
for _, handler := range s.onBeforeDelete {
if handler != nil {
session.AddBeforeDeleteListener(handler)
}
}
for _, handler := range s.onBeforeQuery {
if handler != nil {
session.AddBeforeQueryListener(handler)
}
}
}
func (s *DocumentStore) afterSessionCreated(session *InMemoryDocumentSessionOperations) {
for _, handler := range s.onSessionCreated {
if handler != nil {
args := &SessionCreatedEventArgs{
Session: session,
}
handler(args)
}
}
}
func (s *DocumentStore) assertInitialized() error {
if !s.initialized {
return newIllegalStateError("DocumentStore must be initialized")
}
return nil
}
func (s *DocumentStore) assertNotInitialized(property string) {
panicIf(s.initialized, "You cannot set '%s' after the document store has been initialized.", property)
}
func (s *DocumentStore) GetDatabase() string {
return s.database
}
func (s *DocumentStore) SetDatabase(database string) {
s.assertNotInitialized("database")
s.database = database
}
func (s *DocumentStore) AggressivelyCache(database string) (CancelFunc, error) {
return s.AggressivelyCacheForDatabase(time.Hour*24, database)
}
func newDocumentStore() *DocumentStore {
s := &DocumentStore{
requestsExecutors: map[string]*RequestExecutor{},
conventions: NewDocumentConventions(),
databaseChanges: map[string]*DatabaseChanges{},
aggressiveCacheChanges: map[string]*evictItemsFromCacheBasedOnChanges{},
}
s.subscriptions = newDocumentSubscriptions(s)
return s
}
func NewDocumentStore(urls []string, database string) *DocumentStore {
res := newDocumentStore()
if len(urls) > 0 {
res.SetUrls(urls)
}
if database != "" {
res.SetDatabase(database)
}
return res
}
// Get an identifier of the store. For debugging / testing.
func (s *DocumentStore) GetIdentifier() string {
if s.identifier != "" {
return s.identifier
}
if len(s.urls) == 0 {
return ""
}
if s.database != "" {
return strings.Join(s.urls, ",") + " (DB: " + s.database + ")"
}
return strings.Join(s.urls, ",")
}
func (s *DocumentStore) SetIdentifier(identifier string) {
s.identifier = identifier
}
// Close closes the Store
func (s *DocumentStore) Close() {
if s.disposed {
redbg("DocumentStore.Close: already disposed\n")
return
}
redbg("DocumentStore.Close\n")
for _, fn := range s.beforeClose {
fn(s)
}
s.beforeClose = nil
for _, evict := range s.aggressiveCacheChanges {
evict.Close()
}
for _, changes := range s.databaseChanges {
changes.Close()
}
if s.multiDbHiLo != nil {
s.multiDbHiLo.ReturnUnusedRange()
}
if s.Subscriptions() != nil {
_ = s.Subscriptions().Close()
}
s.disposed = true
for _, fn := range s.afterClose {
fn(s)
}
s.afterClose = nil
for _, re := range s.requestsExecutors {
re.Close()
}
}
// OpenSession opens a new session to document Store.
// If database is not given, we'll use store's database name
func (s *DocumentStore) OpenSession(database string) (*DocumentSession, error) {
sessionOptions := &SessionOptions{
Database: database,
}
return s.OpenSessionWithOptions(sessionOptions)
}
func (s *DocumentStore) OpenSessionWithOptions(options *SessionOptions) (*DocumentSession, error) {
if err := s.assertInitialized(); err != nil {
return nil, err
}
if err := s.ensureNotClosed(); err != nil {
return nil, err
}
sessionID := NewUUID().String()
databaseName := options.Database
if databaseName == "" {
databaseName = s.GetDatabase()
}
requestExecutor := options.RequestExecutor
if requestExecutor == nil {
requestExecutor = s.GetRequestExecutor(databaseName)
}
transactionMode := options.TransactionMode
err := assertTransactionMode(transactionMode)
if err != nil {
return nil, err
}
disableAtomicDocumentWritesInClusterWideTransaction := options.DisableAtomicDocumentWritesInClusterWideTransaction
session := newDocumentSessionBase(databaseName, s, sessionID, requestExecutor, transactionMode, disableAtomicDocumentWritesInClusterWideTransaction)
s.registerEvents(session.InMemoryDocumentSessionOperations)
s.afterSessionCreated(session.InMemoryDocumentSessionOperations)
return session, nil
}
func (s *DocumentStore) ExecuteIndex(task *IndexCreationTask, database string) error {
if err := s.assertInitialized(); err != nil {
return err
}
return task.Execute(s, s.conventions, database)
}
func (s *DocumentStore) ExecuteIndexes(tasks []*IndexCreationTask, database string) error {
if err := s.assertInitialized(); err != nil {
return err
}
indexesToAdd := indexCreationCreateIndexesToAdd(tasks, s.conventions)
op := NewPutIndexesOperation(indexesToAdd...)
if database == "" {
database = s.GetDatabase()
}
return s.Maintenance().ForDatabase(database).Send(op)
}
// GetRequestExecutor gets a request executor.
// database is optional
func (s *DocumentStore) GetRequestExecutor(database string) *RequestExecutor {
must(s.assertInitialized())
if database == "" {
database = s.GetDatabase()
}
database = strings.ToLower(database)
s.mu.Lock()
executor, ok := s.requestsExecutors[database]
s.mu.Unlock()
if ok {
return executor
}
if !s.GetConventions().IsDisableTopologyUpdates() {
executor = RequestExecutorCreate(s.GetUrls(), database, s.Certificate, s.TrustStore, s.GetConventions())
} else {
executor = RequestExecutorCreateForSingleNodeWithConfigurationUpdates(s.GetUrls()[0], database, s.Certificate, s.TrustStore, s.GetConventions())
}
s.mu.Lock()
s.requestsExecutors[database] = executor
s.mu.Unlock()
return executor
}
// Initialize initializes document Store,
// Must be called before executing any operation.
func (s *DocumentStore) Initialize() error {
if s.initialized {
return nil
}
err := s.assertValidConfiguration()
if err != nil {
return err
}
conventions := s.conventions
if conventions.GetDocumentIDGenerator() == nil {
generator := NewMultiDatabaseHiLoIDGenerator(s, s.GetConventions())
s.multiDbHiLo = generator
genID := func(dbName string, entity interface{}) (string, error) {
return generator.GenerateDocumentID(dbName, entity)
}
conventions.SetDocumentIDGenerator(genID)
}
s.initialized = true
return nil
}
func (s *DocumentStore) assertValidConfiguration() error {
if len(s.urls) == 0 {
return newIllegalArgumentError("Must provide urls to NewDocumentStore")
}
return nil
}
type RestoreCaching struct {
re *RequestExecutor
old *AggressiveCacheOptions
}
func (r *RestoreCaching) Close() error {
r.re.aggressiveCaching = r.old
return nil
}
func (s *DocumentStore) DisableAggressiveCaching(databaseName string) *RestoreCaching {
if databaseName == "" {
databaseName = s.GetDatabase()
}
re := s.GetRequestExecutor(databaseName)
old := re.aggressiveCaching
re.aggressiveCaching = nil
res := &RestoreCaching{
re: re,
old: old,
}
return res
}
func (s *DocumentStore) Changes(database string) *DatabaseChanges {
must(s.assertInitialized())
if database == "" {
database = s.GetDatabase()
}
s.mu.Lock()
changes, ok := s.databaseChanges[database]
s.mu.Unlock()
if !ok {
changes = s.createDatabaseChanges(database)
s.mu.Lock()
s.databaseChanges[database] = changes
s.mu.Unlock()
}
return changes
}
func (s *DocumentStore) createDatabaseChanges(database string) *DatabaseChanges {
panicIf(database == "", "database can't be empty string")
onDispose := func() {
s.mu.Lock()
delete(s.databaseChanges, database)
s.mu.Unlock()
}
re := s.GetRequestExecutor(database)
return newDatabaseChanges(re, database, onDispose)
}
func (s *DocumentStore) GetLastDatabaseChangesStateError(database string) error {
if database == "" {
database = s.GetDatabase()
}
s.mu.Lock()
databaseChanges, ok := s.databaseChanges[database]
s.mu.Unlock()
if !ok {
return nil
}
ch := databaseChanges
return ch.getLastConnectionStateError()
}
func (s *DocumentStore) AggressivelyCacheFor(cacheDuration time.Duration) (CancelFunc, error) {
return s.AggressivelyCacheForDatabase(cacheDuration, "")
}
func (s *DocumentStore) AggressivelyCacheForDatabase(cacheDuration time.Duration, database string) (CancelFunc, error) {
if database == "" {
database = s.GetDatabase()
}
if database == "" {
return nil, newIllegalArgumentError("must have database")
}
s.mu.Lock()
cachingUsed := s.aggressiveCachingUsed
s.mu.Unlock()
if !cachingUsed {
err := s.listenToChangesAndUpdateTheCache(database)
if err != nil {
return nil, err
}
}
// TODO: protect access to aggressiveCaching
opts := &AggressiveCacheOptions{
Duration: cacheDuration,
}
re := s.GetRequestExecutor(database)
oldOpts := re.aggressiveCaching
re.aggressiveCaching = opts
restorer := func() {
re.aggressiveCaching = oldOpts
}
return restorer, nil
}
func (s *DocumentStore) listenToChangesAndUpdateTheCache(database string) error {
s.mu.Lock()
s.aggressiveCachingUsed = true
evict := s.aggressiveCacheChanges[database]
s.mu.Unlock()
if evict != nil {
return nil
}
evict, err := newEvictItemsFromCacheBasedOnChanges(s, database)
if err != nil {
return err
}
s.mu.Lock()
s.aggressiveCacheChanges[database] = evict
s.mu.Unlock()
return nil
}
func (s *DocumentStore) AddBeforeCloseListener(fn func(*DocumentStore)) int {
s.beforeClose = append(s.beforeClose, fn)
return len(s.beforeClose) - 1
}
func (s *DocumentStore) RemoveBeforeCloseListener(idx int) {
s.beforeClose[idx] = nil
}
func (s *DocumentStore) AddAfterCloseListener(fn func(*DocumentStore)) int {
s.afterClose = append(s.afterClose, fn)
return len(s.afterClose) - 1
}
func (s *DocumentStore) RemoveAfterCloseListener(idx int) {
s.afterClose[idx] = nil
}
func (s *DocumentStore) Maintenance() *MaintenanceOperationExecutor {
must(s.assertInitialized())
if s.maintenanceOperationExecutor == nil {
s.maintenanceOperationExecutor = NewMaintenanceOperationExecutor(s, "")
}
return s.maintenanceOperationExecutor
}
func (s *DocumentStore) Operations() *OperationExecutor {
if s.operationExecutor == nil {
s.operationExecutor = NewOperationExecutor(s, "")
}
return s.operationExecutor
}
func (s *DocumentStore) BulkInsert(database string) *BulkInsertOperation {
if database == "" {
database = s.GetDatabase()
}
return NewBulkInsertOperation(database, s)
}