Dùng CoAkka Runtime trong workflow Temporal

Đơn hàng có thể chờ duyệt qua đêm. Giữ Temporal để lưu tiến độ và thời hạn duyệt. Khi đơn được duyệt, một Activity có thể dùng CoAkka Runtime để gửi lời gọi tính giá đến dịch vụ đang phụ trách.

Ai phụ trách từng phần của đơn chờ duyệt?

Việc cần làm Temporal CoAkka Runtime
Chờ người duyệt qua đêm Workflow chờ tín hiệu duyệt hoặc mốc hết hạn. Temporal ghi lại các mốc đó trong lịch sử. Chuyển yêu cầu khi ứng dụng gửi đến target. Thời gian chờ phản hồi áp dụng cho một lời gọi.
Tiếp tục sau khi Worker dừng Worker mới dùng lịch sử để dựng lại trạng thái workflow và tiếp tục từ bước đang chờ. Định tuyến những lời gọi được gửi đến. Lịch sử và bước tiếp theo của đơn do workflow hoặc ứng dụng quản lý.
Tính giá sau khi duyệt Workflow lên lịch Activity và ghi kết quả Activity khi hoàn tất. Chuyển yêu cầu đến hàm xử lý billing.quote và trả kết quả của từng lời gọi.
Xử lý khi chưa nhận được giá Temporal áp dụng chính sách thử lại của Activity. Workflow quyết định bước tiếp theo theo kết quả. Bên gọi nhận kết quả giao nhận như phản hồi, timeout hoặc Deadletter, tùy tình huống.

Activity gọi billing.quote thế nào?

Đường duyệt do Temporal quản lý
Tạo đơn → chờ tín hiệu duyệt hoặc hết hạn → nếu được duyệt, lên lịch quoteOrder
Đường tính giá bên trong Activity
Worker Node.js → CoAkka Runtime gọi billing.quote với "3" → hàm Python tính giá → Activity trả $36.00 về workflow

Đặt lời gọi mạng trong Activity để Temporal có thể dùng kết quả đã ghi khi phát lại workflow. Bài thử dùng chung một RuntimeHost cho các lời gọi và đóng khi kết thúc.

Kiểm tra trước khi thử lại một Activity

Ví dụ tính giá chỉ đọc dữ liệu. Mỗi lời gọi chờ tối đa 2 giây, còn Temporal có thể chạy Activity tối đa 2 lần. Nếu thay bằng bước ghi dữ liệu hoặc thu tiền, dùng mã thao tác ổn định qua các lần thử lại và kiểm tra kết quả đã ghi trước khi thực hiện lại. Timeout chỉ cho biết bên gọi chưa nhận được kết quả trong thời gian chờ.

Phân biệt timeout và Deadletter.

Khi nào nên giữ Temporal?

Giữ Temporal khi đơn phải chờ người duyệt, có thời hạn, hoặc cần tiếp tục sau khi Worker dừng. Nếu ứng dụng chỉ cần nhận báo giá ngay và không có tiến độ cần lưu, có thể gọi thẳng target từ ứng dụng. Với đơn đã duyệt, giữ quy tắc xác nhận hoặc bù trừ trong workflow hay ứng dụng phụ trách.

Xem khi nào cần bù trừ trong bài Saga.

Chạy đơn chờ duyệt trên máy local

Chạy trên máy local với Node.js và Python. Bài thử khởi động một Temporal dev server tạm thời. Lần chạy đầu cần Internet để tải gói và tiến trình dev server.

Mở một terminal và làm theo phần cài Python và chạy hàm tính giá. Giữ tiến trình Python lắng nghe ở 127.0.0.1:19326. Mở bài Node.js gọi Python.

Tạo một thư mục Node.js riêng. Sao chép 2 tệp dưới đây vào cùng thư mục rồi chạy các lệnh cài và chạy thử.

Workflow · chờ duyệt hoặc hết hạn
temporal-approval-workflow.cjs
const { condition, defineQuery, defineSignal, proxyActivities, setHandler } =
  require("@temporalio/workflow");

const approveOrder = defineSignal("approveOrder");
const approvalStatus = defineQuery("approvalStatus");
const { quoteOrder } = proxyActivities({
  startToCloseTimeout: "5 seconds",
  scheduleToCloseTimeout: "20 seconds",
  retry: { maximumAttempts: 2 },
});

