Product knowledge · Advanced · Service-owned outbound

Outbound HTTP bắt đầu từ dependency đã khai báo, không phải URL tùy ý.

Application chọn logical dependency và business policy. CoAkka HTTP Runtime sở hữu bounded target registry, endpoint/DNS/pool/TLS mechanics, request progress và typed terminal outcome.

01 · Ownership model

Một service gọi dependency qua contract của chính nó

Application

Đặt tên dependency, authorization/credential intent, request meaning, status mapping, idempotency và retry policy.

CoAkka HTTP Runtime

Validate target snapshot; sở hữu endpoint selection, DNS, connection pool, TLS, redirects, HTTP framing, deadlines và terminal facts.

Connector

Chiếu builder/request/terminal tự nhiên cho host language và bảo vệ type, buffer, callback cùng owner lifetime.

Remote service

Sở hữu HTTP response/business effect của nó. Received response không tự có nghĩa business success.

Không gọi surface này là CoAkka HTTP Client. Đây là outbound API của service trong CoAkka HTTP Runtime; CoAkka HTTP Client là product riêng đang được hoạch định.

02 · Logical target declaration

Đóng băng nơi được phép gọi trước khi nhận traffic

logical target: sample.upstream · generation 1
  endpoint: loopback
  connect: 127.0.0.1:<port>
  HTTP authority: 127.0.0.1:<port>
  security: plaintext for this local example

incoming request data ──X──► arbitrary scheme/host/port

Logical targets là construction-time snapshots. Handler chọn tên dependency đã khai báo; không biến query, header hoặc body của caller thành arbitrary outbound destination.

03 · Target fields

Address, authority và identity trả lời ba câu hỏi khác nhau

Name
Stable application key như sample.upstream; request dùng key này thay vì URL tùy ý.
Generation
Identity/version của target snapshot được terminal phản chiếu; không phải timestamp hay quyền retry.
Strategy
SINGLE_OWNER chọn một owner hợp lệ; WEIGHTED_ROUND_ROBIN phân phối theo relative endpoint weights khi có nhiều candidate.
Endpoint + node ID
Allowed candidate và stable attribution để biết endpoint nào được chọn; list phải hữu hạn.
Weight / available
Weight là relative selection input, không phải phần trăm hay connection limit. Available quyết định endpoint có nằm trong candidate set của snapshot, không phải health proof.
Connect host / port
Network address cho DNS/connect. Nó không tự là HTTP authority hoặc TLS peer identity.
HTTP authority
Authority/Host của HTTP request theo target contract; tách khỏi socket address.
Security + TLS peer identity
Plaintext, TLS hoặc mTLS intent và certificate identity cần verify; exact loaded package phải chấp nhận provider.
Trust / client identity generation
Chọn immutable CA set và optional mTLS certificate/key set đã khai báo; generation là identity, không phải secret hoặc file watcher.

04 · Request intent

Path là concrete origin-form value, không phải route template

submit:
  logical target = sample.upstream
  method         = GET
  path/query     = /orders/A%2FB?view=summary
  headers/body   = bounded application values
  call deadline  = 3000 ms

returns: call identity · not an HTTP response

Resolve variables và URL-encode value trước submit. Không gửi /orders/{id}, arbitrary full URL hoặc raw untrusted text vào field path/query.

05 · Request fields

Mỗi field thuộc một budget và owner cụ thể

FieldMeaning
Logical targetChọn declared dependency snapshot; không trực tiếp chọn arbitrary socket.
MethodHTTP method của call; không tự nói operation có idempotent hay safe để retry.
Path/queryConcrete encoded origin-form request target; không có fragment hoặc route syntax.
Headers/bodyOrdered bounded HTTP values; application sở hữu auth token, media type, codec và secret policy.
Call deadlineFinite monotonic budget của operation; khác reader wait và inbound handler/transport timeouts.
Call identityOpaque slot/generation identity trả về khi admission thành công; dùng để match terminal chính xác.

06 · Call lifecycle

Submit thành công mới chỉ là admission

1

Declare + start

Builder cung cấp finite target snapshot; Core validate capability, target và bounds trước service readiness.

2

Submit

Core admit/refuse request và trả call identity. Chưa có remote response ở bước này.

3

Progress

Core chọn endpoint, resolve/connect, áp dụng security, gửi request và đọc bounded response theo deadline.

4

Terminal

Một typed terminal gắn call identity cho biết cause/phase/certainty cùng optional HTTP response.

07 · Terminal facts

Match identity trước; status chỉ có nghĩa khi terminal là response

