Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2c085b688 | ||
|
|
63ec2ddf68 | ||
|
|
e4fed02809 | ||
|
|
eab6bc50c9 | ||
|
|
a8e20f437b | ||
|
|
4487ac99b4 | ||
|
|
23f909b9d8 | ||
|
|
6b089ff223 |
+19
-20
@@ -21,9 +21,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
apt-get update
|
apt-get update
|
||||||
apt-get install -y docker.io curl nodejs
|
apt-get install -y docker.io curl nodejs
|
||||||
curl -sLO "https://dl.k8s.io/release/$(curl -sL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
|
|
||||||
chmod +x kubectl && mv kubectl /usr/local/bin/
|
|
||||||
kubectl version --client
|
|
||||||
|
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -32,7 +29,7 @@ jobs:
|
|||||||
run: go vet ./...
|
run: go vet ./...
|
||||||
|
|
||||||
- name: Go test
|
- name: Go test
|
||||||
run: go test ./...
|
run: go test -short ./...
|
||||||
|
|
||||||
- name: Get short SHA
|
- name: Get short SHA
|
||||||
id: sha
|
id: sha
|
||||||
@@ -63,17 +60,17 @@ jobs:
|
|||||||
# (Temporal, Gotify). Tests run against its pod IP directly.
|
# (Temporal, Gotify). Tests run against its pod IP directly.
|
||||||
# Zero downtime: production pods untouched until tests pass.
|
# Zero downtime: production pods untouched until tests pass.
|
||||||
- name: Setup kubeconfig
|
- name: Setup kubeconfig
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: false # SKIP: only needed for canary deploy
|
||||||
run: |
|
run: |
|
||||||
mkdir -p ~/.kube
|
mkdir -p ~/.kube
|
||||||
echo "${KUBECONFIG_B64}" | base64 -d > ~/.kube/config
|
echo "${KUBECONFIG_B64}" | base64 -d > ~/.kube/config
|
||||||
kubectl get nodes --no-headers | head -1
|
kubectl get namespaces --no-headers | head -1
|
||||||
echo '✓ kubeconfig works'
|
echo '✓ kubeconfig works'
|
||||||
env:
|
env:
|
||||||
KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
|
KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
|
||||||
|
|
||||||
- name: Deploy canary pod
|
- name: Deploy canary pod
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: false # SKIP: SA lacks pod create RBAC. Re-enable when fixed.
|
||||||
id: canary
|
id: canary
|
||||||
run: |
|
run: |
|
||||||
SHA="${{ steps.sha.outputs.short_sha }}"
|
SHA="${{ steps.sha.outputs.short_sha }}"
|
||||||
@@ -136,7 +133,7 @@ jobs:
|
|||||||
echo "✓ Canary ready at ${POD_IP}:8080"
|
echo "✓ Canary ready at ${POD_IP}:8080"
|
||||||
|
|
||||||
- name: Run integration tests against canary
|
- name: Run integration tests against canary
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: false # SKIP: depends on canary pod
|
||||||
id: tests
|
id: tests
|
||||||
run: |
|
run: |
|
||||||
POD_IP="${{ steps.canary.outputs.pod_ip }}"
|
POD_IP="${{ steps.canary.outputs.pod_ip }}"
|
||||||
@@ -154,14 +151,18 @@ jobs:
|
|||||||
echo "result=${RESULT}" >> $GITHUB_OUTPUT
|
echo "result=${RESULT}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
- name: Cleanup canary pod
|
- name: Cleanup canary pod
|
||||||
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: false # SKIP: depends on canary pod
|
||||||
run: |
|
run: |
|
||||||
POD_NAME="${{ steps.canary.outputs.pod_name }}"
|
POD_NAME="${{ steps.canary.outputs.pod_name }}"
|
||||||
kubectl delete pod "${POD_NAME}" -n api --ignore-not-found || true
|
if [ -n "${POD_NAME}" ]; then
|
||||||
echo "✓ Canary pod removed"
|
kubectl delete pod "${POD_NAME}" -n api --ignore-not-found || true
|
||||||
|
echo "✓ Canary pod removed"
|
||||||
|
else
|
||||||
|
echo "⚠ No canary pod to clean up (name was empty)"
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Gate on test result
|
- name: Gate on test result
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.tests.outputs.result != 'pass'
|
if: false # SKIP: depends on canary pod
|
||||||
run: |
|
run: |
|
||||||
echo "✗ Integration tests FAILED — production deployment unchanged"
|
echo "✗ Integration tests FAILED — production deployment unchanged"
|
||||||
exit 1
|
exit 1
|
||||||
@@ -169,14 +170,12 @@ jobs:
|
|||||||
# ── Zero-downtime promotion ──────────────────────────────
|
# ── Zero-downtime promotion ──────────────────────────────
|
||||||
# kubectl set image triggers a rolling update: new pods come up
|
# kubectl set image triggers a rolling update: new pods come up
|
||||||
# before old pods are terminated. Production traffic uninterrupted.
|
# before old pods are terminated. Production traffic uninterrupted.
|
||||||
- name: Promote — rolling update
|
# TODO: Re-enable k8s rolling update when kubeconfig/RBAC is ready
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
# - name: Promote — rolling update
|
||||||
run: |
|
# if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
SHA="${{ steps.sha.outputs.short_sha }}"
|
# run: |
|
||||||
kubectl set image deployment/api-gateway \
|
# kubectl set image deployment/api-gateway api-gateway="${IMAGE}:${SHA}" -n api
|
||||||
api-gateway="${IMAGE}:${SHA}" -n api
|
# kubectl rollout status deployment/api-gateway -n api --timeout=120s
|
||||||
kubectl rollout status deployment/api-gateway -n api --timeout=120s
|
|
||||||
echo "✓ Rolling update complete: ${IMAGE}:${SHA}"
|
|
||||||
|
|
||||||
- name: Tag :latest (informational)
|
- name: Tag :latest (informational)
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
|||||||
@@ -108,6 +108,10 @@ func main() {
|
|||||||
}
|
}
|
||||||
_ = registry.Add(notifAdapter)
|
_ = registry.Add(notifAdapter)
|
||||||
|
|
||||||
|
// Add Poimen orchestrator adapter (typed REST for AI orchestrator frontend)
|
||||||
|
poimenAdapter := serviceadapter.NewPoimenAdapter(temporalHandler)
|
||||||
|
_ = registry.Add(poimenAdapter)
|
||||||
|
|
||||||
// Add other adapters from config (skip if already registered in code)
|
// Add other adapters from config (skip if already registered in code)
|
||||||
for _, a := range cfg.Adapters {
|
for _, a := range cfg.Adapters {
|
||||||
if existing := registry.Get(a.ServiceName); existing != nil {
|
if existing := registry.Get(a.ServiceName); existing != nil {
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package serviceadapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/temporal"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewPoimenAdapter creates a ServiceAdapter for the Poimen orchestrator service.
|
||||||
|
func NewPoimenAdapter(h *temporal.Handler) *ServiceAdapter {
|
||||||
|
return &ServiceAdapter{
|
||||||
|
Namespace: "poimen",
|
||||||
|
ServiceName: "poimen",
|
||||||
|
Handler: temporal.NewPoimenHandler(h),
|
||||||
|
Spec: *GetPoimenSpec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPoimenSpec returns the ServiceAdapter spec for the Poimen service.
|
||||||
|
func GetPoimenSpec() *Spec {
|
||||||
|
return &Spec{
|
||||||
|
ServiceName: "poimen",
|
||||||
|
Upstream: Upstream{
|
||||||
|
URL: "internal://poimen",
|
||||||
|
TimeoutSeconds: 60,
|
||||||
|
},
|
||||||
|
Auth: Auth{
|
||||||
|
Required: true,
|
||||||
|
Capability: "workflow:read",
|
||||||
|
},
|
||||||
|
Resources: []Resource{
|
||||||
|
{
|
||||||
|
Name: "plan",
|
||||||
|
Methods: []Method{{
|
||||||
|
Verb: "POST",
|
||||||
|
UpstreamPath: "/v1/poimen/plan",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:execute"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "execute",
|
||||||
|
Methods: []Method{{
|
||||||
|
Verb: "POST",
|
||||||
|
UpstreamPath: "/v1/poimen/execute",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:execute"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "executions",
|
||||||
|
Methods: []Method{
|
||||||
|
{
|
||||||
|
Verb: "GET",
|
||||||
|
UpstreamPath: "/v1/poimen/executions",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:read"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "execution-detail",
|
||||||
|
Methods: []Method{
|
||||||
|
{
|
||||||
|
Verb: "GET",
|
||||||
|
UpstreamPath: "/v1/poimen/executions/{id}",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:read"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Verb: "DELETE",
|
||||||
|
UpstreamPath: "/v1/poimen/executions/{id}",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:execute"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "execution-history",
|
||||||
|
Methods: []Method{{
|
||||||
|
Verb: "GET",
|
||||||
|
UpstreamPath: "/v1/poimen/executions/{id}/history",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:read"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "execution-stream",
|
||||||
|
Methods: []Method{{
|
||||||
|
Verb: "GET",
|
||||||
|
UpstreamPath: "/v1/poimen/executions/{id}/stream",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:read"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "execution-signal",
|
||||||
|
Methods: []Method{{
|
||||||
|
Verb: "POST",
|
||||||
|
UpstreamPath: "/v1/poimen/executions/{id}/signal",
|
||||||
|
Auth: &Auth{Required: true, Capability: "workflow:execute"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -359,6 +359,19 @@ func GetWorkflowSpec() *Spec {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "stream",
|
||||||
|
Methods: []Method{
|
||||||
|
{
|
||||||
|
Verb: "GET",
|
||||||
|
UpstreamPath: "/workflow/stream",
|
||||||
|
Auth: &Auth{
|
||||||
|
Required: true,
|
||||||
|
Capability: "workflow:read",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+37
-112
@@ -10,7 +10,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.temporal.io/api/common/v1"
|
"go.temporal.io/api/common/v1"
|
||||||
query "go.temporal.io/api/query/v1"
|
|
||||||
"go.temporal.io/api/taskqueue/v1"
|
"go.temporal.io/api/taskqueue/v1"
|
||||||
update "go.temporal.io/api/update/v1"
|
update "go.temporal.io/api/update/v1"
|
||||||
"go.temporal.io/api/workflowservice/v1"
|
"go.temporal.io/api/workflowservice/v1"
|
||||||
@@ -38,6 +37,8 @@ type ResponsePayload struct {
|
|||||||
type Handler struct {
|
type Handler struct {
|
||||||
hostPort string
|
hostPort string
|
||||||
grpcClient *GRPCClient
|
grpcClient *GRPCClient
|
||||||
|
ops *WorkflowGRPCImpl
|
||||||
|
searchOps *SearchAttributesGRPCImpl
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHandler creates a new Temporal HTTP handler
|
// NewHandler creates a new Temporal HTTP handler
|
||||||
@@ -51,10 +52,15 @@ func NewHandler(hostPort string) *Handler {
|
|||||||
log.Printf("WARNING: Failed to connect to Temporal at %s: %v", hostPort, err)
|
log.Printf("WARNING: Failed to connect to Temporal at %s: %v", hostPort, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Handler{
|
h := &Handler{
|
||||||
hostPort: hostPort,
|
hostPort: hostPort,
|
||||||
grpcClient: grpcClient,
|
grpcClient: grpcClient,
|
||||||
}
|
}
|
||||||
|
if grpcClient != nil {
|
||||||
|
h.ops = NewWorkflowGRPCImpl(grpcClient)
|
||||||
|
h.searchOps = NewSearchAttributesGRPCImpl(grpcClient)
|
||||||
|
}
|
||||||
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
// unavailable returns TEMPORAL_UNAVAILABLE when grpcClient is nil
|
// unavailable returns TEMPORAL_UNAVAILABLE when grpcClient is nil
|
||||||
@@ -72,6 +78,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.handleHealth(w, r)
|
h.handleHealth(w, r)
|
||||||
case "/workflow/metrics":
|
case "/workflow/metrics":
|
||||||
h.handleMetrics(w, r)
|
h.handleMetrics(w, r)
|
||||||
|
case "/workflow/stream":
|
||||||
|
h.StreamWorkflowEvents(w, r)
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
h.writeError(w, "", "NOT_FOUND", "Endpoint not found")
|
h.writeError(w, "", "NOT_FOUND", "Endpoint not found")
|
||||||
@@ -206,7 +214,7 @@ func (h *Handler) handleMetrics(w http.ResponseWriter, r *http.Request) {
|
|||||||
// ── Workflow operations ──────────────────────────────────────────────────────
|
// ── Workflow operations ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
func (h *Handler) startWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) startWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
@@ -221,31 +229,16 @@ func (h *Handler) startWorkflow(ctx context.Context, namespace string, payload m
|
|||||||
if taskQueue == "" {
|
if taskQueue == "" {
|
||||||
return nil, "INVALID_REQUEST", "task_queue is required"
|
return nil, "INVALID_REQUEST", "task_queue is required"
|
||||||
}
|
}
|
||||||
|
input := getMap(payload, "input")
|
||||||
req := &workflowservice.StartWorkflowExecutionRequest{
|
result, err := h.ops.StartWorkflowExecution(ctx, namespace, workflowID, workflowType, taskQueue, input)
|
||||||
Namespace: namespace,
|
|
||||||
WorkflowId: workflowID,
|
|
||||||
WorkflowType: &common.WorkflowType{Name: workflowType},
|
|
||||||
TaskQueue: &taskqueue.TaskQueue{Name: taskQueue},
|
|
||||||
}
|
|
||||||
if input := getMap(payload, "input"); len(input) > 0 {
|
|
||||||
b, _ := json.Marshal(input)
|
|
||||||
req.Input = &common.Payloads{Payloads: []*common.Payload{{Data: b}}}
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := h.grpcClient.GetWorkflowServiceStub().StartWorkflowExecution(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to start workflow: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to start workflow: %v", err)
|
||||||
}
|
}
|
||||||
return map[string]interface{}{
|
return result, "", ""
|
||||||
"workflow_id": workflowID,
|
|
||||||
"run_id": resp.RunId,
|
|
||||||
"started_at": time.Now(),
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) describeWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) describeWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
@@ -253,25 +246,11 @@ func (h *Handler) describeWorkflow(ctx context.Context, namespace string, payloa
|
|||||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||||
}
|
}
|
||||||
runID := getString(payload, "run_id")
|
runID := getString(payload, "run_id")
|
||||||
|
result, err := h.ops.DescribeWorkflowExecution(ctx, namespace, workflowID, runID)
|
||||||
resp, err := h.grpcClient.GetWorkflowServiceStub().DescribeWorkflowExecution(ctx,
|
|
||||||
&workflowservice.DescribeWorkflowExecutionRequest{
|
|
||||||
Namespace: namespace,
|
|
||||||
Execution: &common.WorkflowExecution{WorkflowId: workflowID, RunId: runID},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "WORKFLOW_NOT_FOUND", fmt.Sprintf("failed to describe workflow: %v", err)
|
return nil, "WORKFLOW_NOT_FOUND", fmt.Sprintf("failed to describe workflow: %v", err)
|
||||||
}
|
}
|
||||||
|
return result, "", ""
|
||||||
status := "UNKNOWN"
|
|
||||||
if resp.WorkflowExecutionInfo != nil {
|
|
||||||
status = resp.WorkflowExecutionInfo.Status.String()
|
|
||||||
}
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"run_id": runID,
|
|
||||||
"status": status,
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) listWorkflows(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) listWorkflows(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
@@ -317,7 +296,7 @@ func (h *Handler) listWorkflows(ctx context.Context, namespace string, payload m
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) getWorkflowHistory(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) getWorkflowHistory(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
@@ -325,79 +304,48 @@ func (h *Handler) getWorkflowHistory(ctx context.Context, namespace string, payl
|
|||||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||||
}
|
}
|
||||||
runID := getString(payload, "run_id")
|
runID := getString(payload, "run_id")
|
||||||
|
result, err := h.ops.GetWorkflowExecutionHistory(ctx, namespace, workflowID, runID)
|
||||||
resp, err := h.grpcClient.GetWorkflowServiceStub().GetWorkflowExecutionHistory(ctx,
|
|
||||||
&workflowservice.GetWorkflowExecutionHistoryRequest{
|
|
||||||
Namespace: namespace,
|
|
||||||
Execution: &common.WorkflowExecution{WorkflowId: workflowID, RunId: runID},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to get history: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to get history: %v", err)
|
||||||
}
|
}
|
||||||
|
return result, "", ""
|
||||||
events := make([]interface{}, 0, len(resp.History.GetEvents()))
|
|
||||||
for _, e := range resp.History.GetEvents() {
|
|
||||||
events = append(events, map[string]interface{}{
|
|
||||||
"event_id": e.EventId,
|
|
||||||
"event_type": e.EventType.String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return map[string]interface{}{
|
|
||||||
"events": events,
|
|
||||||
"next_page_token": string(resp.NextPageToken),
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) terminateWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) terminateWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
if workflowID == "" {
|
if workflowID == "" {
|
||||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||||
}
|
}
|
||||||
|
runID := getString(payload, "run_id")
|
||||||
reason := getString(payload, "reason")
|
reason := getString(payload, "reason")
|
||||||
|
result, err := h.ops.TerminateWorkflowExecution(ctx, namespace, workflowID, runID, reason)
|
||||||
_, err := h.grpcClient.GetWorkflowServiceStub().TerminateWorkflowExecution(ctx,
|
|
||||||
&workflowservice.TerminateWorkflowExecutionRequest{
|
|
||||||
Namespace: namespace,
|
|
||||||
WorkflowExecution: &common.WorkflowExecution{WorkflowId: workflowID},
|
|
||||||
Reason: reason,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to terminate workflow: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to terminate workflow: %v", err)
|
||||||
}
|
}
|
||||||
return map[string]interface{}{
|
return result, "", ""
|
||||||
"workflow_id": workflowID,
|
|
||||||
"terminated_at": time.Now(),
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) cancelWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) cancelWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
if workflowID == "" {
|
if workflowID == "" {
|
||||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||||
}
|
}
|
||||||
|
runID := getString(payload, "run_id")
|
||||||
_, err := h.grpcClient.GetWorkflowServiceStub().RequestCancelWorkflowExecution(ctx,
|
result, err := h.ops.CancelWorkflowExecution(ctx, namespace, workflowID, runID)
|
||||||
&workflowservice.RequestCancelWorkflowExecutionRequest{
|
|
||||||
Namespace: namespace,
|
|
||||||
WorkflowExecution: &common.WorkflowExecution{WorkflowId: workflowID},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to cancel workflow: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to cancel workflow: %v", err)
|
||||||
}
|
}
|
||||||
return map[string]interface{}{
|
return result, "", ""
|
||||||
"workflow_id": workflowID,
|
|
||||||
"status": "canceling",
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) signalWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) signalWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
@@ -408,30 +356,17 @@ func (h *Handler) signalWorkflow(ctx context.Context, namespace string, payload
|
|||||||
if signalName == "" {
|
if signalName == "" {
|
||||||
return nil, "INVALID_REQUEST", "signal_name is required"
|
return nil, "INVALID_REQUEST", "signal_name is required"
|
||||||
}
|
}
|
||||||
|
runID := getString(payload, "run_id")
|
||||||
req := &workflowservice.SignalWorkflowExecutionRequest{
|
signalData := getMap(payload, "signal_data")
|
||||||
Namespace: namespace,
|
result, err := h.ops.SignalWorkflowExecution(ctx, namespace, workflowID, runID, signalName, signalData)
|
||||||
WorkflowExecution: &common.WorkflowExecution{WorkflowId: workflowID},
|
|
||||||
SignalName: signalName,
|
|
||||||
}
|
|
||||||
if data := getMap(payload, "signal_data"); len(data) > 0 {
|
|
||||||
b, _ := json.Marshal(data)
|
|
||||||
req.Input = &common.Payloads{Payloads: []*common.Payload{{Data: b}}}
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := h.grpcClient.GetWorkflowServiceStub().SignalWorkflowExecution(ctx, req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to signal workflow: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to signal workflow: %v", err)
|
||||||
}
|
}
|
||||||
return map[string]interface{}{
|
return result, "", ""
|
||||||
"workflow_id": workflowID,
|
|
||||||
"signal_name": signalName,
|
|
||||||
"signaled_at": time.Now(),
|
|
||||||
}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) queryWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) queryWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
if h.grpcClient == nil {
|
if h.ops == nil {
|
||||||
return h.unavailable()
|
return h.unavailable()
|
||||||
}
|
}
|
||||||
workflowID := getString(payload, "workflow_id")
|
workflowID := getString(payload, "workflow_id")
|
||||||
@@ -442,22 +377,12 @@ func (h *Handler) queryWorkflow(ctx context.Context, namespace string, payload m
|
|||||||
if queryType == "" {
|
if queryType == "" {
|
||||||
return nil, "INVALID_REQUEST", "query_type is required"
|
return nil, "INVALID_REQUEST", "query_type is required"
|
||||||
}
|
}
|
||||||
|
runID := getString(payload, "run_id")
|
||||||
resp, err := h.grpcClient.GetWorkflowServiceStub().QueryWorkflow(ctx,
|
result, err := h.ops.QueryWorkflowExecution(ctx, namespace, workflowID, runID, queryType)
|
||||||
&workflowservice.QueryWorkflowRequest{
|
|
||||||
Namespace: namespace,
|
|
||||||
Execution: &common.WorkflowExecution{WorkflowId: workflowID},
|
|
||||||
Query: &query.WorkflowQuery{QueryType: queryType},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to query workflow: %v", err)
|
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to query workflow: %v", err)
|
||||||
}
|
}
|
||||||
|
return result, "", ""
|
||||||
var result interface{}
|
|
||||||
if resp.QueryResult != nil && len(resp.QueryResult.Payloads) > 0 {
|
|
||||||
json.Unmarshal(resp.QueryResult.Payloads[0].Data, &result)
|
|
||||||
}
|
|
||||||
return map[string]interface{}{"query_result": result}, "", ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) resetWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
func (h *Handler) resetWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
// Package temporal provides operation wrappers for Temporal operations
|
|
||||||
package temporal
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// OperationHandler handles Temporal operations
|
|
||||||
type OperationHandler struct {
|
|
||||||
grpc *GRPCClient
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewOperationHandler creates a new operation handler
|
|
||||||
func NewOperationHandler(grpcClient *GRPCClient) *OperationHandler {
|
|
||||||
return &OperationHandler{
|
|
||||||
grpc: grpcClient,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// StartWorkflowExecution starts a new workflow execution
|
|
||||||
func (oh *OperationHandler) StartWorkflowExecution(ctx context.Context, namespace, workflowID, workflowType, taskQueue string, input map[string]interface{}) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
// This is a placeholder for actual implementation
|
|
||||||
if oh.grpc == nil {
|
|
||||||
return nil, fmt.Errorf("gRPC client not initialized")
|
|
||||||
}
|
|
||||||
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"run_id": fmt.Sprintf("run_%d", time.Now().UnixNano()),
|
|
||||||
"start_time": time.Now(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DescribeWorkflowExecution gets workflow details
|
|
||||||
func (oh *OperationHandler) DescribeWorkflowExecution(ctx context.Context, namespace, workflowID, runID string) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"run_id": runID,
|
|
||||||
"status": "RUNNING",
|
|
||||||
"start_time": time.Now(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TerminateWorkflowExecution terminates a workflow
|
|
||||||
func (oh *OperationHandler) TerminateWorkflowExecution(ctx context.Context, namespace, workflowID, runID, reason string) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"run_id": runID,
|
|
||||||
"terminated_at": time.Now(),
|
|
||||||
"reason": reason,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CancelWorkflowExecution cancels a workflow
|
|
||||||
func (oh *OperationHandler) CancelWorkflowExecution(ctx context.Context, namespace, workflowID, runID string) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"status": "canceling",
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SignalWorkflowExecution sends a signal to a workflow
|
|
||||||
func (oh *OperationHandler) SignalWorkflowExecution(ctx context.Context, namespace, workflowID, runID, signalName string, input map[string]interface{}) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"signal_name": signalName,
|
|
||||||
"signaled_at": time.Now(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// QueryWorkflowExecution queries a workflow
|
|
||||||
func (oh *OperationHandler) QueryWorkflowExecution(ctx context.Context, namespace, workflowID, runID, queryType string) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"workflow_id": workflowID,
|
|
||||||
"query_type": queryType,
|
|
||||||
"query_result": map[string]interface{}{},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListWorkflowExecutions lists workflows
|
|
||||||
func (oh *OperationHandler) ListWorkflowExecutions(ctx context.Context, namespace string, pageSize int32) (map[string]interface{}, error) {
|
|
||||||
// TODO: Implement gRPC call to Temporal
|
|
||||||
return map[string]interface{}{
|
|
||||||
"executions": []interface{}{},
|
|
||||||
"next_page_token": "",
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
package temporal
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PoimenHandler provides typed REST endpoints for Poimen workflows.
|
||||||
|
// Accessed via X-Service: poimen header through the ServiceAdapter dispatcher.
|
||||||
|
type PoimenHandler struct {
|
||||||
|
handler *Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPoimenHandler creates a new Poimen handler wrapping the Temporal handler.
|
||||||
|
func NewPoimenHandler(h *Handler) *PoimenHandler {
|
||||||
|
return &PoimenHandler{handler: h}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServeHTTP routes based on X-Upstream-Path set by the dispatcher.
|
||||||
|
func (p *PoimenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case path == "/v1/poimen/plan" && r.Method == http.MethodPost:
|
||||||
|
p.handlePlan(w, r)
|
||||||
|
case path == "/v1/poimen/execute" && r.Method == http.MethodPost:
|
||||||
|
p.handleExecute(w, r)
|
||||||
|
case path == "/v1/poimen/executions" && r.Method == http.MethodGet:
|
||||||
|
p.handleListExecutions(w, r)
|
||||||
|
case strings.HasPrefix(path, "/v1/poimen/executions/") && strings.HasSuffix(path, "/stream") && r.Method == http.MethodGet:
|
||||||
|
p.handleStream(w, r)
|
||||||
|
case strings.HasPrefix(path, "/v1/poimen/executions/") && strings.HasSuffix(path, "/signal") && r.Method == http.MethodPost:
|
||||||
|
p.handleSignal(w, r)
|
||||||
|
case strings.HasPrefix(path, "/v1/poimen/executions/") && strings.HasSuffix(path, "/history") && r.Method == http.MethodGet:
|
||||||
|
p.handleHistory(w, r)
|
||||||
|
case strings.HasPrefix(path, "/v1/poimen/executions/") && r.Method == http.MethodDelete:
|
||||||
|
p.handleTerminate(w, r)
|
||||||
|
case strings.HasPrefix(path, "/v1/poimen/executions/") && r.Method == http.MethodGet:
|
||||||
|
p.handleDescribe(w, r)
|
||||||
|
default:
|
||||||
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": "endpoint not found"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractWorkflowID extracts the workflow ID from paths like /v1/poimen/executions/{id}/...
|
||||||
|
func extractWorkflowID(path string) string {
|
||||||
|
parts := strings.Split(strings.TrimPrefix(path, "/v1/poimen/executions/"), "/")
|
||||||
|
if len(parts) > 0 && parts[0] != "" {
|
||||||
|
return parts[0]
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// PoimenWorkflowTypes maps Poimen workflow names to Temporal workflow types and task queues.
|
||||||
|
var PoimenWorkflowTypes = map[string]struct {
|
||||||
|
WorkflowType string
|
||||||
|
TaskQueue string
|
||||||
|
}{
|
||||||
|
"dag": {WorkflowType: "DAGWorkflow", TaskQueue: "poimen-worker"},
|
||||||
|
"orchestrator": {WorkflowType: "OrchestratorWorkflow", TaskQueue: "poimen-worker"},
|
||||||
|
"routing": {WorkflowType: "RoutingWorkflow", TaskQueue: "poimen-worker"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Plan ---
|
||||||
|
|
||||||
|
type PlanRequest struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Context map[string]interface{} `json:"context,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handlePlan(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req PlanRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Message == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "message is required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Call PlannerActivity directly (not via Temporal) for low latency.
|
||||||
|
// For now, return a placeholder indicating the plan endpoint is wired.
|
||||||
|
writeJSON(w, http.StatusNotImplemented, map[string]interface{}{
|
||||||
|
"error": "PlannerActivity not yet available",
|
||||||
|
"message": req.Message,
|
||||||
|
"context": req.Context,
|
||||||
|
"hint": "Depends on poimen-workflows#23 (PlannerActivity)",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Execute ---
|
||||||
|
|
||||||
|
type ExecuteRequest struct {
|
||||||
|
WorkflowType string `json:"workflow_type"` // "dag", "orchestrator", "routing"
|
||||||
|
Namespace string `json:"namespace,omitempty"`
|
||||||
|
Input map[string]interface{} `json:"input"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleExecute(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req ExecuteRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Namespace == "" {
|
||||||
|
req.Namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
wfType, ok := PoimenWorkflowTypes[req.WorkflowType]
|
||||||
|
if !ok {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": fmt.Sprintf("unknown workflow_type: %s", req.WorkflowType),
|
||||||
|
"valid_types": []string{"dag", "orchestrator", "routing"},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
workflowID := fmt.Sprintf("poimen-%s-%d", req.WorkflowType, time.Now().UnixMilli())
|
||||||
|
|
||||||
|
result, err := p.handler.ops.StartWorkflowExecution(
|
||||||
|
r.Context(),
|
||||||
|
req.Namespace,
|
||||||
|
workflowID,
|
||||||
|
wfType.WorkflowType,
|
||||||
|
wfType.TaskQueue,
|
||||||
|
req.Input,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": fmt.Sprintf("failed to start workflow: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- List Executions ---
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleListExecutions(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace := r.URL.Query().Get("namespace")
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := p.handler.ops.ListWorkflowExecutions(r.Context(), namespace, 100)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": fmt.Sprintf("failed to list: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Describe ---
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleDescribe(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
workflowID := extractWorkflowID(path)
|
||||||
|
if workflowID == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "workflow_id required in path"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace := r.URL.Query().Get("namespace")
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
runID := r.URL.Query().Get("run_id")
|
||||||
|
|
||||||
|
result, err := p.handler.ops.DescribeWorkflowExecution(r.Context(), namespace, workflowID, runID)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": fmt.Sprintf("workflow not found: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- History ---
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleHistory(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
workflowID := extractWorkflowID(path)
|
||||||
|
if workflowID == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "workflow_id required in path"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace := r.URL.Query().Get("namespace")
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
runID := r.URL.Query().Get("run_id")
|
||||||
|
|
||||||
|
result, err := p.handler.ops.GetWorkflowExecutionHistory(r.Context(), namespace, workflowID, runID)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": fmt.Sprintf("failed to get history: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Signal ---
|
||||||
|
|
||||||
|
type SignalRequest struct {
|
||||||
|
SignalName string `json:"signal_name"`
|
||||||
|
Data map[string]interface{} `json:"data,omitempty"`
|
||||||
|
Namespace string `json:"namespace,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleSignal(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
// Remove /signal suffix to get workflow ID
|
||||||
|
cleanPath := strings.TrimSuffix(path, "/signal")
|
||||||
|
workflowID := extractWorkflowID(cleanPath)
|
||||||
|
if workflowID == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "workflow_id required in path"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req SignalRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.SignalName == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "signal_name is required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Namespace == "" {
|
||||||
|
req.Namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := p.handler.ops.SignalWorkflowExecution(r.Context(), req.Namespace, workflowID, "", req.SignalName, req.Data)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": fmt.Sprintf("failed to signal: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Terminate ---
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleTerminate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if p.handler.ops == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "Temporal not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
workflowID := extractWorkflowID(path)
|
||||||
|
if workflowID == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "workflow_id required in path"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace := r.URL.Query().Get("namespace")
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := p.handler.ops.TerminateWorkflowExecution(r.Context(), namespace, workflowID, "", "terminated via API")
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": fmt.Sprintf("failed to terminate: %v", err)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Stream (delegate to existing SSE handler) ---
|
||||||
|
|
||||||
|
func (p *PoimenHandler) handleStream(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path := r.Header.Get("X-Upstream-Path")
|
||||||
|
if path == "" {
|
||||||
|
path = r.URL.Path
|
||||||
|
}
|
||||||
|
// Remove /stream suffix
|
||||||
|
cleanPath := strings.TrimSuffix(path, "/stream")
|
||||||
|
workflowID := extractWorkflowID(cleanPath)
|
||||||
|
if workflowID == "" {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "workflow_id required in path"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set query params for the SSE handler
|
||||||
|
q := r.URL.Query()
|
||||||
|
q.Set("workflow_id", workflowID)
|
||||||
|
if q.Get("namespace") == "" {
|
||||||
|
q.Set("namespace", "default")
|
||||||
|
}
|
||||||
|
r.URL.RawQuery = q.Encode()
|
||||||
|
|
||||||
|
p.handler.StreamWorkflowEvents(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ---
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, data interface{}) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
json.NewEncoder(w).Encode(data) //nolint:errcheck
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
package temporal
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SSEEvent represents a Server-Sent Event
|
||||||
|
type SSEEvent struct {
|
||||||
|
Event string `json:"event"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamWorkflowEvents streams workflow execution history as SSE events.
|
||||||
|
// Polls Temporal GetWorkflowExecutionHistory every 2s and sends new events.
|
||||||
|
// Sends heartbeat every 15s. Closes on workflow completion or client disconnect.
|
||||||
|
func (h *Handler) StreamWorkflowEvents(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Only GET allowed
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract workflow_id from query params
|
||||||
|
workflowID := r.URL.Query().Get("workflow_id")
|
||||||
|
if workflowID == "" {
|
||||||
|
http.Error(w, `{"error":"workflow_id query parameter required"}`, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runID := r.URL.Query().Get("run_id")
|
||||||
|
namespace := r.URL.Query().Get("namespace")
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check gRPC client
|
||||||
|
if h.grpcClient == nil {
|
||||||
|
http.Error(w, `{"error":"Temporal server not available"}`, http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set SSE headers
|
||||||
|
flusher, ok := w.(http.Flusher)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
w.Header().Set("X-Accel-Buffering", "no") // disable nginx buffering
|
||||||
|
|
||||||
|
// Use request context for cancellation (client disconnect)
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
var lastEventID int64
|
||||||
|
pollTicker := time.NewTicker(2 * time.Second)
|
||||||
|
heartbeatTicker := time.NewTicker(15 * time.Second)
|
||||||
|
defer pollTicker.Stop()
|
||||||
|
defer heartbeatTicker.Stop()
|
||||||
|
|
||||||
|
// Send initial connected event
|
||||||
|
writeSSE(w, flusher, "connected", map[string]interface{}{
|
||||||
|
"workflow_id": workflowID,
|
||||||
|
"run_id": runID,
|
||||||
|
"namespace": namespace,
|
||||||
|
"timestamp": time.Now().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
// Client disconnected
|
||||||
|
return
|
||||||
|
|
||||||
|
case <-heartbeatTicker.C:
|
||||||
|
writeSSE(w, flusher, "heartbeat", map[string]string{
|
||||||
|
"timestamp": time.Now().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
|
||||||
|
case <-pollTicker.C:
|
||||||
|
events, workflowDone, err := h.pollNewEvents(ctx, namespace, workflowID, runID, lastEventID)
|
||||||
|
if err != nil {
|
||||||
|
writeSSE(w, flusher, "error", map[string]string{
|
||||||
|
"error": err.Error(),
|
||||||
|
"timestamp": time.Now().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, evt := range events {
|
||||||
|
writeSSE(w, flusher, evt.Event, evt.Data)
|
||||||
|
if evtData, ok := evt.Data.(map[string]interface{}); ok {
|
||||||
|
if id, ok := evtData["event_id"]; ok {
|
||||||
|
if idInt, ok := id.(int64); ok {
|
||||||
|
if idInt > lastEventID {
|
||||||
|
lastEventID = idInt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if workflowDone {
|
||||||
|
writeSSE(w, flusher, "workflow_completed", map[string]string{
|
||||||
|
"workflow_id": workflowID,
|
||||||
|
"timestamp": time.Now().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pollNewEvents fetches workflow history from Temporal and returns new events since lastEventID.
|
||||||
|
// Returns (events, workflowDone, error).
|
||||||
|
func (h *Handler) pollNewEvents(ctx context.Context, namespace, workflowID, runID string, lastEventID int64) ([]SSEEvent, bool, error) {
|
||||||
|
pollCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
grpcImpl := NewWorkflowGRPCImpl(h.grpcClient)
|
||||||
|
result, err := grpcImpl.GetWorkflowExecutionHistory(pollCtx, namespace, workflowID, runID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, fmt.Errorf("failed to get history: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
eventsRaw, ok := result["events"]
|
||||||
|
if !ok {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
events, ok := eventsRaw.([]map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var sseEvents []SSEEvent
|
||||||
|
workflowDone := false
|
||||||
|
|
||||||
|
for _, evt := range events {
|
||||||
|
eventID, _ := evt["event_id"].(int64)
|
||||||
|
if eventID <= lastEventID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// operations_grpc.go stores event type under "type" key
|
||||||
|
eventType, _ := evt["type"].(string)
|
||||||
|
sseEvent := mapTemporalEvent(eventType, evt)
|
||||||
|
if sseEvent != nil {
|
||||||
|
sseEvents = append(sseEvents, *sseEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
if isTerminalEvent(eventType) {
|
||||||
|
workflowDone = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sseEvents, workflowDone, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// mapTemporalEvent converts a Temporal history event to an SSE event.
|
||||||
|
func mapTemporalEvent(eventType string, evt map[string]interface{}) *SSEEvent {
|
||||||
|
data := map[string]interface{}{
|
||||||
|
"event_id": evt["event_id"],
|
||||||
|
"event_type": eventType,
|
||||||
|
"timestamp": evt["timestamp"],
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED"):
|
||||||
|
return &SSEEvent{Event: "activity_scheduled", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_ACTIVITY_TASK_STARTED"):
|
||||||
|
return &SSEEvent{Event: "activity_started", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_ACTIVITY_TASK_COMPLETED"):
|
||||||
|
return &SSEEvent{Event: "activity_completed", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_ACTIVITY_TASK_FAILED"):
|
||||||
|
return &SSEEvent{Event: "activity_failed", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_ACTIVITY_TASK_TIMED_OUT"):
|
||||||
|
return &SSEEvent{Event: "activity_timed_out", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED"):
|
||||||
|
return &SSEEvent{Event: "workflow_started", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED"):
|
||||||
|
return &SSEEvent{Event: "workflow_completed", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_FAILED"):
|
||||||
|
return &SSEEvent{Event: "workflow_failed", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT"):
|
||||||
|
return &SSEEvent{Event: "workflow_timed_out", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED"):
|
||||||
|
return &SSEEvent{Event: "workflow_canceled", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED"):
|
||||||
|
return &SSEEvent{Event: "workflow_terminated", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_CHILD_WORKFLOW"):
|
||||||
|
return &SSEEvent{Event: "child_workflow", Data: data}
|
||||||
|
case strings.Contains(eventType, "EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED"):
|
||||||
|
return &SSEEvent{Event: "workflow_signaled", Data: data}
|
||||||
|
default:
|
||||||
|
// Skip internal/uninteresting events (timer, decision task, etc.)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isTerminalEvent returns true if the event type indicates workflow completion.
|
||||||
|
func isTerminalEvent(eventType string) bool {
|
||||||
|
return strings.Contains(eventType, "COMPLETED") ||
|
||||||
|
strings.Contains(eventType, "FAILED") ||
|
||||||
|
strings.Contains(eventType, "TIMED_OUT") ||
|
||||||
|
strings.Contains(eventType, "CANCELED") ||
|
||||||
|
strings.Contains(eventType, "TERMINATED")
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeSSE writes a single SSE event to the response writer.
|
||||||
|
func writeSSE(w http.ResponseWriter, flusher http.Flusher, event string, data interface{}) {
|
||||||
|
jsonData, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, string(jsonData))
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user