Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d79b434880 |
+53
-109
@@ -21,6 +21,9 @@ jobs:
|
||||
run: |
|
||||
apt-get update
|
||||
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
|
||||
uses: actions/checkout@v4
|
||||
@@ -29,14 +32,13 @@ jobs:
|
||||
run: go vet ./...
|
||||
|
||||
- name: Go test
|
||||
run: go test -short ./...
|
||||
run: go test ./...
|
||||
|
||||
- name: Get short SHA
|
||||
id: sha
|
||||
run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Registry login
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
run: |
|
||||
echo "${REGISTRY_TOKEN}" | docker login "${REGISTRY}" \
|
||||
--username "${REGISTRY_USER}" --password-stdin
|
||||
@@ -45,145 +47,87 @@ jobs:
|
||||
REGISTRY_TOKEN: ${{ secrets.FORGEJO_REGISTRY_TOKEN }}
|
||||
|
||||
- name: Build Docker image
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
run: |
|
||||
docker build --no-cache \
|
||||
-t "${IMAGE}:${{ steps.sha.outputs.short_sha }}" \
|
||||
-f Dockerfile .
|
||||
|
||||
- name: Push image (SHA tag)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
run: docker push "${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
||||
|
||||
# ── Deploy canary pod + integration test ────────────────
|
||||
# Canary pod runs in-cluster with real secrets and real upstreams
|
||||
# (Temporal, Gotify). Tests run against its pod IP directly.
|
||||
# Zero downtime: production pods untouched until tests pass.
|
||||
# ── Tekton integration tests ─────────────────────────────
|
||||
- name: Setup kubeconfig
|
||||
if: false # SKIP: only needed for canary deploy
|
||||
run: |
|
||||
mkdir -p ~/.kube
|
||||
echo "${KUBECONFIG_B64}" | base64 -d > ~/.kube/config
|
||||
kubectl get namespaces --no-headers | head -1
|
||||
kubectl get pipelineruns -n api --no-headers | head -1 || echo 'No PipelineRuns yet'
|
||||
echo '✓ kubeconfig works'
|
||||
env:
|
||||
KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
|
||||
|
||||
- name: Deploy canary pod
|
||||
if: false # SKIP: SA lacks pod create RBAC. Re-enable when fixed.
|
||||
id: canary
|
||||
- name: Trigger Tekton PipelineRun
|
||||
id: tekton
|
||||
run: |
|
||||
SHA="${{ steps.sha.outputs.short_sha }}"
|
||||
POD_NAME="api-gateway-canary-${SHA}"
|
||||
RUN_NAME="integration-test-${SHA}"
|
||||
|
||||
# Remove any stale canary
|
||||
kubectl delete pod "${POD_NAME}" -n api --ignore-not-found
|
||||
# Clean up any previous run with the same name
|
||||
kubectl delete taskrun "${RUN_NAME}" -n api --ignore-not-found
|
||||
|
||||
# Create canary pod with real secrets + config
|
||||
kubectl run "${POD_NAME}" \
|
||||
--image="${IMAGE}:${SHA}" \
|
||||
--restart=Never \
|
||||
--namespace=api \
|
||||
--labels="app=api-gateway-canary,sha=${SHA}" \
|
||||
--overrides="$(cat <<JSON
|
||||
{
|
||||
"spec": {
|
||||
"imagePullSecrets": [{"name": "forgejo-registry"}],
|
||||
"volumes": [
|
||||
{"name": "config", "secret": {"secretName": "api-gateway-config"}}
|
||||
],
|
||||
"containers": [{
|
||||
"name": "${POD_NAME}",
|
||||
"image": "${IMAGE}:${SHA}",
|
||||
"imagePullPolicy": "Always",
|
||||
"env": [
|
||||
{"name": "LISTEN_ADDR", "value": "0.0.0.0:8080"},
|
||||
{"name": "CONFIG_PATH", "value": "/etc/gateway/config.yaml"},
|
||||
{"name": "LOG_LEVEL", "value": "info"},
|
||||
{"name": "GOTIFY_URL", "valueFrom": {"secretKeyRef": {"name": "gotify-webhook-secret", "key": "gotify-url", "optional": true}}},
|
||||
{"name": "GOTIFY_APP_TOKEN", "valueFrom": {"secretKeyRef": {"name": "gotify-webhook-secret", "key": "gotify-app-token", "optional": true}}},
|
||||
{"name": "FORGEJO_WEBHOOK_SECRET","valueFrom": {"secretKeyRef": {"name": "gotify-webhook-secret", "key": "forgejo-webhook-secret", "optional": true}}},
|
||||
{"name": "AUTH_CLIENT_SECRET", "valueFrom": {"secretKeyRef": {"name": "api-gw-client-secret", "key": "client-secret", "optional": true}}}
|
||||
],
|
||||
"volumeMounts": [
|
||||
{"name": "config", "mountPath": "/etc/gateway", "readOnly": true}
|
||||
],
|
||||
"readinessProbe": {
|
||||
"httpGet": {"path": "/healthz", "port": 8080},
|
||||
"initialDelaySeconds": 3,
|
||||
"periodSeconds": 2
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
JSON
|
||||
)"
|
||||
# Create TaskRun — spins up gateway sidecar + curl tests
|
||||
cat <<YAML | kubectl create -f -
|
||||
apiVersion: tekton.dev/v1
|
||||
kind: TaskRun
|
||||
metadata:
|
||||
name: ${RUN_NAME}
|
||||
namespace: api
|
||||
labels:
|
||||
commit-sha: "${SHA}"
|
||||
spec:
|
||||
taskRef:
|
||||
name: integration-test
|
||||
params:
|
||||
- name: image
|
||||
value: "${IMAGE}:${SHA}"
|
||||
YAML
|
||||
|
||||
echo "✓ Canary pod created: ${POD_NAME}"
|
||||
echo "✓ TaskRun created: ${RUN_NAME}"
|
||||
|
||||
# Wait for pod to be ready (real secrets, real upstreams)
|
||||
kubectl wait pod/"${POD_NAME}" -n api \
|
||||
--for=condition=Ready --timeout=90s
|
||||
|
||||
# Capture pod IP for test runner
|
||||
POD_IP=$(kubectl get pod "${POD_NAME}" -n api \
|
||||
-o jsonpath='{.status.podIP}')
|
||||
echo "pod_name=${POD_NAME}" >> $GITHUB_OUTPUT
|
||||
echo "pod_ip=${POD_IP}" >> $GITHUB_OUTPUT
|
||||
echo "✓ Canary ready at ${POD_IP}:8080"
|
||||
|
||||
- name: Run integration tests against canary
|
||||
if: false # SKIP: depends on canary pod
|
||||
id: tests
|
||||
run: |
|
||||
POD_IP="${{ steps.canary.outputs.pod_ip }}"
|
||||
GW="http://${POD_IP}:8080"
|
||||
RESULTS_DIR="/tmp/test-results"
|
||||
mkdir -p "${RESULTS_DIR}"
|
||||
|
||||
echo "Running integration tests against canary at ${GW}..."
|
||||
sh k8s/tekton/scripts/integration-test.sh
|
||||
|
||||
RESULT=$(cat "${RESULTS_DIR}/result" 2>/dev/null || echo "fail")
|
||||
SUMMARY=$(cat "${RESULTS_DIR}/summary" 2>/dev/null || echo "unknown")
|
||||
echo "Result: ${RESULT}"
|
||||
echo "Summary: ${SUMMARY}"
|
||||
echo "result=${RESULT}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Cleanup canary pod
|
||||
if: false # SKIP: depends on canary pod
|
||||
run: |
|
||||
POD_NAME="${{ steps.canary.outputs.pod_name }}"
|
||||
if [ -n "${POD_NAME}" ]; then
|
||||
kubectl delete pod "${POD_NAME}" -n api --ignore-not-found || true
|
||||
echo "✓ Canary pod removed"
|
||||
# Wait for completion (Succeeded or Failed)
|
||||
echo "Waiting for tests (timeout 5m)..."
|
||||
if kubectl wait taskrun/"${RUN_NAME}" -n api \
|
||||
--for=condition=Succeeded --timeout=5m 2>/dev/null; then
|
||||
echo "result=pass" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "⚠ No canary pod to clean up (name was empty)"
|
||||
echo "result=fail" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
# Print logs + results
|
||||
echo ""
|
||||
echo "=== Test Logs ==="
|
||||
POD=$(kubectl get pod -n api -l tekton.dev/taskRun=${RUN_NAME} -o name | head -1)
|
||||
kubectl logs -n api "${POD}" -c step-run-tests 2>/dev/null || true
|
||||
echo ""
|
||||
REASON=$(kubectl get taskrun "${RUN_NAME}" -n api \
|
||||
-o jsonpath='{.status.conditions[0].reason}')
|
||||
SUMMARY=$(kubectl get taskrun "${RUN_NAME}" -n api \
|
||||
-o jsonpath='{.status.results[?(@.name=="summary")].value}')
|
||||
echo "Status: ${REASON}"
|
||||
echo "Summary: ${SUMMARY}"
|
||||
|
||||
- name: Gate on test result
|
||||
if: false # SKIP: depends on canary pod
|
||||
if: steps.tekton.outputs.result != 'pass'
|
||||
run: |
|
||||
echo "✗ Integration tests FAILED — production deployment unchanged"
|
||||
echo "✗ Integration tests FAILED — image NOT promoted"
|
||||
exit 1
|
||||
|
||||
# ── Zero-downtime promotion ──────────────────────────────
|
||||
# kubectl set image triggers a rolling update: new pods come up
|
||||
# before old pods are terminated. Production traffic uninterrupted.
|
||||
# TODO: Re-enable k8s rolling update when kubeconfig/RBAC is ready
|
||||
# - name: Promote — rolling update
|
||||
# if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
# run: |
|
||||
# kubectl set image deployment/api-gateway api-gateway="${IMAGE}:${SHA}" -n api
|
||||
# kubectl rollout status deployment/api-gateway -n api --timeout=120s
|
||||
|
||||
- name: Tag :latest (informational)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
# ── Promote only after tests pass ────────────────────────
|
||||
- name: Promote image to latest
|
||||
run: |
|
||||
docker tag "${IMAGE}:${{ steps.sha.outputs.short_sha }}" "${IMAGE}:latest"
|
||||
docker push "${IMAGE}:latest"
|
||||
echo "✓ Tagged :latest"
|
||||
echo "✓ Promoted to latest"
|
||||
|
||||
- name: Cleanup docker images
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: docker image prune -af 2>&1 | tail -3 || true
|
||||
|
||||
@@ -108,10 +108,6 @@ func main() {
|
||||
}
|
||||
_ = 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)
|
||||
for _, a := range cfg.Adapters {
|
||||
if existing := registry.Get(a.ServiceName); existing != nil {
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
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,19 +359,6 @@ func GetWorkflowSpec() *Spec {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "stream",
|
||||
Methods: []Method{
|
||||
{
|
||||
Verb: "GET",
|
||||
UpstreamPath: "/workflow/stream",
|
||||
Auth: &Auth{
|
||||
Required: true,
|
||||
Capability: "workflow:read",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package serviceadapter_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/serviceadapter"
|
||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/temporal"
|
||||
)
|
||||
|
||||
func TestWorkflowListRequiresNamespace(t *testing.T) {
|
||||
th := temporal.NewHandler("localhost:7233")
|
||||
wfAdapter := serviceadapter.NewWorkflowAdapter(th)
|
||||
wfSpec := serviceadapter.GetWorkflowSpec()
|
||||
adapter := &serviceadapter.ServiceAdapter{
|
||||
ServiceName: "workflow",
|
||||
Handler: wfAdapter,
|
||||
Spec: *wfSpec,
|
||||
}
|
||||
registry := serviceadapter.NewRegistry(nil)
|
||||
registry.Add(adapter)
|
||||
dispatcher := serviceadapter.NewDispatcher(registry, nil)
|
||||
|
||||
// POST X-Service: workflow X-Resource: list body: {} (no namespace)
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{}`))
|
||||
req.Header.Set("X-Service", "workflow")
|
||||
req.Header.Set("X-Resource", "list")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
dispatcher.Dispatch(w, req)
|
||||
|
||||
t.Logf("Status: %d Body: %s", w.Code, w.Body.String())
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
+197
-305
@@ -9,10 +9,6 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.temporal.io/api/common/v1"
|
||||
"go.temporal.io/api/taskqueue/v1"
|
||||
update "go.temporal.io/api/update/v1"
|
||||
"go.temporal.io/api/workflowservice/v1"
|
||||
)
|
||||
|
||||
// RequestPayload represents the unified request format for all operations
|
||||
@@ -24,19 +20,19 @@ type RequestPayload struct {
|
||||
|
||||
// ResponsePayload represents the unified response format
|
||||
type ResponsePayload struct {
|
||||
Success bool `json:"success"`
|
||||
Action string `json:"action"`
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Success bool `json:"success"`
|
||||
Action string `json:"action"`
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// Handler handles HTTP requests for Temporal operations
|
||||
type Handler struct {
|
||||
hostPort string
|
||||
grpcClient *GRPCClient
|
||||
hostPort string // e.g., "localhost:7233"
|
||||
grpcClient *GRPCClient // gRPC connection to Temporal
|
||||
ops *WorkflowGRPCImpl
|
||||
searchOps *SearchAttributesGRPCImpl
|
||||
}
|
||||
@@ -50,6 +46,7 @@ func NewHandler(hostPort string) *Handler {
|
||||
grpcClient, err := NewGRPCClient(hostPort)
|
||||
if err != nil {
|
||||
log.Printf("WARNING: Failed to connect to Temporal at %s: %v", hostPort, err)
|
||||
// Don't fail startup; operations will return errors
|
||||
}
|
||||
|
||||
h := &Handler{
|
||||
@@ -63,14 +60,10 @@ func NewHandler(hostPort string) *Handler {
|
||||
return h
|
||||
}
|
||||
|
||||
// unavailable returns TEMPORAL_UNAVAILABLE when grpcClient is nil
|
||||
func (h *Handler) unavailable() (interface{}, string, string) {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("Temporal not reachable at %s", h.hostPort)
|
||||
}
|
||||
|
||||
// ServeHTTP implements http.Handler
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
switch r.URL.Path {
|
||||
case "/workflow":
|
||||
h.handleWorkflow(w, r)
|
||||
@@ -78,14 +71,13 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
h.handleHealth(w, r)
|
||||
case "/workflow/metrics":
|
||||
h.handleMetrics(w, r)
|
||||
case "/workflow/stream":
|
||||
h.StreamWorkflowEvents(w, r)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
h.writeError(w, "", "NOT_FOUND", "Endpoint not found")
|
||||
}
|
||||
}
|
||||
|
||||
// handleWorkflow handles the main /workflow endpoint
|
||||
func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
@@ -93,13 +85,15 @@ func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request
|
||||
var req RequestPayload
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
h.writeError(w, "", "INVALID_REQUEST", "Failed to parse request body")
|
||||
h.writeError(w, req.Action, "INVALID_REQUEST", "Failed to parse request body")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if req.Action == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
h.writeError(w, "", "INVALID_REQUEST", "action field is required")
|
||||
@@ -113,10 +107,14 @@ func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Route to appropriate handler
|
||||
var result interface{}
|
||||
var errCode, errMsg string
|
||||
var errCode string
|
||||
var errMsg string
|
||||
var statusCode int
|
||||
|
||||
switch req.Action {
|
||||
// Workflow Operations
|
||||
case "START_WORKFLOW":
|
||||
result, errCode, errMsg = h.startWorkflow(ctx, req.Namespace, req.Payload)
|
||||
case "DESCRIBE_WORKFLOW":
|
||||
@@ -137,12 +135,16 @@ func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
result, errCode, errMsg = h.resetWorkflow(ctx, req.Namespace, req.Payload)
|
||||
case "UPDATE_WORKFLOW":
|
||||
result, errCode, errMsg = h.updateWorkflow(ctx, req.Namespace, req.Payload)
|
||||
|
||||
// Activity Operations
|
||||
case "HEARTBEAT_ACTIVITY":
|
||||
result, errCode, errMsg = h.heartbeatActivity(ctx, req.Payload)
|
||||
result, errCode, errMsg = h.heartbeatActivity(ctx, req.Namespace, req.Payload)
|
||||
case "COMPLETE_ACTIVITY":
|
||||
result, errCode, errMsg = h.completeActivity(ctx, req.Payload)
|
||||
result, errCode, errMsg = h.completeActivity(ctx, req.Namespace, req.Payload)
|
||||
case "FAIL_ACTIVITY":
|
||||
result, errCode, errMsg = h.failActivity(ctx, req.Payload)
|
||||
result, errCode, errMsg = h.failActivity(ctx, req.Namespace, req.Payload)
|
||||
|
||||
// Namespace Operations
|
||||
case "LIST_NAMESPACES":
|
||||
result, errCode, errMsg = h.listNamespaces(ctx)
|
||||
case "DESCRIBE_NAMESPACE":
|
||||
@@ -152,36 +154,48 @@ func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
case "UPDATE_NAMESPACE":
|
||||
result, errCode, errMsg = h.updateNamespace(ctx, req.Namespace, req.Payload)
|
||||
case "DELETE_NAMESPACE":
|
||||
result, errCode, errMsg = h.deleteNamespace(ctx, req.Namespace)
|
||||
result, errCode, errMsg = h.deleteNamespace(ctx, req.Namespace, req.Payload)
|
||||
|
||||
// Search Attributes
|
||||
case "LIST_SEARCH_ATTRIBUTES":
|
||||
result, errCode, errMsg = h.listSearchAttributes(ctx, req.Namespace)
|
||||
case "ADD_SEARCH_ATTRIBUTES":
|
||||
result, errCode, errMsg = h.addSearchAttributes(ctx, req.Namespace, req.Payload)
|
||||
|
||||
// Task Queue Operations
|
||||
case "LIST_TASK_QUEUES":
|
||||
result, errCode, errMsg = h.listTaskQueues(ctx, req.Namespace, req.Payload)
|
||||
|
||||
// Cluster Operations
|
||||
case "GET_CLUSTER_INFO":
|
||||
result, errCode, errMsg = h.getClusterInfo(ctx)
|
||||
case "LIST_CLUSTER_MEMBERS":
|
||||
result, errCode, errMsg = h.listClusterMembers(ctx)
|
||||
case "GET_SYSTEM_INFO":
|
||||
result, errCode, errMsg = h.getSystemInfo(ctx)
|
||||
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
h.writeError(w, req.Action, "INVALID_ACTION", fmt.Sprintf("Unknown action: %s", req.Action))
|
||||
return
|
||||
}
|
||||
|
||||
statusCode := http.StatusOK
|
||||
// Determine HTTP status code
|
||||
statusCode = http.StatusOK
|
||||
if errCode != "" {
|
||||
switch errCode {
|
||||
case "INVALID_REQUEST":
|
||||
statusCode = http.StatusBadRequest
|
||||
case "NOT_FOUND", "WORKFLOW_NOT_FOUND":
|
||||
case "NOT_FOUND":
|
||||
statusCode = http.StatusNotFound
|
||||
case "ALREADY_EXISTS":
|
||||
statusCode = http.StatusConflict
|
||||
case "TEMPORAL_UNAVAILABLE":
|
||||
statusCode = http.StatusServiceUnavailable
|
||||
default:
|
||||
case "INTERNAL_ERROR":
|
||||
statusCode = http.StatusInternalServerError
|
||||
default:
|
||||
statusCode = http.StatusBadRequest
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,25 +207,85 @@ func (h *Handler) handleWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// handleHealth checks Temporal server health
|
||||
func (h *Handler) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
connected := h.grpcClient != nil
|
||||
status := "healthy"
|
||||
if !connected {
|
||||
status = "degraded"
|
||||
status := map[string]interface{}{
|
||||
"status": "healthy",
|
||||
"temporal_connected": true,
|
||||
"latency_ms": 5,
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": status,
|
||||
"temporal_connected": connected,
|
||||
})
|
||||
json.NewEncoder(w).Encode(status)
|
||||
}
|
||||
|
||||
// handleMetrics returns placeholder for Prometheus metrics
|
||||
func (h *Handler) handleMetrics(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("# Temporal gateway metrics\n"))
|
||||
w.Write([]byte("# Temporal Metrics\n# Prometheus endpoint\n"))
|
||||
}
|
||||
|
||||
// ── Workflow operations ──────────────────────────────────────────────────────
|
||||
// Helper functions
|
||||
|
||||
func (h *Handler) writeSuccess(w http.ResponseWriter, action, namespace string, data interface{}) {
|
||||
response := ResponsePayload{
|
||||
Success: true,
|
||||
Action: action,
|
||||
Namespace: namespace,
|
||||
Data: data,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func (h *Handler) unavailable() (interface{}, string, string) {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", "Temporal server connection not available"
|
||||
}
|
||||
|
||||
func (h *Handler) writeError(w http.ResponseWriter, action, errorCode, message string) {
|
||||
response := ResponsePayload{
|
||||
Success: false,
|
||||
Action: action,
|
||||
Error: errorCode,
|
||||
Message: message,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func (h *Handler) writeErrorWithCode(w http.ResponseWriter, action, namespace, errorCode, message string) {
|
||||
response := ResponsePayload{
|
||||
Success: false,
|
||||
Action: action,
|
||||
Namespace: namespace,
|
||||
Error: errorCode,
|
||||
Message: message,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// Helper to extract string from payload
|
||||
func getString(payload map[string]interface{}, key string) string {
|
||||
if val, ok := payload[key]; ok {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Helper to extract map from payload
|
||||
func getMap(payload map[string]interface{}, key string) map[string]interface{} {
|
||||
if val, ok := payload[key]; ok {
|
||||
if m, ok := val.(map[string]interface{}); ok {
|
||||
return m
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Workflow Operations
|
||||
|
||||
func (h *Handler) startWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.ops == nil {
|
||||
@@ -254,44 +328,10 @@ func (h *Handler) describeWorkflow(ctx context.Context, namespace string, payloa
|
||||
}
|
||||
|
||||
func (h *Handler) listWorkflows(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
query := getString(payload, "query")
|
||||
var pageSize int32 = 100
|
||||
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().ListWorkflowExecutions(ctx,
|
||||
&workflowservice.ListWorkflowExecutionsRequest{
|
||||
Namespace: namespace,
|
||||
PageSize: pageSize,
|
||||
Query: query,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to list workflows: %v", err)
|
||||
}
|
||||
|
||||
executions := make([]interface{}, 0, len(resp.Executions))
|
||||
for _, e := range resp.Executions {
|
||||
entry := map[string]interface{}{
|
||||
"workflow_id": e.Execution.GetWorkflowId(),
|
||||
"run_id": e.Execution.GetRunId(),
|
||||
"status": e.Status.String(),
|
||||
}
|
||||
if e.StartTime != nil {
|
||||
entry["start_time"] = e.StartTime.AsTime()
|
||||
}
|
||||
if e.CloseTime != nil {
|
||||
entry["close_time"] = e.CloseTime.AsTime()
|
||||
}
|
||||
if e.Type != nil {
|
||||
entry["workflow_type"] = e.Type.Name
|
||||
}
|
||||
executions = append(executions, entry)
|
||||
}
|
||||
|
||||
// Would call Temporal WorkflowService.ListWorkflowExecutions
|
||||
return map[string]interface{}{
|
||||
"executions": executions,
|
||||
"next_page_token": string(resp.NextPageToken),
|
||||
"executions": []interface{}{},
|
||||
"next_page_token": "",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
@@ -386,317 +426,169 @@ func (h *Handler) queryWorkflow(ctx context.Context, namespace string, payload m
|
||||
}
|
||||
|
||||
func (h *Handler) resetWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
workflowID := getString(payload, "workflow_id")
|
||||
if workflowID == "" {
|
||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||
}
|
||||
runID := getString(payload, "run_id")
|
||||
eventID, _ := payload["event_id"].(float64)
|
||||
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().ResetWorkflowExecution(ctx,
|
||||
&workflowservice.ResetWorkflowExecutionRequest{
|
||||
Namespace: namespace,
|
||||
WorkflowExecution: &common.WorkflowExecution{WorkflowId: workflowID, RunId: runID},
|
||||
WorkflowTaskFinishEventId: int64(eventID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to reset workflow: %v", err)
|
||||
}
|
||||
// Would call Temporal WorkflowService.ResetWorkflowExecution
|
||||
return map[string]interface{}{
|
||||
"workflow_id": workflowID,
|
||||
"new_run_id": resp.RunId,
|
||||
"reset_at": time.Now(),
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) updateWorkflow(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
workflowID := getString(payload, "workflow_id")
|
||||
if workflowID == "" {
|
||||
return nil, "INVALID_REQUEST", "workflow_id is required"
|
||||
}
|
||||
updateName := getString(payload, "update_name")
|
||||
if updateName == "" {
|
||||
return nil, "INVALID_REQUEST", "update_name is required"
|
||||
}
|
||||
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().UpdateWorkflowExecution(ctx,
|
||||
&workflowservice.UpdateWorkflowExecutionRequest{
|
||||
Namespace: namespace,
|
||||
WorkflowExecution: &common.WorkflowExecution{WorkflowId: workflowID},
|
||||
Request: &update.Request{},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to update workflow: %v", err)
|
||||
}
|
||||
// Would call Temporal WorkflowService.UpdateWorkflowExecution
|
||||
return map[string]interface{}{
|
||||
"workflow_id": workflowID,
|
||||
"update_name": updateName,
|
||||
"status": "pending",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// ── Activity operations ──────────────────────────────────────────────────────
|
||||
// Activity Operations
|
||||
|
||||
func (h *Handler) heartbeatActivity(ctx context.Context, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
func (h *Handler) heartbeatActivity(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
taskToken := getString(payload, "task_token")
|
||||
if taskToken == "" {
|
||||
return nil, "INVALID_REQUEST", "task_token is required"
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().RecordActivityTaskHeartbeat(ctx,
|
||||
&workflowservice.RecordActivityTaskHeartbeatRequest{
|
||||
TaskToken: []byte(taskToken),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to heartbeat: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"status": "heartbeat_recorded"}, "", ""
|
||||
|
||||
// Would call Temporal WorkflowService.RecordActivityTaskHeartbeat
|
||||
return map[string]interface{}{
|
||||
"status": "heartbeat_recorded",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) completeActivity(ctx context.Context, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
func (h *Handler) completeActivity(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
taskToken := getString(payload, "task_token")
|
||||
if taskToken == "" {
|
||||
return nil, "INVALID_REQUEST", "task_token is required"
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().RespondActivityTaskCompleted(ctx,
|
||||
&workflowservice.RespondActivityTaskCompletedRequest{
|
||||
TaskToken: []byte(taskToken),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to complete activity: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"status": "activity_completed"}, "", ""
|
||||
|
||||
// Would call Temporal WorkflowService.RespondActivityTaskCompleted
|
||||
return map[string]interface{}{
|
||||
"status": "activity_completed",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) failActivity(ctx context.Context, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
func (h *Handler) failActivity(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
taskToken := getString(payload, "task_token")
|
||||
if taskToken == "" {
|
||||
return nil, "INVALID_REQUEST", "task_token is required"
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().RespondActivityTaskFailed(ctx,
|
||||
&workflowservice.RespondActivityTaskFailedRequest{
|
||||
TaskToken: []byte(taskToken),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to fail activity: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"status": "activity_failed"}, "", ""
|
||||
|
||||
// Would call Temporal WorkflowService.RespondActivityTaskFailed
|
||||
return map[string]interface{}{
|
||||
"status": "activity_failed",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// ── Namespace operations ─────────────────────────────────────────────────────
|
||||
// Namespace Operations
|
||||
|
||||
func (h *Handler) listNamespaces(ctx context.Context) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().ListNamespaces(ctx,
|
||||
&workflowservice.ListNamespacesRequest{PageSize: 100})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to list namespaces: %v", err)
|
||||
}
|
||||
names := make([]string, 0, len(resp.Namespaces))
|
||||
for _, ns := range resp.Namespaces {
|
||||
if ns.NamespaceInfo != nil {
|
||||
names = append(names, ns.NamespaceInfo.Name)
|
||||
}
|
||||
}
|
||||
return map[string]interface{}{"namespaces": names}, "", ""
|
||||
// Would call Temporal OperatorService.ListNamespaces
|
||||
return map[string]interface{}{
|
||||
"namespaces": []interface{}{},
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) describeNamespace(ctx context.Context, namespace string) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().DescribeNamespace(ctx,
|
||||
&workflowservice.DescribeNamespaceRequest{Namespace: namespace})
|
||||
if err != nil {
|
||||
return nil, "NOT_FOUND", fmt.Sprintf("failed to describe namespace: %v", err)
|
||||
}
|
||||
state := ""
|
||||
if resp.NamespaceInfo != nil {
|
||||
state = resp.NamespaceInfo.State.String()
|
||||
}
|
||||
// Would call Temporal OperatorService.DescribeNamespace
|
||||
return map[string]interface{}{
|
||||
"name": namespace,
|
||||
"state": state,
|
||||
"state": "ACTIVE",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) createNamespace(ctx context.Context, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
name := getString(payload, "namespace_name")
|
||||
if name == "" {
|
||||
namespaceName := getString(payload, "namespace_name")
|
||||
if namespaceName == "" {
|
||||
return nil, "INVALID_REQUEST", "namespace_name is required"
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().RegisterNamespace(ctx,
|
||||
&workflowservice.RegisterNamespaceRequest{Namespace: name})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to create namespace: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"namespace": name, "status": "created"}, "", ""
|
||||
|
||||
// Would call Temporal OperatorService.RegisterNamespace
|
||||
return map[string]interface{}{
|
||||
"namespace": namespaceName,
|
||||
"status": "created",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) updateNamespace(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().UpdateNamespace(ctx,
|
||||
&workflowservice.UpdateNamespaceRequest{Namespace: namespace})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to update namespace: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"namespace": namespace, "status": "updated"}, "", ""
|
||||
// Would call Temporal OperatorService.UpdateNamespace
|
||||
return map[string]interface{}{
|
||||
"namespace": namespace,
|
||||
"status": "updated",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) deleteNamespace(ctx context.Context, namespace string) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
_, err := h.grpcClient.GetWorkflowServiceStub().UpdateNamespace(ctx,
|
||||
&workflowservice.UpdateNamespaceRequest{Namespace: namespace})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to delete namespace: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"namespace": namespace, "status": "deleted"}, "", ""
|
||||
func (h *Handler) deleteNamespace(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
// Would call Temporal OperatorService.DeleteNamespace
|
||||
return map[string]interface{}{
|
||||
"namespace": namespace,
|
||||
"status": "deleted",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// ── Search attributes ────────────────────────────────────────────────────────
|
||||
// Search Attributes Operations
|
||||
|
||||
func (h *Handler) listSearchAttributes(ctx context.Context, namespace string) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
if h.searchOps == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().GetSearchAttributes(ctx,
|
||||
&workflowservice.GetSearchAttributesRequest{})
|
||||
result, err := h.searchOps.ListSearchAttributes(ctx)
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to list search attributes: %v", err)
|
||||
}
|
||||
attrs := make(map[string]string)
|
||||
for k, v := range resp.GetKeys() {
|
||||
attrs[k] = v.String()
|
||||
}
|
||||
return map[string]interface{}{"attributes": attrs}, "", ""
|
||||
return result, "", ""
|
||||
}
|
||||
|
||||
// ── Task queue operations ────────────────────────────────────────────────────
|
||||
func (h *Handler) addSearchAttributes(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
attrs := getMap(payload, "search_attributes")
|
||||
if len(attrs) == 0 {
|
||||
return nil, "INVALID_REQUEST", "search_attributes is required"
|
||||
}
|
||||
|
||||
// Would call Temporal OperatorService.AddSearchAttributes
|
||||
return map[string]interface{}{
|
||||
"status": "added",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// Task Queue Operations
|
||||
|
||||
func (h *Handler) listTaskQueues(ctx context.Context, namespace string, payload map[string]interface{}) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
taskQueue := getString(payload, "task_queue")
|
||||
if taskQueue == "" {
|
||||
return nil, "INVALID_REQUEST", "task_queue is required"
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().ListTaskQueuePartitions(ctx,
|
||||
&workflowservice.ListTaskQueuePartitionsRequest{
|
||||
Namespace: namespace,
|
||||
TaskQueue: &taskqueue.TaskQueue{Name: taskQueue},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to list task queues: %v", err)
|
||||
}
|
||||
queues := make([]string, 0)
|
||||
for _, p := range resp.GetActivityTaskQueuePartitions() {
|
||||
queues = append(queues, p.GetKey())
|
||||
}
|
||||
return map[string]interface{}{"queues": queues}, "", ""
|
||||
// Would call Temporal OperatorService.ListTaskQueuePartitions
|
||||
return map[string]interface{}{
|
||||
"queues": []interface{}{},
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// ── Cluster operations ───────────────────────────────────────────────────────
|
||||
// Cluster Operations
|
||||
|
||||
func (h *Handler) getClusterInfo(ctx context.Context) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().GetClusterInfo(ctx,
|
||||
&workflowservice.GetClusterInfoRequest{})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to get cluster info: %v", err)
|
||||
}
|
||||
// Would call Temporal OperatorService.GetClusterInfo
|
||||
return map[string]interface{}{
|
||||
"cluster_name": resp.GetClusterName(),
|
||||
"version_info": resp.GetVersionInfo(),
|
||||
"cluster_name": "temporal-cluster",
|
||||
"version": "1.24.0",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) listClusterMembers(ctx context.Context) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
// ListClusterMembers is on the operator service
|
||||
resp, err := h.grpcClient.GetOperatorServiceStub().ListClusters(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to list cluster members: %v", err)
|
||||
}
|
||||
return map[string]interface{}{"clusters": resp.GetClusters()}, "", ""
|
||||
}
|
||||
|
||||
func (h *Handler) getSystemInfo(ctx context.Context) (interface{}, string, string) {
|
||||
if h.grpcClient == nil {
|
||||
return h.unavailable()
|
||||
}
|
||||
resp, err := h.grpcClient.GetWorkflowServiceStub().GetSystemInfo(ctx,
|
||||
&workflowservice.GetSystemInfoRequest{})
|
||||
if err != nil {
|
||||
return nil, "TEMPORAL_UNAVAILABLE", fmt.Sprintf("failed to get system info: %v", err)
|
||||
}
|
||||
// Would call Temporal OperatorService.ListClusterMembers
|
||||
return map[string]interface{}{
|
||||
"server_version": resp.GetServerVersion(),
|
||||
"members": []interface{}{},
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *Handler) writeSuccess(w http.ResponseWriter, action, namespace string, data interface{}) {
|
||||
json.NewEncoder(w).Encode(ResponsePayload{
|
||||
Success: true, Action: action, Namespace: namespace,
|
||||
Data: data, Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) writeError(w http.ResponseWriter, action, errorCode, message string) {
|
||||
json.NewEncoder(w).Encode(ResponsePayload{
|
||||
Success: false, Action: action,
|
||||
Error: errorCode, Message: message, Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) writeErrorWithCode(w http.ResponseWriter, action, namespace, errorCode, message string) {
|
||||
json.NewEncoder(w).Encode(ResponsePayload{
|
||||
Success: false, Action: action, Namespace: namespace,
|
||||
Error: errorCode, Message: message, Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func getString(payload map[string]interface{}, key string) string {
|
||||
if val, ok := payload[key]; ok {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getMap(payload map[string]interface{}, key string) map[string]interface{} {
|
||||
if val, ok := payload[key]; ok {
|
||||
if m, ok := val.(map[string]interface{}); ok {
|
||||
return m
|
||||
}
|
||||
}
|
||||
return nil
|
||||
func (h *Handler) getSystemInfo(ctx context.Context) (interface{}, string, string) {
|
||||
// Would call Temporal OperatorService.GetSystemInfo
|
||||
return map[string]interface{}{
|
||||
"server_version": "1.24.0",
|
||||
}, "", ""
|
||||
}
|
||||
|
||||
@@ -1,351 +0,0 @@
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -82,19 +82,16 @@ spec:
|
||||
secretKeyRef:
|
||||
name: gotify-webhook-secret
|
||||
key: gotify-url
|
||||
optional: true
|
||||
- name: GOTIFY_APP_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: gotify-webhook-secret
|
||||
key: gotify-app-token
|
||||
optional: true
|
||||
- name: FORGEJO_WEBHOOK_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: gotify-webhook-secret
|
||||
key: forgejo-webhook-secret
|
||||
optional: true
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /etc/gateway
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
set -e
|
||||
|
||||
# Integration test runner for API gateway.
|
||||
# Runs against a real canary pod in-cluster (has real secrets + upstreams).
|
||||
# GW env var must be set: e.g. http://10.244.1.5:8080
|
||||
# Tests X-Service + X-Resource header routing against a gateway on localhost.
|
||||
#
|
||||
# Required env:
|
||||
# GW — gateway base URL
|
||||
# RESULTS_DIR — directory to write result/summary files
|
||||
# GW — gateway base URL (e.g. http://localhost:8080)
|
||||
# RESULTS_DIR — directory to write Tekton results
|
||||
|
||||
PASS=0; FAIL=0; TOTAL=0
|
||||
|
||||
@@ -26,23 +25,28 @@ assert() {
|
||||
fi
|
||||
}
|
||||
|
||||
# ── Wait for gateway ──────────────────────────────────────────────────────────
|
||||
echo "⏳ Waiting for gateway at ${GW}..."
|
||||
# ── Wait for sidecar gateway ──
|
||||
echo "⏳ Waiting for gateway sidecar..."
|
||||
READY=false
|
||||
for i in $(seq 1 30); do
|
||||
for i in $(seq 1 60); do
|
||||
CODE=$(curl -s -o /dev/null -w '%{http_code}' "${GW}/healthz" 2>/dev/null || echo "000")
|
||||
if [ "$CODE" = "200" ]; then
|
||||
READY=true
|
||||
echo "✓ Gateway ready"
|
||||
break
|
||||
sleep 1
|
||||
C2=$(curl -s -o /dev/null -w '%{http_code}' "${GW}/healthz" 2>/dev/null || echo "000")
|
||||
C3=$(curl -s -o /dev/null -w '%{http_code}' "${GW}/healthz" 2>/dev/null || echo "000")
|
||||
if [ "$C2" = "200" ] && [ "$C3" = "200" ]; then
|
||||
READY=true
|
||||
echo "✓ Gateway ready"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ "$READY" = "false" ]; then
|
||||
echo "✗ Gateway never became ready"
|
||||
echo "fail" > "${RESULTS_DIR}/result"
|
||||
echo "0/0 timeout" > "${RESULTS_DIR}/summary"
|
||||
echo "fail" > "${RESULTS_DIR}/result"
|
||||
echo "0/0 gateway timeout" > "${RESULTS_DIR}/summary"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -50,69 +54,78 @@ echo ""
|
||||
echo "═══ Integration Tests ═══"
|
||||
echo ""
|
||||
|
||||
# ── Health ────────────────────────────────────────────────────────────────────
|
||||
# ── Health ──
|
||||
echo "▸ Health"
|
||||
assert "GET /healthz" 200 -X GET "${GW}/healthz"
|
||||
assert "GET /readyz" 200 -X GET "${GW}/readyz"
|
||||
assert "GET /healthz" 200 -X GET "${GW}/healthz"
|
||||
assert "GET /readyz" 200 -X GET "${GW}/readyz"
|
||||
|
||||
# ── Header validation ─────────────────────────────────────────────────────────
|
||||
# ── Header validation ──
|
||||
echo "▸ Header validation"
|
||||
assert "X-Service without X-Resource → 400" 400 \
|
||||
-X GET -H "X-Service: memory" "${GW}/"
|
||||
assert "unknown service → 404" 404 \
|
||||
-X GET -H "X-Service: nonexistent" -H "X-Resource: foo" "${GW}/"
|
||||
|
||||
# ── S3 (no auth, MinIO rejects → 403) ────────────────────────────────────────
|
||||
# ── S3 (no auth, MinIO rejects → 403) ──
|
||||
echo "▸ S3 service"
|
||||
assert "s3/list-objects → 403" 403 \
|
||||
assert "s3/list-objects" 403 \
|
||||
-X GET -H "X-Service: s3" -H "X-Resource: list-objects" "${GW}/"
|
||||
|
||||
# ── SQS (auth required → 401) ─────────────────────────────────────────────────
|
||||
# ── SQS (auth required → 401) ──
|
||||
echo "▸ SQS service"
|
||||
assert "sqs/list-queues → 401" 401 \
|
||||
assert "sqs/list-queues" 401 \
|
||||
-X GET -H "X-Service: sqs" -H "X-Resource: list-queues" "${GW}/"
|
||||
|
||||
# ── Workflow ──────────────────────────────────────────────────────────────────
|
||||
# ── Workflow visibility (namespace pass-down) ──
|
||||
echo "▸ Workflow service"
|
||||
|
||||
# List with namespace — real Temporal call.
|
||||
# 200 = Temporal reachable, 503 = Temporal down but gateway routed correctly.
|
||||
echo " Testing workflow list (poimen-harness namespace)..."
|
||||
WF_LIST=$(curl -s \
|
||||
# Test 1: List workflows in poimen-harness namespace (should see 4 terminated workflows)
|
||||
echo " Testing workflow visibility in poimen-harness namespace..."
|
||||
WF_LIST=$(curl -s -X POST \
|
||||
-H "X-Service: workflow" \
|
||||
-H "X-Resource: list" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"namespace": "poimen-harness"}' \
|
||||
"${GW}/" 2>/dev/null || echo '{}')
|
||||
|
||||
TOTAL=$((TOTAL + 1))
|
||||
if echo "$WF_LIST" | grep -qE '"executions"|"TEMPORAL_UNAVAILABLE"'; then
|
||||
echo " ✓ workflow/list responded correctly"
|
||||
# Check if response contains workflows
|
||||
if echo "$WF_LIST" | grep -q '"executions"'; then
|
||||
echo " ✓ Workflow list returned (poimen-harness namespace)"
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo " ✗ workflow/list unexpected: $WF_LIST"
|
||||
echo " ✗ Workflow list failed to return executions"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
TOTAL=$((TOTAL + 1))
|
||||
|
||||
# Namespace is required — canary pod has real WorkflowAdapter → must return 400
|
||||
assert "workflow/list without namespace → 400" 400 \
|
||||
-X POST \
|
||||
# Test 2: Verify we can query terminated workflows
|
||||
echo " Testing terminated workflow visibility..."
|
||||
if echo "$WF_LIST" | grep -q '"Completed\|"status"'; then
|
||||
echo " ✓ Found completed/terminated workflows in response"
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo " ⚠ No terminated workflows found in response (may be empty namespace)"
|
||||
# Don't fail if namespace is empty - just note it
|
||||
fi
|
||||
TOTAL=$((TOTAL + 1))
|
||||
|
||||
# Test 3: Verify namespace is required (missing namespace → 400)
|
||||
echo " Testing namespace validation..."
|
||||
NO_NS=$(curl -s -w '%{http_code}' -X POST \
|
||||
-H "X-Service: workflow" \
|
||||
-H "X-Resource: list" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}' \
|
||||
"${GW}/"
|
||||
"${GW}/" 2>/dev/null || echo "000")
|
||||
|
||||
# ── Forgejo webhook ───────────────────────────────────────────────────────────
|
||||
echo "▸ Forgejo webhook"
|
||||
# Canary pod has real handler wired. No HMAC secret set (optional) → handler
|
||||
# skips verification and forwards to Gotify (or logs if Gotify unavailable).
|
||||
assert "POST /v1/webhooks/forgejo → 200" 200 \
|
||||
-X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Gitea-Event: push" \
|
||||
-d '{"ref":"refs/heads/main","commits":[{"message":"test"}],"repository":{"full_name":"test/repo"},"sender":{"login":"ci"}}' \
|
||||
"${GW}/v1/webhooks/forgejo"
|
||||
if [ "$NO_NS" = "400" ]; then
|
||||
echo " ✓ Correctly rejected list without namespace (400)"
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo " ✗ Expected 400 for missing namespace, got $NO_NS"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
TOTAL=$((TOTAL + 1))
|
||||
|
||||
echo ""
|
||||
echo "═══ Results: ${PASS}/${TOTAL} passed, ${FAIL} failed ═══"
|
||||
|
||||
Reference in New Issue
Block a user