|
| 1 | +package web_server |
| 2 | + |
| 3 | +import ( |
| 4 | + webtypes "github.com/bcdevtools/node-management/services/web_server/types" |
| 5 | + "github.com/bcdevtools/node-management/types" |
| 6 | + "github.com/bcdevtools/node-management/utils" |
| 7 | + "github.com/gin-gonic/gin" |
| 8 | + "github.com/pkg/errors" |
| 9 | + "net/http" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +var cacheAddrBook *types.TimeBasedCache |
| 14 | + |
| 15 | +func HandleDownloadAddrBook(c *gin.Context) { |
| 16 | + w := wrapGin(c) |
| 17 | + |
| 18 | + addrBook, err := getAddrbook(w.Config()) |
| 19 | + if err != nil { |
| 20 | + utils.PrintlnStdErr("ERR: failed to get addrbook.json:", err) |
| 21 | + w.PrepareDefaultErrorResponse(). |
| 22 | + WithResult("failed to get addrbook.json"). |
| 23 | + SendResponse() |
| 24 | + return |
| 25 | + } |
| 26 | + if addrBook == nil || len(addrBook.Addrs) == 0 { |
| 27 | + w.PrepareDefaultErrorResponse(). |
| 28 | + WithHttpStatusCode(http.StatusServiceUnavailable). |
| 29 | + WithResult("failed to get addrbook.json"). |
| 30 | + SendResponse() |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + c.Header("Content-Disposition", "attachment; filename=addrbook.json") |
| 35 | + c.JSON(http.StatusOK, addrBook) |
| 36 | +} |
| 37 | + |
| 38 | +func getAddrbook(cfg webtypes.Config) (*types.AddrBook, error) { |
| 39 | + if addrBook := cacheAddrBook.GetRL(); addrBook != nil { |
| 40 | + return addrBook.(*types.AddrBook), nil |
| 41 | + } |
| 42 | + |
| 43 | + addrBook, err := cacheAddrBook.UpdateWL(func() (any, error) { |
| 44 | + addrBook := &types.AddrBook{} |
| 45 | + if err := addrBook.ReadAddrBook(cfg.GetAddrBookFilePath()); err != nil { |
| 46 | + return nil, errors.Wrap(err, "failed to read addrbook") |
| 47 | + } |
| 48 | + |
| 49 | + livePeers := addrBook.GetLivePeers(48 * time.Hour) |
| 50 | + |
| 51 | + if len(livePeers) == 0 && cfg.Debug { |
| 52 | + // load random, include dead peers, on debug mode |
| 53 | + livePeers = addrBook.Addrs |
| 54 | + if len(livePeers) > 10 { |
| 55 | + livePeers = livePeers[:10] |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + addrBook.Addrs = livePeers |
| 60 | + |
| 61 | + return addrBook, nil |
| 62 | + }, true) |
| 63 | + |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + |
| 68 | + return addrBook.(*types.AddrBook), nil |
| 69 | +} |
| 70 | + |
| 71 | +func init() { |
| 72 | + cacheAddrBook = types.NewTimeBasedCache(60 * time.Second) |
| 73 | +} |
0 commit comments