localstore.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package storage
  17. import (
  18. "encoding/binary"
  19. )
  20. // LocalStore is a combination of inmemory db over a disk persisted db
  21. // implements a Get/Put with fallback (caching) logic using any 2 ChunkStores
  22. type LocalStore struct {
  23. memStore ChunkStore
  24. DbStore ChunkStore
  25. }
  26. // This constructor uses MemStore and DbStore as components
  27. func NewLocalStore(hash SwarmHasher, params *StoreParams) (*LocalStore, error) {
  28. dbStore, err := NewDbStore(params.ChunkDbPath, hash, params.DbCapacity, params.Radius)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return &LocalStore{
  33. memStore: NewMemStore(dbStore, params.CacheCapacity),
  34. DbStore: dbStore,
  35. }, nil
  36. }
  37. // LocalStore is itself a chunk store
  38. // unsafe, in that the data is not integrity checked
  39. func (self *LocalStore) Put(chunk *Chunk) {
  40. chunk.dbStored = make(chan bool)
  41. self.memStore.Put(chunk)
  42. if chunk.wg != nil {
  43. chunk.wg.Add(1)
  44. }
  45. go func() {
  46. self.DbStore.Put(chunk)
  47. if chunk.wg != nil {
  48. chunk.wg.Done()
  49. }
  50. }()
  51. }
  52. // Get(chunk *Chunk) looks up a chunk in the local stores
  53. // This method is blocking until the chunk is retrieved
  54. // so additional timeout may be needed to wrap this call if
  55. // ChunkStores are remote and can have long latency
  56. func (self *LocalStore) Get(key Key) (chunk *Chunk, err error) {
  57. chunk, err = self.memStore.Get(key)
  58. if err == nil {
  59. return
  60. }
  61. chunk, err = self.DbStore.Get(key)
  62. if err != nil {
  63. return
  64. }
  65. chunk.Size = int64(binary.LittleEndian.Uint64(chunk.SData[0:8]))
  66. self.memStore.Put(chunk)
  67. return
  68. }
  69. // Close local store
  70. func (self *LocalStore) Close() {}