Nexus Relay
Forward service calls through an intermediate context and manage callbacks, remote references, and disconnect cleanup.
Nexus Relay forwards service calls to a selected peer. Callers use the same service interface, and callbacks and remote references can be called through Relay too.
Use cases
A side panel displays document changes, and the background tracks the selected page. The panel connects to the background’s document service. The background uses Relay to send calls to that page’s content script.
Page selection stays in the background. If the panel selects the page itself, it can connect directly to the content script. Relay also connects networks using different adapters, such as a host forwarding iframe calls to a Chrome background.
Service forwarding
The panel, background, and content script share DocumentToken and
DocumentService. Its watch() method accepts a document-change callback and
returns a reference to an observation object with a stop() method. See
Remote resources for the contract and implementation.
The content script registers the service on its configured instance:
contentNexus.provide(DocumentToken, documents);The background registers forwarding with relay(). selectedDocument contains
the application’s selected tabId and documentId. The application loads the
content script; Relay connects to it when a call needs it.
import { chromeTarget, usingBackgroundScript } from "@nexus-js/chrome";
import { DocumentToken } from "./shared";
import { selectedDocument } from "./selection";
const backgroundNexus = usingBackgroundScript();
const relay = backgroundNexus.relay({
services: [DocumentToken],
to: {
target: chromeTarget.contentDocument(selectedDocument),
},
});Once registered, DocumentToken appears in the background’s service catalog.
services selects which services to forward, and to.target selects their
provider. With to.nexus omitted, backgroundNexus connects to that target.
The side panel connects to the background and gets the same Token:
import { chromeTarget, usingSidePanel } from "@nexus-js/chrome";
import { DocumentToken } from "./shared";
const panelNexus = usingSidePanel();
const connection = await panelNexus.connect({
target: chromeTarget.background(),
});
const documents = connection.get(DocumentToken);
const observation = await documents.watch("intro", (change) => {
panel.apply(change);
});panel is the application’s UI object. get() creates a proxy in the panel;
await documents.watch(...) starts the remote call. The connection from the
background to the content script is called the upstream connection.
relay() synchronously returns a RelayHandle for disposing the registration.
It does not wait for the content script to be online. Even after get() succeeds,
watch() can fail if the background cannot reach the content script.
Use safeRelay() to receive a synchronous Result for registration. Use await
or Nexus.safeCall() to receive the result of a remote method such as watch().
Register synchronously in the startup module, or dynamically after
await backgroundNexus.ready(). An instance cannot register the same Token
twice, whether as a local service or a Relay.
All Tokens in services use the same destination selection and are disposed
together. If any Token conflicts, the entire batch fails to register.
Callbacks and remote references
The callback and its captured panel stay in the side panel. When the content
script invokes that callback, the function runs in the panel and updates its UI.
The observation object stays in the content script. The service returns its
reference through ref(...). Calling observation.stop() runs that object’s
method in the content script. The background delivers these calls and their
results to the appropriate context.
After stopping an observation, call Nexus.release(observation) to release that
reference, or close the scope it belongs to.
Resource scopes
Several views can observe the same document through the background, reusing one content-script connection. When view A closes, view B still needs updates. Disconnecting their shared connection would interrupt B too.
A ResourceScope groups related calls, callbacks, and remote references for
cleanup. Give A and B separate scopes. When A closes its scope, Relay tells the
other instances on the path to release A’s communication resources.
Calling connection.get(DocumentToken) uses a default scope. Getting the same
Token again on the same Connection reuses the current live default scope.
Create a scope for each view when views share a connection and need to clean up their resource groups independently:
const scope = connection.createScope(DocumentToken);
const documents = connection.get(DocumentToken, { scope });
try {
const observation = await documents.watch("intro", (change) => {
panel.apply(change);
});
await waitUntilPanelCloses();
await observation.stop();
} finally {
scope.close();
}The application implements waitUntilPanelCloses() to resolve when the view
closes. The code calls stop() to end observation in the content script, then
closes the scope to release its callbacks and references. The finally block
closes the scope even if stop() fails.
scope.close() invalidates the scope’s calls, callbacks, and references while
leaving the shared Connection open. The service remains responsible for removing
its business listeners. Completed operations are not undone.
The panel may disconnect before it can call observation.stop(). The service in
the content script must handle that case too, removing the document listener it
installed for this observation. Releasing a callback reference does not remove
an application-installed listener. See the
remote resource cleanup example.
Calling close() again has no further effect. [Symbol.dispose]() performs the
same closure. Read closed to check whether the scope has closed, or use
onClosed(listener) for notification. Listeners added after closure run immediately.
Each scope belongs to the Connection and Token that created it. Once an explicit scope closes, create a new one to continue.
Disconnects and recovery
Suppose the content script exits while the panel remains connected to the background. Once the background detects the disconnect, it closes the affected scopes and notifies the panel. The panel’s pending calls fail, and its old observation references become invalid.
The effect depends on what closes:
- Closing only A’s scope leaves B receiving updates.
- Losing the shared background-to-content connection invalidates both A’s and B’s observation references created through that connection.
- Losing the panel-to-background connection requires the panel to call
connect()again and get a fresh service proxy.
The adapter takes time to detect a disconnect. A call can time out first. A request may also have executed without its result arriving, so Nexus does not automatically repeat failed calls.
Connection recovery
The background keeps its Relay registration after the upstream disconnects.
When the panel’s connection to the background still works and the original
target is available again, call documents.watch(...) again. A proxy without an
explicit scope establishes a new scope, and the background acquires a connection
using the original target.
A successful call returns a new observation reference. Calls through the old
observation.stop() still fail.
If you created an explicit scope, create a new one and get its service proxy first. Resubscribe to replace a disconnected State mirror.
A Relay configured with only where waits for a matching connection to appear.
Supplying target allows it to initiate that connection.
Target changes
The example’s contentDocument target identifies a specific documentId.
Navigation creates a document with its own ID. When the background selects that
new document, dispose the old registration and register the new target:
relay.dispose();
const nextRelay = backgroundNexus.relay({
services: [DocumentToken],
to: {
target: chromeTarget.contentDocument(nextDocument),
},
});nextDocument is the document the application selected. dispose() removes the
service entries published by this registration and closes its scopes, keeping
shared Connections open. The new registration sends subsequent calls to the new
document.
Connections and routing
Cross-instance forwarding
One context can own several Nexus instances. For example, a host can receive
calls from an embedded page through its iframe instance and connect to the
background through its Chrome instance. Specify to.nexus for that case:
// Both local instances are configured through their respective adapters.
const relay = iframeNexus.relay({
services: [DocumentToken],
to: {
nexus: chromeNexus,
target: chromeTarget.background(),
},
});The embedded page connects to iframeNexus and gets DocumentToken from its
catalog. When a call arrives, the host uses chromeNexus to connect to the
Chrome background. Both instances run in the host.
target and where use the adapter types of chromeNexus. When to.nexus is
omitted, the instance receiving relay() also connects to the target.
Multiple hops and target selection
On a path A → B → C → D, B registers forwarding to C, and C registers forwarding
to D. A connects to B, and D provides the service. Callbacks and references use
the established path, with separate sessions at each hop.
to.target and to.where follow connection acquisition
rules. target supplies the address, and where(contextMeta, connectionMeta)
checks the peer’s identity and adapter-observed connection information. Both
conditions must pass.
Without a target, acquisition waits for exactly one matching existing session; multiple matches produce an ambiguity error.
A registration uses the same target and where for every caller. Once a scope
is established, it uses the upstream session acquired at that time. New
connections do not redirect existing observation references.
Each instance checks permissions through policy.canConnect and
policy.canCall. The content script’s direct peer is the background, so its
authorization checks see the background’s connection identity.
If the service needs to know which user or view started the call, pass that information in the contract and validate it in the service. See Authorization.
State forwarding
Include a shared StoreToken in services. The panel can then connect to the
background with connectNexusStore() and subscribe to the Store. Each
subscription automatically creates its own scope.
Calling destroy() on a mirror cleans up that subscription. Other mirrors keep
receiving updates. After a scope closes, resubscribe to read a fresh complete
snapshot. See Nexus State.