Call identity
Phải match call đã submit; với JavaScript giữ exact integer identity, không round qua Number.
Target / generation / selected endpoint
Runtime attribution cho declared snapshot và endpoint thực sự được chọn.
Reason
Stable terminal cause; branch bằng enum/code, không parse text.
Phase
Một trong ADMISSION, PROVIDER_ADOPTION, TRANSPORT, RESPONSE, CANCELLATION, SHUTDOWN.
Retry disposition
Runtime transport fact; không cấp quyền replay business operation hoặc bỏ idempotency check.
Certainty
Runtime biết gì về request/response bytes; ambiguous fact không chứng minh remote business effect chưa xảy ra.
Optional response
Status, headers và bounded body chỉ dùng khi reason xác nhận response. HTTP 404/500 vẫn có thể là RESPONSE.

Giữ unknown numeric enum value để forward compatibility; không tự đổi nó thành một known category.

08 · Exact terminal vocabulary

Đọc runtime fact trước khi quyết định application action

DimensionStable values và nghĩa
ReasonRESPONSE; PROVIDER_FAILURE/PROVIDER_REJECTED/INVALID_PROVIDER_RESULT; CANCELLED/DEADLINE_EXCEEDED/STOPPED; RESPONSE_HEAD_LIMIT/RESPONSE_BODY_LIMIT/RESPONSE_AGGREGATE_LIMIT; OUT_OF_MEMORY; CLOCK_FAILURE.
RetryNEVER, IF_SAFE, DELIVERY_UNCERTAIN. Đây là transport disposition; IF_SAFE vẫn yêu cầu application chứng minh safe/idempotent.
CertaintyNO_REQUEST_BYTES_SENT, REQUEST_UNCERTAIN, RESPONSE_HEAD_OBSERVED, COMPLETE_RESPONSE. Nó mô tả wire evidence, không phải business commit state.
Provider code / diagnosticBounded operator evidence; không branch business logic bằng diagnostic text hoặc đưa nó thẳng vào public response.

09 · Capacity and time

Không có pool, redirect hoặc terminal queue vô hạn

BoundaryRequired law
Target registry / endpointsFinite declared entries; invalid/unsupported target fails closed.
DNS / connections / poolsFinite work, connections and retained idle state; exact target owns capability/effective facts.
In-flight callsFinite ceiling; pressure/refusal không trở thành application hidden queue.
RedirectsFinite hop/policy bound; authority, credential scope và TLS identity phải vẫn đúng.
ResponseFinite header/body/retained terminal bytes; application không collect vượt ceiling.
Call deadlineOperation progress budget. Deadline terminal khác reader wait timeout.
Terminal reader waitKhoảng chờ để lấy event; hết wait chỉ nghĩa chưa quan sát terminal trong cửa sổ đó.

10 · DNS, TLS and redirects

Kết nối tới đâu, nói HTTP với ai và xác thực ai là ba facts

Connect address

DNS/IP/port dùng mở connection; có thể khác HTTP authority.

HTTP authority

Host/authority logic của request và virtual hosting; không suy từ resolved IP.

TLS peer identity

Danh tính certificate cần verify cùng trust roots; mTLS client identity là material riêng.

Redirect

Mỗi hop vẫn chịu finite bound và configured trust/credential policy; không forward secret theo phỏng đoán.

Feature-check outbound và security provider của exact package. Không log private key, token, raw credential hoặc operator-only TLS diagnostic vào public response.

Advanced · Outbound HTTP

Gọi một dịch vụ cục bộ và phân biệt HTTP 404 với lỗi gọi

Chạy dịch vụ đích trên cùng máy trước. Mỗi ví dụ CoAkka khai báo upstream với địa chỉ cố định, gửi một GET rồi đọc kết quả tương ứng. Ví dụ không lấy URL bất kỳ từ request đầu vào.

Terminal · dịch vụ đích · Python 3.11+
mkdir -p upstream-lab
printf 'hello upstream\n' > upstream-lab/hello.txt
python3 -m http.server --protocol HTTP/1.1 8091 --bind 127.0.0.1 --directory upstream-lab
C/C++ · SDK 2.3.0

Dùng SDK 2.3.0 đã kiểm tra. Lưu outbound.c trong thư mục dự án ở terminal thứ hai. Cùng mã C ABI này build được bằng trình biên dịch C hoặc C++ trên Linux và macOS.

outbound.c
#include <coakka/http/host.h>

#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static coakka_http_host_bytes_t bytes(const char *text) {
  coakka_http_host_bytes_t span;
  span.data = (const uint8_t *)text;
  span.size = strlen(text);
  return span;
}

static bool check(coakka_http_host_status_t status, const char *operation) {
  if (status == COAKKA_HTTP_HOST_OK) {
    return true;
  }
  fprintf(stderr, "%s: %s\n", operation, coakka_http_host_status_name(status));
  return false;
}

