This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
)
|
||||
|
||||
var (
|
||||
errCreatorSessionDenied = errors.New("creator session denied")
|
||||
errCreatorOwnerDenied = errors.New("creator owner denied")
|
||||
errCreatorSubjectMissing = errors.New("creator subject not found")
|
||||
errCreatorQueryUnavailable = errors.New("creator query unavailable")
|
||||
)
|
||||
|
||||
type creatorCoreClient struct {
|
||||
baseURL *url.URL
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type creatorContinuityClient struct {
|
||||
baseURL *url.URL
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newCreatorCoreClient(rawURL string, client *http.Client) (creatorCoreClient, error) {
|
||||
baseURL, err := parseCreatorRuntimeURL(rawURL)
|
||||
return creatorCoreClient{baseURL: baseURL, client: client}, err
|
||||
}
|
||||
|
||||
func newCreatorContinuityClient(rawURL string, client *http.Client) (creatorContinuityClient, error) {
|
||||
baseURL, err := parseCreatorRuntimeURL(rawURL)
|
||||
return creatorContinuityClient{baseURL: baseURL, client: client}, err
|
||||
}
|
||||
|
||||
func parseCreatorRuntimeURL(rawURL string) (*url.URL, error) {
|
||||
baseURL, err := url.Parse(rawURL)
|
||||
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" {
|
||||
return nil, fmt.Errorf("invalid Creator runtime URL")
|
||||
}
|
||||
return baseURL, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) Session(ctx context.Context, authorization string) (identity.CreatorSession, error) {
|
||||
var session identity.CreatorSession
|
||||
status, err := c.get(ctx, "/v1/creator/sessions/current", authorization, &session)
|
||||
if err != nil {
|
||||
return identity.CreatorSession{}, err
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
return identity.CreatorSession{}, errCreatorSessionDenied
|
||||
}
|
||||
if status != http.StatusOK || session.ActorID == "" || session.PrincipalID == "" {
|
||||
return identity.CreatorSession{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) Task(ctx context.Context, id work.TaskID) (work.TaskTarget, error) {
|
||||
var target work.TaskTarget
|
||||
status, err := c.get(ctx, "/v1/tasks/"+url.PathEscape(string(id)), "", &target)
|
||||
if err != nil {
|
||||
return work.TaskTarget{}, err
|
||||
}
|
||||
if status == http.StatusNotFound {
|
||||
return work.TaskTarget{}, errCreatorSubjectMissing
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return work.TaskTarget{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) Binding(ctx context.Context, actor identity.ActorID, principal identity.PrincipalID) (identity.PrincipalBinding, error) {
|
||||
var binding identity.PrincipalBinding
|
||||
status, err := c.get(ctx, "/v1/principal-bindings/"+url.PathEscape(string(actor))+"/"+url.PathEscape(string(principal)), "", &binding)
|
||||
if err != nil {
|
||||
return identity.PrincipalBinding{}, err
|
||||
}
|
||||
if status == http.StatusNotFound {
|
||||
return identity.PrincipalBinding{}, errCreatorOwnerDenied
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return identity.PrincipalBinding{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) get(ctx context.Context, path, authorization string, destination any) (int, error) {
|
||||
target := *c.baseURL
|
||||
target.Path = path
|
||||
target.RawQuery = ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return 0, errCreatorQueryUnavailable
|
||||
}
|
||||
if authorization != "" {
|
||||
request.Header.Set("Authorization", authorization)
|
||||
}
|
||||
response, err := c.client.Do(request)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%w: %v", errCreatorQueryUnavailable, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode == http.StatusOK {
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, 32<<10)).Decode(destination); err != nil {
|
||||
return 0, errCreatorQueryUnavailable
|
||||
}
|
||||
}
|
||||
return response.StatusCode, nil
|
||||
}
|
||||
|
||||
func (c creatorContinuityClient) Item(ctx context.Context, authorization string, id continuity.ProspectiveItemID) (continuity.ProspectiveItem, error) {
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
return continuity.ProspectiveItem{}, errCreatorSessionDenied
|
||||
}
|
||||
target := *c.baseURL
|
||||
target.Path = "/v1/creator/prospective-items/" + url.PathEscape(string(id))
|
||||
target.RawQuery = ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return continuity.ProspectiveItem{}, errCreatorQueryUnavailable
|
||||
}
|
||||
request.Header.Set("Authorization", authorization)
|
||||
response, err := c.client.Do(request)
|
||||
if err != nil {
|
||||
return continuity.ProspectiveItem{}, fmt.Errorf("%w: %v", errCreatorQueryUnavailable, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
switch response.StatusCode {
|
||||
case http.StatusUnauthorized:
|
||||
return continuity.ProspectiveItem{}, errCreatorSessionDenied
|
||||
case http.StatusForbidden:
|
||||
return continuity.ProspectiveItem{}, errCreatorOwnerDenied
|
||||
case http.StatusNotFound:
|
||||
return continuity.ProspectiveItem{}, errCreatorSubjectMissing
|
||||
case http.StatusOK:
|
||||
var item continuity.ProspectiveItem
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, 32<<10)).Decode(&item); err != nil {
|
||||
return continuity.ProspectiveItem{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return item, nil
|
||||
default:
|
||||
return continuity.ProspectiveItem{}, errCreatorQueryUnavailable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
commitdomain "git.cin.su/m/Assistant/modules/commit/domain"
|
||||
"git.cin.su/m/Assistant/modules/commit/ports"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
const creatorGrantID authority.GrantID = "domovoy-creator-grant"
|
||||
|
||||
type creatorSessionSource interface {
|
||||
Session(context.Context, string) (identity.CreatorSession, error)
|
||||
Task(context.Context, work.TaskID) (work.TaskTarget, error)
|
||||
Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error)
|
||||
}
|
||||
|
||||
type creatorContinuitySource interface {
|
||||
Item(context.Context, string, continuity.ProspectiveItemID) (continuity.ProspectiveItem, error)
|
||||
}
|
||||
|
||||
type creatorAuthoritySource interface {
|
||||
LoadGrant(context.Context, authority.GrantID) (authority.AuthorityGrant, authority.Scope, error)
|
||||
}
|
||||
|
||||
type creatorCommitRepository interface {
|
||||
executionRepository
|
||||
SaveAuthorized(context.Context, commitcontract.AuthorizedAction) error
|
||||
}
|
||||
|
||||
type creatorCommandHandler struct {
|
||||
core creatorSessionSource
|
||||
continuity creatorContinuitySource
|
||||
authority creatorAuthoritySource
|
||||
repository creatorCommitRepository
|
||||
executor ports.Executor
|
||||
reconciler ports.Reconciler
|
||||
newID func() (ids.ID, error)
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type creatorSatisfyRequest struct {
|
||||
Target work.TaskTarget
|
||||
ProspectiveItemID continuity.ProspectiveItemID
|
||||
ExpectedRevision continuity.ProspectiveRevision
|
||||
EvidenceRef string
|
||||
}
|
||||
|
||||
type creatorActionResponse struct {
|
||||
AuthorizedActionID commitcontract.AuthorizedActionID
|
||||
ActionIntentID commitcontract.ActionIntentID
|
||||
ActionAttemptID commitcontract.ActionAttemptID
|
||||
State commitcontract.ActionState
|
||||
}
|
||||
|
||||
func registerCreatorCommandRoutes(mux *http.ServeMux, handler creatorCommandHandler) {
|
||||
mux.HandleFunc("POST /v1/creator/continuity/satisfy-delivered", handler.satisfyDelivered)
|
||||
mux.HandleFunc("POST /v1/creator/authorized-actions/{id}/reconcile", handler.reconcile)
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) satisfyDelivered(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
session, ok := h.creatorSession(w, r, authorization)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request creatorSatisfyRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&request); err != nil ||
|
||||
request.Target.TaskID == "" || request.Target.GoalID == "" || request.Target.ScopeID == "" || request.Target.Revision == 0 ||
|
||||
request.ProspectiveItemID == "" || request.ExpectedRevision == 0 || strings.TrimSpace(request.EvidenceRef) == "" || len(request.EvidenceRef) > 512 {
|
||||
http.Error(w, "invalid Creator satisfaction request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
item, err := h.continuity.Item(r.Context(), authorization, request.ProspectiveItemID)
|
||||
if errors.Is(err, errCreatorOwnerDenied) {
|
||||
http.Error(w, "prospective item denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errCreatorSubjectMissing) {
|
||||
http.Error(w, "prospective item not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Continuity owner validation unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if item.OwnerPrincipalID != session.PrincipalID {
|
||||
http.Error(w, "prospective item denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if item.State != continuity.ProspectiveDelivered || item.Revision != request.ExpectedRevision ||
|
||||
item.ScopeID != request.Target.ScopeID || item.GoalID != request.Target.GoalID {
|
||||
http.Error(w, "prospective item is stale or outside justification", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
target, err := h.core.Task(r.Context(), request.Target.TaskID)
|
||||
if err != nil || target != request.Target {
|
||||
http.Error(w, "work target is stale or unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
grant, scope, err := h.authority.LoadGrant(r.Context(), creatorGrantID)
|
||||
if err != nil {
|
||||
http.Error(w, "Creator authority unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
binding, err := h.core.Binding(r.Context(), session.ActorID, session.PrincipalID)
|
||||
if err != nil {
|
||||
http.Error(w, "Creator identity binding unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
intentID, authorizedID, attemptID, err := h.actionIDs()
|
||||
if err != nil {
|
||||
http.Error(w, "action identity unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
proposal := commitcontract.ActionProposal{
|
||||
IntentID: intentID, ActorID: session.ActorID, CapabilityID: commitcontract.CapabilityContinuityTransition,
|
||||
Target: request.Target, Operation: commitcontract.OperationSatisfyDelivered,
|
||||
ContinuitySubject: continuity.SatisfyDeliveredSubject{
|
||||
ProspectiveItemID: request.ProspectiveItemID, ExpectedRevision: request.ExpectedRevision,
|
||||
FromState: continuity.ProspectiveDelivered, ToState: continuity.ProspectiveSatisfied,
|
||||
EvidenceRef: strings.TrimSpace(request.EvidenceRef),
|
||||
},
|
||||
}
|
||||
action, err := commitdomain.Authorize(proposal, commitdomain.AuthorizationContext{Binding: binding, Scope: scope, Grant: grant}, authorityValidator{}, authorizedID, h.now().UnixMilli())
|
||||
if err != nil {
|
||||
http.Error(w, "Creator authorization denied", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err = h.repository.SaveAuthorized(r.Context(), action); err != nil {
|
||||
http.Error(w, "commit authorized action", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
attempt, operationErr := executeAuthorized(r.Context(), h.repository, h.executor, action, attemptID)
|
||||
if operationErr != nil && !errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
http.Error(w, "execute committed action", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
status := http.StatusCreated
|
||||
if errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeCreatorActionResponse(w, status, action, attempt)
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) reconcile(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
session, ok := h.creatorSession(w, r, authorization)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
action, err := h.repository.LoadAuthorized(r.Context(), commitcontract.AuthorizedActionID(r.PathValue("id")))
|
||||
if err != nil {
|
||||
http.Error(w, "authorized action not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if action.PrincipalID != session.PrincipalID || action.Proposal.ActorID != session.ActorID {
|
||||
http.Error(w, "authorized action denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
newID, err := h.newID()
|
||||
if err != nil {
|
||||
http.Error(w, "action identity unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
attempt, operationErr := reconcileAuthorized(r.Context(), h.repository, h.reconciler, action, commitcontract.ActionAttemptID(newID))
|
||||
if errors.Is(operationErr, errActionDoesNotNeedReconcile) {
|
||||
http.Error(w, "action does not require reconciliation", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if operationErr != nil && !errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
http.Error(w, "reconciliation unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeCreatorActionResponse(w, status, action, attempt)
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) creatorSession(w http.ResponseWriter, r *http.Request, authorization string) (identity.CreatorSession, bool) {
|
||||
session, err := h.core.Session(r.Context(), authorization)
|
||||
if errors.Is(err, errCreatorSessionDenied) {
|
||||
http.Error(w, "Creator session denied", http.StatusUnauthorized)
|
||||
return identity.CreatorSession{}, false
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Identity validation unavailable", http.StatusServiceUnavailable)
|
||||
return identity.CreatorSession{}, false
|
||||
}
|
||||
return session, true
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) actionIDs() (commitcontract.ActionIntentID, commitcontract.AuthorizedActionID, commitcontract.ActionAttemptID, error) {
|
||||
intent, err := h.newID()
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
authorized, err := h.newID()
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
attempt, err := h.newID()
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
return commitcontract.ActionIntentID(intent), commitcontract.AuthorizedActionID(authorized), commitcontract.ActionAttemptID(attempt), nil
|
||||
}
|
||||
|
||||
func writeCreatorActionResponse(w http.ResponseWriter, status int, action commitcontract.AuthorizedAction, attempt commitcontract.ActionAttempt) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(creatorActionResponse{AuthorizedActionID: action.ID, ActionIntentID: action.Proposal.IntentID, ActionAttemptID: attempt.ID, State: attempt.State})
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
type fakeCreatorCore struct {
|
||||
session identity.CreatorSession
|
||||
target work.TaskTarget
|
||||
binding identity.PrincipalBinding
|
||||
sessionErr error
|
||||
}
|
||||
|
||||
func (f fakeCreatorCore) Session(context.Context, string) (identity.CreatorSession, error) {
|
||||
return f.session, f.sessionErr
|
||||
}
|
||||
func (f fakeCreatorCore) Task(context.Context, work.TaskID) (work.TaskTarget, error) {
|
||||
return f.target, nil
|
||||
}
|
||||
func (f fakeCreatorCore) Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error) {
|
||||
return f.binding, nil
|
||||
}
|
||||
|
||||
type fakeCreatorContinuity struct {
|
||||
item continuity.ProspectiveItem
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeCreatorContinuity) Item(context.Context, string, continuity.ProspectiveItemID) (continuity.ProspectiveItem, error) {
|
||||
return f.item, f.err
|
||||
}
|
||||
|
||||
type fakeCreatorAuthority struct {
|
||||
grant authority.AuthorityGrant
|
||||
scope authority.Scope
|
||||
}
|
||||
|
||||
func (f fakeCreatorAuthority) LoadGrant(context.Context, authority.GrantID) (authority.AuthorityGrant, authority.Scope, error) {
|
||||
return f.grant, f.scope, nil
|
||||
}
|
||||
|
||||
func TestCreatorCommandDerivesAuthorityAndActionFieldsServerSide(t *testing.T) {
|
||||
handler, repository, executor := validCreatorCommandHandler()
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/continuity/satisfy-delivered", strings.NewReader(`{
|
||||
"Target":{"TaskID":"task-1","GoalID":"goal-1","ScopeID":"scope-1","Revision":3},
|
||||
"ProspectiveItemID":"prospective-1","ExpectedRevision":4,"EvidenceRef":" artifact://evidence/1 "
|
||||
}`))
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var result creatorActionResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.State != commitcontract.ActionSucceeded || executor.calls != 1 {
|
||||
t.Fatalf("result=%#v calls=%d", result, executor.calls)
|
||||
}
|
||||
action := repository.action
|
||||
if action.Proposal.ActorID != "creator-actor" || action.PrincipalID != "creator-principal" ||
|
||||
action.GrantID != creatorGrantID || action.Proposal.CapabilityID != commitcontract.CapabilityContinuityTransition ||
|
||||
action.Proposal.Operation != commitcontract.OperationSatisfyDelivered || action.Proposal.ContinuitySubject.FromState != continuity.ProspectiveDelivered ||
|
||||
action.Proposal.ContinuitySubject.ToState != continuity.ProspectiveSatisfied || action.Proposal.ContinuitySubject.EvidenceRef != "artifact://evidence/1" {
|
||||
t.Fatalf("server-derived envelope is invalid: %#v", action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorCommandRejectsSessionForeignOwnerStaleStateAndRevokedGrant(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*creatorCommandHandler)
|
||||
status int
|
||||
}{
|
||||
{name: "session", mutate: func(h *creatorCommandHandler) {
|
||||
core := h.core.(fakeCreatorCore)
|
||||
core.sessionErr = errCreatorSessionDenied
|
||||
h.core = core
|
||||
}, status: http.StatusUnauthorized},
|
||||
{name: "foreign owner", mutate: func(h *creatorCommandHandler) {
|
||||
source := h.continuity.(fakeCreatorContinuity)
|
||||
source.item.OwnerPrincipalID = "foreign"
|
||||
h.continuity = source
|
||||
}, status: http.StatusForbidden},
|
||||
{name: "stale state", mutate: func(h *creatorCommandHandler) {
|
||||
source := h.continuity.(fakeCreatorContinuity)
|
||||
source.item.State = continuity.ProspectiveArmed
|
||||
h.continuity = source
|
||||
}, status: http.StatusConflict},
|
||||
{name: "revoked grant", mutate: func(h *creatorCommandHandler) {
|
||||
source := h.authority.(fakeCreatorAuthority)
|
||||
source.grant.Active = false
|
||||
h.authority = source
|
||||
}, status: http.StatusConflict},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
handler, repository, executor := validCreatorCommandHandler()
|
||||
test.mutate(&handler)
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/continuity/satisfy-delivered", strings.NewReader(`{"Target":{"TaskID":"task-1","GoalID":"goal-1","ScopeID":"scope-1","Revision":3},"ProspectiveItemID":"prospective-1","ExpectedRevision":4,"EvidenceRef":"evidence"}`))
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != test.status || executor.calls != 0 || repository.action.ID != "" {
|
||||
t.Fatalf("status=%d calls=%d action=%#v", response.Code, executor.calls, repository.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func validCreatorCommandHandler() (creatorCommandHandler, *fakeExecutionRepository, *knownExecutor) {
|
||||
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
|
||||
target := work.TaskTarget{TaskID: "task-1", GoalID: "goal-1", ScopeID: "scope-1", Revision: 3}
|
||||
core := fakeCreatorCore{session: session, target: target, binding: identity.PrincipalBinding{ActorID: session.ActorID, PrincipalID: session.PrincipalID, Active: true}}
|
||||
item := continuity.ProspectiveItem{ID: "prospective-1", OwnerPrincipalID: session.PrincipalID, ScopeID: target.ScopeID, GoalID: target.GoalID, State: continuity.ProspectiveDelivered, Revision: 4}
|
||||
grant := authority.AuthorityGrant{ID: creatorGrantID, ActorID: session.ActorID, PrincipalID: session.PrincipalID, ScopeID: target.ScopeID, Class: authority.GrantClassCreator, Revision: 2, Active: true}
|
||||
repository := &fakeExecutionRepository{}
|
||||
executor := &knownExecutor{}
|
||||
identities := []ids.ID{"intent-generated", "authorized-generated", "attempt-generated"}
|
||||
return creatorCommandHandler{
|
||||
core: core, continuity: fakeCreatorContinuity{item: item}, authority: fakeCreatorAuthority{grant: grant, scope: authority.Scope{ID: target.ScopeID, Global: true}},
|
||||
repository: repository, executor: executor, reconciler: executor,
|
||||
newID: func() (ids.ID, error) {
|
||||
if len(identities) == 0 {
|
||||
return "", errors.New("identity exhaustion")
|
||||
}
|
||||
value := identities[0]
|
||||
identities = identities[1:]
|
||||
return value, nil
|
||||
},
|
||||
now: func() time.Time { return time.UnixMilli(10) },
|
||||
}, repository, executor
|
||||
}
|
||||
@@ -14,6 +14,11 @@ import (
|
||||
"git.cin.su/m/Assistant/modules/commit/ports"
|
||||
)
|
||||
|
||||
var (
|
||||
errActionAlreadyAttempted = errors.New("action already has an execution attempt")
|
||||
errActionDoesNotNeedReconcile = errors.New("action does not require reconciliation")
|
||||
)
|
||||
|
||||
type executionRepository interface {
|
||||
LoadAuthorized(context.Context, commitcontract.AuthorizedActionID) (commitcontract.AuthorizedAction, error)
|
||||
LoadLatestAttempt(context.Context, commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, error)
|
||||
@@ -36,25 +41,17 @@ func registerExecutionRoutes(mux *http.ServeMux, repository executionRepository,
|
||||
http.Error(w, "authorized action unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if _, err = repository.LoadLatestAttempt(r.Context(), action.ID); err == nil {
|
||||
http.Error(w, "action already has an execution attempt", http.StatusConflict)
|
||||
return
|
||||
} else if !errors.Is(err, postgres.ErrActionAttemptNotFound) {
|
||||
http.Error(w, "action attempt unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
request, ok := decodeAttemptRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
begun := commitcontract.ActionAttempt{ID: request.AttemptID, AuthorizedID: action.ID, IntentID: action.Proposal.IntentID, State: commitcontract.ActionExecuting}
|
||||
if err = repository.BeginAttempt(r.Context(), begun); err != nil {
|
||||
http.Error(w, "begin execution attempt", http.StatusConflict)
|
||||
attempt, executeErr := executeAuthorized(r.Context(), repository, executor, action, request.AttemptID)
|
||||
if errors.Is(executeErr, errActionAlreadyAttempted) {
|
||||
http.Error(w, "action already has an execution attempt", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
attempt, executeErr := commitdomain.Execute(action, request.AttemptID, executor)
|
||||
if err = repository.FinishAttempt(r.Context(), attempt); err != nil {
|
||||
http.Error(w, "finish execution attempt", http.StatusInternalServerError)
|
||||
if executeErr != nil && !errors.Is(executeErr, commitdomain.ErrUnknownOutcome) {
|
||||
http.Error(w, "execute authorized action", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeAttempt(w, attempt, executeErr)
|
||||
@@ -70,40 +67,65 @@ func registerExecutionRoutes(mux *http.ServeMux, repository executionRepository,
|
||||
http.Error(w, "authorized action unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
previous, err := repository.LoadLatestAttempt(r.Context(), action.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "unknown execution attempt not found", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if previous.State == commitcontract.ActionExecuting {
|
||||
previous.State = commitcontract.ActionUnknownOutcome
|
||||
if err = repository.FinishAttempt(r.Context(), previous); err != nil {
|
||||
http.Error(w, "recover interrupted attempt", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if previous.State != commitcontract.ActionUnknownOutcome {
|
||||
http.Error(w, "action does not require reconciliation", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
request, ok := decodeAttemptRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
begun := commitcontract.ActionAttempt{ID: request.AttemptID, AuthorizedID: action.ID, IntentID: action.Proposal.IntentID, State: commitcontract.ActionExecuting}
|
||||
if err = repository.BeginAttempt(r.Context(), begun); err != nil {
|
||||
http.Error(w, "begin reconciliation attempt", http.StatusConflict)
|
||||
attempt, reconcileErr := reconcileAuthorized(r.Context(), repository, reconciler, action, request.AttemptID)
|
||||
if errors.Is(reconcileErr, errActionDoesNotNeedReconcile) {
|
||||
http.Error(w, "action does not require reconciliation", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
attempt, reconcileErr := commitdomain.Reconcile(action, previous, request.AttemptID, reconciler)
|
||||
if err = repository.FinishAttempt(r.Context(), attempt); err != nil {
|
||||
http.Error(w, "finish reconciliation attempt", http.StatusInternalServerError)
|
||||
if reconcileErr != nil && !errors.Is(reconcileErr, commitdomain.ErrUnknownOutcome) {
|
||||
http.Error(w, "reconcile authorized action", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeAttempt(w, attempt, reconcileErr)
|
||||
}))
|
||||
}
|
||||
|
||||
func executeAuthorized(ctx context.Context, repository executionRepository, executor ports.Executor, action commitcontract.AuthorizedAction, attemptID commitcontract.ActionAttemptID) (commitcontract.ActionAttempt, error) {
|
||||
if _, err := repository.LoadLatestAttempt(ctx, action.ID); err == nil {
|
||||
return commitcontract.ActionAttempt{}, errActionAlreadyAttempted
|
||||
} else if !errors.Is(err, postgres.ErrActionAttemptNotFound) {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
begun := commitcontract.ActionAttempt{ID: attemptID, AuthorizedID: action.ID, IntentID: action.Proposal.IntentID, State: commitcontract.ActionExecuting}
|
||||
if err := repository.BeginAttempt(ctx, begun); err != nil {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
attempt, operationErr := commitdomain.Execute(action, attemptID, executor)
|
||||
if err := repository.FinishAttempt(ctx, attempt); err != nil {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
return attempt, operationErr
|
||||
}
|
||||
|
||||
func reconcileAuthorized(ctx context.Context, repository executionRepository, reconciler ports.Reconciler, action commitcontract.AuthorizedAction, attemptID commitcontract.ActionAttemptID) (commitcontract.ActionAttempt, error) {
|
||||
previous, err := repository.LoadLatestAttempt(ctx, action.ID)
|
||||
if err != nil {
|
||||
return commitcontract.ActionAttempt{}, errActionDoesNotNeedReconcile
|
||||
}
|
||||
if previous.State == commitcontract.ActionExecuting {
|
||||
previous.State = commitcontract.ActionUnknownOutcome
|
||||
if err = repository.FinishAttempt(ctx, previous); err != nil {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
}
|
||||
if previous.State != commitcontract.ActionUnknownOutcome {
|
||||
return commitcontract.ActionAttempt{}, errActionDoesNotNeedReconcile
|
||||
}
|
||||
begun := commitcontract.ActionAttempt{ID: attemptID, AuthorizedID: action.ID, IntentID: action.Proposal.IntentID, State: commitcontract.ActionExecuting}
|
||||
if err = repository.BeginAttempt(ctx, begun); err != nil {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
attempt, operationErr := commitdomain.Reconcile(action, previous, attemptID, reconciler)
|
||||
if err = repository.FinishAttempt(ctx, attempt); err != nil {
|
||||
return commitcontract.ActionAttempt{}, err
|
||||
}
|
||||
return attempt, operationErr
|
||||
}
|
||||
|
||||
func decodeAttemptRequest(w http.ResponseWriter, r *http.Request) (attemptRequest, bool) {
|
||||
var request attemptRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10)).Decode(&request); err != nil || request.AttemptID == "" {
|
||||
|
||||
@@ -38,6 +38,10 @@ func (f *fakeExecutionRepository) FinishAttempt(_ context.Context, attempt commi
|
||||
f.attempts[len(f.attempts)-1] = attempt
|
||||
return nil
|
||||
}
|
||||
func (f *fakeExecutionRepository) SaveAuthorized(_ context.Context, action commitcontract.AuthorizedAction) error {
|
||||
f.action = action
|
||||
return nil
|
||||
}
|
||||
|
||||
type knownExecutor struct{ calls int }
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
authoritydomain "git.cin.su/m/Assistant/modules/authority/domain"
|
||||
commitdomain "git.cin.su/m/Assistant/modules/commit/domain"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
"git.cin.su/m/Assistant/runtime/health"
|
||||
)
|
||||
|
||||
@@ -65,6 +66,19 @@ func main() {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "commit-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
registerExecutionRoutes(mux, repository, executor, executor, executorToken)
|
||||
creatorHTTPClient := &http.Client{Timeout: 5 * time.Second}
|
||||
creatorCore, err := newCreatorCoreClient(coreURL, creatorHTTPClient)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
creatorContinuity, err := newCreatorContinuityClient(envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"), creatorHTTPClient)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
registerCreatorCommandRoutes(mux, creatorCommandHandler{
|
||||
core: creatorCore, continuity: creatorContinuity, authority: authorityRepository, repository: repository,
|
||||
executor: executor, reconciler: executor, newID: ids.New, now: time.Now,
|
||||
})
|
||||
mux.HandleFunc("POST /v1/authorized-actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
var request authorizationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user