| 274 | return fmt.Errorf("local write failed after successful ipfs write: localErr=%v, metaErr=%v", localErr, metaErr) |
| 275 | } |
| 276 | |
| 277 | db.cache.Set(key, value, 0) |
| 278 | return nil |
| 279 | } |
| 280 | |
| 281 | func (db *DB) Get(key []byte) ([]byte, error) { |
| 282 | if v, ok := db.cache.Get(key); ok { |
| 283 | return v.([]byte), nil |
| 284 | } |
| 285 | |
| 286 | var wg sync.WaitGroup |
| 287 | var ipfsValue, localValue, ipfsVersionBytes, localVersionBytes []byte |
| 288 | var ipfsErr, localErr error |
| 289 | |
| 290 | wg.Add(2) |
| 291 | |
| 292 | // Concurrently get from localDB and ipfsDB |
| 293 | go func() { |
| 294 | defer wg.Done() |
| 295 | metaKey := append([]byte("_meta:"), key...) |
| 296 | localValue, localErr = db.localDB.Get(key, nil) |
| 297 | localVersionBytes, _ = db.localDB.Get(metaKey, nil) |
| 298 | }() |
| 299 | |
| 300 | go func() { |
| 301 | defer wg.Done() |
| 302 | metaKey := append([]byte("_meta:"), key...) |
| 303 | ipfsValue, ipfsErr = db.ipfsDB.Get(key) |
| 304 | ipfsVersionBytes, _ = db.ipfsDB.Get(metaKey) |
| 305 | }() |
| 306 | |
| 307 | wg.Wait() |
| 308 | |
| 309 | // Decrypt IPFS value if needed |
| 310 | if ipfsErr == nil && ipfsValue != nil && db.encryptionKey != nil { |
| 311 | pt, derr := decrypt(ipfsValue, db.encryptionKey) |
| 312 | if derr != nil { |
| 313 | // Decrypt failure (corrupt/tampered IPFS copy): drop it so the local value wins rather than crashing. |
| 314 | log.Printf("ipfs-synckv: decrypt failed for key %q: %v", key, derr) |
| 315 | ipfsValue = nil |
| 316 | } else { |
| 317 | ipfsValue = pt |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | // --- Conflict Resolution --- |
| 322 | var value []byte |
| 323 | localExists := localErr == nil && localValue != nil |
| 324 | ipfsExists := ipfsErr == nil && ipfsValue != nil |
| 325 | |
| 326 | switch { |
| 327 | case ipfsExists && localExists: |
| 328 | // Both exist, compare versions correctly |
| 329 | localVer, _ := strconv.ParseUint(string(localVersionBytes), 10, 64) |
| 330 | ipfsVer, _ := strconv.ParseUint(string(ipfsVersionBytes), 10, 64) |
| 331 | |
| 332 | if ipfsVer > localVer { |
| 333 | value = ipfsValue |