static bool request_once(coakka_http_host_service_t *service) {
  coakka_http_host_outbound_request_t request;
  coakka_http_host_outbound_request_init(&request);
  request.logical_target = bytes("upstream");
  request.method = bytes("GET");
  request.target = bytes("/hello.txt");
  request.timeout_ms = 3000U;

  coakka_http_host_outbound_call_t call;
  if (!check(coakka_http_host_submit_outbound(service, &request, &call),
             "submit outbound request")) {
    return false;
  }

  coakka_http_host_outbound_event_t event;
  coakka_http_host_outbound_event_init(&event);
  if (!check(coakka_http_host_take_outbound(service, 5000U, &event),
             "take outbound result")) {
    return false;
  }
  const bool matched =
      event.call.slot == call.slot && event.call.generation == call.generation;
  const bool replied =
      matched && event.reason == COAKKA_HTTP_HOST_OUTBOUND_RESPONSE;
  if (replied) {
    printf("HTTP %u\n", (unsigned)event.response_status);
    if (event.response_status == 200U && event.response_body.size != 0U) {
      // The response body is borrowed until the result is released.
      fwrite(event.response_body.data, 1U, event.response_body.size, stdout);
    }
  } else {
    fprintf(stderr,
            "Outbound result: matched=%d reason=%" PRIu32 " phase=%" PRIu32
            "\n",
            (int)matched, event.reason, event.phase);
  }
  const bool released =
      check(coakka_http_host_release_outbound(service, &event),
            "release outbound result");
  return replied && released;
}

