Skip to content

Latest commit

 

History

History
1425 lines (1189 loc) · 65.9 KB

PHALANX.adoc

File metadata and controls

1425 lines (1189 loc) · 65.9 KB

SmallMind Phalanx: Broker-Backed RPC For Plain Java Interfaces

Two JVM processes need to talk, and the call site wants to look like an ordinary Java method invocation. The obvious options all require boilerplate the call site should not be writing:

  • hand-written producer/consumer code that serialises arguments, routes by string tag, correlates replies, and materialises exceptions;

  • a REST client generated from an external schema, with its own stub generation and transport coupling;

  • a service mesh or gRPC runtime that commits the service topology and wire format before the first call is placed.

smallmind-phalanx is the piece in the middle. A Java interface plus a handful of annotations becomes a JDK dynamic proxy on the client side and a message-broker endpoint on the server side. One argument-named payload is produced per call, one correlated reply is consumed, and server-side exceptions arrive back at the caller as throwables.

What the module owns:

  • encoding each call as an InvocationSignal, dispatching it by voice (load-balanced, directed, or broadcast), and waiting for the correlated ResultSignal;

  • reflecting the target interface to dispatch the inbound signal;

  • carrying thread-local WireContext values and ScopedValue-bound WireScope values across the wire and re-establishing them on the server thread;

  • broker wiring for RabbitMQ, Kafka, JMS, and an in-process mock router.

What stays with the caller:

  • the actual ConnectionFactory (RabbitMQ), KafkaServer[] list, or JMS connection factory;

  • choosing a SignalCodec — JsonSignalCodec (Jackson 3) or JavaSerializationSignalCodec;

  • choosing a concurrency limit and default timeout on each transport pair;

  • supplying a ParameterExtractor for the service group — and, for @Whisper interfaces, one for the target instance id.

Concern Entry point

Declare a remotely callable method

@InOut(timeoutSeconds = N), @InOnly, @Whisper(timeoutSeconds = N), or @Shout on the method; @Argument("name") on every parameter

Rename a method on the wire

@CallAs("wire-name")

Build the client-side proxy

WireProxyFactory.generateProxy(transport, version, name, iface, groupExtractor, instanceIdExtractor, timeoutExtractor)

Expose the implementation

responseTransport.register(Interface.class, wiredService); the implementation must implement WiredService

Unit-test without a broker

MockMessageRouter + MockRequestTransport + MockResponseTransport

Run over RabbitMQ

RabbitMQConnector, RabbitMQRequestTransport, RabbitMQResponseTransport, NameConfiguration

Run over Kafka

KafkaRequestTransport, KafkaResponseTransport, KafkaConnector, KafkaServer…​, KafkaGroupProtocol

Run over JMS (Jakarta Messaging 3.x)

JmsRequestTransport, JmsResponseTransport, RoutingFactories, MessagePolicy, ReconnectionPolicy

Flow a tenant/user/trace value through every call

Subclass WireContext, @Wire(adapter = …​), WireContextManager.register("handle", Cls) on a thread with a PerApplicationContext attached, push with ContextFactory.pushContext(…​)

Flow the same kind of value with no push/pop to balance

Subclass WireScope, WireScopeManager.register("handle", Cls) inside the application’s PerApplicationScope, bind with ScopeFactory.callInScope(…​)

Convert a non-trivial domain type on the wire

@Wire(adapter = MyAdapter.class) on the type; extend WireAdapter<V,B> (getValueType, marshal, unmarshal)

Reuse the worker pool outside the wire layer

org.smallmind.phalanx.worker.WorkManager with TransferringWorkQueue or BlockingWorkQueue

The wire layer uses a small vocabulary that the rest of the doc depends on.

Service interface

Any Java interface whose methods carry a dispatch annotation (@InOut, @InOnly, @Whisper, @Shout) and whose parameters all carry @Argument. It does not extend any marker interface. WireInvocationHandler validates both constraints when the proxy is created.

Signal

The serialised form of one request (InvocationSignal) or one reply (ResultSignal). A SignalCodec owns the byte encoding. Two codecs ship: JsonSignalCodec (Jackson 3) and JavaSerializationSignalCodec.

Route

The (version, serviceName, function) tuple inside every invocation signal. Version and name come from the proxy configuration. The function carries the Java method name (or the @CallAs override), its parameter types, and its return type.

Voice

The routing-plus-conversation pair for a single call. A Voice combines a VocalMode — TALK (load-balanced within a service group), WHISPER (directed at one instance), or SHOUT (broadcast to every instance) — with a Conversation (OneWayConversation for fire-and-forget, TwoWayConversation for request/reply with a timeout). The three concrete voices are Talking, Whispering, and Shouting. WireInvocationHandler picks the right one from the method’s annotations.

Wire context

A subclass of abstract WireContext (which extends the nutsnbolts Context). Pushed onto the thread-local ContextFactory stack by the caller, attached to every outbound invocation signal, re-pushed on the server thread for the duration of the dispatch, and visible to the service implementation via ContextFactory.getContext.

Wire scope

A subclass of abstract WireScope (which implements the nutsnbolts Scope). Bound on the caller’s thread for the extent of a ScopeFactory.callInScope / runInScope operation, attached to every outbound invocation signal made inside that operation, re-bound on the server thread for the duration of the dispatch through ScopeFactory.callInScopes, and visible to the service implementation via ScopeFactory.getScope. Contexts and scopes travel side by side in the same signal and are independent of each other.

Wired service

The server-side wrapper around a service implementation. WiredService.getServiceName() and getVersion() supply the routing key, and setResponseTransport(…​) gives the wrapper a back-channel to reply. ResponseTransport.register(Class, WiredService) binds the wrapper to an interface.

Transport pair

RequestTransport on the client, ResponseTransport on the server. Both sides share a SignalCodec and matching configuration (service group, NameConfiguration for RabbitMQ, or nodeName/serviceGroup for Kafka). Each pair is independent; a JVM can host many.

The module is a single artifact; the transport-client dependencies it declares are optional, so you only drag in the broker client for the transport you actually use.

<dependency>
    <groupId>org.smallmind</groupId>
    <artifactId>smallmind-phalanx</artifactId>
    <version>${project.version}</version>
</dependency>

Module name (for requires): org.smallmind.phalanx

Add the matching runtime dependencies:

Transport Required runtime dependency

RabbitMQ

com.rabbitmq:amqp-client

Kafka

org.apache.kafka:kafka-clients (and org.smallmind:kafka-utility which the module already declares as optional)

JMS

any Jakarta Messaging 3.x provider; the API is compiled against jakarta.jms:jakarta.jms-api

Mock

nothing; in-process only

