feat: add notification delivery foundation
This commit was merged in pull request #9.
This commit is contained in:
@@ -17,6 +17,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -183,6 +184,43 @@ func main() {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(status)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/capability-bindings/{id}/revisions/{revision}", func(w http.ResponseWriter, r *http.Request) {
|
||||
revision, err := strconv.ParseInt(r.PathValue("revision"), 10, 64)
|
||||
if err != nil || revision < 1 {
|
||||
http.Error(w, "invalid binding revision", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
binding, err := capabilityRepository.LoadBinding(r.Context(), capability.CapabilityBindingID(r.PathValue("id")), revision)
|
||||
if err != nil {
|
||||
http.Error(w, "capability binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err = capabilitydomain.ValidateBinding(binding); err != nil {
|
||||
http.Error(w, "capability binding invalid", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(binding)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/capability-bindings/active", func(w http.ResponseWriter, r *http.Request) {
|
||||
capabilityID := capability.CapabilityID(r.URL.Query().Get("capability_id"))
|
||||
ownerID := identity.PrincipalID(r.URL.Query().Get("owner_principal_id"))
|
||||
if capabilityID == "" || ownerID == "" {
|
||||
http.Error(w, "invalid binding query", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
binding, err := capabilityRepository.LoadActiveBinding(r.Context(), capabilityID, ownerID)
|
||||
if err != nil {
|
||||
http.Error(w, "active capability binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err = capabilitydomain.UsableBinding(binding); err != nil {
|
||||
http.Error(w, "active capability binding unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(binding)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/capabilities/health-projection/rebuild", func(w http.ResponseWriter, r *http.Request) {
|
||||
rebuilt, err := capabilityRepository.RebuildHealthProjection(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := envOr("LISTEN_ADDR", ":8085")
|
||||
writeToken, err := readSecretFile("RECEIVER_WRITE_TOKEN_FILE")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
readToken, err := readSecretFile("RECEIVER_READ_TOKEN_FILE")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
server, err := newReceiverServer(envOr("RECEIPT_DIRECTORY", "/var/lib/notification-receiver"), writeToken, readToken, time.Now)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("notification-receiver listening on %s", addr)
|
||||
if err = http.ListenAndServe(addr, server.routes()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func readSecretFile(name string) (string, error) {
|
||||
path := os.Getenv(name)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
value, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", name, err)
|
||||
}
|
||||
secret := strings.TrimSpace(string(value))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", name)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
func envOr(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
)
|
||||
|
||||
const maxDeliveryBytes = 8 << 10
|
||||
|
||||
var safeIntent = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
|
||||
|
||||
type storedReceipt struct {
|
||||
notificationexecutor.Receipt
|
||||
Payload notificationexecutor.Payload `json:"payload"`
|
||||
}
|
||||
|
||||
type receiverServer struct {
|
||||
directory string
|
||||
writeToken string
|
||||
readToken string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newReceiverServer(directory, writeToken, readToken string, now func() time.Time) (*receiverServer, error) {
|
||||
if directory == "" || strings.TrimSpace(writeToken) == "" || strings.TrimSpace(readToken) == "" ||
|
||||
writeToken == readToken || now == nil {
|
||||
return nil, errors.New("invalid receiver configuration")
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
return nil, fmt.Errorf("create receipt directory: %w", err)
|
||||
}
|
||||
return &receiverServer{directory: directory, writeToken: writeToken, readToken: readToken, now: now}, nil
|
||||
}
|
||||
|
||||
func (s *receiverServer) routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"status":"ok"}`)
|
||||
})
|
||||
mux.HandleFunc("PUT /delivery/v1/deliveries/{intent}", s.put)
|
||||
mux.HandleFunc("GET /delivery/v1/receipts/{intent}", s.get)
|
||||
mux.HandleFunc("GET /delivery/v1/receipts", s.list)
|
||||
return mux
|
||||
}
|
||||
|
||||
func (s *receiverServer) put(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.writeToken, r) {
|
||||
http.Error(w, "receiver writer denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
intent := r.PathValue("intent")
|
||||
if !safeIntent.MatchString(intent) {
|
||||
http.Error(w, "invalid action intent", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request notificationexecutor.DeliveryRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDeliveryBytes))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil || string(request.ActionIntentID) != intent {
|
||||
http.Error(w, "invalid delivery", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := ensureEOF(decoder); err != nil {
|
||||
http.Error(w, "invalid delivery", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
digest, err := notificationexecutor.Digest(request.Payload)
|
||||
if err != nil || digest != request.RequestDigest {
|
||||
http.Error(w, "delivery digest mismatch", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
receipt := storedReceipt{Receipt: notificationexecutor.Receipt{ReceiptID: "receipt-" + intent, ActionIntentID: request.ActionIntentID, RequestDigest: digest, AcceptedAt: s.now().UnixMilli()}, Payload: request.Payload}
|
||||
created, existing, err := s.create(receipt)
|
||||
if err != nil {
|
||||
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !created {
|
||||
if existing.RequestDigest != digest {
|
||||
http.Error(w, "action intent digest conflict", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
receipt = existing
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if created {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(receipt)
|
||||
}
|
||||
|
||||
func (s *receiverServer) get(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.writeToken, r) && !tokenMatches(s.readToken, r) {
|
||||
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
intent := r.PathValue("intent")
|
||||
if !safeIntent.MatchString(intent) {
|
||||
http.Error(w, "invalid action intent", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
receipt, err := s.load(intent)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
http.Error(w, "receipt not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeStoredReceipt(w, receipt)
|
||||
}
|
||||
|
||||
func (s *receiverServer) list(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.readToken, r) {
|
||||
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
http.Error(w, "invalid limit", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
entries, err := os.ReadDir(s.directory)
|
||||
if err != nil {
|
||||
http.Error(w, "receipts unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
receipts := make([]storedReceipt, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
|
||||
continue
|
||||
}
|
||||
receipt, loadErr := s.load(strings.TrimSuffix(entry.Name(), ".json"))
|
||||
if loadErr != nil {
|
||||
continue
|
||||
}
|
||||
receipts = append(receipts, receipt)
|
||||
}
|
||||
sort.Slice(receipts, func(i, j int) bool {
|
||||
if receipts[i].AcceptedAt == receipts[j].AcceptedAt {
|
||||
return receipts[i].ReceiptID > receipts[j].ReceiptID
|
||||
}
|
||||
return receipts[i].AcceptedAt > receipts[j].AcceptedAt
|
||||
})
|
||||
if len(receipts) > limit {
|
||||
receipts = receipts[:limit]
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Items []storedReceipt `json:"items"`
|
||||
}{Items: receipts})
|
||||
}
|
||||
|
||||
func (s *receiverServer) create(receipt storedReceipt) (bool, storedReceipt, error) {
|
||||
encoded, err := json.Marshal(receipt)
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
temporary, err := os.CreateTemp(s.directory, ".receipt-*.tmp")
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
temporaryName := temporary.Name()
|
||||
defer os.Remove(temporaryName)
|
||||
if err = temporary.Chmod(0600); err == nil {
|
||||
_, err = temporary.Write(encoded)
|
||||
}
|
||||
if err == nil {
|
||||
err = temporary.Sync()
|
||||
}
|
||||
closeErr := temporary.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
target := s.path(string(receipt.ActionIntentID))
|
||||
if err = os.Link(temporaryName, target); err == nil {
|
||||
return true, storedReceipt{}, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrExist) {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
existing, err := s.load(string(receipt.ActionIntentID))
|
||||
return false, existing, err
|
||||
}
|
||||
|
||||
func (s *receiverServer) load(intent string) (storedReceipt, error) {
|
||||
var receipt storedReceipt
|
||||
file, err := os.Open(s.path(intent))
|
||||
if err != nil {
|
||||
return receipt, err
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, maxDeliveryBytes+1))
|
||||
if err = decoder.Decode(&receipt); err != nil {
|
||||
return storedReceipt{}, err
|
||||
}
|
||||
if string(receipt.ActionIntentID) != intent {
|
||||
return storedReceipt{}, errors.New("receipt identity mismatch")
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func (s *receiverServer) path(intent string) string {
|
||||
return filepath.Join(s.directory, intent+".json")
|
||||
}
|
||||
func tokenMatches(expected string, r *http.Request) bool {
|
||||
provided := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
return len(provided) == len(expected) && subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
|
||||
}
|
||||
func ensureEOF(decoder *json.Decoder) error {
|
||||
var extra any
|
||||
err := decoder.Decode(&extra)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("trailing JSON")
|
||||
}
|
||||
func writeStoredReceipt(w http.ResponseWriter, receipt storedReceipt) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(receipt)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
)
|
||||
|
||||
func delivery(t *testing.T, intent, message string) notificationexecutor.DeliveryRequest {
|
||||
t.Helper()
|
||||
payload := notificationexecutor.Payload{ActionIntentID: commitcontract.ActionIntentID(intent), TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 1, Title: "Домовой", Message: message}
|
||||
digest, err := notificationexecutor.Digest(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return notificationexecutor.DeliveryRequest{Payload: payload, RequestDigest: digest}
|
||||
}
|
||||
|
||||
func request(t *testing.T, handler http.Handler, method, path, token string, value any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var body bytes.Buffer
|
||||
if value != nil {
|
||||
if err := json.NewEncoder(&body).Encode(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest(method, path, &body)
|
||||
if token != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestReceiverIdempotencyConflictAndRestart(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
clock := func() time.Time { return time.UnixMilli(100) }
|
||||
server, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := delivery(t, "intent-1", "message one")
|
||||
w := request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("repeat status %d", w.Code)
|
||||
}
|
||||
conflict := delivery(t, "intent-1", "different")
|
||||
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", conflict)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("conflict status %d", w.Code)
|
||||
}
|
||||
restarted, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts/intent-1", "write-secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("restart get status %d", w.Code)
|
||||
}
|
||||
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts?limit=10", "read-secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("list status %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverSeparatesReadAndWriteAuthority(t *testing.T) {
|
||||
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := server.routes()
|
||||
value := delivery(t, "intent-1", "message")
|
||||
if w := request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-1", "read-secret", value); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("reader wrote: %d", w.Code)
|
||||
}
|
||||
if w := request(t, handler, http.MethodGet, "/delivery/v1/receipts", "write-secret", nil); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("writer listed: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentDuplicateCreatesOneReceipt(t *testing.T) {
|
||||
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value := delivery(t, "intent-concurrent", "message")
|
||||
handler := server.routes()
|
||||
codes := make(chan int, 8)
|
||||
var group sync.WaitGroup
|
||||
for range 8 {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
codes <- request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-concurrent", "write-secret", value).Code
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(codes)
|
||||
created := 0
|
||||
for code := range codes {
|
||||
if code == http.StatusCreated {
|
||||
created++
|
||||
} else if code != http.StatusOK {
|
||||
t.Fatalf("unexpected status %d", code)
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Fatalf("created=%d", created)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user