async function orderApproval(quantity, approvalWindow = "24 hours") {
  let approved = false;
  setHandler(approveOrder, () => { approved = true; });
  setHandler(approvalStatus, () => (approved ? "approved" : "waiting"));

  if (!(await condition(() => approved, approvalWindow))) {
    return { status: "expired" };
  }

  // The Activity performs the network call. Replay uses its recorded result.
  const quote = await quoteOrder(quantity);
  return { status: "quoted", quote };
}

module.exports = { orderApproval };
Worker và bài thử · gọi billing.quote
temporal-approval.mjs
import assert from "node:assert/strict";
import { Buffer } from "node:buffer";
import { fileURLToPath } from "node:url";
import { TestWorkflowEnvironment } from "@temporalio/testing";
import { bundleWorkflowCode, Worker } from "@temporalio/worker";
import {
  RouteStrategy,
  RuntimeHost,
  outboundOnlyNetwork,
} from "coakka-runtime-node";

const taskQueue = "checkout-approval";
const target = "billing.quote";
const runtime = RuntimeHost.start({
  systemName: "temporal-checkout",
  nodeId: "approval-worker-1",
  network: outboundOnlyNetwork(),
  routes: [{
    target,
    strategy: RouteStrategy.SINGLE_OWNER,
    endpoints: [{ host: "127.0.0.1", port: 19326, weight: 1, flags: 0 }],
  }],
});

let quoteCalls = 0;
async function quoteOrder(quantity) {
  quoteCalls += 1;
  const reply = await runtime.askPayload(
    "temporal-checkout",
    target,
    Buffer.from(String(quantity), "utf8"),
    2000,
  );
  return Buffer.from(reply).toString("utf8");
}

try {
  const env = await TestWorkflowEnvironment.createLocal();
  try {
    const workflowBundle = await bundleWorkflowCode({
      workflowsPath: fileURLToPath(new URL("./temporal-approval-workflow.cjs", import.meta.url)),
    });
    const workerOptions = {
      connection: env.nativeConnection,
      taskQueue,
      workflowBundle,
      activities: { quoteOrder },
    };

    const order = await env.client.workflow.start("orderApproval", {
      taskQueue,
      workflowId: "order-42",
      args: [3],
    });
    const firstWorker = await Worker.create(workerOptions);
    const status = await firstWorker.runUntil(() => order.query("approvalStatus"));
    assert.equal(status, "waiting");
    assert.equal(quoteCalls, 0);
    console.log("order-42: waiting for approval, worker stopped");

    // The service accepts the signal while the worker is stopped.
    await order.signal("approveOrder");
    const nextWorker = await Worker.create(workerOptions);
    await nextWorker.runUntil(async () => {
      const quoted = await order.result();
      assert.deepEqual(quoted, { status: "quoted", quote: "$36.00" });
      assert.equal(quoteCalls, 1);
      console.log("order-42: approved, quote", quoted.quote);

      const expiringOrder = await env.client.workflow.start("orderApproval", {
        taskQueue,
        workflowId: "order-43",
        args: [3, "1 second"],
      });
      assert.deepEqual(await expiringOrder.result(), { status: "expired" });
      assert.equal(quoteCalls, 1);
      console.log("order-43: approval expired, no quote call");
    });
  } finally {
    await env.teardown();
  }
} finally {
  await runtime.close();
}
Cài gói và chạy thử
npm install 1.27.0 1.27.0 1.27.0 [email protected]
node temporal-approval.mjs

Kết quả mong đợi

order-42: waiting for approval, worker stopped
order-42: approved, quote $36.00
order-43: approval expired, no quote call

Đơn đầu gửi tín hiệu duyệt khi Worker đã dừng. Worker tiếp theo đọc lại lịch sử và nhận giá từ Python. Đơn thứ hai chờ 1 giây để thử hết hạn và không gọi tính giá. Chương trình tự đóng Runtime và dev server. Dừng tiến trình Python bằng Ctrl+C khi xong.

Khi thử trên hệ thống hiện có, giữ đường tính giá cũ để đối chiếu. Chạy 2 ca duyệt và hết hạn. Nếu cần quay lại, dùng đường cũ cho các đơn thử mới.

Tài liệu tham khảo