forked from omniscale/imposm3
/
diff.go
639 lines (552 loc) · 13.5 KB
/
diff.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
package cache
import (
"log"
"os"
"path/filepath"
"runtime"
"sort"
"sync"
"github.com/jmhodges/levigo"
"github.com/omniscale/imposm3/cache/binary"
"github.com/omniscale/imposm3/element"
)
type byInt64 []int64
func (a byInt64) Len() int { return len(a) }
func (a byInt64) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byInt64) Less(i, j int) bool { return a[i] < a[j] }
type DiffCache struct {
Dir string
Coords *CoordsRefIndex // Stores which ways a coord references
CoordsRel *CoordsRelRefIndex // Stores which relations a coord references
Ways *WaysRefIndex // Stores which relations a way references
opened bool
}
func NewDiffCache(dir string) *DiffCache {
cache := &DiffCache{Dir: dir}
return cache
}
func (c *DiffCache) Close() {
if c.Coords != nil {
c.Coords.Close()
c.Coords = nil
}
if c.CoordsRel != nil {
c.CoordsRel.Close()
c.CoordsRel = nil
}
if c.Ways != nil {
c.Ways.Close()
c.Ways = nil
}
}
func (c *DiffCache) Flush() {
if c.Coords != nil {
c.Coords.Flush()
}
if c.CoordsRel != nil {
c.CoordsRel.Flush()
}
if c.Ways != nil {
c.Ways.Flush()
}
}
func (c *DiffCache) Open() error {
var err error
c.Coords, err = newCoordsRefIndex(filepath.Join(c.Dir, "coords_index"))
if err != nil {
c.Close()
return err
}
c.CoordsRel, err = newCoordsRelRefIndex(filepath.Join(c.Dir, "coords_rel_index"))
if err != nil {
c.Close()
return err
}
c.Ways, err = newWaysRefIndex(filepath.Join(c.Dir, "ways_index"))
if err != nil {
c.Close()
return err
}
c.opened = true
return nil
}
func (c *DiffCache) Exists() bool {
if c.opened {
return true
}
if _, err := os.Stat(filepath.Join(c.Dir, "coords_index")); !os.IsNotExist(err) {
return true
}
if _, err := os.Stat(filepath.Join(c.Dir, "coords_rel_index")); !os.IsNotExist(err) {
return true
}
if _, err := os.Stat(filepath.Join(c.Dir, "ways_index")); !os.IsNotExist(err) {
return true
}
return false
}
func (c *DiffCache) Remove() error {
if c.opened {
c.Close()
}
if err := os.RemoveAll(filepath.Join(c.Dir, "coords_index")); err != nil {
return err
}
if err := os.RemoveAll(filepath.Join(c.Dir, "coords_rel_index")); err != nil {
return err
}
if err := os.RemoveAll(filepath.Join(c.Dir, "ways_index")); err != nil {
return err
}
return nil
}
const bufferSize = 64 * 1024
type idRef struct {
id int64
ref int64
}
// idRefBunch stores multiple IdRefs
type idRefBunch struct {
id int64 // the bunch id
idRefs []element.IdRefs
}
// idRefBunches can hold multiple idRefBunch
type idRefBunches map[int64]idRefBunch
func (bunches *idRefBunches) add(bunchId, id, ref int64) {
idRefs := bunches.getCreate(bunchId, id)
idRefs.Add(ref)
}
func (bunches *idRefBunches) getCreate(bunchId, id int64) *element.IdRefs {
bunch, ok := (*bunches)[bunchId]
if !ok {
bunch = idRefBunch{id: bunchId}
}
result := bunch.getCreate(id)
(*bunches)[bunchId] = bunch
return result
}
func (bunch *idRefBunch) get(id int64) *element.IdRefs {
var result *element.IdRefs
i := sort.Search(len(bunch.idRefs), func(i int) bool {
return bunch.idRefs[i].Id >= id
})
if i < len(bunch.idRefs) && bunch.idRefs[i].Id == id {
result = &bunch.idRefs[i]
}
return result
}
func (bunch *idRefBunch) getCreate(id int64) *element.IdRefs {
var result *element.IdRefs
i := sort.Search(len(bunch.idRefs), func(i int) bool {
return bunch.idRefs[i].Id >= id
})
if i < len(bunch.idRefs) && bunch.idRefs[i].Id >= id {
if bunch.idRefs[i].Id == id {
result = &bunch.idRefs[i]
} else {
bunch.idRefs = append(bunch.idRefs, element.IdRefs{})
copy(bunch.idRefs[i+1:], bunch.idRefs[i:])
bunch.idRefs[i] = element.IdRefs{Id: id}
result = &bunch.idRefs[i]
}
} else {
bunch.idRefs = append(bunch.idRefs, element.IdRefs{Id: id})
result = &bunch.idRefs[len(bunch.idRefs)-1]
}
return result
}
var idRefBunchesPool chan idRefBunches
func init() {
idRefBunchesPool = make(chan idRefBunches, 1)
}
// bunchRefCache
type bunchRefCache struct {
cache
linearImport bool
buffer idRefBunches
write chan idRefBunches
addc chan idRef
mu sync.Mutex
waitAdd *sync.WaitGroup
waitWrite *sync.WaitGroup
}
func newRefIndex(path string, opts *cacheOptions) (*bunchRefCache, error) {
index := bunchRefCache{}
index.options = opts
err := index.open(path)
if err != nil {
return nil, err
}
index.write = make(chan idRefBunches, 2)
index.buffer = make(idRefBunches, bufferSize)
index.addc = make(chan idRef, 1024)
index.waitWrite = &sync.WaitGroup{}
index.waitAdd = &sync.WaitGroup{}
return &index, nil
}
type CoordsRefIndex struct {
bunchRefCache
}
type CoordsRelRefIndex struct {
bunchRefCache
}
type WaysRefIndex struct {
bunchRefCache
}
func newCoordsRefIndex(dir string) (*CoordsRefIndex, error) {
cache, err := newRefIndex(dir, &globalCacheOptions.CoordsIndex)
if err != nil {
return nil, err
}
return &CoordsRefIndex{*cache}, nil
}
func newCoordsRelRefIndex(dir string) (*CoordsRelRefIndex, error) {
cache, err := newRefIndex(dir, &globalCacheOptions.CoordsIndex)
if err != nil {
return nil, err
}
return &CoordsRelRefIndex{*cache}, nil
}
func newWaysRefIndex(dir string) (*WaysRefIndex, error) {
cache, err := newRefIndex(dir, &globalCacheOptions.WaysIndex)
if err != nil {
return nil, err
}
return &WaysRefIndex{*cache}, nil
}
func (index *bunchRefCache) getBunchId(id int64) int64 {
return id / 64
}
func (index *bunchRefCache) Flush() {
if index.linearImport {
// disable linear import flushes buffer
index.SetLinearImport(false)
index.SetLinearImport(true)
}
}
func (index *bunchRefCache) Close() {
if index.linearImport {
// disable linear import first to flush buffer
index.SetLinearImport(false)
}
index.cache.Close()
}
func (index *bunchRefCache) Get(id int64) []int64 {
if index.linearImport {
panic("programming error: get not supported in linearImport mode")
}
keyBuf := idToKeyBuf(index.getBunchId(id))
data, err := index.db.Get(index.ro, keyBuf)
if err != nil {
panic(err)
}
if data != nil {
idRefs := idRefsPool.get()
defer idRefsPool.release(idRefs)
for _, idRef := range binary.UnmarshalIdRefsBunch2(data, idRefs) {
if idRef.Id == id {
return idRef.Refs
}
}
}
return nil
}
func (index *bunchRefCache) Add(id, ref int64) error {
keyBuf := idToKeyBuf(index.getBunchId(id))
data, err := index.db.Get(index.ro, keyBuf)
if err != nil {
return err
}
var idRefs []element.IdRefs
if data != nil {
idRefs = idRefsPool.get()
defer idRefsPool.release(idRefs)
idRefs = binary.UnmarshalIdRefsBunch2(data, idRefs)
}
idRefBunch := idRefBunch{index.getBunchId(id), idRefs}
idRef := idRefBunch.getCreate(id)
idRef.Add(ref)
data = bytePool.get()
defer bytePool.release(data)
data = binary.MarshalIdRefsBunch2(idRefBunch.idRefs, data)
return index.db.Put(index.wo, keyBuf, data)
}
func (index *bunchRefCache) DeleteRef(id, ref int64) error {
if index.linearImport {
panic("programming error: delete not supported in linearImport mode")
}
keyBuf := idToKeyBuf(index.getBunchId(id))
data, err := index.db.Get(index.ro, keyBuf)
if err != nil {
return err
}
if data != nil {
idRefs := idRefsPool.get()
defer idRefsPool.release(idRefs)
idRefs = binary.UnmarshalIdRefsBunch2(data, idRefs)
idRefBunch := idRefBunch{index.getBunchId(id), idRefs}
idRef := idRefBunch.get(id)
if idRef != nil {
idRef.Delete(ref)
data := bytePool.get()
defer bytePool.release(data)
data = binary.MarshalIdRefsBunch2(idRefs, data)
return index.db.Put(index.wo, keyBuf, data)
}
}
return nil
}
func (index *bunchRefCache) Delete(id int64) error {
if index.linearImport {
panic("programming error: delete not supported in linearImport mode")
}
keyBuf := idToKeyBuf(index.getBunchId(id))
data, err := index.db.Get(index.ro, keyBuf)
if err != nil {
return err
}
if data != nil {
idRefs := idRefsPool.get()
defer idRefsPool.release(idRefs)
idRefs = binary.UnmarshalIdRefsBunch2(data, idRefs)
idRefBunch := idRefBunch{index.getBunchId(id), idRefs}
idRef := idRefBunch.get(id)
if idRef != nil {
idRef.Refs = []int64{}
data := bytePool.get()
defer bytePool.release(data)
data = binary.MarshalIdRefsBunch2(idRefs, data)
return index.db.Put(index.wo, keyBuf, data)
}
}
return nil
}
func (index *CoordsRefIndex) AddFromWay(way *element.Way) {
for _, node := range way.Nodes {
if index.linearImport {
index.addc <- idRef{id: node.Id, ref: way.Id}
} else {
index.Add(node.Id, way.Id)
}
}
}
func (index *CoordsRefIndex) DeleteFromWay(way *element.Way) {
if index.linearImport {
panic("programming error: delete not supported in linearImport mode")
}
for _, node := range way.Nodes {
index.DeleteRef(node.Id, way.Id)
}
}
func (index *CoordsRelRefIndex) AddFromMembers(relId int64, members []element.Member) {
for _, member := range members {
if member.Type == element.NODE {
if index.linearImport {
index.addc <- idRef{id: member.Id, ref: relId}
} else {
index.Add(member.Id, relId)
}
}
}
}
func (index *WaysRefIndex) AddFromMembers(relId int64, members []element.Member) {
for _, member := range members {
if member.Type == element.WAY {
if index.linearImport {
index.addc <- idRef{id: member.Id, ref: relId}
} else {
index.Add(member.Id, relId)
}
}
}
}
// SetLinearImport optimizes the cache for write operations.
// Get/Delete operations will panic during linear import.
func (index *bunchRefCache) SetLinearImport(val bool) {
if val == index.linearImport {
// already in this mode
return
}
if val {
index.waitWrite.Add(1)
index.waitAdd.Add(1)
go index.writer()
go index.dispatch()
index.linearImport = true
} else {
close(index.addc)
index.waitAdd.Wait()
close(index.write)
index.waitWrite.Wait()
index.linearImport = false
}
}
func (index *bunchRefCache) writer() {
for buffer := range index.write {
if err := index.writeRefs(buffer); err != nil {
log.Println("error while writing ref index", err)
}
}
index.waitWrite.Done()
}
func (index *bunchRefCache) dispatch() {
for idRef := range index.addc {
index.buffer.add(index.getBunchId(idRef.id), idRef.id, idRef.ref)
if len(index.buffer) >= bufferSize {
index.write <- index.buffer
select {
case index.buffer = <-idRefBunchesPool:
default:
index.buffer = make(idRefBunches, bufferSize)
}
}
}
if len(index.buffer) > 0 {
index.write <- index.buffer
index.buffer = nil
}
index.waitAdd.Done()
}
type loadBunchItem struct {
bunchId int64
bunch idRefBunch
}
type writeBunchItem struct {
bunchIdBuf []byte
data []byte
}
func (index *bunchRefCache) writeRefs(idRefs idRefBunches) error {
batch := levigo.NewWriteBatch()
defer batch.Close()
wg := sync.WaitGroup{}
putc := make(chan writeBunchItem)
loadc := make(chan loadBunchItem)
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
go func() {
for item := range loadc {
keyBuf := idToKeyBuf(item.bunchId)
putc <- writeBunchItem{
keyBuf,
index.loadMergeMarshal(keyBuf, item.bunch.idRefs),
}
}
wg.Done()
}()
}
go func() {
for bunchId, bunch := range idRefs {
loadc <- loadBunchItem{bunchId, bunch}
}
close(loadc)
wg.Wait()
close(putc)
}()
for item := range putc {
batch.Put(item.bunchIdBuf, item.data)
bytePool.release(item.data)
}
go func() {
for k, _ := range idRefs {
delete(idRefs, k)
}
select {
case idRefBunchesPool <- idRefs:
}
}()
return index.db.Write(index.wo, batch)
}
func mergeBunch(bunch, newBunch []element.IdRefs) []element.IdRefs {
lastIdx := 0
NextIdRef:
// for each new idRef...
for _, newIdRefs := range newBunch {
// search place in bunch
for i := lastIdx; i < len(bunch); i++ {
if bunch[i].Id == newIdRefs.Id {
// id already present
if len(newIdRefs.Refs) == 0 {
// no new refs -> delete
bunch = append(bunch[:i], bunch[i+1:]...)
} else { // otherwise add refs
for _, r := range newIdRefs.Refs {
bunch[i].Add(r)
}
}
lastIdx = i
continue NextIdRef
}
if bunch[i].Id > newIdRefs.Id {
// insert before
if len(newIdRefs.Refs) > 0 {
bunch = append(bunch, element.IdRefs{})
copy(bunch[i+1:], bunch[i:])
bunch[i] = newIdRefs
}
lastIdx = i
continue NextIdRef
}
}
// insert at the end
if len(newIdRefs.Refs) > 0 {
bunch = append(bunch, newIdRefs)
lastIdx = len(bunch) - 1
}
}
return bunch
}
// loadMergeMarshal loads an existing bunch, merges the IdRefs and
// marshals the result again.
func (index *bunchRefCache) loadMergeMarshal(keyBuf []byte, newBunch []element.IdRefs) []byte {
data, err := index.db.Get(index.ro, keyBuf)
if err != nil {
panic(err)
}
var bunch []element.IdRefs
if data != nil {
bunch = idRefsPool.get()
defer idRefsPool.release(bunch)
bunch = binary.UnmarshalIdRefsBunch2(data, bunch)
}
if bunch == nil {
bunch = newBunch
} else {
bunch = mergeBunch(bunch, newBunch)
}
data = bytePool.get()
data = binary.MarshalIdRefsBunch2(bunch, data)
return data
}
// pools to reuse memory
var idRefsPool = make(idRefsPoolWrapper, 8)
var bytePool = make(bytePoolWrapper, 8)
type bytePoolWrapper chan []byte
func (p *bytePoolWrapper) get() []byte {
select {
case buf := <-(*p):
return buf
default:
return nil
}
}
func (p *bytePoolWrapper) release(buf []byte) {
select {
case (*p) <- buf:
default:
}
}
type idRefsPoolWrapper chan []element.IdRefs
func (p *idRefsPoolWrapper) get() []element.IdRefs {
select {
case idRefs := <-(*p):
return idRefs
default:
return nil
}
}
func (p *idRefsPoolWrapper) release(idRefs []element.IdRefs) {
select {
case (*p) <- idRefs:
default:
}
}