certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

badger.go (5407B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package storage
     16 
     17 import (
     18 	"errors"
     19 	"fmt"
     20 	"sync"
     21 
     22 	"github.com/dgraph-io/badger/v4"
     23 )
     24 
     25 // badgerStore is the concrete implementation of the Store interface using BadgerDB.
     26 type badgerStore struct {
     27 	mu sync.RWMutex
     28 	db *badger.DB
     29 }
     30 
     31 // NewBadgerStore opens or creates a BadgerDB at the given path.
     32 func NewBadgerStore(path string) (Store, error) {
     33 	opts := badger.DefaultOptions(path).
     34 		WithLogger(nil).     // Suppress verbose Badger logs
     35 		WithSyncWrites(true) // Ensure writes are flushed to disk
     36 
     37 	db, err := badger.Open(opts)
     38 	if err != nil {
     39 		return nil, fmt.Errorf("storage: failed to open badger at %s: %w", path, err)
     40 	}
     41 
     42 	return &badgerStore{db: db}, nil
     43 }
     44 
     45 // Get reads a value by its key. Returns ErrNotFound if the key does not exist.
     46 func (s *badgerStore) Get(key []byte) ([]byte, error) {
     47 	s.mu.RLock()
     48 	defer s.mu.RUnlock()
     49 
     50 	if s.db == nil {
     51 		return nil, ErrClosed
     52 	}
     53 	if len(key) == 0 {
     54 		return nil, ErrEmptyKey
     55 	}
     56 
     57 	var val []byte
     58 	err := s.db.View(func(txn *badger.Txn) error {
     59 		item, err := txn.Get(key)
     60 		if err != nil {
     61 			return err
     62 		}
     63 		val, err = item.ValueCopy(nil)
     64 		return err
     65 	})
     66 	if err != nil {
     67 		if errors.Is(err, badger.ErrKeyNotFound) {
     68 			return nil, ErrNotFound
     69 		}
     70 		return nil, fmt.Errorf("storage: get failed: %w", err)
     71 	}
     72 
     73 	return val, nil
     74 }
     75 
     76 // Set writes a key-value pair. Validates that both key and value are non-empty.
     77 func (s *badgerStore) Set(key, value []byte) error {
     78 	s.mu.Lock()
     79 	defer s.mu.Unlock()
     80 
     81 	if s.db == nil {
     82 		return ErrClosed
     83 	}
     84 	if len(key) == 0 {
     85 		return ErrEmptyKey
     86 	}
     87 	if len(value) == 0 {
     88 		return ErrEmptyValue
     89 	}
     90 
     91 	err := s.db.Update(func(txn *badger.Txn) error {
     92 		return txn.Set(key, value)
     93 	})
     94 	if err != nil {
     95 		return fmt.Errorf("storage: set failed: %w", err)
     96 	}
     97 	return nil
     98 }
     99 
    100 // Delete removes a key from the database.
    101 func (s *badgerStore) Delete(key []byte) error {
    102 	s.mu.Lock()
    103 	defer s.mu.Unlock()
    104 
    105 	if s.db == nil {
    106 		return ErrClosed
    107 	}
    108 	if len(key) == 0 {
    109 		return ErrEmptyKey
    110 	}
    111 
    112 	err := s.db.Update(func(txn *badger.Txn) error {
    113 		return txn.Delete(key)
    114 	})
    115 	if err != nil {
    116 		return fmt.Errorf("storage: delete failed: %w", err)
    117 	}
    118 	return nil
    119 }
    120 
    121 // Has checks for the existence of a key without reading its value.
    122 func (s *badgerStore) Has(key []byte) (bool, error) {
    123 	s.mu.RLock()
    124 	defer s.mu.RUnlock()
    125 
    126 	if s.db == nil {
    127 		return false, ErrClosed
    128 	}
    129 	if len(key) == 0 {
    130 		return false, ErrEmptyKey
    131 	}
    132 
    133 	err := s.db.View(func(txn *badger.Txn) error {
    134 		_, err := txn.Get(key)
    135 		return err
    136 	})
    137 
    138 	if err == nil {
    139 		return true, nil
    140 	}
    141 	if errors.Is(err, badger.ErrKeyNotFound) {
    142 		return false, nil
    143 	}
    144 
    145 	return false, fmt.Errorf("storage: has check failed: %w", err)
    146 }
    147 
    148 // Iterate loops over all keys starting with the given prefix.
    149 func (s *badgerStore) Iterate(prefix []byte, fn func(key, value []byte) error) error {
    150 	s.mu.RLock()
    151 	if s.db == nil {
    152 		s.mu.RUnlock()
    153 		return ErrClosed
    154 	}
    155 	db := s.db
    156 	s.mu.RUnlock()
    157 
    158 	return db.View(func(txn *badger.Txn) error {
    159 		opts := badger.DefaultIteratorOptions
    160 		it := txn.NewIterator(opts)
    161 		defer it.Close()
    162 
    163 		for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
    164 			item := it.Item()
    165 			key := item.KeyCopy(nil)
    166 			val, err := item.ValueCopy(nil)
    167 			if err != nil {
    168 				return fmt.Errorf("storage: iteration value read failed: %w", err)
    169 			}
    170 
    171 			if err := fn(key, val); err != nil {
    172 				return err
    173 			}
    174 		}
    175 		return nil
    176 	})
    177 }
    178 
    179 // NewBatch returns a new badgerBatch wrapping a write transaction.
    180 func (s *badgerStore) NewBatch() (Batch, error) {
    181 	s.mu.Lock()
    182 	defer s.mu.Unlock()
    183 
    184 	if s.db == nil {
    185 		return nil, ErrClosed
    186 	}
    187 
    188 	return &badgerBatch{
    189 		txn: s.db.NewTransaction(true),
    190 	}, nil
    191 }
    192 
    193 // Close gracefully shuts down the database.
    194 func (s *badgerStore) Close() error {
    195 	s.mu.Lock()
    196 	defer s.mu.Unlock()
    197 
    198 	if s.db == nil {
    199 		return nil
    200 	}
    201 
    202 	err := s.db.Close()
    203 	s.db = nil
    204 
    205 	if err != nil {
    206 		return fmt.Errorf("storage: close failed: %w", err)
    207 	}
    208 	return nil
    209 }
    210 
    211 // badgerBatch implementation of the Batch interface for atomic writes.
    212 type badgerBatch struct {
    213 	txn *badger.Txn
    214 }
    215 
    216 // Set stages a key-value pair in the transaction.
    217 func (b *badgerBatch) Set(key, value []byte) error {
    218 	if b.txn == nil {
    219 		return ErrClosed
    220 	}
    221 
    222 	if len(key) == 0 {
    223 		return ErrEmptyKey
    224 	}
    225 	if len(value) == 0 {
    226 		return ErrEmptyValue
    227 	}
    228 
    229 	if err := b.txn.Set(key, value); err != nil {
    230 		return fmt.Errorf("storage: batch set failed: %v", err)
    231 	}
    232 	return nil
    233 }
    234 
    235 // Commit persists all staged operations atomically.
    236 func (b *badgerBatch) Commit() error {
    237 	if b.txn == nil {
    238 		return ErrClosed
    239 	}
    240 
    241 	if err := b.txn.Commit(); err != nil {
    242 		return fmt.Errorf("storage: batch commit failed: %v", err)
    243 	}
    244 	b.txn = nil
    245 
    246 	return nil
    247 }
    248 
    249 // Discard releases the transaction resources.
    250 func (b *badgerBatch) Discard() {
    251 	if b.txn != nil {
    252 		b.txn.Discard()
    253 		b.txn = nil
    254 	}
    255 }