Compare commits

...

5 Commits

Author SHA1 Message Date
Branden J Brown
9610513384 implement set on client/server 2025-03-13 21:20:26 -04:00
Branden J Brown
4b44ffcd13 use path values instead of query parameters for lookup 2025-03-13 21:07:10 -04:00
Branden J Brown
8047f4f13e fix Find client url 2025-03-13 21:05:02 -04:00
Branden J Brown
70f4e149d4 add Set operation 2025-03-13 20:58:14 -04:00
Branden J Brown
ef03e13a87 don't handle keys that aren't owned 2025-03-13 20:54:31 -04:00
4 changed files with 87 additions and 14 deletions

View File

@ -13,13 +13,15 @@ type Client interface {
// If the ID is not associated with a key, the result must be the empty
// string with a nil error.
Find(ctx context.Context, s Peer, id ID) (Peer, string, error)
// Set asks s to save a value for an ID.
Set(ctx context.Context, s Peer, id ID, v string) error
// Notify tells s we believe n to be its predecessor.
Notify(ctx context.Context, n *Node, s Peer) error
// Neighbors requests a peer's beliefs about its own neighbors.
Neighbors(ctx context.Context, p Peer) (pred Peer, succ []Peer, err error)
}
// TODO(branden): FindSuccessor should be plural; if we have multiple keys to
// TODO(branden): Find should be plural; if we have multiple keys to
// search, we shouldn't have to do the whole query for all of them, especially
// considering we can sort by increasing distance from the origin and then do
// the query in linear time.
@ -33,6 +35,18 @@ func Find(ctx context.Context, cl Client, n *Node, id ID) (Peer, string, error)
return p, s, err
}
// TODO(branden): Set should be plural for the same reasons. It should also
// return an error if the key isn't local to the peer.
// Set saves a value in the Chord network.
func Set(ctx context.Context, cl Client, n *Node, key ID, val string) error {
p, _, err := Find(ctx, cl, n, key)
if err != nil {
return fmt.Errorf("couldn't find peer to save key: %w", err)
}
return cl.Set(ctx, p, key, val)
}
// Join creates a new node joining an existing Chord network by communicating
// with any peer already in the network.
func Join(ctx context.Context, cl Client, addr netip.AddrPort, np Peer) (*Node, error) {

View File

@ -2,11 +2,13 @@ package httpnode
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"git.sunturtle.xyz/zephyr/chord/chord"
)
@ -25,10 +27,9 @@ func (cl *Client) Find(ctx context.Context, s chord.Peer, id chord.ID) (chord.Pe
return chord.Peer{}, "", errors.New("Find with invalid peer")
}
url := url.URL{
Scheme: "http",
Host: addr.String(),
Path: path.Join("/", cl.APIBase, "succ"),
RawQuery: url.Values{"s": {id.String()}}.Encode(),
Scheme: "http",
Host: addr.String(),
Path: path.Join("/", cl.APIBase, "key", id.String()),
}
req, err := http.NewRequestWithContext(ctx, "GET", url.String(), nil)
if err != nil {
@ -45,6 +46,29 @@ func (cl *Client) Find(ctx context.Context, s chord.Peer, id chord.ID) (chord.Pe
return chord.Address(p.Peer), p.Value, nil
}
func (cl *Client) Set(ctx context.Context, s chord.Peer, id chord.ID, v string) error {
_, addr := s.Values()
url := url.URL{
Scheme: "http",
Host: addr.String(),
Path: path.Join("/", cl.APIBase, "key", id.String()),
}
body := strings.NewReader(base64.StdEncoding.EncodeToString([]byte(v)))
req, err := http.NewRequestWithContext(ctx, "POST", url.String(), body)
if err != nil {
return err
}
resp, err := cl.HTTP.Do(req)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
_, err := readResponse[struct{}](resp)
return err
}
return nil
}
// Notify tells s we believe n to be its predecessor.
func (cl *Client) Notify(ctx context.Context, n *chord.Node, s chord.Peer) error {
_, addr := s.Values()

View File

@ -2,8 +2,10 @@ package httpnode
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
@ -45,7 +47,8 @@ func New(l net.Listener, cl chord.Client) (*Node, error) {
// Router creates a handler for the Chord HTTP endpoints.
func (n *Node) Router() http.Handler {
m := http.NewServeMux()
m.HandleFunc("GET /key", n.key)
m.HandleFunc("GET /key/{id}", n.key)
m.HandleFunc("POST /key/{id}", n.set)
m.HandleFunc("POST /pred", n.notify)
m.HandleFunc("GET /neighbors", n.neighbors)
return m
@ -66,7 +69,7 @@ func (n *Node) Check(ctx context.Context) error {
}
func (n *Node) key(w http.ResponseWriter, r *http.Request) {
s := r.FormValue("s")
s := r.PathValue("id")
id, err := chord.ParseID(s)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
@ -82,6 +85,25 @@ func (n *Node) key(w http.ResponseWriter, r *http.Request) {
writeOk(w, pv)
}
func (n *Node) set(w http.ResponseWriter, r *http.Request) {
s := r.PathValue("id")
id, err := chord.ParseID(s)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
val, err := io.ReadAll(base64.NewDecoder(base64.StdEncoding, r.Body))
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if !n.self.SetLocal(id, string(val)) {
writeError(w, http.StatusNotFound, "id does not belong to this peer")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (n *Node) notify(w http.ResponseWriter, r *http.Request) {
s := r.FormValue("p")
addr, err := netip.ParseAddrPort(s)

View File

@ -47,9 +47,15 @@ func (n *Node) Neighbors(s []Peer) (Peer, []Peer) {
return n.pred, append(s, n.succ...)
}
func (n *Node) localLocked(id ID) bool {
return contains(n.self.id, n.succ[0].id, id)
}
// IsLocal reports whether this node owns the given key.
func (n *Node) IsLocal(id ID) bool {
return contains(n.self.id, n.Successor().id, id)
n.mu.Lock()
defer n.mu.Unlock()
return n.localLocked(id)
}
// Closest finds the locally known peer which is the closest predecessor of key.
@ -85,19 +91,26 @@ func (n *Node) Closest(id ID) Peer {
return n.self
}
// Get obtains the value for a key owned by the node.
func (n *Node) Get(k ID) (v string, found bool) {
// GetLocal obtains the value for a key if it is local to and owned by the node.
func (n *Node) GetLocal(k ID) (v string, found bool) {
n.mu.Lock()
defer n.mu.Unlock()
v, found = n.data[k]
if n.localLocked(k) {
v, found = n.data[k]
}
return v, found
}
// Set sets the value for a key.
func (n *Node) Set(k ID, v string) {
// SetLocal sets the value for a key.
// Returns false if the key is not owned by the node.
func (n *Node) SetLocal(k ID, v string) bool {
n.mu.Lock()
defer n.mu.Unlock()
n.data[k] = v
if n.localLocked(k) {
n.data[k] = v
return true
}
return false
}
// Peer is the ID and address of a node.