Skip to content

Commit

Permalink
p2p/http: cache json wellknown mappings in the .well-known handler (#…
Browse files Browse the repository at this point in the history
…2537)

We are expecting this to be vastly read dominated, caching this makes sense.
  • Loading branch information
Jorropo committed Aug 29, 2023
1 parent ac038db commit 4eb5ba5
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion p2p/http/libp2phttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type PeerMeta map[protocol.ID]ProtocolMeta
type WellKnownHandler struct {
wellknownMapMu sync.Mutex
wellKnownMapping PeerMeta
wellKnownCache []byte
}

// streamHostListen retuns a net.Listener that listens on libp2p streams for HTTP/1.1 messages.
Expand All @@ -67,7 +68,14 @@ func (h *WellKnownHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

// Return a JSON object with the well-known protocols
h.wellknownMapMu.Lock()
mapping, err := json.Marshal(h.wellKnownMapping)
mapping := h.wellKnownCache
var err error
if mapping == nil {
mapping, err = json.Marshal(h.wellKnownMapping)
if err == nil {
h.wellKnownCache = mapping
}
}
h.wellknownMapMu.Unlock()
if err != nil {
http.Error(w, "Marshal error", http.StatusInternalServerError)
Expand All @@ -84,6 +92,7 @@ func (h *WellKnownHandler) AddProtocolMeta(p protocol.ID, protocolMeta ProtocolM
h.wellKnownMapping = make(map[protocol.ID]ProtocolMeta)
}
h.wellKnownMapping[p] = protocolMeta
h.wellKnownCache = nil
h.wellknownMapMu.Unlock()
}

Expand All @@ -92,6 +101,7 @@ func (h *WellKnownHandler) RemoveProtocolMeta(p protocol.ID) {
if h.wellKnownMapping != nil {
delete(h.wellKnownMapping, p)
}
h.wellKnownCache = nil
h.wellknownMapMu.Unlock()
}

Expand Down

0 comments on commit 4eb5ba5

Please sign in to comment.