Hoox Docs

🔗 Isolate Communication Spec

In a traditional server-based monorepo or Docker cluster, microservices communicate over TCP/IP connections using protocols like REST, gRPC, or WebSockets. These introduce significant networking overhead: DNS resolution, TCP handshakes, TLS negotiation, and data serialization.

Hoox completely bypasses the networking stack by leveraging Cloudflare’s Service Bindings. This document details the low-level V8 routing mechanics, internal authentication protocols, and diagnostic mocking configurations of the Hoox communication layer.


âš¡ 1. Service Bindings: Zero-Overhead V8 Routing

Cloudflare Service Bindings allow one edge worker to call another without ever hitting the public internet.

The Under-the-Hood V8 Mechanics

  • Direct Execution: When hoox calls env.TRADE_SERVICE.fetch(), the Cloudflare runtime does not construct a TCP packet or route it through a virtual network. Instead, the runtime spawns the target worker’s V8 isolate in the same physical memory thread and executes its entry point function directly.
  • Zero Serialization Overhead: Payloads are passed directly as active V8 memory pointers, cutting JSON serialization and parsing costs.
  • Latency Guarantee: Internal isolate transitions are completed in under 1 microsecond, making microservice communication practically instant.
// Declarative bindings inside workers/hoox/wrangler.jsonc
{
  "services": [
    { "binding": "TRADE_SERVICE", "service": "trade-worker" },
    { "binding": "TELEGRAM_SERVICE", "service": "telegram-worker" },
    { "binding": "ANALYTICS_SERVICE", "service": "analytics-worker" },
  ],
}

💻 2. Complete Service Invocations Implementation

Below is the standard, production-grade template used to route authenticated, structured HTTP payloads between workers:

import { requireInternalAuth } from "@jango-blockchained/hoox-shared/middleware";

export interface Env {
  TRADE_SERVICE: Fetcher; // Service Binding Fetcher
  INTERNAL_KEY_BINDING: string; // Authorized Internal Key secret
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // 1. Build and validate payload
    const payload = {
      exchange: "bybit",
      action: "LONG",
      symbol: "BTCUSDT",
      quantity: 0.002,
    };

    // 2. Invoke the internal trade-worker V8 isolate
    try {
      const tradeResponse = await env.TRADE_SERVICE.fetch(
        "https://trade-worker/webhook",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-Internal-Auth-Key": env.INTERNAL_KEY_BINDING, // Bearer Auth
          },
          body: JSON.stringify(payload),
        }
      );

      if (!tradeResponse.ok) {
        throw new Error(
          `Internal binding returned HTTP status: ${tradeResponse.status}`
        );
      }

      const result = await tradeResponse.json();
      return new Response(JSON.stringify({ success: true, result }), {
        status: 200,
        headers: { "Content-Type": "application/json" },
      });
    } catch (error: any) {
      return new Response(
        JSON.stringify({ success: false, error: error.message }),
        {
          status: 502, // Bad Gateway
          headers: { "Content-Type": "application/json" },
        }
      );
    }
  },
};

🛅 3. Internal Authorization Middleware Standard

To prevent unauthorized, cross-tenant, or direct internal calls, every internal endpoint is secured using the shared requireInternalAuth middleware from @jango-blockchained/hoox-shared/middleware:

import { requireInternalAuth } from "@jango-blockchained/hoox-shared/middleware";

// Inside target worker's router or fetch handler:
export async function handleRequest(
  request: Request,
  env: Env
): Promise<Response> {
  // Returns 401 Unauthorized Response if the header is invalid or missing
  const authError = requireInternalAuth(request, env, "INTERNAL_KEY_BINDING");
  if (authError) return authError;

  // Key is valid — continue execution
  return new Response("Authorized", { status: 200 });
}

Standardization Alert: Every single internal worker (hoox, trade-worker, d1-worker, agent-worker, telegram-worker, email-worker) binds the exact same secret name: INTERNAL_KEY_BINDING. This eliminates variable footprint drift and simplifies secret deployments across your workspace.


🧪 4. Testing & Mocking Service Bindings

During local testing (via native bun test), you can mock the Service Binding Fetcher object cleanly to run full-coverage unit tests without provisioning real Cloudflare APIs:

import { expect, test, mock } from "bun:test";

test("Should mock internal trade-worker service bindings", async () => {
  const mockEnv = {
    INTERNAL_KEY_BINDING: "secret_local_test_key",
    TRADE_SERVICE: {
      fetch: async (url: string, init?: RequestInit) => {
        // Confirm headers are present and valid
        const headers = init?.headers as Record<string, string>;
        if (headers["X-Internal-Auth-Key"] !== "secret_local_test_key") {
          return new Response(JSON.stringify({ success: false }), {
            status: 401,
          });
        }

        return new Response(
          JSON.stringify({
            success: true,
            orderId: "mock_order_10482",
          }),
          { status: 200 }
        );
      },
    } as Fetcher,
  };

  // Run call test assertions
  const res = await mockEnv.TRADE_SERVICE.fetch(
    "https://trade-worker/webhook",
    {
      headers: { "X-Internal-Auth-Key": "secret_local_test_key" },
    }
  );

  const data = await res.json();
  expect(res.status).toBe(200);
  expect(data.orderId).toBe("mock_order_10482");
});

🔗 Next Steps

  • Data Flow Mapping — Step-by-step sequence charts of trade executions, backups, and metrics.
  • Bindings Catalog — Review complete environment namespaces and bound objects.