Runtime environment:

  • Java 25 — the parent pom sets maven.compiler.release to 25.

  • Spring Beans 7.x — used by the classes under wire/spring/ and transport/amqp/rabbitmq/spring/; the rest of the module is Spring-free.

  • Jackson 3.x — required by JsonSignalCodec.

  • Jakarta 3.x APIs (jakarta.jms, jakarta.xml.bind, jakarta.ws.rs).

Logging is routed through scribe-pen; LoggerManager.getLogger(…​) is the internal entry point.

The jar ships an explicit module descriptor for org.smallmind.phalanx that exports all of its packages and re-exports (requires transitive) jakarta.messaging, jakarta.xml.bind, tools.jackson.databind, java.management, java.naming, org.smallmind.nutsnbolts, org.smallmind.quorum, and org.smallmind.scribe.pen. On the classpath the descriptor is ignored. See Module Path And Classpath for the repository-wide rules.

The transport clients are requires static, so a module-path application requires the one it uses:

Transport Also require

RabbitMQ

com.rabbitmq.client

Kafka

org.smallmind.kafka.utility and kafka.clients

JMS

your Jakarta Messaging provider’s module

Without that requires (or --add-modules), the transport fails with NoClassDefFoundError even though the client jar is on the module path. kafka.clients is derived from the jar’s file name. A module that uses the Spring factory beans also requires spring.beans.

The descriptor opens org.smallmind.phalanx.wire unconditionally, so classpath:org/smallmind/phalanx/wire/mock-wire.xml and rabbitmq-wire.xml stay loadable from other modules; org.smallmind.phalanx.wire.signal to jakarta.xml.bind and tools.jackson.databind; and the two Spring packages (wire.spring, wire.transport.amqp.rabbitmq.spring) to spring.core and spring.beans.

An application on a module path also:

  • Exports each service interface package to org.smallmind.phalanx, which invokes the interface’s methods reflectively on the serving side:

    exports com.example.api to org.smallmind.phalanx;

    Without it the call fails with UndeclaredThrowableException caused by IllegalAccessException: class org.smallmind.phalanx.wire.transport.MethodInvoker … cannot access interface com.example.api.GreetService … because module … does not export com.example.api to module org.smallmind.phalanx.

  • Opens the packages holding argument and result types to tools.jackson.databind, because JsonSignalCodec serializes them with Jackson. Without it a call passing or returning such a type fails with DatabindException: access to public member failed. Strings, numbers, and other JDK types need nothing.

A complete end-to-end example against the mock router. No broker is needed, nothing is thread-local except the WireContext stack, and the example fits in one file.

Declare the interface:

public interface CalculatorService {

    @InOut(timeoutSeconds = 5)
    Integer add (@Argument("a") int a, @Argument("b") int b);

    @InOnly
    void logCalculation (@Argument("operation") String operation);
}

Implement it, including the WiredService metadata that ResponseTransport.register requires:

public class CalculatorServiceImpl implements CalculatorService, WiredService {

    public Integer add (int a, int b) { return a + b; }

    public void logCalculation (String operation) {
        System.out.println("Performed: " + operation);
    }

    @Override public String getServiceName ()          { return "CalculatorService"; }
    @Override public int    getVersion     ()          { return 1; }
    @Override public void   setResponseTransport (ResponseTransport transport) { }
}

Wire both sides through a shared MockMessageRouter:

MockMessageRouter router = new MockMessageRouter(null);   // null adopts the scope bound on this thread, if any
JsonSignalCodec   codec  = new JsonSignalCodec();

MockResponseTransport server = new MockResponseTransport(router, codec);
server.register(CalculatorService.class, new CalculatorServiceImpl());      (1)

MockRequestTransport client = new MockRequestTransport(router, codec, 30);  (2)

CalculatorService calculator = (CalculatorService)WireProxyFactory.generateProxy(
    client,
    1,                                           (3)
    "CalculatorService",                         (4)
    CalculatorService.class,
    new StaticParameterExtractor<>("default"),   (5)
    null,                                        (6)
    null                                         (7)
);

Integer sum = calculator.add(5, 3);              // returns 8
calculator.logCalculation("5 + 3");              // returns immediately

client.close();                                  // then the server, then the router that owns the dispatch threads
server.close();
router.close();
  1. register returns the response transport’s instance id — hold on to it if the client proxy will issue @Whisper calls targeted at this node.

  2. 30 is the default @InOut timeout in seconds for methods that don’t supply one.

  3. Protocol version written into every outbound Route.

  4. Logical service name; must match WiredService.getServiceName().

  5. The service-group extractor is required. StaticParameterExtractor returns the same constant for every call.

  6. Instance-id extractor; required only if the interface contains any @Whisper method, null otherwise.

  7. Per-call timeout extractor; optional. When it returns non-null, it overrides both the annotation and the transport default.

Each method picks exactly one dispatch annotation. WireInvocationHandler resolves them in the order @Shout, @Whisper, @InOnly, @InOut — the first annotation found wins, so combining them (for example @Whisper + @InOut) has no extra effect.

@InOut(timeoutSeconds = N) — request/reply (load-balanced)

The caller blocks until the remote implementation returns or the effective timeout elapses. timeoutSeconds is a required attribute; values ≤ 0 fall back to the request transport’s default timeout.

@InOnly — fire-and-forget

The method must return void and must not declare a throws list; WireInvocationHandler rejects both at invocation time. Server-side exceptions are logged and swallowed — the caller has no way to observe them.

@Whisper(timeoutSeconds = N) — directed request/reply

Delivered to a single instance whose id is supplied by the proxy’s instance-id extractor. Whisper is itself request/reply; do not also mark the method @InOut. timeoutSeconds defaults to 0 ("use the transport default"). If the interface contains any @Whisper methods and no instance-id extractor was supplied to WireProxyFactory.generateProxy, proxy creation fails with ServiceDefinitionException.

@Shout — broadcast

Delivered to every subscriber of the service group. Shouts collect no responses; a return value, if declared, is discarded. Use void to make the intent obvious.

@Argument("name") — per-parameter, required on every parameter

The name must be unique within the method. Missing annotations cause a ServiceDefinitionException at proxy-creation time. An optional type() attribute overrides the automatically inferred type tag; leave it empty for normal use.

@CallAs("wire-name") — method-level, optional

Overrides the function name carried in the wire signal. The Java method name on the caller side is unchanged.

Example:

public interface OrderService {

    @InOut(timeoutSeconds = 30)
    Order createOrder (@Argument("order") Order order) throws InvalidOrderException;  (1)

    @CallAs("cancel-order")
    @InOut(timeoutSeconds = 5)
    void cancelOrder (@Argument("orderId") String orderId);

    @Whisper(timeoutSeconds = 5)
    Status probe (@Argument("component") String component);

    @Shout
    void clearCache (@Argument("namespace") String namespace);

