github.com/0chain/gosdk@v1.17.11/winsdk/cache.go (about) 1 package main 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "errors" 7 "time" 8 9 "github.com/0chain/gosdk/zboxcore/marker" 10 "github.com/0chain/gosdk/zboxcore/sdk" 11 lru "github.com/hashicorp/golang-lru/v2" 12 ) 13 14 type cachedAllocation struct { 15 CacheExpiresAt time.Time 16 Allocation *sdk.Allocation 17 } 18 19 type cachedFileMeta struct { 20 CacheExpiresAt time.Time 21 FileMeta *sdk.ConsolidatedFileMeta 22 } 23 24 var ( 25 cachedAllocations, _ = lru.New[string, *cachedAllocation](100) 26 cachedFileMetas, _ = lru.New[string, *cachedFileMeta](1000) 27 ) 28 29 func getAllocation(allocationID string) (*sdk.Allocation, error) { 30 31 var it *cachedAllocation 32 var ok bool 33 34 it, ok = cachedAllocations.Get(allocationID) 35 36 if ok && it.CacheExpiresAt.After(time.Now()) { 37 return it.Allocation, nil 38 } 39 40 a, err := sdk.GetAllocation(allocationID) 41 if err != nil { 42 return nil, err 43 } 44 45 it = &cachedAllocation{ 46 Allocation: a, 47 CacheExpiresAt: time.Now().Add(30 * time.Minute), 48 } 49 50 cachedAllocations.Add(allocationID, it) 51 52 return it.Allocation, nil 53 } 54 55 func getAllocationWith(authTicket string) (*sdk.Allocation, *marker.AuthTicket, error) { 56 57 sEnc, err := base64.StdEncoding.DecodeString(authTicket) 58 if err != nil { 59 return nil, nil, errors.New("Error decoding the auth ticket." + err.Error()) 60 } 61 at := &marker.AuthTicket{} 62 err = json.Unmarshal(sEnc, at) 63 if err != nil { 64 return nil, nil, errors.New("Error unmarshaling the auth ticket." + err.Error()) 65 } 66 alloc, err := getAllocation(at.AllocationID) 67 return alloc, at, err 68 } 69 70 func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { 71 72 var it *cachedFileMeta 73 var ok bool 74 75 it, ok = cachedFileMetas.Get(allocationID + ":" + remotePath) 76 77 if ok && it.CacheExpiresAt.After(time.Now()) { 78 return it.FileMeta, nil 79 } 80 81 a, err := getAllocation(allocationID) 82 if err != nil { 83 return nil, err 84 } 85 86 f, err := a.GetFileMeta(remotePath) 87 if err != nil { 88 return nil, err 89 } 90 91 it = &cachedFileMeta{ 92 FileMeta: f, 93 CacheExpiresAt: time.Now().Add(30 * time.Minute), 94 } 95 96 cachedFileMetas.Add(allocationID, it) 97 98 return it.FileMeta, nil 99 }