Operations: links, logs, rules and fleets in service · 7 MIN READ

A fleet backend in Go: a mission API, idempotent POST and a dispatch state machine

Build a mission API with Go 1.22 ServeMux method and wildcard patterns, make POST safe to retry with an Idempotency-Key, dispatch missions to drones through an explicit queued, assigned, flying, done or failed state machine driven by the autopilot, and exercise it all through httptest without opening a socket.

Behind every delivery or inspection service sits a backend: clients create missions, a dispatcher hands them to vehicles, and everyone polls for progress. Mobile networks lose responses, so clients retry, and a retried POST that creates a second mission sends a second drone. The dispatcher must also tell the truth about outcomes: a mission that ended in a failsafe has failed, even if the drone landed safely at home.

drones · A MAP OF THE IDEA

  1. Validate and store by key
  2. Queue, assign, fly
  3. Fail on any failsafe
  4. Expose state over GET

Useful when

  • Client retries never create a second flight.
  • Illegal transitions fail loudly instead of corrupting state.

Watch out

  • The key must be stored atomically with the mission it created.
  • An API that ignores radio range accepts unflyable missions.

Implementation & operation cost: A mission store with an idempotency table, a dispatcher loop with a state machine, and handler tests on httptest recorders.

01

Routes with Go 1.22 patterns

Since Go 1.22, http.ServeMux patterns can name a method and contain wildcards, so most mission APIs need no router library. "POST /missions" matches only POST; "GET /missions/{id}" matches one path segment after /missions/ and the handler reads it with r.PathValue("id"). GET patterns also match HEAD. When the path matches but the method does not, the mux answers 405 Method Not Allowed with an Allow header listing the methods that would work. When two patterns overlap, the more specific one wins, and registering two that overlap with neither more specific panics at start-up rather than routing at random. The GODEBUG setting httpmuxgo121=1 restores the old behaviour while you migrate.

go
mux := http.NewServeMux()
mux.HandleFunc("POST /missions", srv.create)
mux.HandleFunc("GET /missions/{id}", srv.get) // r.PathValue("id")

// In production the same mux sits behind a server with timeouts.
server := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(server.ListenAndServe())
Read the code

Two lines register the whole API; the method and the wildcard live in the pattern, not in an if inside the handler. DELETE /missions/m1 never reaches a handler: the mux answers 405 with Allow: GET, HEAD. The http.Server sets ReadHeaderTimeout because with it and ReadTimeout left at zero there is no timeout at all, and a slow client could hold a connection open indefinitely. The lesson program skips the listener entirely.

02

Idempotency-Key: a retry is not a new mission

POST is not idempotent: sending it twice may create two missions. The IETF HTTPAPI working group's Idempotency-Key draft standardises the usual fix. The client sends a unique key with the request and reuses it on every retry; the server stores the key with the result and answers a duplicate with the stored result instead of acting again. The draft asks for 400 when a required key is missing, 422 when a key is reused with a different payload (detected with a fingerprint, such as a checksum of the body), and 409 when a retry arrives while the first request is still being processed; it also asks servers to document when keys expire. Store the key in the same atomic step that creates the mission, under one lock or in one transaction with a unique index on the key, and scope keys to the client that sent them. The program compares raw bodies, so the same JSON with different spacing counts as a different payload; comparing a canonical form is kinder to clients.

03

A dispatch state machine

A mission moves through queued, assigned, flying, and then done or failed, and the table next lists the only legal moves; move panics on any other, because an impossible transition is a bug to find, not a state to store. Queued missions wait for an idle drone: on the ground, at least 50 percent charge and not already assigned. A flying mission follows its vehicle through climb, outbound, hover and return phases. The autopilot outranks the dispatcher: if the drone switches to a return or a landing that the dispatcher did not command, the mission has failed, and the reason is the autopilot's own latest note, read from sim.Events() as a ground station reads STATUSTEXT. The drone stays busy until it is on the ground, so a failed mission never frees a vehicle that is still flying home. Write every transition to an append-only log as well; it is the first thing anyone asks for when a customer calls.