    @InOnly
    void notifyWarehouse (@Argument("orderId") String orderId);  (2)
}
  1. Checked exceptions declared on an @InOut or @Whisper method are materialised on the caller side; see Error Propagation.

  2. @InOnly methods can declare no exceptions.

WireProxyFactory.generateProxy builds a JDK dynamic Proxy whose calls are dispatched by WireInvocationHandler. The return value is typed as java.lang.reflect.Proxy; cast it to the service interface.

public static Proxy generateProxy (
    RequestTransport             transport,
    int                          version,
    String                       serviceName,
    Class<?>                     serviceInterface,
    ParameterExtractor<String>   serviceGroupExtractor,    // required
    ParameterExtractor<String>   instanceIdExtractor,      // required if @Whisper
    ParameterExtractor<Long>     timeoutExtractor          // optional
) throws Exception

A ParameterExtractor<T> receives the Method, the resolved argument map, and the attached WireContext and WireScope instances (either array may be empty, never null); it returns a single value. Two typical implementations:

  • StaticParameterExtractor<>(value) — always returns the same constant, suitable for fixed service groups.

  • A custom extractor that reads a WireContext (for example, a TenantContext that picks the service group dynamically based on tenant).

On the server side, the implementation must implement WiredService:

public interface WiredService {
    int    getVersion     ();                                // routing discriminator
    String getServiceName ();                                // routing key
    void   setResponseTransport (ResponseTransport transport) throws Exception;
}

Register the implementation with the response transport. The transport stores a (version, serviceName) → MethodInvoker mapping; subsequent calls to register with the same (version, serviceName) are no-ops.

String instanceId = responseTransport.register(OrderService.class, new OrderServiceImpl());

register returns the response transport’s instance id — the value a client-side instanceIdExtractor must resolve for @Whisper calls targeted at this node.

Lifecycle control on ResponseTransport:

Method Effect

play()

Resume request consumption (if previously `pause()`d).

pause()

Suspend request consumption on the shout, talk, and whisper paths; already-dispatched work continues. (The in-process Mock transport pauses talk only.)

close()

Stop the transport, shut the worker pool down, release broker resources.

getState()

Returns the current TransportState (PLAYING, PAUSED, CLOSED).

isHealthy()

Whether the transport is actually connected, bound, and consuming. A transport reports PLAYING whether or not a single consumer is attached to a single queue, so this — not the state — is what a liveness probe should read. A deliberately paused transport is healthy but idle.

getDiagnostic()

A description of connection, binding, and consumer state, written for an operator reading it during an incident.

Only the RabbitMQ response transport answers the last two meaningfully; the others take the interface defaults of true and the state name.

ResponseTransportMonitor (org.smallmind.phalanx.wire.jmx) wraps any ResponseTransport as a StandardMBean exposing that same surface through ResponseTransportMXBean, so health can be read and consumption toggled at runtime without a redeployment.

Each transport ships a matched RequestTransport and ResponseTransport. Construct and configure the pair explicitly — nothing is auto-wired.

org.smallmind.phalanx.wire.transport.mock. Message routing happens inside a single MockMessageRouter; the mock server dispatches inline on the listener thread, so there is no worker pool.

MockMessageRouter     router = new MockMessageRouter(null);
JsonSignalCodec       codec  = new JsonSignalCodec();
MockRequestTransport  client = new MockRequestTransport(router, codec, 30);
MockResponseTransport server = new MockResponseTransport(router, codec);

The third argument to MockRequestTransport is the default @InOut timeout in seconds. The router owns the three daemon dispatch threads; closing the transports stops none of them, so close the transports and then call router.close(). Messages still queued are dropped; an idle dispatch thread stops within one 100 ms poll, one inside a dispatch stops when that service call returns. The shipped mock-wire.xml declares destroy-method="close" on the router bean and on both transport beans, and Spring destroys the transports, which depend on the router, first.

org.smallmind.phalanx.wire.transport.amqp.rabbitmq.

RabbitMQConnector wraps a RabbitMQ ConnectionFactory and a list of broker Address objects. Configure authentication and virtual host on the ConnectionFactory before handing it over, but leave its recovery flags alone — the constructor turns automatic and topology recovery off unconditionally, because recovery belongs to RabbitMQConnectionManager and two mechanisms racing on the same broker-side drop leave zombie connections with duplicate consumers.

ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");

RabbitMQConnector connector = new RabbitMQConnector(
    factory,
    new Address("localhost", 5672)
);

The connector also carries the retry tuning that the connection manager applies while recovering. Each of these is defaulted; set them only where the deployment calls for something else.

Setter Default Effect

setInitialRetryMilliseconds

250

Delay before the first recovery attempt.

setMaximumRetryMilliseconds

30000

Ceiling on the delay. There is no attempt limit, and the ceiling matters more than any limit would: a broker that has lost majority cannot accept topology at all, and the only correct behaviour is to keep asking patiently until it can.

setRetryMultiplier

2.0

Factor by which the delay grows after each failed attempt.

setRetryJitterRatio

0.2

Proportion of the delay applied as random jitter, which keeps a fleet of pods from retrying against a recovering broker in lockstep.

setChannelFailureEscalationCount

3

Consecutive channel-rebuild failures tolerated before the connection itself is replaced. Replacing the connection is what frees this instance’s exclusive queues, so it is the escape from a queue the broker will not hand back.

Queue types are not configurable, because the correct type follows from the queue’s role and a wrong choice is an outage rather than a preference.

The per-instance queues — shout, whisper, and the caller’s response queue — are declared exclusive. An exclusive queue belongs to the connection that declared it and the broker deletes it the moment that connection ends, so its name can never be left behind as a record whose process has stopped and which no client can then declare, delete or consume from. The shared talk queue cannot be exclusive, so it is declared as a quorum queue, which is what keeps it serving when a node is lost. Its replica count is the response transport’s quorumReplicationCount argument, and three is the floor — the constructor throws IllegalArgumentException below that, since a quorum queue needs a majority of its members and two replicas tolerate no node failure at all. Asking for more replicas than the cluster has is not an error; the broker clamps the initial group size to the nodes available, which is how a single-node development broker serves a three-replica declaration.

NameConfiguration supplies the suffix tokens used when composing queue and exchange names. The out-of-the-box suffixes are requestExchange, responseExchange, responseQueue, shoutQueue, talkQueue, and whisperQueue; both sides of a deployment must use identical names.

NameConfiguration names = new NameConfiguration();

RabbitMQRequestTransport client = new RabbitMQRequestTransport(
    connector, names, codec,
    /* clusterSize              */ 4,
    /* concurrencyLimit         */ 8,
    /* defaultTimeoutSeconds    */ 30L,
    /* messageTTLSeconds        */ 60,
    /* autoAcknowledge          */ true,
    /* publisherConfirmationHandler */ null,
    /* perApplicationScope      */ scope            // (1)
);

