MCPcopy Create free account
hub / github.com/IceFireDB/IceFireDB / Put

Method Put

driver/ipfs-synckv/db.go:226–274  ·  view source on GitHub ↗
(key, value []byte)

Source from the content-addressed store, hash-verified

224}
225
226func (db *DB) Put(key, value []byte) error {
227 db.versionMu.Lock()
228 defer db.versionMu.Unlock()
229
230 // Increment version
231 db.versions[string(key)]++
232 version := db.versions[string(key)]
233 versionBytes := []byte(fmt.Sprintf("%d", version))
234
235 // Prepare data for IPFS (encrypt if key is available)
236 ipfsValue := value
237 if db.encryptionKey != nil {
238 ipfsValue = encrypt(value, db.encryptionKey)
239 }
240
241 // --- Atomic Write (IPFS-first) ---
242 // 1. Write to IPFS first. This is the source of truth for the network.
243 ipfsErr := db.ipfsDB.Put(db.ctx, key, ipfsValue)
244 if ipfsErr != nil {
245 // If IPFS write fails, we abort the whole operation.
246 return fmt.Errorf("ipfs write failed, aborting put: %w", ipfsErr)
247 }
248
249 // 2. Write to local DB and metadata only after IPFS success.
250 var wg sync.WaitGroup
251 var localErr, metaErr error
252 wg.Add(2)
253 go func() {
254 defer wg.Done()
255 localErr = db.localDB.Put(key, value, nil)
256 }()
257 go func() {
258 defer wg.Done()
259 // Store version in both local and ipfs for consistency checks
260 metaKey := append([]byte("_meta:"), key...)
261 metaErr = db.localDB.Put(metaKey, versionBytes, nil)
262 _ = db.ipfsDB.Put(db.ctx, metaKey, versionBytes) // Also store version on IPFS
263 }()
264 wg.Wait()
265
266 if localErr != nil || metaErr != nil {
267 // This indicates a critical local failure. The data is on IPFS but not fully on local disk.
268 // A more robust solution might involve a local recovery process.
269 return fmt.Errorf("local write failed after successful ipfs write: localErr=%v, metaErr=%v", localErr, metaErr)
270 }
271
272 db.cache.Set(key, value, 0)
273 return nil
274}
275
276func (db *DB) Get(key []byte) ([]byte, error) {
277 if v, ok := db.cache.Get(key); ok {

Callers 6

TestIteratorFunction · 0.45
TestIteratorPrefixFunction · 0.45
GetMethod · 0.45
SyncPutMethod · 0.45
TestDBPutGetFunction · 0.45
TestDBDeleteFunction · 0.45

Calls 3

DoneMethod · 0.80
SetMethod · 0.80
encryptFunction · 0.70

Tested by 4

TestIteratorFunction · 0.36
TestIteratorPrefixFunction · 0.36
TestDBPutGetFunction · 0.36
TestDBDeleteFunction · 0.36