go project - add a migration and rename the dockerfiles so that Go is the primary

This commit is contained in:
2026-08-06 15:54:40 -05:00
parent 459b90dcd7
commit e17fbc14a0
15 changed files with 771 additions and 0 deletions
+130
View File
@@ -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)
}
+80
View File
@@ -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())
}
}
+94
View File
@@ -0,0 +1,94 @@
package store
import (
"errors"
"sync"
"time"
)
// ErrOutOfSequence is returned when a heartbeat timestamp is earlier than
// the latest accepted heartbeat for that device.
var ErrOutOfSequence = errors.New("heartbeat out of sequence")
// heartbeatHistory tracks one device's heartbeat timeline.
// Unexported: only Store methods expose behavior.
type heartbeatHistory struct {
mu sync.Mutex
count int64
first time.Time
last time.Time
}
func (h *heartbeatHistory) add(sentAt time.Time) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.first.IsZero() {
h.first = sentAt
h.last = sentAt
h.count = 1
return nil
}
// Equal timestamps are allowed (matches C#: sentAt < LastHeartBeat only).
if sentAt.Before(h.last) {
return ErrOutOfSequence
}
h.last = sentAt
h.count++
return nil
}
func (h *heartbeatHistory) uptime() float64 {
h.mu.Lock()
defer h.mu.Unlock()
if h.first.IsZero() {
return 0
}
minutes := h.last.Sub(h.first).Minutes()
// Single heartbeat (or identical timestamps): treat span as one minute.
if minutes == 0 {
minutes = 1
}
return float64(h.count) / minutes * 100
}
// historyFor returns the per-device history, creating it if needed.
// The store-level lock only covers map insert/lookup; callers then use
// the history's own lock for mutations/reads.
func (s *Store) historyFor(id DeviceID) *heartbeatHistory {
s.mu.Lock()
defer s.mu.Unlock()
h, ok := s.heartbeats[id]
if !ok {
h = &heartbeatHistory{}
s.heartbeats[id] = h
}
return h
}
// AddHeartbeat records a heartbeat for deviceID.
// Returns ErrOutOfSequence if sentAt is earlier than the last accepted beat.
func (s *Store) AddHeartbeat(deviceID DeviceID, sentAt time.Time) error {
return s.historyFor(deviceID).add(sentAt)
}
// Uptime returns uptime percent for deviceID:
//
// (heartbeatCount / minutesBetweenFirstAndLast) * 100
//
// Unknown / never-seen devices return 0. A zero-length span is treated as 1 minute.
func (s *Store) Uptime(deviceID DeviceID) float64 {
s.mu.Lock()
h, ok := s.heartbeats[deviceID]
s.mu.Unlock()
if !ok {
return 0
}
return h.uptime()
}
+106
View File
@@ -0,0 +1,106 @@
package store
import (
"errors"
"testing"
"time"
)
func TestAddHeartbeat_FirstSetsFirstLastAndCount(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
if err := s.AddHeartbeat(id, t0); err != nil {
t.Fatalf("AddHeartbeat: %v", err)
}
if got := s.Uptime(id); got != 100 {
t.Fatalf("uptime = %v, want 100 (1 beat / 1 minute)", got)
}
}
func TestAddHeartbeat_LaterUpdatesLast(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
t1 := t0.Add(time.Minute)
_ = s.AddHeartbeat(id, t0)
if err := s.AddHeartbeat(id, t1); err != nil {
t.Fatalf("AddHeartbeat: %v", err)
}
// (2 beats / 1 minute) * 100
if got := s.Uptime(id); got != 200 {
t.Fatalf("uptime = %v, want 200", got)
}
}
func TestAddHeartbeat_SameTimestampAccepted(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
_ = s.AddHeartbeat(id, t0)
if err := s.AddHeartbeat(id, t0); err != nil {
t.Fatalf("same timestamp should be accepted: %v", err)
}
// span still zero → 1 minute floor; 2 beats → 200
if got := s.Uptime(id); got != 200 {
t.Fatalf("uptime = %v, want 200", got)
}
}
func TestAddHeartbeat_OutOfSequence(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
t1 := t0.Add(time.Minute)
_ = s.AddHeartbeat(id, t1)
err := s.AddHeartbeat(id, t0)
if !errors.Is(err, ErrOutOfSequence) {
t.Fatalf("err = %v, want ErrOutOfSequence", err)
}
// rejected beat must not affect uptime: still 1 beat → 100
if got := s.Uptime(id); got != 100 {
t.Fatalf("uptime = %v, want 100", got)
}
}
func TestUptime_TwoHeartbeatsOverTwoMinutes(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
_ = s.AddHeartbeat(id, t0)
_ = s.AddHeartbeat(id, t0.Add(2*time.Minute))
if got := s.Uptime(id); got != 100 {
t.Fatalf("uptime = %v, want 100", got)
}
}
func TestUptime_UnknownDevice(t *testing.T) {
s := New(nil)
if got := s.Uptime(DeviceID("missing")); got != 0 {
t.Fatalf("uptime = %v, want 0", got)
}
}
func TestUptime_IsPerDevice(t *testing.T) {
s := New(nil)
a := DeviceID("device-1")
b := DeviceID("device-2")
t0 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
_ = s.AddHeartbeat(a, t0)
_ = s.AddHeartbeat(a, t0.Add(time.Minute))
_ = s.AddHeartbeat(b, t0)
if got := s.Uptime(a); got != 200 {
t.Fatalf("device-1 uptime = %v, want 200", got)
}
if got := s.Uptime(b); got != 100 {
t.Fatalf("device-2 uptime = %v, want 100 (single beat = 1 minute)", got)
}
}
+38
View File
@@ -0,0 +1,38 @@
package store
import "sync"
// DeviceID is a typed device identifier.
// Using a named type (instead of plain string) makes call sites clearer
// and prevents accidentally mixing unrelated string values.
type DeviceID string
// Store holds in-memory fleet metrics for known devices.
type Store struct {
known map[DeviceID]struct{}
// mu protects the heartbeats/uploads maps (insert/lookup of entries only).
// Each per-device history has its own mutex for mutations.
mu sync.Mutex
heartbeats map[DeviceID]*heartbeatHistory
uploads map[DeviceID]*uploadHistory
}
// New creates a Store seeded with the given known device IDs.
func New(known []DeviceID) *Store {
m := make(map[DeviceID]struct{}, len(known))
for _, id := range known {
m[id] = struct{}{}
}
return &Store{
known: m,
heartbeats: make(map[DeviceID]*heartbeatHistory),
uploads: make(map[DeviceID]*uploadHistory),
}
}
// Known reports whether deviceID was present in the startup device list.
func (s *Store) Known(deviceID DeviceID) bool {
_, ok := s.known[deviceID]
return ok
}
+61
View File
@@ -0,0 +1,61 @@
package store
import (
"sync"
"time"
)
// uploadHistory tracks running total/count of upload durations for one device.
type uploadHistory struct {
mu sync.Mutex
total time.Duration
count int64
}
func (u *uploadHistory) add(d time.Duration) {
u.mu.Lock()
defer u.mu.Unlock()
u.total += d
u.count++
}
func (u *uploadHistory) average() time.Duration {
u.mu.Lock()
defer u.mu.Unlock()
if u.count == 0 {
return 0
}
// Truncating integer division — same idea as C# BigInteger total / count.
return u.total / time.Duration(u.count)
}
func (s *Store) uploadFor(id DeviceID) *uploadHistory {
s.mu.Lock()
defer s.mu.Unlock()
u, ok := s.uploads[id]
if !ok {
u = &uploadHistory{}
s.uploads[id] = u
}
return u
}
// AddUpload records an upload duration (nanoseconds as time.Duration) for deviceID.
// sent_at from the API is intentionally ignored here; the HTTP layer still accepts it.
func (s *Store) AddUpload(deviceID DeviceID, uploadTime time.Duration) {
s.uploadFor(deviceID).add(uploadTime)
}
// AverageUploadTime returns the mean upload duration for deviceID.
// Formatting for the API (duration.String()) belongs at the HTTP edge.
// Unknown / never-seen devices return 0.
func (s *Store) AverageUploadTime(deviceID DeviceID) time.Duration {
s.mu.Lock()
u, ok := s.uploads[deviceID]
s.mu.Unlock()
if !ok {
return 0
}
return u.average()
}
+69
View File
@@ -0,0 +1,69 @@
package store
import (
"testing"
"time"
)
func TestAddUpload_AverageOfOne(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
d := 197331667813 * time.Nanosecond // ~3m17.331667813s
s.AddUpload(id, d)
if got := s.AverageUploadTime(id); got != d {
t.Fatalf("avg = %v, want %v", got, d)
}
}
func TestAddUpload_AverageOfMany(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
s.AddUpload(id, 100*time.Nanosecond)
s.AddUpload(id, 200*time.Nanosecond)
s.AddUpload(id, 300*time.Nanosecond)
// (100+200+300)/3 = 200
if got := s.AverageUploadTime(id); got != 200*time.Nanosecond {
t.Fatalf("avg = %v, want 200ns", got)
}
}
func TestAverageUploadTime_UnknownDevice(t *testing.T) {
s := New(nil)
if got := s.AverageUploadTime(DeviceID("missing")); got != 0 {
t.Fatalf("avg = %v, want 0", got)
}
}
func TestAverageUploadTime_IsPerDevice(t *testing.T) {
s := New(nil)
a := DeviceID("device-1")
b := DeviceID("device-2")
s.AddUpload(a, 100*time.Nanosecond)
s.AddUpload(a, 300*time.Nanosecond)
s.AddUpload(b, 50*time.Nanosecond)
if got := s.AverageUploadTime(a); got != 200*time.Nanosecond {
t.Fatalf("device-1 avg = %v, want 200ns", got)
}
if got := s.AverageUploadTime(b); got != 50*time.Nanosecond {
t.Fatalf("device-2 avg = %v, want 50ns", got)
}
}
func TestAverageUploadTime_TruncatingDivision(t *testing.T) {
s := New(nil)
id := DeviceID("device-1")
// 10+11 = 21; 21/2 = 10 in integer division
s.AddUpload(id, 10*time.Nanosecond)
s.AddUpload(id, 11*time.Nanosecond)
if got := s.AverageUploadTime(id); got != 10*time.Nanosecond {
t.Fatalf("avg = %v, want 10ns (truncating)", got)
}
}