RabbitMQResponseTransport server = new RabbitMQResponseTransport(
    connector, names,
    InvocationWorker.class, codec,
    /* serviceGroup             */ "default",
    /* clusterSize              */ 4,
    /* concurrencyLimit         */ 8,
    /* messageTTLSeconds        */ 60,
    /* quorumReplicationCount   */ 3,
    /* autoAcknowledge          */ true,
    /* publisherConfirmationHandler */ null,
    /* perApplicationScope      */ scope            // (1)
);
  1. Trailing parameter on both RabbitMQ transport constructors, resolved once by the constructor on the constructing thread: the scope to bind, or null to adopt the scope bound on that thread. A scope that differs from the one bound there fails the constructor with ScopeException. With neither, the transport’s threads run with no scope, carrying only the PerApplicationContext each inherits: the response transport’s WorkManager workers from the constructing thread, the handleDelivery callbacks from the RabbitMQ client’s connection thread chain. See Per-application scope on transport threads.

clusterSize sets how many distinct RequestMessageRouter (or ResponseMessageRouter) instances are created — each owns its own channel — while concurrencyLimit sets how many handler slots the pool round- robins through. The pool always has max(clusterSize, concurrencyLimit) slots.

All of a transport’s routers share a single connection, owned by a RabbitMQConnectionManager. That is a requirement rather than an economy: every router of a transport declares the same per-instance queue names, and an exclusive queue belongs to a connection, so a connection per router would mean a queue per router — and a shout or whisper delivered once per router instead of once. The manager also owns recovery, retrying with capped exponential backoff for as long as the transport is open, so automatic recovery is disabled on the underlying ConnectionFactory; two recovery mechanisms racing on the same drop leave duplicate consumers behind. The backoff it applies is the connector’s, tuned through the setters above. ResponseTransport.isHealthy() reports whether the transport is genuinely connected, bound and consuming, which is what a liveness probe should read rather than the lifecycle state, and getDiagnostic() describes that same state in a form an operator can read during an incident.

A Spring assembly is available via the transport/amqp/rabbitmq/spring/ helper beans. RabbitMQConnectorFactoryBean builds the connector from RabbitMQServer endpoints, credentials, and a heartbeatSeconds value — which also bounds how quickly a dead connection is noticed — and exposes each retry property above as an optional override. A worked assembly of the whole request/response pair ships at org/smallmind/phalanx/wire/rabbitmq-wire.xml on the module’s classpath (mock-wire.xml is its in-memory twin). Both pass <null/> for the scope — to every transport in the RabbitMQ/Kafka file, and to the MockMessageRouter in the mock file, since the mock transports take none — so each adopts whatever scope is bound on the thread that refreshes the context: under the Tanuki wrapper with its scope on (spark.per.application.scope=true in wrapper.conf, or perApplicationScope on the plugin), the listener’s scope (see the per-application scope); under PerApplicationScopeContextLoaderListener, the one it published; and in a context-only application (the wrapper with its scope off, or any host with no scope bound on that thread) none, so the transport threads run with no scope. To hand in a specific instance, copy the file and replace <null/> with a ref — for example to org.smallmind.spark.perApplicationScope, which the wrapper registers while refreshing when its scope is on; with the scope off no bean exists under that name and the ref fails the refresh with Spring’s NoSuchBeanDefinitionException — bearing in mind that any instance other than the one bound on the refreshing thread fails the refresh with ScopeException.

org.smallmind.phalanx.wire.transport.kafka. There is no Properties- based configuration surface; brokers are passed as KafkaServer instances and KafkaConnector (from smallmind-kafka-utility) handles producer, consumer, and startup-check mechanics.

Topic names are derived by TopicNames from a fixed prefix of "wire":

Role Topic

shout

wire-shout-<serviceGroup>

talk

wire-talk-<serviceGroup>

whisper

wire-whisper-<serviceGroup>-<instanceId>

response

wire-response-<callerId>

Each transport creates the topics it consumes at construction (AdminClient.createTopics with the broker’s default partition count and replication factor; topics that already exist are left untouched). The whisper topic and the response topic are per-instance and are deleted from the broker when their transport is closed.

KafkaServer[] servers = { new KafkaServer("localhost", 9092) };

KafkaRequestTransport client = new KafkaRequestTransport(
    /* nodeName                 */ "orders-api",
    codec,
    /* concurrencyLimit         */ 8,
    /* defaultTimeoutSeconds    */ 30L,
    /* startupGracePeriodSeconds */ 15,
    /* groupProtocol            */ KafkaGroupProtocol.CLASSIC,
    /* dynamicConsumers         */ true,
    /* perApplicationScope      */ scope,           // (1)
    servers
);

KafkaResponseTransport server = new KafkaResponseTransport(
    /* nodeName                 */ "orders-worker",
    /* serviceGroup             */ "default",
    InvocationWorker.class,
    codec,
    /* concurrencyLimit         */ 8,
    /* startupGracePeriodSeconds */ 15,
    /* groupProtocol            */ KafkaGroupProtocol.CLASSIC,
    /* dynamicConsumers         */ true,
    /* perApplicationScope      */ scope,           // (1)
    servers
);
  1. Parameter placed before the servers varargs, resolved once by the constructor on the constructing thread: the scope to bind, or null to adopt the scope bound on that thread. A scope that differs from the one bound there fails the constructor with ScopeException. With neither, the transport’s threads run with no scope, carrying only the PerApplicationContext the ingester’s consumer workers and the WorkManager workers inherit from the constructing thread. See Per-application scope on transport threads.

groupProtocol is the Kafka consumer group protocol applied to every worker consumer: KafkaGroupProtocol.CLASSIC (the classic client-side rebalance protocol) or KafkaGroupProtocol.CONSUMER (the KIP-848 broker-coordinated protocol). It comes from smallmind-kafka-utility.

dynamicConsumers selects Kafka group membership for those same consumers. true joins every consumer group as a dynamic member: no group.instance.id is set, and a consumer leaves its group the moment it is closed, so a node’s talk partitions are reassigned immediately on shutdown. false joins as a static member identified by <nodeName>-<workerIndex>; a node that restarts under the same nodeName within the session timeout reclaims its talk partitions without rebalancing the rest of the group, but the partitions of a node that goes away are held unread for that same timeout. Use true for deployments whose node identity changes on every restart (a Kubernetes Deployment, for example) and false only when nodeName is stable across restarts and rebalance avoidance is worth the delayed reassignment.

Consumer groups are derived from the constructor arguments as follows:

Role Consumer group Membership

talk

wire-talk-<serviceGroup>

Shared by every response transport in the service group. Kafka partitions the talk topic across all of their workers, so each request is handled by exactly one node.

shout

wire-shout-<instanceId>

One group per response transport instance. Every instance reads the whole shout topic independently, so each request reaches every node.

whisper

wire-whisper-<instanceId>

