Implement Knowledge City platform, organizer and DAV integration

Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
This commit is contained in:
Anya Tokugawa committed 2026-09-27 14:44:43 +09:00
1 parent 288e6e94ac
commit c1175d389f
699 files changed
+110197 -4117

No files matched your search

+296
View File
@@ -0,0 +1,296 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"pageswiki/internal/store"
)
func writeEventJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func decodeEventJSON(w http.ResponseWriter, r *http.Request, value any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
if err := json.NewDecoder(r.Body).Decode(value); err != nil {
writeEventJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return false
}
return true
}
func (s *Server) handleEventAPI(w http.ResponseWriter, r *http.Request) {
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/event"), "/")
switch action {
case "":
if r.Method == http.MethodGet {
definitions, err := s.store.ListEventDefinitions()
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"events": definitions})
return
}
if r.Method == http.MethodPost {
var definition store.EventDefinition
if !decodeEventJSON(w, r, &definition) {
return
}
if err := s.store.SaveEventDefinition(&definition); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
s.wakeEventScheduler()
writeEventJSON(w, http.StatusCreated, definition)
return
}
case "run":
if r.Method == http.MethodPost {
var input struct {
UUID string `json:"uuid"`
}
if !decodeEventJSON(w, r, &input) {
return
}
queued, err := s.store.RunEventDefinition(input.UUID)
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
s.wakeEventScheduler()
writeEventJSON(w, 202, map[string]any{"queued": queued})
return
}
case "delete":
if r.Method == http.MethodPost || r.Method == http.MethodDelete {
var input struct {
UUID string `json:"uuid"`
}
if !decodeEventJSON(w, r, &input) {
return
}
if err := s.store.DeleteEventDefinition(input.UUID); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]bool{"deleted": true})
return
}
case "logs":
if r.Method == http.MethodGet {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
before, err := strconv.ParseInt(r.URL.Query().Get("before_id"), 10, 64)
if r.URL.Query().Has("before_id") && (err != nil || before < 0) {
writeEventJSON(w, 400, map[string]string{"error": "invalid log cursor"})
return
}
logs, err := s.store.ListEventLogsBefore(r.URL.Query().Get("job_uuid"), limit, before)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"logs": logs})
return
}
case "logs/trends":
if r.Method == http.MethodGet {
hours, _ := strconv.Atoi(r.URL.Query().Get("hours"))
if hours < 1 || hours > 24*365 {
hours = 24
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
trends, err := s.store.ListEventLogTrends(r.Context(), r.URL.Query().Get("event_type"), time.Now().Add(-time.Duration(hours)*time.Hour).UnixMilli(), limit)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"trends": trends, "hours": hours})
return
}
case "policies":
if r.Method == http.MethodGet {
policies, err := s.store.ListEventLogPolicies()
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"policies": policies})
return
}
if r.Method == http.MethodPost || r.Method == http.MethodPut {
var policy store.EventLogPolicy
if !decodeEventJSON(w, r, &policy) {
return
}
if err := s.store.SetEventLogPolicy(policy); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, policy)
return
}
}
w.Header().Set("Allow", "GET, POST, DELETE")
writeEventJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "unsupported event operation"})
}
func (s *Server) handleQueueAPI(w http.ResponseWriter, r *http.Request) {
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/queue"), "/")
switch action {
case "jobs":
if r.Method == http.MethodGet {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
jobs, next, err := s.store.EventJobPage(r.Context(), r.URL.Query().Get("status"), r.URL.Query().Get("cursor"), limit)
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, store.ErrEventJobFilter) {
code = http.StatusBadRequest
}
writeEventJSON(w, code, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{"jobs": jobs, "next_cursor": next})
return
}
case "":
if r.Method == http.MethodGet {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
jobs, err := s.store.ListEventJobs(limit)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
stats, err := s.store.EventStats()
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
settings, err := s.store.GetQueueSettings()
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]any{
"stats": stats, "settings": settings, "jobs": jobs,
"active_workers": s.schedulerRunning.Load(),
})
return
}
case "settings":
if r.Method == http.MethodGet {
settings, err := s.store.GetQueueSettings()
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, settings)
return
}
if r.Method == http.MethodPost || r.Method == http.MethodPut {
var settings store.QueueSettings
if !decodeEventJSON(w, r, &settings) {
return
}
if err := s.store.SetQueueSettings(settings); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
s.wakeEventScheduler()
writeEventJSON(w, 200, settings)
return
}
case "cancel", "retry":
if r.Method == http.MethodPost {
var input struct {
UUID string `json:"uuid"`
}
if !decodeEventJSON(w, r, &input) {
return
}
var err error
if action == "cancel" {
err = s.store.CancelEventJob(input.UUID)
} else {
err = s.store.RetryEventJob(input.UUID)
}
if err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
s.wakeEventScheduler()
writeEventJSON(w, 200, map[string]bool{"ok": true})
return
}
case "resources":
if r.Method == http.MethodGet {
writeEventJSON(w, 200, s.resourceStatus())
return
}
case "resources/history":
if r.Method == http.MethodGet {
hours, _ := strconv.Atoi(r.URL.Query().Get("hours"))
if hours != 1 && hours != 24 && hours != 168 {
hours = 24
}
samples, err := s.store.ResourceHistory(r.Context(), hours, time.Now())
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": "could not load resource history"})
return
}
writeEventJSON(w, 200, map[string]any{"samples": samples, "hours": hours, "retention_days": 7})
return
}
}
w.Header().Set("Allow", "GET, POST, PUT")
writeEventJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "unsupported queue operation"})
}
func (s *Server) resourceStatus() map[string]any {
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
root := s.store.DocumentRoot
if root == "" {
root = "."
}
root, _ = filepath.Abs(root)
var fs syscall.Statfs_t
_ = syscall.Statfs(root, &fs)
total := fs.Blocks * uint64(fs.Bsize)
available := fs.Bavail * uint64(fs.Bsize)
loadAverage := ""
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
fields := strings.Fields(string(data))
if len(fields) >= 3 {
loadAverage = strings.Join(fields[:3], " ")
}
}
stats, _ := s.store.ActiveEventStats()
settings, _ := s.store.GetQueueSettings()
return map[string]any{
"timestamp_ms": time.Now().UnixMilli(),
"io": readProcessIO(),
"cpu": map[string]any{"logical_cpus": runtime.NumCPU(), "load_average": loadAverage},
"memory": map[string]any{
"heap_bytes": memory.HeapAlloc, "go_system_bytes": memory.Sys,
"gc_cycles": memory.NumGC, "goroutines": runtime.NumGoroutine(),
},
"storage": map[string]any{
"path": root, "total_bytes": total, "used_bytes": total - available,
"available_bytes": available,
},
"queue": map[string]any{"stats": map[string]int{"queued": stats.Queued, "running": stats.Running}, "active_workers": s.schedulerRunning.Load(), "paused": settings.Paused},
}
}