Store stores a chunk in the RAM and adds it to the disk storage queue
(id RequestID, bytes []byte)
| 360 | |
| 361 | // Store stores a chunk in the RAM and adds it to the disk storage queue |
| 362 | func (s *Storage) Store(id RequestID, bytes []byte) (err error) { |
| 363 | s.lock.RLock() |
| 364 | |
| 365 | // Avoid storing same chunk multiple times |
| 366 | chunk := s.fetch(id) |
| 367 | if nil != chunk && chunk.clean { |
| 368 | Log.Tracef("Create chunk %v (exists: clean)", id) |
| 369 | s.lock.RUnlock() |
| 370 | return nil |
| 371 | } |
| 372 | |
| 373 | s.lock.RUnlock() |
| 374 | s.lock.Lock() |
| 375 | defer s.lock.Unlock() |
| 376 | |
| 377 | if nil != chunk { |
| 378 | if chunk.valid(id) { |
| 379 | Log.Debugf("Create chunk %v (exists: valid)", id) |
| 380 | return nil |
| 381 | } |
| 382 | Log.Warningf("Create chunk %v(exists: overwrite)", id) |
| 383 | } else { |
| 384 | index := s.stack.Pop() |
| 385 | if -1 == index { |
| 386 | Log.Debugf("Create chunk %v (failed)", id) |
| 387 | return fmt.Errorf("No buffers available") |
| 388 | } |
| 389 | chunk = s.buffers[index] |
| 390 | deleteID := chunk.id |
| 391 | if blankRequestID != deleteID { |
| 392 | delete(s.chunks, deleteID) |
| 393 | Log.Debugf("Create chunk %v (reused)", id) |
| 394 | } else { |
| 395 | Log.Debugf("Create chunk %v (stored)", id) |
| 396 | } |
| 397 | s.chunks[id] = index |
| 398 | chunk.item = s.stack.Push(index) |
| 399 | } |
| 400 | |
| 401 | chunk.update(id, bytes) |
| 402 | |
| 403 | return nil |
| 404 | } |
| 405 | |
| 406 | // fetch chunk and index by id |
| 407 | func (s *Storage) fetch(id RequestID) *Chunk { |