One group per response transport instance, on that instance’s private whisper topic.

response

wire-response-<callerId>

One group per request transport instance, on that instance’s private response topic.

When dynamicConsumers is false, every consumer carries <nodeName>-<workerIndex> as its Kafka group.instance.id; the index keeps a node’s own workers distinct, so the only collision that can occur is between nodes. Two operational requirements follow (neither applies when dynamicConsumers is true):

  • nodeName must be unique across every node in a service group. The talk group spans nodes, and Kafka allows only one live member per group.instance.id in a group: a second node joining with the same nodeName fences the first, which fails its next poll or commit with FencedInstanceIdException, recreates its consumer, and fences the second in turn. Both nodes flap and talk requests intermittently time out.

  • nodeName should be stable across restarts of the same node. A restart that presents the same id within the session timeout (45 seconds under CLASSIC; the broker’s group.consumer.session.timeout.ms under CONSUMER) reclaims its talk partitions without rebalancing the rest of the group.

The talk topic’s partition count caps how far the talk group can spread. Because the transport creates wire-talk-<serviceGroup> with the broker’s default num.partitions, a topic with fewer partitions than nodes × concurrencyLimit leaves the surplus workers idle, and a topic with a single partition routes every talk request to one node no matter how many have joined. Pre-create the talk topic with enough partitions, or raise the broker default (see the KafkaConfiguration guidance in the Kafka chapter).

pause() and play() on the Kafka response transport unsubscribe and resubscribe each ingester’s consumers in turn. Each call blocks until the worker’s current poll cycle completes — up to three seconds per ingester while playing, up to one second while paused — so a full pause() across the whisper, talk, and shout ingesters can take up to nine seconds and a play() up to three. The Kafka calls themselves are milliseconds; the wait is the hand-off from the poll loop.

startupGracePeriodSeconds bounds two checks during construction. First KafkaConnector retries the broker connectivity check for up to that many seconds, throwing KafkaConnectionException if no broker becomes reachable. The transport then waits — within the same budget — for every consumer ingester to be assigned its partitions and resolve a fetch position (awaitConsumerAssignment); if that readiness is not confirmed before the budget is exhausted, construction fails with a KafkaConnectionException reporting that consumer readiness could not be confirmed. Because the topics use auto.offset.reset=latest, this readiness wait is what guarantees the first request published after construction is not silently dropped.

org.smallmind.phalanx.wire.transport.jms. The transport targets Jakarta Messaging 3.x (jakarta.jms). Configuration is split across three collaborators:

  • RoutingFactories — ManagedObjectFactory instances for the request queue, request topic, and response topic. Each factory provides a JMS ConnectionFactory and a Destination. The jndi/ subpackage contains JNDI-backed implementations.

  • MessagePolicy — delivery mode, priority, TTL, and related producer-side settings; combined with DeliveryMode and JmsAcknowledgeMode enums.

  • ReconnectionPolicy — reconnection timing and attempt limits applied by the ConnectionManager on broker failure.

JmsRequestTransport client = new JmsRequestTransport(
    routingFactories, messagePolicy, reconnectionPolicy, codec,
    /* clusterSize           */ 4,
    /* concurrencyLimit      */ 8,
    /* maximumMessageLength  */ 1 << 20,
    /* defaultTimeoutSeconds */ 30L,
    /* perApplicationScope   */ scope              // (1)
);

JmsResponseTransport server = new JmsResponseTransport(
    routingFactories, messagePolicy, reconnectionPolicy, codec,
    /* serviceGroup           */ "default",
    /* clusterSize            */ 4,
    /* concurrencyLimit       */ 8,
    /* maximumMessageLength   */ 1 << 20,
    /* perApplicationScope    */ scope             // (1)
);
  1. Trailing parameter, resolved once by the constructor on the constructing thread: the scope to bind, or null to adopt the scope bound on that thread. A scope that differs from the one bound there fails the constructor with ScopeException. With neither, the transport’s threads run with no scope, carrying only the PerApplicationContext each inherits: the response transport’s WorkManager workers from the constructing thread, the provider’s onMessage delivery threads from whatever the provider’s own thread chain carries. See Per-application scope on transport threads.

A JNDI-less Spring assembly is available via the transport/jms/spring/ helper beans.

Wire contexts are thread-local values that must follow every call into remote services without polluting method signatures. Typical examples are a tenant id, an authenticated principal, a trace/correlation id, or a request-scoped feature-flag snapshot.

Subclass WireContext and attach a @Wire(adapter = …​) annotation naming the adapter that serialises it:

@Wire(adapter = TenantContextAdapter.class)
public class TenantContext extends WireContext {

    private final String tenantId;

    public TenantContext (String tenantId) { this.tenantId = tenantId; }

    public String getTenantId () { return tenantId; }
}

WireAdapter<V, B> maps a wire value V to a business type B. The abstract methods are getValueType(), marshal(B) → V, and unmarshal(V) → B.

public class TenantContextAdapter extends WireAdapter<String, TenantContext> {

    @Override public Class<String>   getValueType ()                         { return String.class; }
    @Override public String          marshal       (TenantContext context)   { return context.getTenantId(); }
    @Override public TenantContext   unmarshal     (String tenantId)         { return new TenantContext(tenantId); }
}

Register the handle at application startup, on both sides of the wire:

WireContextManager.register("tenant", TenantContext.class);

WireContextManager keeps its registry in the PerApplicationContext, so the registering thread must have one attached; otherwise register throws MissingPerApplicationContextException. A context is attached by new PerApplicationContext() on the startup thread, by WebContextLoaderListener in a servlet container, by the testbench foundation Spring assembly’s perApplicationContext bean, or by the Tanuki wrapper listener — which also binds its PerApplicationScope when spark.per.application.scope is true in wrapper.conf, so a wrapped application runs with both bindings only when that scope is on (see the per-application scope).

Push before calling, pop in finally:

ContextFactory.pushContext(new TenantContext("customer-123"));
try {
    orderService.createOrder(order);
} finally {
    ContextFactory.popContext(TenantContext.class);
}

Read on the server side:

TenantContext tenant = ContextFactory.getContext(TenantContext.class);
String tenantId      = tenant.getTenantId();

MethodInvoker pushes the invocation’s contexts before calling the service method and pops them immediately afterward, so nested outbound calls inside the same service method see the same contexts.

WireScope is the ScopedValue-backed alternative to WireContext. The wire format is the same — a single-key JSON object per scope, keyed by the @XmlRootElement name or the simple class name — but the binding model is that of nutsnbolts ScopeFactory: a scope exists only for the extent of the operation that entered it, so there is no pop to balance and nothing can leak onto a pooled thread.

Subclass WireScope:

public class TenantScope extends WireScope {

    private String tenantId;

    public TenantScope () { }

    public TenantScope (String tenantId) { this.tenantId = tenantId; }

