-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp_stash.go
More file actions
246 lines (212 loc) · 7.45 KB
/
Copy pathhttp_stash.go
File metadata and controls
246 lines (212 loc) · 7.45 KB
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
package nara
import (
"encoding/json"
"fmt"
"net/http"
"github.com/sirupsen/logrus"
"github.com/eljojo/nara/types"
)
// GET /api/stash/status - Get current stash data, confidants, and metrics
func (network *Network) httpStashStatusHandler(w http.ResponseWriter, r *http.Request) {
// Get storage limit from stash service (based on memory mode)
storageLimit := 5 // Default if service not available
if network.stashService != nil {
storageLimit = network.stashService.StorageLimit()
}
response := map[string]interface{}{
"has_stash": false,
"my_stash": nil,
"confidants": []map[string]interface{}{},
"metrics": map[string]interface{}{
"stashes_stored": 0,
"total_bytes": 0,
"storage_limit": storageLimit,
},
}
if network.stashService == nil {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(response); err != nil {
logrus.Errorf("Failed to encode stash status response: %v", err)
}
return
}
// Get current stash data
myStashData, timestamp := network.stashService.GetStashData()
if len(myStashData) > 0 {
var dataMap map[string]interface{}
_ = json.Unmarshal(myStashData, &dataMap)
response["has_stash"] = true
response["my_stash"] = map[string]interface{}{
"timestamp": timestamp,
"data": dataMap,
}
}
// Get current stash state
if stateBytes, err := network.stashService.MarshalState(); err == nil && len(stateBytes) > 0 {
var state struct {
Confidants []string `json:"confidants"`
Stored map[string]interface{} `json:"stored"`
}
if err := json.Unmarshal(stateBytes, &state); err == nil {
// Build confidants list with peer details
// Quickly gather references with minimal lock time
confidantList := make([]map[string]interface{}, 0, len(state.Confidants))
for _, confidantID := range state.Confidants {
info := map[string]interface{}{
"id": confidantID,
"status": "confirmed",
}
// Try to get peer details from NeighbourhoodByID (confidantID is a types.NaraID, not a name!)
naraID := types.NaraID(confidantID)
network.local.mu.Lock()
nara, exists := network.NeighbourhoodByID[naraID]
network.local.mu.Unlock()
if exists {
nara.mu.Lock()
naraName := nara.Name
info["name"] = naraName
info["memory_mode"] = nara.Status.MemoryMode
nara.mu.Unlock()
// Check if online via observation (using name, not ID)
network.local.mu.Lock()
if obs, ok := network.local.Me.Status.Observations[naraName]; ok {
info["online"] = obs.isOnline()
}
network.local.mu.Unlock()
}
confidantList = append(confidantList, info)
}
response["confidants"] = confidantList
response["target_count"] = network.stashService.TargetConfidants()
// Metrics from stored stashes (we're a confidant for these)
totalBytes := 0
for _, stash := range state.Stored {
if encStash, ok := stash.(map[string]interface{}); ok {
if ciphertext, ok := encStash["Ciphertext"].([]interface{}); ok {
totalBytes += len(ciphertext)
}
}
}
response["metrics"] = map[string]interface{}{
"stashes_stored": len(state.Stored),
"total_bytes": totalBytes,
"storage_limit": storageLimit,
}
}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(response); err != nil {
logrus.Errorf("Failed to encode stash status response: %v", err)
}
}
// POST /api/stash/update - Update stash data and distribute to confidants
func (network *Network) httpStashUpdateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if network.stashService == nil {
http.Error(w, "Stash service not initialized", http.StatusInternalServerError)
return
}
// Read raw JSON body
var data json.RawMessage
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Update stash data and distribute to all confidants
if err := network.stashService.SetStashData(data); err != nil {
logrus.Errorf("📦 Failed to update stash: %v", err)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if encErr := json.NewEncoder(w).Encode(map[string]interface{}{
"success": false,
"message": fmt.Sprintf("Failed to distribute stash: %v", err),
}); encErr != nil {
logrus.Errorf("Failed to encode stash update error response: %v", encErr)
}
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"message": "Stash updated and distributed to confidants",
}); err != nil {
logrus.Errorf("Failed to encode stash update success response: %v", err)
}
}
// POST /api/stash/recover - Trigger manual stash recovery from confidants
func (network *Network) httpStashRecoverHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if network.stashService == nil {
http.Error(w, "Stash service not initialized", http.StatusInternalServerError)
return
}
// Trigger recovery from any available confidant
go func() {
data, err := network.stashService.RecoverFromAny()
if err != nil {
logrus.Errorf("📦 Stash recovery failed: %v", err)
} else {
logrus.Infof("📦 Stash recovered successfully (%d bytes)", len(data))
// Store the recovered data locally
if err := network.stashService.SetStashData(data); err != nil {
logrus.Errorf("📦 Failed to store recovered stash: %v", err)
}
}
}()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"message": "Stash recovery initiated from confidants",
}); err != nil {
logrus.Errorf("Failed to encode stash recovery response: %v", err)
}
}
// GET /api/stash/confidants - Get list of confidants with details
func (network *Network) httpStashConfidantsHandler(w http.ResponseWriter, r *http.Request) {
confidants := []map[string]interface{}{}
if network.stashService != nil {
if stateBytes, err := network.stashService.MarshalState(); err == nil {
var state struct {
Confidants []string `json:"confidants"`
}
if err := json.Unmarshal(stateBytes, &state); err == nil {
for _, confidantID := range state.Confidants {
info := map[string]interface{}{
"id": confidantID,
"status": "confirmed",
}
// Get peer details if available (confidantID is a types.NaraID, not a name!)
naraID := types.NaraID(confidantID)
network.local.mu.Lock()
nara, exists := network.NeighbourhoodByID[naraID]
network.local.mu.Unlock()
if exists {
nara.mu.Lock()
naraName := nara.Name
info["name"] = naraName
info["memory_mode"] = nara.Status.MemoryMode
nara.mu.Unlock()
// Check if online via observation (using name, not ID)
network.local.mu.Lock()
if obs, ok := network.local.Me.Status.Observations[naraName]; ok {
info["online"] = obs.isOnline()
}
network.local.mu.Unlock()
}
confidants = append(confidants, info)
}
}
}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(map[string]interface{}{
"confidants": confidants,
}); err != nil {
logrus.Errorf("Failed to encode stash confidants response: %v", err)
}
}