How Peer Mesh Host Connections Work in Apache Maka
Apache Maka's Peer Mesh subsystem enables runtime hosts to discover, join, and communicate through a cryptographically verified, atomically persisted mesh network using JSON state stores and signed invitations.
Peer Mesh is the foundational networking layer in Apache Maka that manages how runtime hosts establish and maintain connections with other peers. This subsystem provides a deterministic, tamper-resistant ledger of mesh membership and reachability information, allowing hosts to participate as either authorities or replicas while ensuring crash-safe topology management. According to the Apache Maka source code, the implementation centers on a persistent state store that coordinates all host interactions through carefully validated state transitions.
Atomic State Persistence and File Locking
All Peer Mesh state for a host is stored in a JSON file named peer-mesh.json, guarded by a lock file (peer-mesh.owner) to ensure single-process write access. The function openPeerMeshStateStore in packages/runtime-host/src/peer-mesh/store.ts (lines 13-23) initializes this system by creating the directory structure, acquiring the file lock via packages/runtime-host/src/peer-mesh/owner.ts, and loading the existing state into memory.
The store guarantees atomic updates by writing to a temporary file before replacing the canonical peer-mesh.json. If a crash occurs during this operation, the PeerMeshPersistenceError or PeerMeshPostCommitError exceptions (lines 76-84 of store.ts) provide the host with specific error context to determine whether to retry or abort the operation.
Authority vs. Replica Roles in Host Connections
Every mesh operates in one of two distinct roles that determine connection privileges. The authority role holds the private cryptographic key and maintains the canonical roster, while replica roles follow the authority's state and cannot issue invitations independently.
The decodePeerMeshState function (lines 67-83 in packages/runtime-host/src/peer-mesh/store.ts) validates these roles when loading state from disk. Authorities use their key pairs defined in packages/runtime-host/src/peer-mesh/model.ts to sign invitations and reachability leases, ensuring that any host connecting to the mesh can cryptographically verify the authority's identity before establishing transport-layer connections.
The Invitation and Join Lifecycle
Creating Cryptographic Invitations
Authorities generate invitations through the createInvitation helper, producing PendingPeerMeshInvitation objects that contain a mesh ID, secret, expiration timestamp, and the authority's public key. The decodeInvitations function (lines 90-110 in store.ts) validates these structures when replicas redeem them, checking cryptographic signatures and expiration windows before permitting membership.
Executing PeerMeshNode.join()
When a runtime host initiates a connection, it invokes PeerMeshNode.join from packages/runtime-host/src/peer-mesh/node.ts. This method creates a pending join entry (PendingPeerMeshJoin) with a specific phase field that tracks progress through prepared, outcome_unknown, or leave_pending states.
State transitions are strictly controlled by assertStateAdvance (lines 21-40 in store.ts), which prevents illegal rollbacks and ensures that once a host commits to joining, it cannot revert to an earlier state without proper cleanup. This guarantees that mesh membership changes follow a monotonic progression visible to all observing hosts.
Runtime Discovery and Reachability
Signed Reachability Leases
Active hosts advertise their network availability through reachability leases (SignedPeerReachabilityLeaseV1). The decodeReachability function (lines 41-50 in store.ts) decodes and cryptographically verifies these leases, allowing hosts to determine which peers are currently accessible and via which transports (TCP, WebSocket, or others).
Member Advertisements
Replicas broadcast member advertisements (SignedPeerMeshMemberAdvertisementV1) that the store validates via decodeAdvertisements (lines 63-71 in store.ts). These advertisements contain the peer's role designation (client or host) and enable the routing layer to make informed decisions about connection prioritization and path selection.
Transit Mesh Selection and Lifecycle Management
Hosts may designate a transit mesh to relay traffic toward other meshes. The transitMeshId field in the stored state is validated during decodePeerMeshStoredState (lines 15-22 in store.ts), with the system throwing errors if the selected transit mesh is inactive or unreachable.
The state store periodically cleans stale data through pruneUnreferencedEvidence (lines 95-104 in store.ts), removing expired reachability leases, old advertisements, and defunct transit selections. When the host shuts down, closing the store releases the file lock (lines 49-55 in store.ts), allowing another process to acquire mastership of the mesh state.
Node Orchestration and Error Handling
The PeerMeshNode class in packages/runtime-host/src/peer-mesh/node.ts runs the mesh's main runtime loop, monitoring the state store via subscribe for membership changes. When the mesh reaches a terminal state, the node throws "Peer Mesh is closed" errors (lines 373-384 in node.ts) to prevent further operations on a disconnected topology.
This orchestration layer coordinates invitation handling, lease renewals, and connection pool management, ensuring that the host's actual network connections remain synchronized with the persisted state in peer-mesh.json.
Implementing Peer Mesh Connections
The following examples demonstrate the complete workflow for establishing Peer Mesh host connections in Apache Maka:
// 1. Open the persisted Peer Mesh state store for the current host
import { openPeerMeshStateStore } from '@maka/runtime-host/peer-mesh/store';
// dataRoot is a directory unique to the host instance
const store = await openPeerMeshStateStore('/var/lib/maka/host1', 'peer-abc123');
// 2. Create a new invitation (run on the authority mesh)
import { authorityKeys } from '@maka/runtime-host/peer-mesh/store';
import { createInvitation } from '@maka/runtime-host/peer-mesh/model';
const authority = authorityKeys(myAuthorityState);
const invitation = await createInvitation({
meshId: 'mesh-001',
authorityPublicKey: authority.publicKey,
authorityPrivateKey: authority.privateKey,
expiresInSec: 300,
});
// 3. Join the mesh as a replica
import { PeerMeshNode } from '@maka/runtime-host/peer-mesh/node';
const node = new PeerMeshNode({
localPeerId: 'peer-abc123',
store,
invitation, // the invitation received from the authority
transportFactory: myTransportFactory,
});
await node.join(); // performs the pending-join mutation and establishes connections
// 4. Listen for mesh changes (e.g., new members, lease updates)
store.subscribe(() => {
const state = store.read();
console.log('Mesh roster updated – members:', state.meshes.flatMap(m => m.roster.roster.members));
});
Summary
- Peer Mesh uses atomic JSON persistence (
peer-mesh.json) with file locking to maintain crash-safe host connection state across restarts. - Role separation between authorities (who sign invitations) and replicas (who redeem them) creates a cryptographically verifiable trust model for mesh membership.
- State transitions are guarded by
assertStateAdvanceto ensure monotonic progression through join phases (prepared,outcome_unknown,leave_pending). - Discovery relies on signed reachability leases and member advertisements decoded by
store.tsfunctions to determine active transport paths. - Transit meshes provide relay capabilities, while
pruneUnreferencedEvidenceensures the state store remains free of stale entries. - Error handling distinguishes between persistence failures (
PeerMeshPersistenceError) and runtime terminal states viaPeerMeshNode.
Frequently Asked Questions
What is the difference between authority and replica roles in Maka Peer Mesh?
An authority is the administrative host that holds the private cryptographic key for a mesh, maintains the canonical roster, and issues signed invitations to new members. A replica is a non-authoritative host that joins by redeeming an invitation and follows the authority's state updates. The decodePeerMeshState function in packages/runtime-host/src/peer-mesh/store.ts validates these roles during state initialization.
How does Maka ensure atomic updates to mesh state?
Maka implements atomic updates through a combination of file locking (peer-mesh.owner) and atomic file replacement. The openPeerMeshStateStore function acquires an exclusive lock, and all mutations write to a temporary file before replacing peer-mesh.json. If corruption occurs, the system throws PeerMeshPersistenceError or PeerMeshPostCommitError to signal whether the operation completed or rolled back.
What happens when a host fails during the join process?
The join process uses PendingPeerMeshJoin entries with explicit phase tracking (prepared, outcome_unknown, leave_pending). If a host crashes, the assertStateAdvance guard prevents state rollbacks when the host restarts, allowing the PeerMeshNode to recover by re-establishing connections based on the last persisted phase stored in peer-mesh.json.
How are reachability leases validated in Peer Mesh?
Each reachability lease is a SignedPeerReachabilityLeaseV1 containing transport endpoints and expiration timestamps. The decodeReachability function (lines 41-50 in store.ts) validates cryptographic signatures and temporal bounds before accepting the lease. This ensures that hosts only attempt connections to peers with verifiably active and unexpired network advertisements.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →