-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathexpress-worker-service.ts
More file actions
173 lines (157 loc) · 5.33 KB
/
express-worker-service.ts
File metadata and controls
173 lines (157 loc) · 5.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/**
* Express Worker Service — HTTP server + Conductor workers in one process
*
* Demonstrates running an Express.js HTTP server alongside Conductor
* task workers. The HTTP server exposes endpoints to trigger workflows
* and check worker health.
*
* Prerequisites:
* npm install express @types/express
*
* Run:
* CONDUCTOR_SERVER_URL=http://localhost:8080 npx ts-node examples/express-worker-service.ts
*
* Then:
* curl http://localhost:3000/health
* curl -X POST http://localhost:3000/execute -H 'Content-Type: application/json' -d '{"name":"World"}'
*/
import {
OrkesClients,
ConductorWorkflow,
TaskHandler,
worker,
simpleTask,
} from "../src/sdk";
import type { Task } from "../src/open-api";
import type { WorkflowExecutor } from "../src/sdk/clients/workflow";
// ── Workers ─────────────────────────────────────────────────────────
const _greetWorker = worker({ taskDefName: "svc_greet", registerTaskDef: true })(
async (task: Task) => {
const name = (task.inputData?.name as string) ?? "World";
return {
status: "COMPLETED",
outputData: { greeting: `Hello, ${name}!`, timestamp: new Date().toISOString() },
};
}
);
const _processWorker = worker({ taskDefName: "svc_process", registerTaskDef: true })(
async (task: Task) => {
const data = task.inputData?.data as string;
return {
status: "COMPLETED",
outputData: { processed: true, length: data?.length ?? 0 },
};
}
);
// ── Express server setup ────────────────────────────────────────────
async function createExpressApp(
workflowClient: WorkflowExecutor,
wf: ConductorWorkflow
) {
// Dynamic import so Express is only required when running this example
const express = (await import("express")).default;
const app = express();
app.use(express.json());
// Health endpoint
app.get("/health", (_req, res) => {
res.json({ status: "UP", workers: ["svc_greet", "svc_process"] });
});
// Execute workflow endpoint
app.post("/execute", async (req, res) => {
try {
const run = await wf.execute(req.body);
res.json({
workflowId: run.workflowId,
status: run.status,
output: run.output,
});
} catch (err) {
res.status(500).json({
error: err instanceof Error ? err.message : "Unknown error",
});
}
});
// Start workflow async (returns workflow ID)
app.post("/start", async (req, res) => {
try {
const workflowId = await wf.startWorkflow(req.body);
res.json({ workflowId });
} catch (err) {
res.status(500).json({
error: err instanceof Error ? err.message : "Unknown error",
});
}
});
// Get workflow status
app.get("/workflow/:id", async (req, res) => {
try {
const status = await workflowClient.getWorkflow(req.params.id, true);
res.json({
workflowId: status.workflowId,
status: status.status,
output: status.output,
});
} catch (err) {
res.status(500).json({
error: err instanceof Error ? err.message : "Unknown error",
});
}
});
return app;
}
// ── Main ────────────────────────────────────────────────────────────
async function main() {
const clients = await OrkesClients.from();
const workflowClient = clients.getWorkflowClient();
const client = clients.getClient();
// Register workflow
const wf = new ConductorWorkflow(workflowClient, "express_service_workflow")
.description("Workflow triggered by Express HTTP endpoints")
.add(
simpleTask("greet_ref", "svc_greet", {
name: "${workflow.input.name}",
})
)
.add(
simpleTask("process_ref", "svc_process", {
data: "${greet_ref.output.greeting}",
})
)
.outputParameters({
greeting: "${greet_ref.output.greeting}",
processed: "${process_ref.output.processed}",
});
await wf.register(true);
// Start workers
const handler = new TaskHandler({ client, scanForDecorated: true });
await handler.startWorkers();
// Start Express server
const app = await createExpressApp(workflowClient, wf);
const PORT = process.env.PORT ?? 3000;
const server = app.listen(PORT, () => {
console.log(`Express server running on http://localhost:${PORT}`);
console.log(`Workers polling for tasks...`);
console.log(`\nEndpoints:`);
console.log(` GET /health — Health check`);
console.log(` POST /execute — Execute workflow (sync)`);
console.log(` POST /start — Start workflow (async)`);
console.log(` GET /workflow/:id — Get workflow status`);
console.log(`\nExample:`);
console.log(
` curl -X POST http://localhost:${PORT}/execute -H 'Content-Type: application/json' -d '{"name":"Conductor"}'`
);
});
// Graceful shutdown
const shutdown = async () => {
console.log("\nShutting down...");
server.close();
await handler.stopWorkers();
process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});