go project - add a migration and rename the dockerfiles so that Go is the primary
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/michaeldileo/SafelyYouCodingChallenge/internal/store"
|
||||
)
|
||||
|
||||
// Server wires HTTP handlers to the in-memory store.
|
||||
// Constructed in main and passed dependencies explicitly (no DI container).
|
||||
type Server struct {
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func NewServer(s *store.Store) *Server {
|
||||
return &Server{store: s}
|
||||
}
|
||||
|
||||
// Handler returns the HTTP routes for this API.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", s.healthz)
|
||||
mux.HandleFunc("POST /api/v1/devices/{device_id}/heartbeat", s.postHeartbeat)
|
||||
mux.HandleFunc("POST /api/v1/devices/{device_id}/stats", s.postStats)
|
||||
mux.HandleFunc("GET /api/v1/devices/{device_id}/stats", s.getStats)
|
||||
return mux
|
||||
}
|
||||
|
||||
type heartbeatRequest struct {
|
||||
SentAt time.Time `json:"sent_at"`
|
||||
}
|
||||
|
||||
type uploadStatsRequest struct {
|
||||
SentAt time.Time `json:"sent_at"` // accepted for contract; ignored in average
|
||||
UploadTime int64 `json:"upload_time"` // nanoseconds
|
||||
}
|
||||
|
||||
type getDeviceStatsResponse struct {
|
||||
AvgUploadTime string `json:"avg_upload_time"`
|
||||
Uptime float64 `json:"uptime"`
|
||||
}
|
||||
|
||||
// OpenAPI NotFoundResponse / ErrorResponse both use {"msg": "..."}.
|
||||
type msgResponse struct {
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}
|
||||
|
||||
func (s *Server) postHeartbeat(w http.ResponseWriter, r *http.Request) {
|
||||
id := store.DeviceID(r.PathValue("device_id"))
|
||||
if !s.store.Known(id) {
|
||||
writeJSON(w, http.StatusNotFound, msgResponse{
|
||||
Msg: fmt.Sprintf("Device ID %s not found", id),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var req heartbeatRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, msgResponse{
|
||||
Msg: "invalid request body",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.store.AddHeartbeat(id, req.SentAt); err != nil {
|
||||
if errors.Is(err, store.ErrOutOfSequence) {
|
||||
writeJSON(w, http.StatusInternalServerError, msgResponse{
|
||||
Msg: "Attempted to add a timestamp that was out of sequence or invalid.",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, msgResponse{Msg: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) postStats(w http.ResponseWriter, r *http.Request) {
|
||||
id := store.DeviceID(r.PathValue("device_id"))
|
||||
if !s.store.Known(id) {
|
||||
writeJSON(w, http.StatusNotFound, msgResponse{
|
||||
Msg: fmt.Sprintf("Device ID %s not found", id),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var req uploadStatsRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, msgResponse{
|
||||
Msg: "invalid request body",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// sent_at is decoded above but intentionally unused for the average.
|
||||
s.store.AddUpload(id, time.Duration(req.UploadTime))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) getStats(w http.ResponseWriter, r *http.Request) {
|
||||
id := store.DeviceID(r.PathValue("device_id"))
|
||||
if !s.store.Known(id) {
|
||||
writeJSON(w, http.StatusNotFound, msgResponse{
|
||||
Msg: fmt.Sprintf("Device ID %s not found", id),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
avg := s.store.AverageUploadTime(id)
|
||||
writeJSON(w, http.StatusOK, getDeviceStatsResponse{
|
||||
AvgUploadTime: avg.String(), // HTTP-edge formatting (Q13)
|
||||
Uptime: s.store.Uptime(id),
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/michaeldileo/SafelyYouCodingChallenge/internal/store"
|
||||
)
|
||||
|
||||
func TestPostHeartbeat_UnknownDevice_404(t *testing.T) {
|
||||
s := store.New([]store.DeviceID{"known"})
|
||||
srv := NewServer(s)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/devices/missing/heartbeat", strings.NewReader(`{"sent_at":"2024-01-01T12:00:00Z"}`))
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", rec.Code)
|
||||
}
|
||||
var body msgResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if body.Msg == "" {
|
||||
t.Fatal("expected non-empty msg")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostAndGetStats_RoundTrip(t *testing.T) {
|
||||
id := store.DeviceID("device-1")
|
||||
s := store.New([]store.DeviceID{id})
|
||||
srv := NewServer(s)
|
||||
h := srv.Handler()
|
||||
|
||||
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
// two heartbeats one minute apart → uptime 200
|
||||
postJSON(t, h, http.MethodPost, "/api/v1/devices/device-1/heartbeat",
|
||||
`{"sent_at":"`+t0.Format(time.RFC3339)+`"}`, http.StatusNoContent)
|
||||
postJSON(t, h, http.MethodPost, "/api/v1/devices/device-1/heartbeat",
|
||||
`{"sent_at":"`+t0.Add(time.Minute).Format(time.RFC3339)+`"}`, http.StatusNoContent)
|
||||
|
||||
// upload 197331667813 ns → "3m17.331667813s"
|
||||
postJSON(t, h, http.MethodPost, "/api/v1/devices/device-1/stats",
|
||||
`{"sent_at":"2024-01-01T12:00:00Z","upload_time":197331667813}`, http.StatusNoContent)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/devices/device-1/stats", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
var got getDeviceStatsResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if got.Uptime != 200 {
|
||||
t.Fatalf("uptime = %v, want 200", got.Uptime)
|
||||
}
|
||||
if got.AvgUploadTime != "3m17.331667813s" {
|
||||
t.Fatalf("avg_upload_time = %q, want 3m17.331667813s", got.AvgUploadTime)
|
||||
}
|
||||
}
|
||||
|
||||
func postJSON(t *testing.T, h http.Handler, method, path, body string, wantStatus int) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != wantStatus {
|
||||
t.Fatalf("%s %s status = %d, want %d; body=%s", method, path, rec.Code, wantStatus, rec.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user