int main(void) {
  coakka_http_host_outbound_endpoint_t endpoint;
  coakka_http_host_outbound_endpoint_init(&endpoint);
  endpoint.node_id = bytes("local");
  endpoint.connect_host = bytes("127.0.0.1");
  endpoint.connect_port = 8091U;
  endpoint.http_authority = bytes("127.0.0.1:8091");
  endpoint.available = 1U;

  coakka_http_host_outbound_target_t target;
  coakka_http_host_outbound_target_init(&target);
  target.name = bytes("upstream");
  target.generation = 1U;
  target.endpoints = &endpoint;
  target.endpoint_count = 1U;

  coakka_http_host_configuration_t configuration;
  coakka_http_host_configuration_init(&configuration);
  configuration.bind_address = bytes("127.0.0.1");
  configuration.outbound_targets = &target;
  configuration.outbound_target_count = 1U;

  coakka_http_host_service_t *service = NULL;
  uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
  if (!check(coakka_http_host_service_create(&configuration, NULL, 0U, &service,
                                             &failed_route),
             "create outbound service")) {
    return EXIT_FAILURE;
  }
  coakka_http_host_issue_t issue;
  coakka_http_host_issue_init(&issue);
  const bool replied =
      check(coakka_http_host_service_start(service, &issue), "start service") &&
      request_once(service);
  const bool closed =
      check(coakka_http_host_service_destroy(&service), "destroy service");
  return replied && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
C11
cc -std=c11 -I"$COAKKA_HTTP_SDK/include" outbound.c -L"$COAKKA_HTTP_SDK/lib" \
  -Wl,-rpath,"$COAKKA_HTTP_SDK/lib" -lcoakka_http_host -o outbound-c
./outbound-c
C++20
c++ -x c++ -std=c++20 -I"$COAKKA_HTTP_SDK/include" outbound.c -L"$COAKKA_HTTP_SDK/lib" \
  -Wl,-rpath,"$COAKKA_HTTP_SDK/lib" -lcoakka_http_host -o outbound-cpp
./outbound-cpp
Kotlin/JVM

Dùng dự án JVM 2.3.2. Lưu file trong thư mục study/ dưới src/main/kotlin hoặc src/main/java. Lệnh mặc định dùng macOS ARM64. Trên Pi, thêm -Dcoakka.target=linux-aarch64 vào Maven hoặc -PcoakkaTarget=linux-aarch64 vào Gradle.

KotlinOutbound.kt
package study

import coakka.http.OutboundEndpoint
import coakka.http.OutboundReason
import coakka.http.OutboundRequest
import coakka.http.OutboundStrategy
import coakka.http.OutboundTarget
import coakka.http.ServiceBuilder

fun main() {
    val endpoint = OutboundEndpoint(
        nodeId = "local",
        connectHost = "127.0.0.1",
        connectPort = 8091,
        httpAuthority = "127.0.0.1:8091",
    )
    val target = OutboundTarget(
        name = "upstream",
        generation = 1,
        strategy = OutboundStrategy.SINGLE_OWNER,
        endpoints = listOf(endpoint),
    )
    ServiceBuilder().listen("127.0.0.1", 0).outboundTarget(target).start().use { service ->
        val call = service.submitOutbound(OutboundRequest(
            logicalTarget = "upstream",
            method = "GET",
            target = "/hello.txt",
            timeoutMillis = 3_000,
        ))
        val result = checkNotNull(service.takeOutbound(5_000)) { "Missing outbound result" }
        check(result.call == call) { "Result belongs to a different call" }
        check(result.reason == OutboundReason.RESPONSE) { "Outbound request ended: ${result.reason}" }
        println("HTTP ${result.responseStatus}")
        if (result.responseStatus == 200) print(result.responseBody().toString(Charsets.UTF_8))
    }
}
Maven
mvn -q compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.KotlinOutboundKt
Gradle
./gradlew runKotlinOutbound
Java/JVM

Dùng dự án JVM 2.3.2. Lưu file trong thư mục study/ dưới src/main/kotlin hoặc src/main/java. Lệnh mặc định dùng macOS ARM64. Trên Pi, thêm -Dcoakka.target=linux-aarch64 vào Maven hoặc -PcoakkaTarget=linux-aarch64 vào Gradle.

JavaOutbound.java
package study;

import coakka.http.Headers;
import coakka.http.OutboundCallId;
import coakka.http.OutboundEndpoint;
import coakka.http.OutboundReason;
import coakka.http.OutboundRequest;
import coakka.http.OutboundStrategy;
import coakka.http.OutboundTarget;
import coakka.http.OutboundTerminal;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

public final class JavaOutbound {
    private JavaOutbound() {}

    public static void main(String[] args) throws Exception {
        OutboundEndpoint endpoint = new OutboundEndpoint(
                "local", "127.0.0.1", 8091, "127.0.0.1:8091");
        OutboundTarget target = new OutboundTarget(
                "upstream", 1L, OutboundStrategy.SINGLE_OWNER, Collections.singletonList(endpoint));
        Service service = new ServiceBuilder()
                .listen("127.0.0.1", 0)
                .outboundTarget(target)
                .start();
        try {
            OutboundCallId call = service.submitOutbound(new OutboundRequest(
                    "upstream", "GET", "/hello.txt", new Headers(), new byte[0], 3_000));
            OutboundTerminal result = service.takeOutbound(5_000L);
            if (result == null || !result.getCall().equals(call)) {
                throw new IllegalStateException("Missing result for this call");
            }
            if (result.getReason() != OutboundReason.RESPONSE) {
                throw new IllegalStateException("Outbound request ended: " + result.getReason());
            }
            System.out.println("HTTP " + result.getResponseStatus());
            if (result.getResponseStatus() == 200) {
                System.out.print(new String(result.responseBody(), StandardCharsets.UTF_8));
            }
        } finally {
            service.close();
        }
    }
}
Maven
mvn -q compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.JavaOutbound
Gradle
./gradlew runJavaOutbound

Với các ngôn ngữ khác, mở bài outbound đầy đủ: Go · Python · Node.js · Bun · C# · Swift.

Khi file còn đó, kết quả là HTTP 200 và hello upstream. Đổi tên hello.txt rồi chạy lại: HTTP 404 vẫn là response, không phải lỗi kết nối. Dừng dịch vụ đích rồi thử lại để thấy kết quả không có response. Hết thời gian chờ không có nghĩa là được phép gửi lại một thao tác nghiệp vụ.

11 · Cancellation, retry and idempotency

Terminal fact là input cho quyết định, không phải lệnh retry

Cancel

Cancellation là intent cho tới khi matching terminal xác nhận outcome. Đừng free caller state khi Core còn sở hữu call.

Deadline

Hết deadline không chứng minh remote chưa nhận hoặc chưa tạo effect; response có thể đã bị mất trên đường về.

Application retry

Tạo attempt/call identity mới, bounded attempts/backoff/total budget; giữ business idempotency key khi contract cần.

Reconcile

Với charge/create/non-idempotent work và outcome ambiguous, đọc authoritative business state trước khi lặp.

12 · Failure law

Đừng biến mọi kết quả thành exception hoặc status

Observed outcomeMeaning / next action
Startup target refusalDeclaration/capability/bound invalid; service chưa ready với candidate đó.
Synchronous submit refusalCall chưa được admit; inspect stable category và pressure/closed state.
Transport/provider terminalKhông có HTTP response; branch reason/phase/retry/certainty và sửa đúng network/security/provider owner.
HTTP 4xx/5xx responseRemote đã trả HTTP response; application quyết định business mapping/retry.
Cancel/deadline terminalGiữ ambiguity; không suy rollback hoặc exactly-once.
Reader wait timeoutChưa lấy được terminal trong wait window; không tự submit duplicate.
Close/drain refusalGiữ service/call/application owner reachable tới khi cleanup contract hội tụ.

13 · Integration checklist

Trước khi chọn API ngôn ngữ