    public String getTenantId () { return tenantId; }

    public void setTenantId (String tenantId) { this.tenantId = tenantId; }
}

Register the handle on both sides of the wire, inside the application’s PerApplicationScope — WireScopeManager stores its registry there and throws MissingPerApplicationScopeException on an unbound thread:

applicationScope.run(() -> WireScopeManager.register("tenant", TenantScope.class));

In Spring, WireScopeInitializingBean is the twin of WireContextInitializingBean; its afterPropertiesSet registers the handle through WireScopeManager, so the refresh must itself run inside the application’s scope (under PerApplicationScopeContextLoaderListener or the Tanuki wrapper with its scope on), otherwise it fails with MissingPerApplicationScopeException:

<bean class="org.smallmind.phalanx.wire.spring.WireScopeInitializingBean">
  <property name="handle" value="tenant"/>
  <property name="scopeClass" value="com.example.TenantScope"/>
</bean>

Bind around the call; nothing to pop:

ScopeFactory.runInScope(new TenantScope("customer-123"), () -> orderService.createOrder(order));

Read on the server side:

TenantScope tenant = ScopeFactory.getScope(TenantScope.class);

MethodInvoker binds the invocation’s scopes with ScopeFactory.callInScopes around the service method; they are unbound when the method returns or throws. A WireScope that implements ScopeLifecycleAware receives beforeEnter / afterExit on the server thread around that call. null elements in the signal’s scope array are skipped, as they are for contexts.

Scopes are bound by concrete class, so a call carries at most one scope of each class to the service method: when two scopes of the same class are bound around the call, the service sees the later one, and a service that relays the invocation onward forwards one per class. Scopes whose handle is not registered on the receiver all decode as ProtoWireScope, so two of them collapse to one in the same way. Contexts behave alike through ContextFactory: a relaying service forwards the innermost context of each class.

The two mechanisms are independent: a call may carry contexts, scopes, both, or neither, and WireContextManager and WireScopeManager are separate registries. They are also decoded differently on the receiving side: with JsonSignalCodec, a WireContext element is resolved through WireContextManager, which needs a PerApplicationContext on the worker thread, and a WireScope element through WireScopeManager, which needs the PerApplicationScope the transport resolved at construction. A receiver whose worker threads lack the binding a received element needs fails inside decode on the worker with (or with a DatabindException caused by) MissingPerApplicationContextException or MissingPerApplicationScopeException — the adapters run inside Jackson deserialization — after the transport has already acknowledged the delivery — RabbitMQ acks once the message is handed to the worker queue, Kafka commits the offset after the hand-off, JMS auto-acknowledges by default. The worker logs the failure at ERROR and drops the message; the broker does not redeliver it. @InOut and @Whisper callers then fail with TransportTimeoutException (checked, so surfacing as UndeclaredThrowableException from a proxy method that does not declare it); @InOnly and @Shout messages are lost with no caller-side signal. The mock router’s dispatch thread decodes under the same rules, so the mismatch reproduces without a broker. JavaSerializationSignalCodec does not run the adapters, so it needs no binding to decode. Both sides of a wire must therefore agree on which kinds they carry, and a receiver that must accept both needs both bound on its workers — a transport constructed with the scope on a thread that has a context, so the workers inherit the context and run inside the scope.

Server-side exceptions are handled inside WireInvocationCircuit.handle:

  • Request/reply calls (@InOut, @Whisper). The exception is wrapped into a Fault (from web-json-scaffold) and sent back in a ResultSignal with error = true. The request transport unwraps the fault on the caller side and the declared checked exception (or a FaultWrappingException for unchecked ones) escapes the caller’s proxy method. TransportException is reserved for transport-layer problems — notably, results that are not Serializable are rejected with a TransportException before transmission.

  • Fire-and-forget calls (@InOnly, @Shout). The exception is logged via LoggerManager and no response is transmitted. The caller cannot observe server-side failure.

Framework-thrown conditions worth catching at the call site:

TransportTimeoutException

Request/reply did not complete within the effective timeout.

TransportException

A transport-level or serialisation-level failure. Most commonly returned when the server-side result is not Serializable.

ServiceDefinitionException

Raised at proxy-creation or registration time when the interface is malformed: missing @Argument, @InOnly with a non-void return or a declared throws, @Whisper without an instance-id extractor, or a service group/instance id that the registered wrapper does not match.

MissingInvocationException / MismatchedArgumentException

The method being invoked is not part of the registered interface, or the argument shape disagrees with what the interface advertised.

Timeouts apply to request/reply voices only: @InOut and @Whisper. For a single call, the effective timeout is resolved in this order:

  1. timeoutExtractor.getParameter(…​) on the proxy, if it returns non-null.

  2. The annotation’s timeoutSeconds, if > 0.

  3. The request transport’s defaultTimeoutSeconds constructor argument.

There is no cancellation. On timeout the framework fails the caller’s callback and discards any late response it later receives for that correlation id. The server-side invocation continues to completion. Design services to be idempotent when the caller might retry.

Client side. Calls are synchronous. The calling thread blocks inside RequestTransport.transmit until the correlated ResultSignal arrives or the timeout fires, for request/reply voices; for fire-and-forget voices the method returns as soon as the signal is queued for dispatch. The request transport allocates no thread pool of its own.

Server side. The RabbitMQ, Kafka, and JMS response transports extend WorkManager<InvocationWorker, …​>. The concurrencyLimit constructor argument sets the number of worker threads; there is no default. Workers drain a shared WorkQueue and dispatch through the WireInvocationCircuit. The mock response transport dispatches inline on the listener thread and has no pool. WorkManager worker threads (phalanx-worker-<fully qualified worker class>-<index>) and the mock router’s dispatch threads (phalanx-mock-queue-talk-request, phalanx-mock-topic-whisper-request, phalanx-mock-topic-response) are daemon threads; the Kafka transports' ingester threads (phalanx-kafka-ingester-<group>-<index>) are non-daemon, so a JVM holding a Kafka transport stays alive until close().

Context propagation across threads. A WireContext lives on the pushing thread’s ContextFactory stack. On the server side MethodInvoker pushes the call’s contexts, invokes the method, and pops them immediately afterward; service code running in the same thread can therefore rely on ContextFactory.getContext(…​). Contexts do not propagate into arbitrary threads spawned from service code — spawn-and- propagate is the caller’s responsibility.

Scope propagation across threads. A WireScope is bound through ScopeFactory only for the extent of the operation that entered it, on the entering thread. On the server side MethodInvoker binds the call’s scopes with ScopeFactory.callInScopes around the method, so service code on that thread can rely on ScopeFactory.getScope(…​). Threads the service spawns, or tasks it submits to a pool, see no scopes unless the work is carried explicitly with ScopeFactory.snapshot() or submitted through ScopeFactory.wrapExecutor(…​).

