blob: 315ec00fc9211be4ce40779ab9d2a660d35f3bc3 [file] [log] [blame]
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +04001package chunk
2
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +04003import "bytes"
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +04004import "context"
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +04005import "io"
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +04006import "sync"
7
8import "pcloud/api"
9
10type ChunkServer struct {
11 chunks sync.Map
12}
13
14func NewChunkServer() *ChunkServer {
15 return &ChunkServer{}
16}
17
18func (s *ChunkServer) ListChunks(
19 ctx context.Context,
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +040020 req *api.ListChunksRequest) (*api.ListChunksResponse, error) {
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +040021 resp := api.ListChunksResponse{}
22 s.chunks.Range(func(k, v interface{}) bool {
23 resp.ChunkId = append(resp.ChunkId, k.(string))
24 return true
25 })
26 return &resp, nil
27}
28
29func (s *ChunkServer) ReadChunk(
30 ctx context.Context,
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +040031 req *api.ReadChunkRequest) (resp *api.ReadChunkResponse, err error) {
32 if value, ok := s.chunks.Load(req.ChunkId); ok {
33 chunk := value.(Chunk)
34 src := chunk.ReadSeeker()
35 if req.Offset != 0 {
36 _, err = src.Seek(int64(req.Offset), io.SeekStart)
37 if err != nil {
38 return
39 }
40 }
41 var dst bytes.Buffer
42 if req.NumBytes != 0 {
43 _, err = io.CopyN(&dst, src, int64(req.NumBytes))
44 } else {
45 _, err = io.Copy(&dst, src)
46 }
47 if err == nil {
48 resp = &api.ReadChunkResponse{Data: dst.Bytes()}
49 }
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +040050 }
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +040051 return
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +040052}
53
54func (s *ChunkServer) StoreChunk(
55 ctx context.Context,
Giorgi Lekveishvili45b4d522020-03-19 21:11:18 +040056 req *api.StoreChunkRequest) (*api.StoreChunkResponse, error) {
57 data := req.Data
58 chunk := NewInMemoryChunk(&data)
59 s.chunks.Store(req.ChunkId, chunk)
Giorgi Lekveishvilib8f089f2020-03-18 23:28:12 +040060 return &api.StoreChunkResponse{}, nil
61}