04

The backend, exercised through httptest

main registers the routes, then sends requests straight into mux.ServeHTTP with httptest.NewRequest and an httptest.NewRecorder: no port, no socket, nothing for the WASI sandbox of the app to refuse. It creates three missions, retries one, misuses the key, forgets it, asks for a mission outside the service area, a mission that does not exist and a method the API does not have. Then the main loop calls Dispatch every 0.2 s of simulated time with two drones and a 100 m radio range, and polls GET /missions/m3 at 20 s, 60 s and at the end.

go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math"
	"net/http"
	"net/http/httptest"
	"slices"
	"strings"
	"sync"

	"gopherforge.app/drone"
)

// State is where a mission is in dispatch; next lists the legal moves.
type State string

const Queued, Assigned, Flying, Done, Failed State = "queued", "assigned", "flying", "done", "failed"

var next = map[State][]State{Queued: {Assigned}, Assigned: {Flying, Failed}, Flying: {Done, Failed}}

// Mission is the stored record and the JSON the API returns.
type Mission struct {
	ID      string     `json:"id"`
	Target  [2]float64 `json:"target"`
	Alt     float64    `json:"alt"`
	Hover   float64    `json:"hover"`
	State   State      `json:"state"`
	Drone   string     `json:"drone,omitempty"`
	Phase   string     `json:"phase,omitempty"`
	Pos     []float64  `json:"pos,omitempty"`
	Battery float64    `json:"battery,omitempty"`
	Reason  string     `json:"reason,omitempty"`
	vehicle *drone.Drone
	since   float64
}

// Server holds the missions and, per Idempotency-Key, the request body and
// the first response. net/http serves each request on its own goroutine
// and the dispatcher runs beside them, so one mutex guards all of it.
type Server struct {
	mu       sync.Mutex
	missions []*Mission
	keys     map[string][2]string
}

// reply writes v as JSON; a string becomes an RFC 9457 problem document.
func reply(w http.ResponseWriter, status int, v any) string {
	kind := "application/json"
	if title, ok := v.(string); ok {
		kind, v = "application/problem+json", map[string]any{"status": status, "title": title}
	}
	body, _ := json.Marshal(v)
	w.Header().Set("Content-Type", kind)
	w.WriteHeader(status)
	w.Write(body)
	return string(body)
}

func (s *Server) create(w http.ResponseWriter, r *http.Request) {
	key := r.Header.Get("Idempotency-Key")
	if key == "" {
		reply(w, http.StatusBadRequest, "Idempotency-Key header required")
		return
	}
	body, _ := io.ReadAll(io.LimitReader(r.Body, 4096)) // longer bodies fail to decode
	s.mu.Lock()
	defer s.mu.Unlock()
	if old, ok := s.keys[key]; ok && old[0] == string(body) {
		reply(w, http.StatusCreated, json.RawMessage(old[1])) // the first answer again
		return
	} else if ok {
		reply(w, http.StatusUnprocessableEntity, "Idempotency-Key reused with another body")
		return
	}
	var req struct {
		Target     [2]float64 `json:"target"`
		Alt, Hover float64
	}
	dec := json.NewDecoder(bytes.NewReader(body))
	dec.DisallowUnknownFields() // a client cannot send "state":"done"
	if err := dec.Decode(&req); err != nil {
		reply(w, http.StatusBadRequest, err.Error())
		return
	}
	if req.Alt < 10 || req.Alt > 60 || req.Hover > 60 || math.Hypot(req.Target[0], req.Target[1]) > 150 {
		reply(w, http.StatusUnprocessableEntity, "outside the service area (150 m, 10..60 m up)")
		return
	}
	m := &Mission{ID: fmt.Sprintf("m%d", len(s.missions)+1), Target: req.Target, Alt: req.Alt, Hover: req.Hover, State: Queued}
	s.missions = append(s.missions, m)
	w.Header().Set("Location", "/missions/"+m.ID)
	s.keys[key] = [2]string{string(body), reply(w, http.StatusCreated, m)}
}

