Public source validation / validate (push) Failing after 3m8s
69 lines
2.1 KiB
Go
69 lines
2.1 KiB
Go
package applicationapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/itworx/pulse/internal/application"
|
|
"github.com/itworx/pulse/internal/auth"
|
|
"github.com/itworx/pulse/internal/problem"
|
|
)
|
|
|
|
type Handler struct {
|
|
Provider interface {
|
|
Snapshot(context.Context) (application.Snapshot, error)
|
|
}
|
|
}
|
|
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet || (r.URL.Path != "/api/v1/applications" && !strings.HasPrefix(r.URL.Path, "/api/v1/applications/")) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if _, ok := auth.PrincipalFromContext(r.Context()); !ok {
|
|
problem.Write(w, r, http.StatusUnauthorized, "UNAUTHORIZED", "Authentication required", "Authentication is required to read applications.", nil)
|
|
return
|
|
}
|
|
snapshot, err := h.snapshot(r)
|
|
if err != nil {
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
return
|
|
}
|
|
problem.Write(w, r, http.StatusServiceUnavailable, "APPLICATIONS_UNAVAILABLE", "Applications not available", "Applicatiegegevens konden niet worden gelezen.", nil)
|
|
return
|
|
}
|
|
if r.URL.Path != "/api/v1/applications" {
|
|
id := strings.TrimPrefix(r.URL.Path, "/api/v1/applications/")
|
|
for _, item := range snapshot.Applications {
|
|
if item.ID == id {
|
|
writeJSON(w, struct {
|
|
Source application.Source `json:"source"`
|
|
Application application.Application `json:"application"`
|
|
}{Source: snapshot.Source, Application: item})
|
|
return
|
|
}
|
|
}
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if len(snapshot.Applications) > 100 {
|
|
snapshot.Applications = snapshot.Applications[:100]
|
|
}
|
|
writeJSON(w, snapshot)
|
|
}
|
|
func (h Handler) snapshot(r *http.Request) (application.Snapshot, error) {
|
|
if h.Provider == nil {
|
|
return application.UnknownSnapshot(time.Now().UTC(), "applications", "agent", "source_unavailable"), nil
|
|
}
|
|
return h.Provider.Snapshot(r.Context())
|
|
}
|
|
func writeJSON(w http.ResponseWriter, value any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "private, max-age=5")
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|