Shutdown. Call close() on each transport, and on the mock router after its transports (its dispatch threads are the router’s, not the transports'). The RabbitMQ, JMS and Kafka response transports run WorkManager.shutDown() internally and each worker’s stop() method is called in sequence (exceptions are logged, not re-thrown); the mock response transport only marks itself closed. To drain cleanly: stop issuing requests on the client, close the request transport, let the response transport’s workers complete in-flight work, then close the response transport.

Every transport records Claxon metrics through Instrument.with, the service side deserializes WireContext`s through `WireContextXmlAdapter, and it deserializes WireScope`s through `WireScopeXmlAdapter, which resolves handles through WireScopeManager and so requires the per-application scope to be bound on the decoding thread; all of these resolve per-application data on whatever thread they run on. The threads involved inherit no ScopedValue binding from the thread that constructed the transport: WorkManager worker threads, the Kafka ingester’s consumer threads, the RabbitMQ client’s consumer threads (which call handleDelivery), the JMS provider’s delivery threads (which call onMessage), and the mock transport’s dispatch threads.

Each RabbitMQ, Kafka, and JMS transport constructor therefore accepts an org.smallmind.nutsnbolts.scope.PerApplicationScope (the last parameter, except on the Kafka transports where it precedes the servers varargs), as does WorkManager. The mock transports take none: MockMessageRouter takes the scope and hands the settled result to the MockQueue / MockTopic it builds, whose dispatch threads run inside it. The parameter has no scope-less overload; each of those constructors settles the scope exactly once, on the constructing thread, through PerApplicationScope.resolve(…​), and every thread the owner later starts reads that stored result:

A scope

The scope is used as given. If the constructing thread is bound to a different PerApplicationScope, the constructor fails with org.smallmind.nutsnbolts.scope.ScopeException before any thread or connection is started, because registrations made under the bound scope could never be resolved through the one handed in. The same instance bound, or no scope bound at all, is accepted.

null

The transport adopts the scope bound on the constructing thread, if there is one. In Spring XML that is <constructor-arg><null/></constructor-arg> at that position; under PerApplicationScopeContextLoaderListener, or the Tanuki wrapper listener with its scope on (spark.per.application.scope), which run the context refresh inside the application’s scope, a null therefore binds the transport’s threads to that same scope.

Neither

A null on a thread with no scope bound starts the transport’s threads with no scope. They carry only the PerApplicationContext each inherits: WorkManager workers and the Kafka ingester’s consumer workers from the thread that constructs the transport; mock dispatch threads from the thread that constructs the MockMessageRouter; RabbitMQ handleDelivery callbacks from the client’s connection thread chain (after a reconnect, the connection manager’s retry thread); JMS onMessage delivery threads from whatever the provider’s thread chain carries, which is provider-dependent. Nothing is logged at start.

With a scope, handed in or adopted, the owner runs each worker’s whole body and each third-party callback inside scope.run(…​), so a WireScope on those threads resolves through that scope’s map and the bridging *Manager lookups (Claxon’s Instrument among them) read it first. KafkaMessageIngester, RequestMessageRouter, ResponseMessageRouter, RequestListener, and ResponseListener receive the scope their owning transport resolved and apply it without resolving again. The resolution is tied to the constructing thread: a transport constructed from a worker thread, a lazily initialized bean, or any other thread that carries no binding resolves null to no scope, whatever the application’s startup thread was bound to. A receiver that must decode both WireContext`s and `WireScope`s needs both bindings on the thread that constructs the transport (or the router), not only on the thread that refreshes the application: the scope arrives through the parameter or is adopted from that thread’s binding, and the context must already be attached to the constructing thread, because the workers inherit it when they are created. On a thread with neither binding only the throwing lookups fail loudly — for example `WireContextManager, WireScopeManager, PoolManager, the persistence and property-accessor bridges, every register, and the application’s own Instrument.register / ClaxonRegistryFactoryBean install. Instrument.with returns an UnpluggedInstrumentation on such a thread, so the transport’s workers drop their Claxon metrics silently; the request transports decode only ResultSignal`s, which carry no contexts or scopes, so for them dropped metrics are the only effect. When passing a scope, pass the same instance the rest of the application binds (the one wired into a web server’s `perApplicationScope property, or registered by the Tanuki listener as org.smallmind.spark.perApplicationScope when its scope is on), or pass null on a thread bound to it. A scope created only for the transport, on a thread with no scope bound, holds no registrations: the bridging *Manager lookups (Claxon’s Instrument among them) fall through to the inherited context, but WireScopeManager has no such fallback, so every WireScope the workers decode arrives as a ProtoWireScope and ScopeFactory.getScope(TenantScope.class) returns null with nothing logged.

Metrics are recorded only when the worker’s binding holds the registry. A registry installed only in the application’s scope is invisible to workers started with no scope, and a registry installed only in a context is invisible to workers given a separate, empty scope when no context was inherited; in both cases Instrument.with returns UnpluggedInstrumentation and each reading is dropped silently, with no signal at start.

Deliberately left unbound, because the work they run never resolves per-application data: the Kafka transports' producer executors (they only call producer.send) and `RabbitMQConnectionManager’s retry thread (it only reconnects).

org.smallmind.phalanx.worker is a small, self-contained worker-pool abstraction. The RabbitMQ, Kafka, and JMS response transports build on it; nothing in the package depends on the wire layer, so it can be reused on its own.

Type Role

WorkManager<W, T>

Owns the worker pool’s full lifecycle: creates workers via a WorkerFactory, wraps them in daemon threads, dispatches work through execute(T), stops them via shutDown(). Concurrent startUp/shutDown calls spin-wait for the transition in flight. Claxon records acquire-worker latency. Both constructors take a PerApplicationScope, resolved once in the constructor through PerApplicationScope.resolve(…​) on the constructing thread and run around each worker’s body: a scope is used as given, null adopts the scope bound on the constructing thread, and a scope that differs from the bound one fails the constructor with ScopeException. With neither, the workers start with no scope, carrying only the PerApplicationContext inherited from the thread that calls startUp. The resolved scope is readable by subclasses through the protected getPerApplicationScope(). Individual dropped readings are not logged.

Worker<T>

Runnable subclass that drains the queue and processes one item at a time.

WorkerFactory<W, T>

Produces Worker instances bound to the shared queue.

WorkQueue<T>

Handoff between producer and workers.

TransferringWorkQueue