func (s *Server) get(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if i := slices.IndexFunc(s.missions, func(m *Mission) bool { return m.ID == r.PathValue("id") }); i >= 0 {
		reply(w, http.StatusOK, s.missions[i])
		return
	}
	reply(w, http.StatusNotFound, "no mission "+r.PathValue("id"))
}

func move(sim *drone.Sim, m *Mission, to State, why string) {
	if !slices.Contains(next[m.State], to) {
		panic(fmt.Sprintf("%s: illegal %s -> %s", m.ID, m.State, to))
	}
	fmt.Printf("%6.1f s  %s %-8s -> %-8s %s\n", sim.Time(), m.ID, m.State, to, why)
	m.State = to
}

// lastNote is the autopilot's latest note about d, as STATUSTEXT would say.
func lastNote(sim *drone.Sim, d *drone.Drone) (note string) {
	for _, e := range sim.Events() {
		if e.Drone >= 0 && sim.Drones()[e.Drone] == d {
			note = e.Text
		}
	}
	return note
}

// Dispatch moves every mission one step: a queued one gets the first idle
// drone, a flying one follows its vehicle, and a failsafe fails it.
func Dispatch(s *Server, sim *drone.Sim) {
	s.mu.Lock()
	defer s.mu.Unlock()
	idle := func(x *drone.Drone) bool {
		return x.State().Landed && x.State().Battery >= 50 &&
			!slices.ContainsFunc(s.missions, func(m *Mission) bool { return m.vehicle == x && m.State == Assigned })
	}
	for _, m := range s.missions {
		d := m.vehicle
		switch m.State {
		case Queued:
			if i := slices.IndexFunc(sim.Drones(), idle); i >= 0 {
				m.vehicle, m.Drone = sim.Drones()[i], sim.Drones()[i].Name
				move(sim, m, Assigned, "to "+m.Drone)
			}
		case Assigned:
			if err := d.Arm(); err != nil {
				move(sim, m, Failed, err.Error())
				continue
			}
			d.TakeOff(m.Alt)
			m.Phase = "climb"
			move(sim, m, Flying, fmt.Sprintf("take off, battery %.0f%%", d.State().Battery))
		case Flying:
			switch st := d.State(); {
			case st.Mode == drone.Crashed || (st.Mode == drone.Returning || st.Mode == drone.Landing) && m.Phase != "return":
				m.Reason = lastNote(sim, d)
				move(sim, m, Failed, m.Reason)
			case m.Phase == "climb" && d.Arrived():
				d.GoTo(drone.Vec3{X: m.Target[0], Y: m.Target[1], Z: m.Alt})
				m.Phase = "outbound"
			case m.Phase == "outbound" && d.Arrived():
				m.Phase, m.since = "hover", sim.Time()
			case m.Phase == "hover" && sim.Time()-m.since >= m.Hover:
				d.ReturnHome()
				m.Phase = "return"
			case m.Phase == "return" && st.Landed:
				move(sim, m, Done, fmt.Sprintf("landed %.1f m from home, battery %.0f%%", st.Pos.Sub(d.Home()).Len(), st.Battery))
			}
		}
		if d != nil && !d.State().Landed { // progress for GET
			st, r := d.State(), func(v float64) float64 { return math.Round(v*10)/10 + 0 }
			m.Pos, m.Battery = []float64{r(st.Pos.X), r(st.Pos.Y), r(st.Pos.Z)}, math.Round(st.Battery)
		}
	}
}

