-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
268 lines (234 loc) · 8.56 KB
/
main.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
ipfsClusterClientApi "github.com/ipfs-cluster/ipfs-cluster/api"
ipfsCluster "github.com/ipfs-cluster/ipfs-cluster/api/rest/client"
"github.com/ipfs/go-cid"
"gopkg.in/yaml.v2"
)
// Define structures for manifest upload requests and responses
type ManifestBatchUploadRequest struct {
Cid []string `json:"cid"`
PoolID int `json:"pool_id"`
ReplicationFactor []int `json:"replication_factor"`
ManifestMetadata []ManifestMetadata `json:"manifest_metadata"`
}
type ManifestBatchUploadResponse struct {
PoolID int `json:"pool_id"`
Storer string `json:"storer"`
Cid []string `json:"cid"`
}
type ManifestMetadata struct {
Job ManifestJob `json:"job"`
}
type ManifestJob struct {
Work string `json:"work"`
Engine string `json:"engine"`
Uri string `json:"uri"`
}
type Pin struct {
CID string `json:"cid"`
Name string `json:"name,omitempty"`
Origins []string `json:"origins,omitempty"`
Meta map[string]string `json:"meta,omitempty"`
}
type PinStatus struct {
RequestID string `json:"requestid"`
Status string `json:"status"`
Created string `json:"created"`
Pin Pin `json:"pin"`
Delegates []string `json:"delegates,omitempty"`
Info map[string]string `json:"info,omitempty"`
}
// Global variables
var (
blockchainEndpoint = "http://127.0.0.1:4000" // Blockchain service endpoint
ipfsClusterAPI ipfsCluster.Client
authTokens = map[string]bool{"your-secret-token": true} // Example token storage
globalConfig *Config
)
type Config struct {
Identity string `yaml:"identity"`
StoreDir string `yaml:"storeDir"`
PoolName string `yaml:"poolName"`
LogLevel string `yaml:"logLevel"`
ListenAddrs []string `yaml:"listenAddrs"`
Authorizer string `yaml:"authorizer"`
AuthorizedPeers []string `yaml:"authorizedPeers"`
IpfsBootstrapNodes []string `yaml:"ipfsBootstrapNodes"`
StaticRelays []string `yaml:"staticRelays"`
ForceReachabilityPrivate bool `yaml:"forceReachabilityPrivate"`
AllowTransientConnection bool `yaml:"allowTransientConnection"`
DisableResourceManager bool `yaml:"disableResourceManger"`
MaxCIDPushRate int `yaml:"maxCIDPushRate"`
IpniPublishDisabled bool `yaml:"ipniPublishDisabled"`
IpniPublishInterval string `yaml:"ipniPublishInterval"`
IpniPublishDirectAnnounce []string `yaml:"IpniPublishDirectAnnounce"`
IpniPublisherIdentity string `yaml:"ipniPublisherIdentity"`
}
func readConfig(configPath string) (*Config, error) {
data, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
var config Config
if err = yaml.Unmarshal(data, &config); err != nil {
return nil, err
}
return &config, nil
}
func init() {
var err error
globalConfig, err = readConfig("/internal/.fula/config.yaml")
if err != nil {
log.Fatalf("Error reading config file: %v", err)
}
ipfsClusterConfig := ipfsCluster.Config{}
ipfsClusterAPI, err = ipfsCluster.NewDefaultClient(&ipfsClusterConfig)
if err != nil {
log.Fatalf("Error creating IPFS Cluster client: %v", err)
}
}
func handleManifestBatchUpload(w http.ResponseWriter, r *http.Request) {
var req ManifestBatchUploadRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// First, add CIDs to the blockchain
resp, statusCode, err := callBlockchain("POST", "fula-manifest-batch_upload", req)
if err != nil {
log.Println("Failed to register CIDs on blockchain:", err)
http.Error(w, "Blockchain interaction failed", statusCode)
return
}
// Assuming blockchain response validates the request to proceed with pinning
var blockchainResp ManifestBatchUploadResponse
if err := json.Unmarshal(resp, &blockchainResp); err != nil {
log.Println("Failed to decode blockchain response:", err)
http.Error(w, "Failed to decode blockchain response", http.StatusInternalServerError)
return
}
// Proceed with IPFS Cluster pinning
pinOptions := ipfsClusterClientApi.PinOptions{
Mode: ipfsClusterClientApi.PinModeRecursive,
}
for _, cidStr := range blockchainResp.Cid {
c, _ := cid.Decode(cidStr)
_, err := ipfsClusterAPI.Pin(context.Background(), ipfsClusterClientApi.NewCid(c), pinOptions)
if err != nil {
log.Printf("Failed to pin CID %s: %v", cidStr, err)
continue
}
}
fmt.Fprintf(w, "CIDs pinned successfully: %v", blockchainResp.Cid)
}
func callBlockchain(method, action string, payload interface{}) ([]byte, int, error) {
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, http.StatusInternalServerError, err
}
req, err := http.NewRequest(method, blockchainEndpoint+"/"+action, bytes.NewBuffer(jsonData))
if err != nil {
return nil, http.StatusInternalServerError, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, http.StatusInternalServerError, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, http.StatusInternalServerError, err
}
return respBody, resp.StatusCode, nil
}
func handleIPFSPinRequest(w http.ResponseWriter, r *http.Request) {
var pinRequest Pin // Change from an anonymous struct to a defined type
if err := json.NewDecoder(r.Body).Decode(&pinRequest); err != nil {
http.Error(w, `{"error":{"reason":"BAD_REQUEST", "details":"`+err.Error()+`"}}`, http.StatusBadRequest)
return
}
poolID, err := strconv.Atoi(globalConfig.PoolName)
if err != nil {
log.Printf("Invalid pool ID in config: %v", err)
http.Error(w, `{"error":{"reason":"BAD_REQUEST", "details":"Invalid pool ID configuration"}}`, http.StatusBadRequest)
return
}
// Translate to internal format
internalRequest := ManifestBatchUploadRequest{
Cid: []string{pinRequest.CID},
PoolID: poolID, // Default or derived value
ReplicationFactor: []int{1}, // Default value
ManifestMetadata: []ManifestMetadata{
{
Job: ManifestJob{
Work: "storage", // Default work type
Engine: "IPFS",
Uri: pinRequest.CID,
},
},
},
}
// Now pass to existing blockchain call
resp, statusCode, err := callBlockchain("POST", "fula-manifest-batch_upload", internalRequest)
if err != nil || statusCode != http.StatusOK {
http.Error(w, `{"error":{"reason":"INTERNAL_SERVER_ERROR", "details":"Failed to process pin request`+err.Error()+`"}}`, http.StatusInternalServerError)
return
}
// Assume blockchain response is in a suitable format
var blockchainResp ManifestBatchUploadResponse
if err := json.Unmarshal(resp, &blockchainResp); err != nil {
http.Error(w, fmt.Sprintf(`{"error":{"reason":"INTERNAL_SERVER_ERROR", "details":"%s"}}`, err.Error()), http.StatusInternalServerError)
return
}
// Translate blockchain response to IPFS Pinning Service format
ipfsPinStatus := translateToIPFSPinStatus(blockchainResp, pinRequest)
json.NewEncoder(w).Encode(ipfsPinStatus)
}
func translateToIPFSPinStatus(blockResp ManifestBatchUploadResponse, pinRequest Pin) PinStatus {
return PinStatus{
RequestID: fmt.Sprintf("%v", blockResp.PoolID), // Assuming PoolID can serve as a RequestID
Status: "queued", // Example status
Created: time.Now().Format(time.RFC3339),
Pin: pinRequest,
Delegates: []string{fmt.Sprintf("/dns4/pools%d.functionyard.fula.network/tcp/4001/p2p/QmServicePeerId", blockResp.PoolID)},
Info: map[string]string{"storer": blockResp.Storer},
}
}
func main() {
r := mux.NewRouter()
apiRouter := r.PathPrefix("").Subrouter()
apiRouter.Use(authenticateMiddleware)
apiRouter.HandleFunc("/pins", handleIPFSPinRequest).Methods("POST")
log.Println("Server is running on port 8008...")
log.Fatal(http.ListenAndServe(":8008", apiRouter))
}
func authenticateMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" || !strings.HasPrefix(token, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
actualToken := strings.TrimPrefix(token, "Bearer ")
if _, exists := authTokens[actualToken]; !exists {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}