SynchronousQueue-style handoff — the producer blocks until a worker takes the item. Used as the default by `WorkManager’s no-queue constructor.

BlockingWorkQueue

Bounded-buffer handoff for cases where some producer burstiness is expected.

WorkManagerException

Thrown by execute(…​) when the manager is not in the STARTED state.

Every call times out. Verify responseTransport.register(Interface.class, wiredService) was called, that wiredService.getServiceName() and getVersion() exactly match the arguments passed to WireProxyFactory.generateProxy, and that both sides share the same NameConfiguration (RabbitMQ) or node-name/service-group (Kafka). Enable debug logging on org.smallmind.phalanx to see outbound and inbound routes.

ServiceDefinitionException thrown at proxy creation. The interface has a method whose parameters are not all annotated with @Argument, an @InOnly method that returns non-void or declares a throws list, or the interface contains @Whisper methods but no instance-id extractor was supplied to WireProxyFactory.generateProxy.

TransportException on an otherwise normal call. Most often: the server-side return value is not Serializable. WireInvocationCircuit rejects non-Serializable results before sending the reply. Make the type serializable or return a serializable projection.

Wire scopes are missing on the server, or the worker fails with MissingPerApplicationScopeException. The handle must be registered on both sides with WireScopeManager.register("handle", Class) inside the application’s PerApplicationScope, and the transport’s workers must run in that same scope — the transport was given it, or was constructed with null on a thread bound to it; an unregistered handle — or a handle registered in a different scope than the one the transport’s workers run in — arrives as a ProtoWireScope, so ScopeFactory.getScope(TenantScope.class) returns null and nothing is logged. The server decodes scopes through WireScopeXmlAdapter on the transport’s worker thread, which consults WireScopeManager; if that thread is not bound to a per-application scope — the transport was constructed with null on a thread with no scope bound — decoding fails with (or with a DatabindException caused by) MissingPerApplicationScopeException. The worker logs it at ERROR and drops the whole message, not just the scope; the delivery was already acknowledged, so the broker does not redeliver it, a request/reply caller times out, and a fire-and-forget message is lost. Also verify the call was made inside the ScopeFactory.callInScope / runInScope operation that bound the scope: a scope bound in one operation is not visible to a call made after it returned.

A transport constructor (or MockMessageRouter / WorkManager) throws ScopeException saying the supplied PerApplicationScope is not the scope bound on the current thread. A scope was handed in on a thread already bound to a different PerApplicationScope, typically a context refresh run under the Tanuki wrapper listener with its scope on or PerApplicationScopeContextLoaderListener with a separately constructed scope wired into the constructor argument. Pass the bound instance (the org.smallmind.spark.perApplicationScope bean under Tanuki with its scope on, or the scope registered under that name as TESTBENCH.adoc shows), or pass null to adopt it (see Per-application scope on transport threads).

Wire contexts are missing on the server, or the worker fails with MissingPerApplicationContextException. The handle must be registered on both sides with WireContextManager.register("handle", Class); an unregistered handle arrives as a ProtoWireContext, so the context is absent for the service and nothing is logged. The server decodes contexts through WireContextXmlAdapter on the transport’s worker thread, which consults WireContextManager; if that thread has no PerApplicationContext — the transport was constructed on a thread with none attached, so its workers inherited none — decoding fails with (or with a DatabindException caused by) MissingPerApplicationContextException. The worker logs it at ERROR and drops the whole message; the delivery was already acknowledged, so the broker does not redeliver it, a request/reply caller times out, and a fire-and-forget message is lost. Attach the context on the constructing thread before building the transport (see Per-application scope on transport threads). Also verify the context was pushed before the call and popped in a finally block, and that the context class’s no-arg constructor or adapter is reachable from the server classloader.

Kafka calls hang after a topic rename or service-group change. Phalanx uses wire-*-<serviceGroup> topic names. Renaming the group without restarting both sides leaves the server subscribed to the old topic while the client publishes to the new one. Coordinate the rollover.

Kafka talk calls time out intermittently; FencedInstanceIdException in the server logs. Two response transports in the same service group were started with dynamicConsumers=false and the same nodeName. nodeName prefixes the Kafka group.instance.id (<nodeName>-<workerIndex>), and the talk group spans nodes, so each worker on one node fences its counterpart on the other in a loop. Give every node in the service group a distinct nodeName, or switch to dynamicConsumers=true.

Every Kafka talk call lands on one node. wire-talk-<serviceGroup> has too few partitions for the group — often exactly one, the stock broker default for num.partitions. Kafka assigns at most one worker per partition, so the rest of the service group sits idle. Pre-create the topic with at least nodes × concurrencyLimit partitions or raise the broker default.

No request cancellation

A transmitted request runs to completion on the server even when the caller has already timed out. Design retries with idempotency in mind.

Single reply per request/reply call

Streaming replies are not supported; return a collection-valued type if the caller needs several values.

Shout has no collection or consensus

@Shout fans out but does not collect responses and does not coordinate subscribers. It is not a distributed-transaction primitive.

Arguments and results must be Serializable

The proxy rejects a non-Serializable argument before sending, with TransportException: The argument(index=…, name=…, class=…) is not Serializable (surfacing as UndeclaredThrowableException from a method that does not declare it), and WireInvocationCircuit rejects non-Serializable returns with a TransportException, independent of which SignalCodec is in use.

@InOnly methods cannot declare checked exceptions

Fire-and-forget contracts cannot participate in checked-exception propagation. Move the exception-declaring signature to @InOut or @Whisper.

No automatic retries

The transport does not retry failed sends. Wrap the call at the application layer if retries are required.

Compile-scope dependencies declared by the module (see phalanx/pom.xml):

  • smallmind-nutsnbolts — Context, ContextFactory, Scope, ScopeFactory, PerApplicationScope, SnowflakeId, and the other utility types the wire layer depends on.

  • smallmind-quorum — connection-management helpers used by the transports.

  • claxon-registry — latency and throughput metrics emitted from the work manager and transports.

  • scribe-pen — logging API. Add a Scribe backend such as scribe-ink-indigenous to the application to see the output.

  • web-json-scaffold — Fault, FaultElement, and FaultWrappingException used for cross-wire error propagation, and JsonCodec.

  • jackson-databind (Jackson 3.x) — JsonSignalCodec.

  • jakarta.jms-api, jakarta.xml.bind-api, jakarta.ws.rs-api — Jakarta API surfaces compiled against.

  • spring-beans — used by the Spring integration beans (WireProxyFactoryBean, WireContextInitializingBean, WireScopeInitializingBean, StaticParameterExtractorFactoryBean, RabbitMQConnectorFactoryBean, RabbitMQServerFactoryBean).

Note

smallmind-phalanx does not depend on web-jersey, so Jersey, Hibernate Validator, the Servlet API, HttpComponents, spring-context, and spring-web do not arrive through it. An application that uses them declares them itself.

Optional dependencies, required only for the corresponding transport:

  • com.rabbitmq:amqp-client — RabbitMQ transport.

  • org.apache.kafka:kafka-clients + org.smallmind:kafka-utility — Kafka transport.

  • A Jakarta Messaging 3.x provider — JMS transport.