Initial commit

This commit is contained in:
2026-08-08 11:04:45 +02:00
commit 4137962252
10 changed files with 1322 additions and 0 deletions
+365
View File
@@ -0,0 +1,365 @@
package server
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"billboard/internal/state"
)
type Config struct {
Addr string
Token string
SnapshotPath string
}
type Server struct {
st *state.State
cfg Config
hub *hub
limit *rateLimiter
}
func New(st *state.State, cfg Config) *Server {
return &Server{
st: st,
cfg: cfg,
hub: newHub(),
limit: newRateLimiter(),
}
}
//go:embed static/index.html
var indexHTML []byte
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(indexHTML)
})
mux.HandleFunc("GET /api/state", s.handleState)
mux.HandleFunc("GET /api/events", s.handleEvents)
mux.HandleFunc("POST /api/pixel", s.handlePixel)
mux.HandleFunc("POST /api/pixels", s.handlePixels)
mux.HandleFunc("POST /api/image", s.handleImage)
mux.HandleFunc("POST /api/message", s.handleMessage)
return mux
}
func (s *Server) Run() error {
if s.cfg.SnapshotPath != "" {
go s.snapshotLoop()
}
httpSrv := &http.Server{Addr: s.cfg.Addr, Handler: s.Handler()}
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
<-sig
if s.cfg.SnapshotPath != "" {
if err := s.st.Save(s.cfg.SnapshotPath); err != nil {
log.Printf("shutdown snapshot save: %v", err)
} else {
log.Printf("saved snapshot to %s", s.cfg.SnapshotPath)
}
}
httpSrv.Shutdown(context.Background())
}()
log.Printf("billboard server listening on %s (canvas %dx%d)", s.cfg.Addr, s.st.Width, s.st.Height)
if err := httpSrv.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return nil
}
func (s *Server) snapshotLoop() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
if err := s.st.Save(s.cfg.SnapshotPath); err != nil {
log.Printf("snapshot save: %v", err)
}
}
}
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
func (s *Server) authorized(r *http.Request) bool {
if s.cfg.Token == "" {
return true
}
return r.Header.Get("Authorization") == "Bearer "+s.cfg.Token
}
func writeErr(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
func decode(w http.ResponseWriter, r *http.Request, v any) bool {
return decodeLimit(w, r, v, 64<<10)
}
func decodeLimit(w http.ResponseWriter, r *http.Request, v any, maxBytes int64) bool {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
writeErr(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return false
}
return true
}
func stateErr(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, state.ErrOutOfBounds),
errors.Is(err, state.ErrInvalidColor),
errors.Is(err, state.ErrImageTooBig),
errors.Is(err, state.ErrEmptyMessage),
errors.Is(err, state.ErrMessageLong):
writeErr(w, http.StatusBadRequest, err.Error())
default:
writeErr(w, http.StatusInternalServerError, "internal error")
}
}
func (s *Server) guard(w http.ResponseWriter, r *http.Request, cost float64) bool {
if !s.authorized(r) {
writeErr(w, http.StatusUnauthorized, "missing or invalid token")
return false
}
if !s.limit.allow(clientIP(r), cost) {
writeErr(w, http.StatusTooManyRequests, "rate limit exceeded")
return false
}
return true
}
func (s *Server) handleState(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(s.st.Snapshot())
}
type pixelReq struct {
X int `json:"x"`
Y int `json:"y"`
Color uint8 `json:"color"`
}
func (s *Server) handlePixel(w http.ResponseWriter, r *http.Request) {
if !s.guard(w, r, 1) {
return
}
var req pixelReq
if !decode(w, r, &req) {
return
}
if err := s.st.SetPixel(req.X, req.Y, req.Color); err != nil {
stateErr(w, err)
return
}
s.hub.broadcast("pixel")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handlePixels(w http.ResponseWriter, r *http.Request) {
var req struct {
Pixels []pixelReq `json:"pixels"`
}
if !decodeLimit(w, r, &req, 256<<10) {
return
}
if len(req.Pixels) == 0 || len(req.Pixels) > 2048 {
writeErr(w, http.StatusBadRequest, "batch must contain 1-2048 pixels")
return
}
cost := float64(len(req.Pixels)) / 8
if cost < 1 {
cost = 1
}
if !s.guard(w, r, cost) {
return
}
for _, p := range req.Pixels {
if err := s.st.CheckPixel(p.X, p.Y, p.Color); err != nil {
stateErr(w, err)
return
}
}
for _, p := range req.Pixels {
s.st.SetPixel(p.X, p.Y, p.Color)
}
s.hub.broadcast("pixel")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleImage(w http.ResponseWriter, r *http.Request) {
if !s.guard(w, r, 10) {
return
}
var req struct {
X int `json:"x"`
Y int `json:"y"`
Pixels []state.Row `json:"pixels"`
}
if !decode(w, r, &req) {
return
}
if err := s.st.StampImage(req.X, req.Y, req.Pixels); err != nil {
stateErr(w, err)
return
}
s.hub.broadcast("image")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleMessage(w http.ResponseWriter, r *http.Request) {
if !s.guard(w, r, 5) {
return
}
var req struct {
Text string `json:"text"`
}
if !decode(w, r, &req) {
return
}
req.Text = strings.TrimSpace(req.Text)
if err := s.st.AddMessage(req.Text); err != nil {
stateErr(w, err)
return
}
s.hub.broadcast("message")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
writeErr(w, http.StatusInternalServerError, "streaming unsupported")
return
}
ch := s.hub.subscribe()
defer s.hub.unsubscribe(ch)
fmt.Fprint(w, "event: hello\ndata: {}\n\n")
flusher.Flush()
for {
select {
case <-r.Context().Done():
return
case ev := <-ch:
fmt.Fprintf(w, "event: %s\ndata: {}\n\n", ev)
flusher.Flush()
}
}
}
type hub struct {
mu sync.Mutex
subs map[chan string]struct{}
}
func newHub() *hub {
return &hub{subs: make(map[chan string]struct{})}
}
func (h *hub) subscribe() chan string {
ch := make(chan string, 16)
h.mu.Lock()
h.subs[ch] = struct{}{}
h.mu.Unlock()
return ch
}
func (h *hub) unsubscribe(ch chan string) {
h.mu.Lock()
delete(h.subs, ch)
h.mu.Unlock()
}
func (h *hub) broadcast(ev string) {
h.mu.Lock()
defer h.mu.Unlock()
for ch := range h.subs {
select {
case ch <- ev:
default:
}
}
}
type bucket struct {
tokens float64
last time.Time
}
type rateLimiter struct {
mu sync.Mutex
buckets map[string]*bucket
}
func newRateLimiter() *rateLimiter {
rl := &rateLimiter{buckets: make(map[string]*bucket)}
go rl.gc()
return rl
}
const (
ratePerSec = 4.0
burst = 40.0
)
func (rl *rateLimiter) allow(key string, cost float64) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
b, ok := rl.buckets[key]
if !ok {
b = &bucket{tokens: burst, last: time.Now()}
rl.buckets[key] = b
}
now := time.Now()
b.tokens += now.Sub(b.last).Seconds() * ratePerSec
if b.tokens > burst {
b.tokens = burst
}
b.last = now
if b.tokens < cost {
return false
}
b.tokens -= cost
return true
}
func (rl *rateLimiter) gc() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for range ticker.C {
rl.mu.Lock()
for k, b := range rl.buckets {
if time.Since(b.last) > 10*time.Minute {
delete(rl.buckets, k)
}
}
rl.mu.Unlock()
}
}
+122
View File
@@ -0,0 +1,122 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>billboard</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body { background:#111; color:#eee; font:14px monospace; display:flex; flex-direction:column; align-items:center; gap:10px; padding:12px; margin:0 }
canvas { image-rendering:pixelated; cursor:crosshair; border:1px solid #444; max-width:96vw }
#pal { display:flex; gap:4px }
#pal div { width:24px; height:24px; cursor:pointer; border:2px solid transparent }
#pal div.sel { border-color:#fff }
#msgs { width:min(96vw,640px); height:120px; overflow-y:auto; background:#000; padding:6px; border:1px solid #333 }
#msgs div { white-space:pre-wrap; word-break:break-word }
#msgs .t { color:#666 }
input { background:#000; color:#eee; border:1px solid #333; font:inherit; padding:6px; width:min(96vw,560px) }
</style>
</head>
<body>
<canvas id="cv"></canvas>
<div id="pal"></div>
<div id="msgs"></div>
<input id="msg" maxlength="140" placeholder="say something + enter">
<script>
const COLORS = ["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0",
"#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff"];
const CELL = 12;
let W, H, px = [], sel = 9, drawing = false;
const cv = document.getElementById("cv"), ctx = cv.getContext("2d");
const pal = document.getElementById("pal"), msgs = document.getElementById("msgs");
COLORS.forEach((c, i) => {
const d = document.createElement("div");
d.style.background = c;
if (i === sel) d.className = "sel";
d.onclick = () => { sel = i; [...pal.children].forEach((e, j) => e.className = j === i ? "sel" : ""); };
pal.appendChild(d);
});
function draw() {
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
ctx.fillStyle = COLORS[px[y][x]];
ctx.fillRect(x * CELL, y * CELL, CELL, CELL);
}
}
async function load() {
const s = await (await fetch("/api/state")).json();
W = s.width; H = s.height; px = s.pixels;
cv.width = W * CELL; cv.height = H * CELL;
draw();
pending.forEach(p => {
px[p.y][p.x] = p.color;
ctx.fillStyle = COLORS[p.color];
ctx.fillRect(p.x * CELL, p.y * CELL, CELL, CELL);
});
msgs.innerHTML = "";
s.messages.forEach(addMsg);
msgs.scrollTop = msgs.scrollHeight;
}
function addMsg(m) {
const d = document.createElement("div");
const t = document.createElement("span");
t.className = "t";
t.textContent = new Date(m.at).toLocaleTimeString() + " ";
d.append(t, m.text);
msgs.appendChild(d);
msgs.scrollTop = msgs.scrollHeight;
}
const pending = new Map();
async function flush() {
if (!pending.size) return;
const batch = [...pending.values()];
pending.clear();
try {
const r = await fetch("/api/pixels", { method:"POST", headers:{"Content-Type":"application/json"},
body: JSON.stringify({pixels: batch}) });
if (!r.ok) throw new Error(r.status);
} catch (e) {
batch.forEach(p => { if (!pending.has(p.x+","+p.y)) pending.set(p.x+","+p.y, p); });
}
}
setInterval(flush, 200);
function place(e) {
const r = cv.getBoundingClientRect();
const x = Math.floor((e.clientX - r.left) * W / r.width);
const y = Math.floor((e.clientY - r.top) * H / r.height);
if (x < 0 || x >= W || y < 0 || y >= H) return;
px[y][x] = sel;
ctx.fillStyle = COLORS[sel];
ctx.fillRect(x * CELL, y * CELL, CELL, CELL);
pending.set(x+","+y, {x, y, color: sel});
}
cv.addEventListener("mousedown", e => { drawing = true; place(e); });
cv.addEventListener("mousemove", e => drawing && place(e));
addEventListener("mouseup", () => { drawing = false; flush(); });
const msgInput = document.getElementById("msg");
msgInput.addEventListener("keydown", async e => {
if (e.key !== "Enter" || !e.target.value.trim()) return;
const text = e.target.value.trim();
try {
const r = await fetch("/api/message", { method:"POST", headers:{"Content-Type":"application/json"},
body: JSON.stringify({text}) });
if (!r.ok) throw new Error(r.status);
e.target.value = "";
e.target.placeholder = "say something + enter";
} catch (err) {
e.target.placeholder = "not sent (rate limited?) — try again";
}
});
load().then(() => {
const es = new EventSource("/api/events");
["pixel", "image", "message"].forEach(ev => es.addEventListener(ev, load));
});
</script>
</body>
</html>