-
Notifications
You must be signed in to change notification settings - Fork 9
/
storage.go
219 lines (179 loc) · 6.73 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package rpc
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/filefilego/filefilego/common"
"github.com/filefilego/filefilego/common/hexutil"
"github.com/filefilego/filefilego/node/protocols/messages"
storageprotocol "github.com/filefilego/filefilego/node/protocols/storage"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"google.golang.org/protobuf/proto"
)
// StorageAPI represents the storage rpc service.
type StorageAPI struct {
host host.Host
publisher NetworkMessagePublisher
storageProtocol storageprotocol.Interface
}
// NewStorageAPI creates a new storage API to be served using JSONRPC.
func NewStorageAPI(host host.Host, publisher NetworkMessagePublisher, storageProtocol storageprotocol.Interface) (*StorageAPI, error) {
if host == nil {
return nil, errors.New("host is nil")
}
if publisher == nil {
return nil, errors.New("publisher is nil")
}
if storageProtocol == nil {
return nil, errors.New("storageProtocol is nil")
}
return &StorageAPI{
publisher: publisher,
storageProtocol: storageProtocol,
}, nil
}
// TestSpeedWithRemotePeerArgs args for testing speed.
type TestSpeedWithRemotePeerArgs struct {
PeerID string `json:"peer_id"`
FileSize uint64 `json:"file_size"`
}
// TestSpeedWithRemotePeerResponse the response of the speed test.
type TestSpeedWithRemotePeerResponse struct {
DownloadThroughputMB float64 `json:"download_throughput_mb"`
}
// TestSpeedWithRemotePeer tests the remote peer speed.
func (api *StorageAPI) TestSpeedWithRemotePeer(r *http.Request, args *TestSpeedWithRemotePeerArgs, response *TestSpeedWithRemotePeerResponse) error {
peerID, err := peer.Decode(args.PeerID)
if err != nil {
return fmt.Errorf("failed to decode remote peer id: %w", err)
}
if args.FileSize == 0 {
return fmt.Errorf("file size is empty")
}
timeelapsed, err := api.storageProtocol.TestSpeedWithRemotePeer(r.Context(), peerID, args.FileSize)
if err != nil {
return fmt.Errorf("failed to perform speed test: %w", err)
}
response.DownloadThroughputMB = calculateThroughput(args.FileSize, timeelapsed)
return nil
}
func calculateThroughput(fileSize uint64, duration time.Duration) float64 {
bytesPerSecond := float64(fileSize) / duration.Seconds()
return bytesPerSecond / (1024 * 1024) // convert to MB/s
}
// FindProvidersArgs args for finding providers
type FindProvidersArgs struct {
PreferredLocation string `json:"preferred_location"`
}
// FindProvidersResponse the response of the finding storage providers mechanism.
type FindProvidersResponse struct {
Success bool `json:"success"`
}
// FindProviders reports the stats of the node.
func (api *StorageAPI) FindProviders(r *http.Request, args *FindProvidersArgs, response *FindProvidersResponse) error {
m := &messages.StorageQueryRequestProto{
FromPeerAddr: api.host.ID().String(),
PreferredLocation: args.PreferredLocation,
}
payload := messages.GossipPayload{
Message: &messages.GossipPayload_StorageQuery{
StorageQuery: m,
},
}
payloadBytes, err := proto.Marshal(&payload)
if err != nil {
return fmt.Errorf("failed to marshal storage query gossip payload: %w", err)
}
err = api.publisher.PublishMessageToNetwork(r.Context(), common.FFGNetPubSubStorageQuery, payloadBytes)
if err != nil {
return fmt.Errorf("failed to publish storage query request proto message: %w", err)
}
response.Success = true
return nil
}
// UploadFileToProviderArgs args for uploading to a provider.
type UploadFileToProviderArgs struct {
PeerID string `json:"peer_id"`
FilePath string `json:"file_path"`
ChannelNodeItemHash string `json:"channel_node_item_hash"`
}
// UploadFileToProviderResponse is the response of the uploaded file to provider.
type UploadFileToProviderResponse struct {
Success bool `json:"success"`
}
// UploadFileToProvider uploads a file to provider.
func (api *StorageAPI) UploadFileToProvider(r *http.Request, args *UploadFileToProviderArgs, response *UploadFileToProviderResponse) error {
peerID, err := peer.Decode(args.PeerID)
if err != nil {
return fmt.Errorf("failed to decode remote peer id: %w", err)
}
if args.FilePath == "" {
return errors.New("filepath is empty")
}
go func() {
fhash, err := api.storageProtocol.UploadFileWithMetadata(context.Background(), peerID, args.FilePath, args.ChannelNodeItemHash)
api.storageProtocol.SetUploadingStatus(peerID, args.FilePath, fhash, err)
}()
response.Success = true
return nil
}
// FileUploadProgressArgs args for upload progress.
type FileUploadProgressArgs struct {
PeerID string `json:"peer_id"`
FilePath string `json:"file_path"`
}
// FileUploadProgressResponse is the response of the progress.
type FileUploadProgressResponse struct {
Progress int `json:"progress"`
FileHash string `json:"file_hash"`
Error string `json:"error"`
}
// FileUploadProgress show the file upload progress and errors
func (api *StorageAPI) FileUploadProgress(r *http.Request, args *FileUploadProgressArgs, response *FileUploadProgressResponse) error {
peerID, err := peer.Decode(args.PeerID)
if err != nil {
return fmt.Errorf("failed to decode remote peer id: %w", err)
}
if args.FilePath == "" {
return errors.New("filepath is empty")
}
progress, fHash, err := api.storageProtocol.GetUploadProgress(peerID, args.FilePath)
response.Progress = progress
response.FileHash = fHash
if err != nil {
response.Error = err.Error()
}
return nil
}
// GetDiscoveredProvidersResponse is the response containing the discovered storage providers.
type GetDiscoveredProvidersResponse struct {
StorageProviders []JSONStorageProvider `json:"storage_providers"`
}
// JSONStorageProvider is a json storage provider.
type JSONStorageProvider struct {
StorageProviderPeerAddr string `json:"storage_provider_peer_addr"`
Location string `json:"location"`
FeesPerByte string `json:"fees_per_byte"`
PublicKey string `json:"public_key"`
Hash string `json:"hash"`
Signature string `json:"signature"`
}
// GetDiscoveredProviders returns a list of discovered storage providers.
func (api *StorageAPI) GetDiscoveredProviders(r *http.Request, args *EmptyArgs, response *GetDiscoveredProvidersResponse) error {
providers := api.storageProtocol.GetDiscoveredStorageProviders()
response.StorageProviders = make([]JSONStorageProvider, len(providers))
for i, v := range providers {
response.StorageProviders[i] = JSONStorageProvider{
StorageProviderPeerAddr: v.StorageProviderPeerAddr,
Location: v.Location,
FeesPerByte: v.FeesPerByte,
PublicKey: hexutil.Encode(v.PublicKey),
Hash: hexutil.Encode(v.Hash),
Signature: hexutil.Encode(v.Signature),
}
}
return nil
}