func main() {
	sim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: 1}, Gust: 1, MaxSpeed: 8, LinkRange: 100, Seed: 12})
	sim.AddDrone("bravo", drone.Vec3{X: 6})
	srv := &Server{keys: map[string][2]string{}}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /missions", srv.create)
	mux.HandleFunc("GET /missions/{id}", srv.get)
	// No listener: requests go straight to the mux, so this runs in a WASI
	// sandbox without sockets too. A real server calls http.ListenAndServe.
	call := func(method, path, key, body string) {
		req := httptest.NewRequest(method, path, strings.NewReader(body))
		if key != "" {
			req.Header.Set("Idempotency-Key", key)
			path += " key=" + key
		}
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, req)
		resp := strings.TrimSpace(rec.Body.String())
		if a := rec.Header().Get("Allow"); a != "" {
			resp = "Allow: " + a + ", " + resp
		}
		fmt.Printf("%s\n    -> %d %s\n", strings.TrimSpace(method+" "+path+" "+body), rec.Code, resp)
	}
	call("POST", "/missions", "k-101", `{"target":[40,30],"alt":20,"hover":5}`)
	call("POST", "/missions", "k-101", `{"target":[40,30],"alt":20,"hover":5}`)
	call("POST", "/missions", "k-101", `{"target":[40,-30],"alt":20,"hover":5}`)
	call("POST", "/missions", "", `{"target":[10,10],"alt":20,"hover":5}`)
	call("POST", "/missions", "k-102", `{"target":[-35,45],"alt":25,"hover":5}`)
	call("POST", "/missions", "k-103", `{"target":[130,20],"alt":20,"hover":5}`)
	call("POST", "/missions", "k-104", `{"target":[400,0],"alt":20,"hover":5}`)
	call("GET", "/missions/m9", "", "")
	call("DELETE", "/missions/m1", "", "")

	for sim.Time() < 120 {
		Dispatch(srv, sim)
		if t := math.Round(sim.Time() * 5); t == 5*20 || t == 5*60 {
			call("GET", "/missions/m3", "", "")
		}
		sim.Run(0.2, nil)
	}
	call("GET", "/missions/m3", "", "")
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

The retry with key k-101 and the same body returns the same 201 response with id m1, and the next mission is m2, so no second mission was created; the same key with another body gets 422, a POST without a key 400, a target 400 m away 422, GET /missions/m9 404, all as problem documents. DELETE is answered by the mux itself: 405 with Allow: GET, HEAD and its plain-text body. At 0.0 s m1 goes to alpha and m2 to bravo, both flying at 0.2 s; m3 stays queued, and the GET at 20 s says so. When m1 lands at 43.0 s, 0.2 m from home with 90 percent, the same pass hands m3 to alpha, which takes off at 43.2 s. The GET at 60 s shows m3 outbound at (61.8, 9.4, 20) with 86 percent. Its target (130, 20) lies inside the 150 m service area but beyond the 100 m radio range: at 69.8 s the autopilot's note 'link lost for 5 s: return to home' fails the mission, and the last GET shows state failed with that reason while alpha lands at home with 75 percent.

05

From recorder to production

The recorder keeps handlers honest about status codes, headers and bodies, which is most of what an API test needs; table-driven tests can send hundreds of requests per second this way. httptest.NewServer adds a real listener on the loopback interface when a test must exercise an HTTP client, timeouts or TLS, and that needs sockets. In production the dispatcher becomes its own goroutine on a ticker with a context for shutdown, the store moves to a database whose transactions take over the mutex's job, and clients retry with backoff and jitter, reusing the key. The failure of m3 shows the last point: validate missions against everything that can make them unflyable, such as radio range, battery, geofences and other operations, before accepting them, or the API promises flights the fleet cannot fly.

06

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Nothing listens on a port, so the program runs unchanged in the app's sandbox. The console shows every request and transition; Output replays both drones, with the dashed circle of the radio range and alpha turning back from m3 at its edge. Add a check in create that rejects targets beyond 100 m with 422 and run it again: m3 is refused at the API instead of failing in the air.

TAKE THIS WITH YOU

Route with Go 1.22 method and wildcard patterns, make POST safe to retry by storing the Idempotency-Key with the first response in the same atomic step that creates the mission, and drive missions through an explicit state machine in which any autopilot failsafe fails the mission. Test handlers through httptest recorders, and validate missions against what the fleet can actually fly.

Check your understanding

A POST /missions times out on the client, which retries with the same Idempotency-Key and the same body. What should the server return?

Go to the source

Progress stays in this browser. No account needed.