Streamd v0.2.0: rename, modules panel, stable/beta channels
All checks were successful
release / build-and-upload (push) Successful in 7m5s
All checks were successful
release / build-and-upload (push) Successful in 7m5s
- Rename product/host binary to streamd (drm compat copy still shipped) - Go module path streamd; STREAMD_* env aliases; agent UA streamd-agent - Panel Modules store + agent pull sync (modstore / modsync) - Rolling stable + beta download tags; README/docs channel curl blocks - Release notes in docs/releases/v0.2.0.md attached by Forgejo Actions
This commit is contained in:
parent
066e018749
commit
da8e1123ec
140 changed files with 2949 additions and 851 deletions
|
|
@ -10,10 +10,11 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/deps"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/deps"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
)
|
||||
|
||||
type Supervisor interface {
|
||||
|
|
@ -56,7 +57,11 @@ type Handler struct {
|
|||
Deps deps.Status
|
||||
WWWRoot string // data/www — used to report variant playlist health
|
||||
LogRoot string // data/logs — source for the log tail endpoints
|
||||
Log *slog.Logger
|
||||
DataDir string // streamd --data root
|
||||
Modules *modstore.Store
|
||||
// ModulesNotify is set when the hub supports module change pushes.
|
||||
ModulesNotify ModulesNotifier
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
func (h *Handler) Mount(mux *http.ServeMux) {
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@ package api
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/repo"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/modhost"
|
||||
"streamd/mpd"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
// appInfo describes one modules/<name>/ provider to the dashboard, so the UI
|
||||
|
|
@ -16,6 +16,7 @@ type appInfo struct {
|
|||
Channels []channelInfo `json:"channels"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
HasConfig bool `json:"has_config"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type channelInfo struct {
|
||||
|
|
@ -23,7 +24,9 @@ type channelInfo struct {
|
|||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// apps answers GET /api/apps: which providers exist under modules/.
|
||||
// apps answers GET /api/apps: which providers exist under the panel modules store.
|
||||
// A single module that fails to describe is skipped with an error field rather
|
||||
// than failing the whole list (bad uploads must not blank the stream pickers).
|
||||
func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
|
|
@ -33,13 +36,27 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
out := []appInfo{}
|
||||
listed, err := modhost.ListAll(repo.Root())
|
||||
mods, err := modhost.Discover(repo.Root())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
for _, L := range listed {
|
||||
d := L.Desc
|
||||
for _, m := range mods {
|
||||
bin, err := modhost.EnsureBuilt(m)
|
||||
if err != nil {
|
||||
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
d, err := modhost.RunDescribe(bin)
|
||||
if err != nil {
|
||||
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
if d.Name == "" {
|
||||
d.Name = m.Name
|
||||
}
|
||||
info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
|
||||
for _, ch := range d.Channels {
|
||||
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/mpd"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/mpd"
|
||||
)
|
||||
|
||||
// MountControl adds the bulk, duplicate, probe, settings and schedule routes.
|
||||
|
|
|
|||
|
|
@ -10,9 +10,9 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/logfile"
|
||||
)
|
||||
|
||||
// logSources maps a caller-supplied source name to the log file suffix the
|
||||
|
|
|
|||
|
|
@ -1,93 +1,160 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
)
|
||||
|
||||
// moduleInfo is one modules/<name>/ entry for agent sync.
|
||||
type moduleInfo struct {
|
||||
Name string `json:"name"`
|
||||
HasYAML bool `json:"has_yaml"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
// ModulesNotifier pushes module change events to agents and the dashboard.
|
||||
type ModulesNotifier interface {
|
||||
NotifyModulesChanged(name, reason string)
|
||||
}
|
||||
|
||||
var moduleNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
|
||||
func (h *Handler) modStore() *modstore.Store {
|
||||
if h.Modules != nil {
|
||||
return h.Modules
|
||||
}
|
||||
root := filepath.Join(h.DataDir, "modules")
|
||||
return modstore.New(root)
|
||||
}
|
||||
|
||||
func (h *Handler) notifyModules(name, reason string) {
|
||||
if h.ModulesNotify != nil {
|
||||
h.ModulesNotify.NotifyModulesChanged(name, reason)
|
||||
return
|
||||
}
|
||||
// Hub also implements Notifier; prefer the dedicated method when available.
|
||||
if n, ok := h.Notifier.(ModulesNotifier); ok {
|
||||
n.NotifyModulesChanged(name, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/modules")
|
||||
path = strings.Trim(path, "/")
|
||||
|
||||
// Module metadata describes the provider plugins installed on this host,
|
||||
// so even reading it needs a principal.
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case path == "" && r.Method == http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
h.listModules(w, r)
|
||||
case path == "upload" && r.Method == http.MethodPost:
|
||||
h.uploadModule(w, r)
|
||||
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
h.getModule(w, r, path)
|
||||
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
|
||||
h.putModule(w, r, path)
|
||||
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodDelete:
|
||||
h.deleteModule(w, r, path)
|
||||
case strings.HasSuffix(path, "/yaml") && r.Method == http.MethodGet:
|
||||
name := strings.TrimSuffix(path, "/yaml")
|
||||
name = strings.Trim(name, "/")
|
||||
h.getModuleYAML(w, r, name)
|
||||
case strings.HasSuffix(path, "/package") && r.Method == http.MethodGet:
|
||||
name := strings.TrimSuffix(path, "/package")
|
||||
name = strings.Trim(name, "/")
|
||||
h.getModulePackage(w, r, name)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
|
||||
root := repo.Root()
|
||||
dir := modhost.ModulesDir(root)
|
||||
ents, err := os.ReadDir(dir)
|
||||
list, err := h.modStore().List()
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}})
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
out := []moduleInfo{}
|
||||
for _, e := range ents {
|
||||
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
info := moduleYAMLInfo(filepath.Join(dir, e.Name()), e.Name())
|
||||
out = append(out, info)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"modules": out})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"modules": list})
|
||||
}
|
||||
|
||||
func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
|
||||
if !moduleNameRe.MatchString(name) {
|
||||
if !modstore.NameRe.MatchString(name) {
|
||||
writeErr(w, http.StatusBadRequest, "invalid module name")
|
||||
return
|
||||
}
|
||||
info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name)
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
info := h.modStore().Info(name)
|
||||
if !info.HasYAML && !info.HasPackage {
|
||||
writeErr(w, http.StatusNotFound, "module not found")
|
||||
return
|
||||
}
|
||||
out := map[string]any{"module": info}
|
||||
if r.URL.Query().Get("include") == "yaml" {
|
||||
// YAML may hold secrets — operator+.
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
raw, err := h.modStore().ReadYAML(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
out["yaml"] = string(raw)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (h *Handler) getModuleYAML(w http.ResponseWriter, r *http.Request, name string) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
if !modstore.NameRe.MatchString(name) {
|
||||
writeErr(w, http.StatusBadRequest, "invalid module name")
|
||||
return
|
||||
}
|
||||
raw, err := h.modStore().ReadYAML(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(raw)
|
||||
}
|
||||
|
||||
func (h *Handler) getModulePackage(w http.ResponseWriter, r *http.Request, name string) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
if !modstore.NameRe.MatchString(name) {
|
||||
writeErr(w, http.StatusBadRequest, "invalid module name")
|
||||
return
|
||||
}
|
||||
f, _, err := h.modStore().OpenPackage(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
modTime := time.Time{}
|
||||
if st, err := f.Stat(); err == nil {
|
||||
modTime = st.ModTime()
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`.zip"`)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
http.ServeContent(w, r, name+".zip", modTime, f)
|
||||
}
|
||||
|
||||
func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
|
||||
// Writing a module.yaml changes how streams are captured on this host:
|
||||
// operator, and recorded.
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !moduleNameRe.MatchString(name) {
|
||||
if !modstore.NameRe.MatchString(name) {
|
||||
writeErr(w, http.StatusBadRequest, "invalid module name")
|
||||
return
|
||||
}
|
||||
|
|
@ -104,47 +171,84 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string)
|
|||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if len(strings.TrimSpace(string(yamlBytes))) == 0 {
|
||||
writeErr(w, http.StatusBadRequest, "empty module.yaml")
|
||||
|
||||
info, err := h.modStore().WriteYAML(name, yamlBytes)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name)
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
dest := filepath.Join(modDir, "module.yaml")
|
||||
tmp := dest + ".tmp"
|
||||
if err := os.WriteFile(tmp, yamlBytes, 0o644); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, dest); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
info := moduleYAMLInfo(modDir, name)
|
||||
h.audit(r, p, http.StatusOK, "uploaded module.yaml for "+name)
|
||||
h.audit(r, p, http.StatusOK, "updated module.yaml for "+name)
|
||||
h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256)
|
||||
h.notifyModules(name, "yaml_updated")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"module": info,
|
||||
})
|
||||
}
|
||||
|
||||
func moduleYAMLInfo(modDir, name string) moduleInfo {
|
||||
info := moduleInfo{Name: name}
|
||||
b, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
|
||||
if err != nil {
|
||||
return info
|
||||
func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
info.HasYAML = true
|
||||
info.YAMLSHA256 = hex.EncodeToString(sum[:])
|
||||
return info
|
||||
if !modstore.NameRe.MatchString(name) {
|
||||
writeErr(w, http.StatusBadRequest, "invalid module name")
|
||||
return
|
||||
}
|
||||
if err := h.modStore().Delete(name); err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "deleted module "+name)
|
||||
h.logger().Info("module deleted", "module", name, "by", p.Actor())
|
||||
h.notifyModules(name, "deleted")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(modstore.MaxPackageBytes + (1 << 20)); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "multipart: "+err.Error())
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(r.FormValue("name"))
|
||||
file, hdr, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "missing file field")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if hdr.Size > modstore.MaxPackageBytes {
|
||||
writeErr(w, http.StatusBadRequest, "zip too large")
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(file, modstore.MaxPackageBytes+1))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if int64(len(raw)) > modstore.MaxPackageBytes {
|
||||
writeErr(w, http.StatusBadRequest, "zip too large")
|
||||
return
|
||||
}
|
||||
info, err := h.modStore().InstallZip(raw, name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "uploaded module package "+info.Name)
|
||||
h.logger().Info("module package uploaded",
|
||||
"module", info.Name, "by", p.Actor(),
|
||||
"package_sha256", info.PackageSHA256, "arches", info.Arches)
|
||||
h.notifyModules(info.Name, "uploaded")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"module": info,
|
||||
})
|
||||
}
|
||||
|
||||
// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
|
||||
|
|
@ -163,7 +267,6 @@ func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
|
|||
}
|
||||
return []byte(wrap.YAML), nil
|
||||
default:
|
||||
// text/yaml, application/x-yaml, or bare body
|
||||
return body, nil
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// stalePlaylistS is how old a playlist may get before the output counts as
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
// Handler serves the auth routes: login/logout/me, user administration, API
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/repo"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
// Status is the resolved path for each tool after Ensure.
|
||||
|
|
@ -202,7 +202,7 @@ func httpGet(url string) (*http.Response, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "null-drm-streamd/1.0")
|
||||
req.Header.Set("User-Agent", "streamd/1.0")
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,10 +17,10 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/tsfanout"
|
||||
)
|
||||
|
||||
// Supervisor is the subset of the media supervisor the gate needs.
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/tsfanout"
|
||||
)
|
||||
|
||||
// fakeSup records what the gate asked for, and can pretend a stream comes up.
|
||||
|
|
|
|||
622
apps/streamd/internal/modstore/modstore.go
Normal file
622
apps/streamd/internal/modstore/modstore.go
Normal file
|
|
@ -0,0 +1,622 @@
|
|||
// Package modstore keeps provider modules under the streamd data directory.
|
||||
// Operators upload release-style zips; agents pull package.zip + module.yaml.
|
||||
package modstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxPackageBytes = 100 << 20 // 100 MiB
|
||||
manifestName = "manifest.json"
|
||||
packageName = "package.zip"
|
||||
yamlName = "module.yaml"
|
||||
)
|
||||
|
||||
var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
|
||||
|
||||
// Info is one module's metadata for the API and agent sync.
|
||||
type Info struct {
|
||||
Name string `json:"name"`
|
||||
HasYAML bool `json:"has_yaml"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
HasPackage bool `json:"has_package"`
|
||||
PackageSHA256 string `json:"package_sha256,omitempty"`
|
||||
Arches []string `json:"arches,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
UploadedAt string `json:"uploaded_at,omitempty"`
|
||||
YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
|
||||
}
|
||||
|
||||
type Manifest struct {
|
||||
Name string `json:"name"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
PackageSHA256 string `json:"package_sha256,omitempty"`
|
||||
Arches []string `json:"arches,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
UploadedAt string `json:"uploaded_at,omitempty"`
|
||||
YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// Store is the on-disk module library under <data>/modules.
|
||||
type Store struct {
|
||||
Root string
|
||||
}
|
||||
|
||||
func New(root string) *Store {
|
||||
return &Store{Root: root}
|
||||
}
|
||||
|
||||
func (s *Store) modulesDir() string {
|
||||
return s.Root
|
||||
}
|
||||
|
||||
func (s *Store) modDir(name string) string {
|
||||
return filepath.Join(s.Root, name)
|
||||
}
|
||||
|
||||
func (s *Store) Ensure() error {
|
||||
return os.MkdirAll(s.Root, 0o755)
|
||||
}
|
||||
|
||||
// List returns every module directory under the store.
|
||||
func (s *Store) List() ([]Info, error) {
|
||||
ents, err := os.ReadDir(s.Root)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return []Info{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Info, 0, len(ents))
|
||||
for _, e := range ents {
|
||||
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
if !NameRe.MatchString(e.Name()) {
|
||||
continue
|
||||
}
|
||||
out = append(out, s.Info(e.Name()))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Info loads manifest + checks for yaml/package files.
|
||||
func (s *Store) Info(name string) Info {
|
||||
info := Info{Name: name}
|
||||
if !NameRe.MatchString(name) {
|
||||
return info
|
||||
}
|
||||
dir := s.modDir(name)
|
||||
m, err := s.readManifest(dir)
|
||||
if err == nil {
|
||||
info.YAMLSHA256 = m.YAMLSHA256
|
||||
info.PackageSHA256 = m.PackageSHA256
|
||||
info.Arches = append([]string(nil), m.Arches...)
|
||||
info.SizeBytes = m.SizeBytes
|
||||
info.UploadedAt = m.UploadedAt
|
||||
info.YAMLUpdatedAt = m.YAMLUpdatedAt
|
||||
info.HasYAML = m.YAMLSHA256 != ""
|
||||
info.HasPackage = m.PackageSHA256 != ""
|
||||
}
|
||||
// Prefer live file hashes when present so a hand-edited yaml still shows.
|
||||
if b, err := os.ReadFile(filepath.Join(dir, yamlName)); err == nil {
|
||||
info.HasYAML = true
|
||||
sum := sha256.Sum256(b)
|
||||
info.YAMLSHA256 = hex.EncodeToString(sum[:])
|
||||
}
|
||||
if st, err := os.Stat(filepath.Join(dir, packageName)); err == nil && !st.IsDir() {
|
||||
info.HasPackage = true
|
||||
if info.PackageSHA256 == "" {
|
||||
if sum, err := fileSHA256(filepath.Join(dir, packageName)); err == nil {
|
||||
info.PackageSHA256 = sum
|
||||
}
|
||||
}
|
||||
if info.SizeBytes == 0 {
|
||||
info.SizeBytes = st.Size()
|
||||
}
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// ReadYAML returns module.yaml bytes.
|
||||
func (s *Store) ReadYAML(name string) ([]byte, error) {
|
||||
if !NameRe.MatchString(name) {
|
||||
return nil, fmt.Errorf("invalid module name")
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(s.modDir(name), yamlName))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("module %s: no module.yaml", name)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// WriteYAML atomically replaces module.yaml and updates the manifest.
|
||||
func (s *Store) WriteYAML(name string, yamlBytes []byte) (Info, error) {
|
||||
if !NameRe.MatchString(name) {
|
||||
return Info{}, fmt.Errorf("invalid module name")
|
||||
}
|
||||
if len(strings.TrimSpace(string(yamlBytes))) == 0 {
|
||||
return Info{}, fmt.Errorf("empty module.yaml")
|
||||
}
|
||||
dir := s.modDir(name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
dest := filepath.Join(dir, yamlName)
|
||||
if err := atomicWrite(dest, yamlBytes, 0o644); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
sum := sha256.Sum256(yamlBytes)
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
m, _ := s.readManifest(dir)
|
||||
m.Name = name
|
||||
m.YAMLSHA256 = hex.EncodeToString(sum[:])
|
||||
m.YAMLUpdatedAt = now
|
||||
if m.UploadedAt == "" {
|
||||
m.UploadedAt = now
|
||||
}
|
||||
if err := s.writeManifest(dir, m); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
return s.Info(name), nil
|
||||
}
|
||||
|
||||
// OpenPackage returns a ReadCloser for package.zip plus size.
|
||||
func (s *Store) OpenPackage(name string) (*os.File, int64, error) {
|
||||
if !NameRe.MatchString(name) {
|
||||
return nil, 0, fmt.Errorf("invalid module name")
|
||||
}
|
||||
path := filepath.Join(s.modDir(name), packageName)
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, 0, fmt.Errorf("module %s: no package.zip", name)
|
||||
}
|
||||
return nil, 0, err
|
||||
}
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return f, st.Size(), nil
|
||||
}
|
||||
|
||||
// Delete removes the module directory.
|
||||
func (s *Store) Delete(name string) error {
|
||||
if !NameRe.MatchString(name) {
|
||||
return fmt.Errorf("invalid module name")
|
||||
}
|
||||
dir := s.modDir(name)
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return fmt.Errorf("module %s not found", name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(dir)
|
||||
}
|
||||
|
||||
// InstallZip stores zipBytes as package.zip, extracts into the module dir,
|
||||
// promotes the host-arch binary, and writes the manifest.
|
||||
// nameHint may be empty; the zip layout is used to infer the name.
|
||||
func (s *Store) InstallZip(zipBytes []byte, nameHint string) (Info, error) {
|
||||
if len(zipBytes) == 0 {
|
||||
return Info{}, fmt.Errorf("empty zip")
|
||||
}
|
||||
if int64(len(zipBytes)) > MaxPackageBytes {
|
||||
return Info{}, fmt.Errorf("zip exceeds %d byte limit", MaxPackageBytes)
|
||||
}
|
||||
|
||||
name, entries, err := inspectZip(zipBytes, nameHint)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
if !NameRe.MatchString(name) {
|
||||
return Info{}, fmt.Errorf("invalid module name %q", name)
|
||||
}
|
||||
|
||||
if err := s.Ensure(); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
dir := s.modDir(name)
|
||||
tmpDir, err := os.MkdirTemp(s.Root, "."+name+".tmp-*")
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
if err := extractZipEntries(zipBytes, entries, tmpDir); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
if err := promoteHostBinary(tmpDir, name); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
yamlPath := filepath.Join(tmpDir, yamlName)
|
||||
if _, err := os.Stat(yamlPath); err != nil {
|
||||
return Info{}, fmt.Errorf("zip missing module.yaml")
|
||||
}
|
||||
arches := detectArches(tmpDir, name)
|
||||
pkgSum := sha256.Sum256(zipBytes)
|
||||
yamlRaw, err := os.ReadFile(yamlPath)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
yamlSum := sha256.Sum256(yamlRaw)
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
m := Manifest{
|
||||
Name: name,
|
||||
YAMLSHA256: hex.EncodeToString(yamlSum[:]),
|
||||
PackageSHA256: hex.EncodeToString(pkgSum[:]),
|
||||
Arches: arches,
|
||||
SizeBytes: int64(len(zipBytes)),
|
||||
UploadedAt: now,
|
||||
YAMLUpdatedAt: now,
|
||||
}
|
||||
if err := s.writeManifest(tmpDir, m); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(tmpDir, packageName), zipBytes, 0o644); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
// Replace the live module dir.
|
||||
backup := dir + ".bak"
|
||||
_ = os.RemoveAll(backup)
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
if err := os.Rename(dir, backup); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmpDir, dir); err != nil {
|
||||
_ = os.Rename(backup, dir)
|
||||
return Info{}, err
|
||||
}
|
||||
_ = os.RemoveAll(backup)
|
||||
return s.Info(name), nil
|
||||
}
|
||||
|
||||
type zipEntry struct {
|
||||
// Rel is the path relative to the module root inside the zip (forward slashes).
|
||||
Rel string
|
||||
File *zip.File
|
||||
}
|
||||
|
||||
func inspectZip(zipBytes []byte, nameHint string) (name string, entries []zipEntry, err error) {
|
||||
zr, err := zip.NewReader(newBytesReaderAt(zipBytes), int64(len(zipBytes)))
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("open zip: %w", err)
|
||||
}
|
||||
return inspectZipReader(zr, nameHint)
|
||||
}
|
||||
|
||||
type bytesReaderAt struct{ b []byte }
|
||||
|
||||
func newBytesReaderAt(b []byte) *bytesReaderAt { return &bytesReaderAt{b: b} }
|
||||
|
||||
func (r *bytesReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if off < 0 {
|
||||
return 0, errors.New("negative offset")
|
||||
}
|
||||
if off >= int64(len(r.b)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.b[off:])
|
||||
if n < len(p) {
|
||||
return n, io.EOF
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, error) {
|
||||
hint := strings.TrimSpace(nameHint)
|
||||
if hint != "" && !NameRe.MatchString(hint) {
|
||||
return "", nil, fmt.Errorf("invalid module name %q", hint)
|
||||
}
|
||||
|
||||
prefix := ""
|
||||
topDirs := map[string]struct{}{}
|
||||
hasRootFile := false
|
||||
|
||||
for _, f := range zr.File {
|
||||
name := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
name = strings.TrimPrefix(name, "./")
|
||||
if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
|
||||
continue
|
||||
}
|
||||
parts := strings.Split(name, "/")
|
||||
if len(parts) > 0 && parts[0] != "" {
|
||||
if f.FileInfo().IsDir() || len(parts) > 1 {
|
||||
topDirs[parts[0]] = struct{}{}
|
||||
}
|
||||
if len(parts) == 1 && !f.FileInfo().IsDir() {
|
||||
hasRootFile = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case hint != "":
|
||||
prefix = ""
|
||||
// If every entry is under hint/, strip it.
|
||||
allUnder := true
|
||||
for _, f := range zr.File {
|
||||
n := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
n = strings.TrimPrefix(n, "./")
|
||||
if n == "" || strings.HasPrefix(n, "__MACOSX/") {
|
||||
continue
|
||||
}
|
||||
if n != hint && !strings.HasPrefix(n, hint+"/") {
|
||||
allUnder = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allUnder {
|
||||
prefix = hint + "/"
|
||||
}
|
||||
case hasRootFile:
|
||||
// Flat zip: module.yaml at root. Name must be provided or inferred from binary.
|
||||
prefix = ""
|
||||
case len(topDirs) == 1:
|
||||
for d := range topDirs {
|
||||
prefix = d + "/"
|
||||
if hint == "" {
|
||||
hint = d
|
||||
}
|
||||
}
|
||||
default:
|
||||
return "", nil, fmt.Errorf("cannot infer module name from zip; pass name= or use a single top-level folder")
|
||||
}
|
||||
|
||||
if hint == "" {
|
||||
// Try to infer from .bin/<arch>/<name> or .bin/<name>.
|
||||
for _, f := range zr.File {
|
||||
n := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
n = strings.TrimPrefix(n, "./")
|
||||
if prefix != "" {
|
||||
if !strings.HasPrefix(n, prefix) {
|
||||
continue
|
||||
}
|
||||
n = strings.TrimPrefix(n, prefix)
|
||||
}
|
||||
base := filepath.Base(n)
|
||||
base = strings.TrimSuffix(base, ".exe")
|
||||
if strings.HasPrefix(n, ".bin/") && NameRe.MatchString(base) && base != ".bin" {
|
||||
hint = base
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if hint == "" {
|
||||
return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
|
||||
}
|
||||
if !NameRe.MatchString(hint) {
|
||||
return "", nil, fmt.Errorf("invalid module name %q", hint)
|
||||
}
|
||||
|
||||
var entries []zipEntry
|
||||
for _, f := range zr.File {
|
||||
n := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
n = strings.TrimPrefix(n, "./")
|
||||
if n == "" || strings.HasPrefix(n, "__MACOSX/") || strings.HasSuffix(n, ".DS_Store") {
|
||||
continue
|
||||
}
|
||||
rel := n
|
||||
if prefix != "" {
|
||||
if !strings.HasPrefix(n, prefix) {
|
||||
continue
|
||||
}
|
||||
rel = strings.TrimPrefix(n, prefix)
|
||||
}
|
||||
if rel == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(rel, "..") {
|
||||
return "", nil, fmt.Errorf("zip slip: %s", f.Name)
|
||||
}
|
||||
entries = append(entries, zipEntry{Rel: rel, File: f})
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
return "", nil, fmt.Errorf("zip has no files for module %s", hint)
|
||||
}
|
||||
return hint, entries, nil
|
||||
}
|
||||
|
||||
func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) error {
|
||||
_ = zipBytes // entries already hold openable *zip.File from the same buffer
|
||||
for _, e := range entries {
|
||||
target := filepath.Join(destDir, filepath.FromSlash(e.Rel))
|
||||
// Zip-slip: ensure target stays under destDir.
|
||||
if !isUnder(destDir, target) {
|
||||
return fmt.Errorf("zip slip: %s", e.Rel)
|
||||
}
|
||||
if e.File.FileInfo().IsDir() || strings.HasSuffix(e.Rel, "/") {
|
||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
rc, err := e.File.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := e.File.Mode()
|
||||
if mode&0o111 != 0 {
|
||||
mode = 0o755
|
||||
} else {
|
||||
mode = 0o644
|
||||
}
|
||||
err = copyToFile(target, rc, mode)
|
||||
_ = rc.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isUnder(root, path string) bool {
|
||||
absRoot, err1 := filepath.Abs(root)
|
||||
absPath, err2 := filepath.Abs(path)
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
rel, err := filepath.Rel(absRoot, absPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return rel == "." || (!strings.HasPrefix(rel, "..") && !filepath.IsAbs(rel))
|
||||
}
|
||||
|
||||
func copyToFile(dest string, r io.Reader, mode os.FileMode) error {
|
||||
tmp := dest + ".partial"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(f, r)
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return closeErr
|
||||
}
|
||||
_ = os.Remove(dest)
|
||||
return os.Rename(tmp, dest)
|
||||
}
|
||||
|
||||
func promoteHostBinary(modDir, name string) error {
|
||||
want := name
|
||||
if runtime.GOOS == "windows" {
|
||||
want += ".exe"
|
||||
}
|
||||
dest := filepath.Join(modDir, ".bin", want)
|
||||
if fileExists(dest) {
|
||||
return nil
|
||||
}
|
||||
archDir := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH)
|
||||
src := filepath.Join(archDir, want)
|
||||
if !fileExists(src) {
|
||||
// Soft: describe may fail later; zip install still succeeds.
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
return copyToFile(dest, in, 0o755)
|
||||
}
|
||||
|
||||
func detectArches(modDir, name string) []string {
|
||||
binRoot := filepath.Join(modDir, ".bin")
|
||||
ents, err := os.ReadDir(binRoot)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
var arches []string
|
||||
add := func(a string) {
|
||||
if _, ok := seen[a]; ok {
|
||||
return
|
||||
}
|
||||
seen[a] = struct{}{}
|
||||
arches = append(arches, a)
|
||||
}
|
||||
for _, e := range ents {
|
||||
if e.IsDir() {
|
||||
sub := e.Name() // e.g. windows-amd64
|
||||
if strings.Contains(sub, "-") {
|
||||
add(sub)
|
||||
}
|
||||
continue
|
||||
}
|
||||
base := strings.TrimSuffix(e.Name(), ".exe")
|
||||
if base == name {
|
||||
add(runtime.GOOS + "-" + runtime.GOARCH)
|
||||
}
|
||||
}
|
||||
sort.Strings(arches)
|
||||
return arches
|
||||
}
|
||||
|
||||
func (s *Store) readManifest(dir string) (Manifest, error) {
|
||||
var m Manifest
|
||||
b, err := os.ReadFile(filepath.Join(dir, manifestName))
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return m, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Store) writeManifest(dir string, m Manifest) error {
|
||||
b, err := json.MarshalIndent(m, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b = append(b, '\n')
|
||||
return atomicWrite(filepath.Join(dir, manifestName), b, 0o644)
|
||||
}
|
||||
|
||||
func atomicWrite(path string, data []byte, mode os.FileMode) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileSHA256(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func fileExists(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
149
apps/streamd/internal/modstore/modstore_test.go
Normal file
149
apps/streamd/internal/modstore/modstore_test.go
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
package modstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func makeZip(t *testing.T, files map[string][]byte) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
for name, body := range files {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestInstallZipFlatAndYAMLOnly(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
|
||||
arch := runtime.GOOS + "-" + runtime.GOARCH
|
||||
binName := "demo"
|
||||
if runtime.GOOS == "windows" {
|
||||
binName += ".exe"
|
||||
}
|
||||
zipBytes := makeZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: com.example\nchannels: {}\n"),
|
||||
".bin/" + arch + "/" + binName: []byte("fake-binary"),
|
||||
".bin/linux-amd64/demo": []byte("linux-bin"),
|
||||
})
|
||||
|
||||
info, err := s.InstallZip(zipBytes, "demo")
|
||||
if err != nil {
|
||||
t.Fatalf("InstallZip: %v", err)
|
||||
}
|
||||
if info.Name != "demo" || !info.HasYAML || !info.HasPackage {
|
||||
t.Fatalf("info = %+v", info)
|
||||
}
|
||||
if info.PackageSHA256 == "" || info.YAMLSHA256 == "" {
|
||||
t.Fatalf("missing hashes: %+v", info)
|
||||
}
|
||||
pkgHash := info.PackageSHA256
|
||||
yamlHash := info.YAMLSHA256
|
||||
|
||||
// Host binary should be promoted.
|
||||
promoted := filepath.Join(root, "demo", ".bin", binName)
|
||||
if !fileExists(promoted) {
|
||||
t.Fatalf("expected promoted binary at %s", promoted)
|
||||
}
|
||||
|
||||
// YAML-only update must not change package hash.
|
||||
info2, err := s.WriteYAML("demo", []byte("package: com.example\nchannels:\n one: {label: One}\n"))
|
||||
if err != nil {
|
||||
t.Fatalf("WriteYAML: %v", err)
|
||||
}
|
||||
if info2.PackageSHA256 != pkgHash {
|
||||
t.Fatalf("package hash changed on yaml edit: %s -> %s", pkgHash, info2.PackageSHA256)
|
||||
}
|
||||
if info2.YAMLSHA256 == yamlHash {
|
||||
t.Fatal("yaml hash should change after edit")
|
||||
}
|
||||
|
||||
raw, err := s.ReadYAML("demo")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(raw), "one:") {
|
||||
t.Fatalf("yaml not updated: %s", raw)
|
||||
}
|
||||
|
||||
f, size, err := s.OpenPackage("demo")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if size != int64(len(zipBytes)) {
|
||||
t.Fatalf("package size %d want %d", size, len(zipBytes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallZipTopLevelFolder(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
zipBytes := makeZip(t, map[string][]byte{
|
||||
"bbc/module.yaml": []byte("package: bbc.iplayer.android\n"),
|
||||
"bbc/.bin/linux-amd64/bbc": []byte("bin"),
|
||||
"bbc/.bin/windows-amd64/bbc.exe": []byte("winbin"),
|
||||
})
|
||||
info, err := s.InstallZip(zipBytes, "")
|
||||
if err != nil {
|
||||
t.Fatalf("InstallZip: %v", err)
|
||||
}
|
||||
if info.Name != "bbc" {
|
||||
t.Fatalf("name=%q", info.Name)
|
||||
}
|
||||
list, err := s.List()
|
||||
if err != nil || len(list) != 1 || list[0].Name != "bbc" {
|
||||
t.Fatalf("list=%v err=%v", list, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZipSlipRejected(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
w, err := zw.Create("../evil.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = w.Write([]byte("x"))
|
||||
_ = zw.Close()
|
||||
_, err = s.InstallZip(buf.Bytes(), "demo")
|
||||
if err == nil {
|
||||
t.Fatal("expected zip-slip error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
zipBytes := makeZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: x\n"),
|
||||
})
|
||||
if _, err := s.InstallZip(zipBytes, "xmod"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Delete("xmod"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "xmod")); !os.IsNotExist(err) {
|
||||
t.Fatalf("dir still present: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import (
|
|||
"log/slog"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// Supervisor is the subset of the media supervisor the scheduler needs.
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@ package supervisor
|
|||
import (
|
||||
"strings"
|
||||
|
||||
"drmdecryption/app"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
"streamd/app"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
// streamSettings are the downloader and packager knobs for one stream. They
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ package supervisor
|
|||
import (
|
||||
"testing"
|
||||
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/app"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/mpd"
|
||||
"streamd/adb"
|
||||
"streamd/app"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/capture"
|
||||
"streamd/mpd"
|
||||
)
|
||||
|
||||
// fakeApp stands in for a compiled-in app module: the supervisor must take its
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// These tests run the real ffmpeg against the real generated command line.
|
||||
|
|
|
|||
|
|
@ -14,10 +14,10 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
"drmdecryption/mpd"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/logfile"
|
||||
"streamd/apps/streamd/internal/tsfanout"
|
||||
"streamd/mpd"
|
||||
)
|
||||
|
||||
// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// Packager defaults. These were literals in the ffmpeg command line before
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// quote and backslash as values, so the test source stays readable where it
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// Stub marks streams as starting/stopped without spawning media workers.
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/logfile"
|
||||
)
|
||||
|
||||
type variantProc struct {
|
||||
|
|
|
|||
|
|
@ -26,6 +26,10 @@
|
|||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 4h12M2 8h12M2 12h8"/></svg></span>
|
||||
Streams
|
||||
</a>
|
||||
<a href="#/modules" data-nav="/modules">
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M3 3.5h4.5v4.5H3zM8.5 3.5H13v4.5H8.5zM3 8.5h4.5V13H3zM8.5 8.5H13V13H8.5z"/></svg></span>
|
||||
Modules
|
||||
</a>
|
||||
<a href="#/schedule" data-nav="/schedule">
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="8" cy="8" r="5.5"/><path d="M8 5v3.5l2.5 1.5"/></svg></span>
|
||||
Schedule
|
||||
|
|
@ -81,7 +85,7 @@
|
|||
<form id="login-form" class="auth-card">
|
||||
<span class="logo big" aria-hidden="true"></span>
|
||||
<h2 id="gate-title">Sign in to streamd</h2>
|
||||
<p class="auth-sub">Null DRM restream control</p>
|
||||
<p class="auth-sub">Streamd control plane</p>
|
||||
<p id="gate-note" class="hint"></p>
|
||||
<label id="setup-row" hidden>Setup token
|
||||
<input name="setup_token" autocomplete="off" spellcheck="false" />
|
||||
|
|
|
|||
|
|
@ -640,6 +640,48 @@ dialog::backdrop { background: rgba(0, 0, 0, .6); backdrop-filter: blur(2px); }
|
|||
.table-wrap { margin: 0 -16px -16px; padding: 0 16px 4px; }
|
||||
}
|
||||
|
||||
/* ---------- modules dropzone / yaml editor ---------- */
|
||||
|
||||
.dropzone {
|
||||
border: 1.5px dashed var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-sunken);
|
||||
padding: 28px 20px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: border-color var(--ease), background var(--ease);
|
||||
}
|
||||
.dropzone:hover, .dropzone:focus-visible {
|
||||
border-color: var(--accent);
|
||||
outline: none;
|
||||
}
|
||||
.dropzone.active {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.dropzone-title {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
color: var(--text);
|
||||
}
|
||||
.dropzone-sub {
|
||||
margin-top: 6px;
|
||||
font-size: 12.5px;
|
||||
color: var(--text-dim);
|
||||
max-width: 36rem;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
textarea.module-yaml {
|
||||
width: 100%;
|
||||
min-height: 28rem;
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
white-space: pre;
|
||||
tab-size: 2;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -131,4 +131,43 @@ export const api = {
|
|||
audit: (limit = 200) => api.get(`/api/audit?limit=${limit}`),
|
||||
agents: () => api.get("/api/agents"),
|
||||
apps: () => api.get("/api/apps"),
|
||||
|
||||
// --- modules ---
|
||||
modules: () => api.get("/api/modules"),
|
||||
module: (name, includeYaml) =>
|
||||
api.get(`/api/modules/${encodeURIComponent(name)}${includeYaml ? "?include=yaml" : ""}`),
|
||||
saveModuleYAML: (name, yaml) =>
|
||||
api.put(`/api/modules/${encodeURIComponent(name)}`, { yaml }),
|
||||
deleteModule: (name) => api.del(`/api/modules/${encodeURIComponent(name)}`),
|
||||
uploadModuleZip: async (file, name) => {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file, file.name || "module.zip");
|
||||
if (name) fd.append("name", name);
|
||||
const headers = {};
|
||||
if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
|
||||
const res = await fetch("/api/modules/upload", {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: fd,
|
||||
credentials: "same-origin",
|
||||
});
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
if (text) {
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch {
|
||||
data = { raw: text };
|
||||
}
|
||||
}
|
||||
if (res.status === 401) {
|
||||
for (const fn of onUnauthorized) fn(data);
|
||||
throw new ApiError((data && data.error) || "not signed in", 401, data);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const msg = (data && data.error) || res.statusText || `upload failed (${res.status})`;
|
||||
throw new ApiError(msg, res.status, data);
|
||||
}
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { dashboard } from "./views/dashboard.js";
|
|||
import { streams } from "./views/streams.js";
|
||||
import { streamView } from "./views/stream.js";
|
||||
import { scheduleView, settingsView, peopleView, auditView } from "./views/admin.js";
|
||||
import { modulesView } from "./views/modules.js";
|
||||
|
||||
const app = $("#app");
|
||||
const gate = $("#gate");
|
||||
|
|
@ -60,6 +61,11 @@ const ROUTES = [
|
|||
path: /^\/stream\/(\d+)(?:\/(live|config|debug))?$/, title: "Stream", nav: "/streams",
|
||||
mount: (root, m) => streamView(root, Number(m[1]), m[2] || "live"),
|
||||
},
|
||||
{ path: /^\/modules$/, title: "Modules", nav: "/modules", mount: (root) => modulesView(root) },
|
||||
{
|
||||
path: /^\/modules\/([^/]+)$/, title: "Edit module", nav: "/modules",
|
||||
mount: (root, m) => modulesView(root, decodeURIComponent(m[1])),
|
||||
},
|
||||
{ path: /^\/schedule$/, title: "Schedule", nav: "/schedule", mount: (root) => scheduleView(root) },
|
||||
{ path: /^\/settings$/, title: "Settings", nav: "/settings", admin: true, mount: (root) => settingsView(root) },
|
||||
{ path: /^\/people$/, title: "People & keys", nav: "/people", admin: true, mount: (root) => peopleView(root) },
|
||||
|
|
|
|||
|
|
@ -175,6 +175,9 @@ function openSocket() {
|
|||
case "claims_changed":
|
||||
scheduleRefresh(msg.type);
|
||||
break;
|
||||
case "modules_changed":
|
||||
emit("modules_changed");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
310
apps/streamd/internal/ui/static/js/views/modules.js
Normal file
310
apps/streamd/internal/ui/static/js/views/modules.js
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
// Provider modules: drag-drop zip upload, list, YAML editor.
|
||||
|
||||
import {
|
||||
el, pill, toast, confirmDialog, fmtDateTime, clear, copyText,
|
||||
} from "../util.js";
|
||||
import { canEdit, subscribe } from "../store.js";
|
||||
import { api } from "../api.js";
|
||||
|
||||
function shortHash(h) {
|
||||
if (!h) return "—";
|
||||
return h.slice(0, 10);
|
||||
}
|
||||
|
||||
function fmtBytes(n) {
|
||||
if (!n) return "—";
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function modulesView(root, editName) {
|
||||
const stack = el("div.stack");
|
||||
root.append(stack);
|
||||
|
||||
let unsub = () => {};
|
||||
let disposed = false;
|
||||
|
||||
async function load() {
|
||||
if (disposed) return;
|
||||
clear(stack);
|
||||
if (editName) {
|
||||
await mountEditor(stack, editName, () => {
|
||||
location.hash = "#/modules";
|
||||
});
|
||||
return;
|
||||
}
|
||||
mountList(stack, load);
|
||||
}
|
||||
|
||||
load();
|
||||
unsub = subscribe((_s, reason) => {
|
||||
if (reason === "modules_changed" && !editName) load();
|
||||
});
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
unsub();
|
||||
if (stack._modulesUnload) stack._modulesUnload();
|
||||
};
|
||||
}
|
||||
|
||||
function mountList(stack, reload) {
|
||||
const body = el("tbody");
|
||||
const drop = el("div.dropzone", {
|
||||
tabindex: "0",
|
||||
role: "button",
|
||||
"aria-label": "Upload module zip",
|
||||
},
|
||||
el("div.dropzone-title", { text: "Drop a module .zip here" }),
|
||||
el("div.dropzone-sub", {
|
||||
text: "Release assets such as bbc.zip from modules-v* tags. Fill secrets in the YAML editor after upload.",
|
||||
}),
|
||||
el("div.row", { style: { marginTop: "10px", justifyContent: "center" } },
|
||||
el("button.sm", {
|
||||
type: "button",
|
||||
text: "Choose file…",
|
||||
onclick: (ev) => {
|
||||
ev.stopPropagation();
|
||||
fileInput.click();
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
const fileInput = el("input", {
|
||||
type: "file",
|
||||
accept: ".zip,application/zip",
|
||||
hidden: true,
|
||||
onchange: async () => {
|
||||
const f = fileInput.files && fileInput.files[0];
|
||||
fileInput.value = "";
|
||||
if (f) await uploadFile(f, reload);
|
||||
},
|
||||
});
|
||||
|
||||
if (canEdit()) {
|
||||
wireDropzone(drop, fileInput, reload);
|
||||
stack.append(el("div.card", drop, fileInput));
|
||||
}
|
||||
|
||||
stack.append(
|
||||
el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Installed modules" }),
|
||||
el("span.spacer"),
|
||||
el("button.ghost.sm", { text: "Reload", onclick: () => reload() }),
|
||||
),
|
||||
el("p.hint", {
|
||||
text: "Agents pull package.zip and module.yaml from this panel. " +
|
||||
"Edit YAML here so every agent gets the same config.",
|
||||
}),
|
||||
el("div.table-wrap", el("table",
|
||||
el("thead", el("tr",
|
||||
el("th", { text: "Name" }),
|
||||
el("th", { text: "YAML" }),
|
||||
el("th", { text: "Package" }),
|
||||
el("th", { text: "Arches" }),
|
||||
el("th", { text: "Size" }),
|
||||
el("th", { text: "Updated" }),
|
||||
el("th", { text: "" }),
|
||||
)),
|
||||
body,
|
||||
)),
|
||||
),
|
||||
);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const d = await api.modules();
|
||||
const list = d.modules || [];
|
||||
clear(body);
|
||||
if (!list.length) {
|
||||
body.append(el("tr", el("td.empty", {
|
||||
colspan: "7",
|
||||
text: canEdit()
|
||||
? "No modules yet — drop a release zip above."
|
||||
: "No modules uploaded yet.",
|
||||
})));
|
||||
return;
|
||||
}
|
||||
for (const m of list) {
|
||||
body.append(moduleRow(m, reload));
|
||||
}
|
||||
} catch (err) {
|
||||
clear(body);
|
||||
body.append(el("tr", el("td.empty", { colspan: "7", text: err.message })));
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function moduleRow(m, reload) {
|
||||
const arches = (m.arches || []).join(", ") || "—";
|
||||
const updated = m.yaml_updated_at || m.uploaded_at || "";
|
||||
return el("tr",
|
||||
el("td",
|
||||
el("div", { text: m.name }),
|
||||
el("div.sub.mono", { text: shortHash(m.package_sha256 || m.yaml_sha256) }),
|
||||
),
|
||||
el("td", m.has_yaml
|
||||
? el("span", { title: m.yaml_sha256 },
|
||||
pill("ok", "ok"),
|
||||
el("span.sub.mono", { text: " " + shortHash(m.yaml_sha256) }),
|
||||
)
|
||||
: pill("missing", "down")),
|
||||
el("td", m.has_package
|
||||
? el("span", { title: m.package_sha256 },
|
||||
pill("ok", "ok"),
|
||||
el("span.sub.mono", { text: " " + shortHash(m.package_sha256) }),
|
||||
)
|
||||
: pill("missing", "warn")),
|
||||
el("td.mono", { text: arches }),
|
||||
el("td", { text: fmtBytes(m.size_bytes) }),
|
||||
el("td", { text: updated ? fmtDateTime(updated) : "—" }),
|
||||
el("td.actions", el("div.row",
|
||||
canEdit() ? el("button.tiny.ghost", {
|
||||
text: "Edit YAML",
|
||||
onclick: () => { location.hash = `#/modules/${encodeURIComponent(m.name)}`; },
|
||||
}) : null,
|
||||
canEdit() ? el("button.tiny.danger", {
|
||||
text: "Delete",
|
||||
onclick: async () => {
|
||||
if (!(await confirmDialog(`Delete module ${m.name}?`,
|
||||
"Agents will stop receiving this module on the next sync.", "Delete"))) return;
|
||||
try {
|
||||
await api.deleteModule(m.name);
|
||||
toast(`Deleted ${m.name}`);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast(err.message, true);
|
||||
}
|
||||
},
|
||||
}) : null,
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
function wireDropzone(drop, fileInput, reload) {
|
||||
const setActive = (on) => drop.classList.toggle("active", on);
|
||||
drop.addEventListener("click", () => fileInput.click());
|
||||
drop.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter" || ev.key === " ") {
|
||||
ev.preventDefault();
|
||||
fileInput.click();
|
||||
}
|
||||
});
|
||||
drop.addEventListener("dragenter", (ev) => { ev.preventDefault(); setActive(true); });
|
||||
drop.addEventListener("dragover", (ev) => { ev.preventDefault(); setActive(true); });
|
||||
drop.addEventListener("dragleave", () => setActive(false));
|
||||
drop.addEventListener("drop", async (ev) => {
|
||||
ev.preventDefault();
|
||||
setActive(false);
|
||||
const f = ev.dataTransfer && ev.dataTransfer.files && ev.dataTransfer.files[0];
|
||||
if (f) await uploadFile(f, reload);
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadFile(file, reload) {
|
||||
if (!canEdit()) {
|
||||
toast("Operator role required to upload", true);
|
||||
return;
|
||||
}
|
||||
const lower = (file.name || "").toLowerCase();
|
||||
if (!lower.endsWith(".zip")) {
|
||||
toast("Upload a .zip module package", true);
|
||||
return;
|
||||
}
|
||||
toast(`Uploading ${file.name}…`);
|
||||
try {
|
||||
const res = await api.uploadModuleZip(file);
|
||||
const name = (res.module && res.module.name) || file.name;
|
||||
toast(`Uploaded ${name}`);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast(err.message || "Upload failed", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function mountEditor(stack, name, onDone) {
|
||||
let data;
|
||||
try {
|
||||
data = await api.module(name, true);
|
||||
} catch (err) {
|
||||
stack.append(el("div.card",
|
||||
el("h2", { text: name }),
|
||||
el("p.msg.err", { text: err.message }),
|
||||
el("button.ghost", { text: "Back", onclick: onDone }),
|
||||
));
|
||||
return;
|
||||
}
|
||||
const m = data.module || { name };
|
||||
const ta = el("textarea.module-yaml", {
|
||||
value: data.yaml || "",
|
||||
spellcheck: "false",
|
||||
rows: "28",
|
||||
});
|
||||
let saved = data.yaml || "";
|
||||
const dirty = () => ta.value !== saved;
|
||||
|
||||
const form = el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: `module.yaml — ${m.name}` }),
|
||||
el("span.spacer"),
|
||||
el("button.ghost.sm", { text: "Back", onclick: onDone }),
|
||||
),
|
||||
el("p.hint", {
|
||||
text: "Secrets and channel config live here. Saving updates every agent on the next sync (or immediately over websocket).",
|
||||
}),
|
||||
el("div.row", { style: { marginBottom: "8px", gap: "8px", flexWrap: "wrap" } },
|
||||
m.yaml_sha256 ? el("span.sub.mono", { text: `yaml ${shortHash(m.yaml_sha256)}` }) : null,
|
||||
m.package_sha256 ? el("span.sub.mono", { text: `pkg ${shortHash(m.package_sha256)}` }) : null,
|
||||
(m.arches || []).length ? el("span.sub", { text: (m.arches || []).join(", ") }) : null,
|
||||
),
|
||||
ta,
|
||||
el("div.row.end", { style: { marginTop: "14px" } },
|
||||
el("button.ghost", {
|
||||
text: "Copy",
|
||||
onclick: () => copyText(ta.value, "YAML"),
|
||||
}),
|
||||
el("button.ghost", {
|
||||
text: "Revert",
|
||||
onclick: () => {
|
||||
ta.value = saved;
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
text: "Save YAML",
|
||||
onclick: async () => {
|
||||
if (!canEdit()) {
|
||||
toast("Operator role required", true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await api.saveModuleYAML(m.name, ta.value);
|
||||
saved = ta.value;
|
||||
toast("YAML saved");
|
||||
if (res.module) {
|
||||
m.yaml_sha256 = res.module.yaml_sha256;
|
||||
}
|
||||
} catch (err) {
|
||||
toast(err.message, true);
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
stack.append(form);
|
||||
|
||||
const onBeforeUnload = (ev) => {
|
||||
if (dirty()) {
|
||||
ev.preventDefault();
|
||||
ev.returnValue = "";
|
||||
}
|
||||
};
|
||||
window.addEventListener("beforeunload", onBeforeUnload);
|
||||
// Caller teardown should remove this; modulesView dispose covers navigation away.
|
||||
const prev = stack._modulesUnload;
|
||||
stack._modulesUnload = () => {
|
||||
window.removeEventListener("beforeunload", onBeforeUnload);
|
||||
if (prev) prev();
|
||||
};
|
||||
}
|
||||
|
|
@ -10,8 +10,8 @@ import (
|
|||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -444,6 +444,22 @@ func (h *Hub) NotifyStreamChanged(name, reason string) {
|
|||
}
|
||||
}
|
||||
|
||||
// NotifyModulesChanged tells agents to pull module updates and the dashboard
|
||||
// to refresh the Modules view.
|
||||
func (h *Hub) NotifyModulesChanged(name, reason string) {
|
||||
h.broadcastUI(outbound{Type: "modules_changed", StreamName: name, Reason: reason})
|
||||
h.mu.Lock()
|
||||
conns := make([]*agentConn, 0, len(h.agents))
|
||||
for _, a := range h.agents {
|
||||
conns = append(conns, a)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, ac := range conns {
|
||||
h.queue(ac, outbound{Type: "modules_changed", StreamName: name, Reason: reason})
|
||||
}
|
||||
h.Log.Info("ws: modules changed", "module", name, "reason", reason, "agents", len(conns))
|
||||
}
|
||||
|
||||
// NotifyRuntime pushes a live health delta to the dashboard, so it does not
|
||||
// have to poll the whole stream list on a timer.
|
||||
func (h *Hub) NotifyRuntime(name, health string) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue