Asking Other Apps¶
An app's page talks to its own backend. Sometimes the data it needs lives in another app of the same mailbox: a chat that completes names from the contacts app, an invoice that looks up a price list, a dashboard that gathers figures from several apps. A cross request is how a page asks. It sends an object that its own backend does not handle, the platform hands it to every app that does, and the answers come back on the page's event stream.
The user decides whether an app may do this, once per kind of object.
This guide follows one example through both sides: a Price List app that answers a GetPrice object, and an Invoice app whose page asks it for the price of an item. It assumes you have built an app before; the Collaborative Counter tutorial covers the basics the snippets here take for granted. The exact requests, replies and status codes are in the Cross Requests reference.
How it works¶
- The page opens its event stream,
GET /api/v2/event. -
The page posts a
GrantRequestnaming the object it wants to send. The first time, Sobamail shows the user a banner over the app:Invoice asks to send GetPrice requests to Price List. Allow · Always Allow Invoice · Deny
The request is answered when the user has chosen. After that the grant is on record, and the same request is answered at once. 3. The page posts a
CrossRequestcarrying an id of its choosing and the object. 4. Every instance of every app that lists the object receives it inprocess(), exactly as if its own page had posted it, and answers withsoba.task.respond(). 5. Each answer arrives on the asking page's stream as aCrossResponseevent with the same id. A lastCrossResponsemarkedeossays everyone has been heard.
All three objects belong to the base namespace, https://sobamail.com/module/base/v1, and are handled by Sobamail itself. The asking app's backend takes no part: nothing is added to its Mutator.mjs.
The answering app¶
An app answers cross requests for the objects it lists in static objects, and for no others. There is nothing else to opt into.
The Price List app declares a request and its answer in its model module, example.com/pricelist/model/v1.mjs:
export const namespace = "https://example.com/pricelist/model/v1";
export class GetPrice {
static KEY = `{${namespace}}${this.name}`;
}
export class Price {
static KEY = `{${namespace}}${this.name}`;
}
lists them in Mutator.mjs:
and answers the request in process(), from a price table it keeps:
if (key == GetPrice.KEY) {
if (typeof content.item != "string" || content.item.length == 0) {
throw new Error("GetPrice.item is empty");
}
const rows = soba.db.exec(
"SELECT amount FROM price WHERE item = ?", content.item).data;
if (rows.length == 0) {
return; // not on this list: no answer
}
let resp = new Price();
resp.item = content.item;
resp.amount = rows[0][0];
return soba.task.respond(resp);
}
That handler serves two callers: the Price List's own page, and any app the user has allowed to send GetPrice. It cannot tell them apart, so design an object with both in mind:
- Listing an object makes it reachable. Once the user allows another app to send it, that app can send it with any content, as often as it likes. Validate the content as you would for anything that comes from outside.
- Keep reading and writing in separate objects. A grant covers one object key. An app allowed to send
GetPricecannot send aSetPriceuntil the user allows that too, and the banner names the object, so the user sees the difference. - A request handler may write. A cross request runs like a request from the app's own page, so it can call
soba.data.insert()and the change replicates as usual. Reserve that for objects whose name says so. - Answer with one object. Whatever is passed to
soba.task.respond()is the answer. A handler that responds with nothing sends no answer, and one that throws sends aStructuredError.
The asking app¶
Everything happens in the page. Put the plumbing in one module, ui/src/lib/cross.ts:
const BASE = "https://sobamail.com/module/base/v1";
const RESPONSE = `{${BASE}}CrossResponse`;
export type Answer = {
appId: string;
instanceId: string;
object: { namespace: string; name: string; content: any; error?: string };
};
type Pending = {
answers: Answer[];
resolve: (answers: Answer[]) => void;
timer: ReturnType<typeof setTimeout>;
};
const events = new EventSource("/api/v2/event"); // (1)
const pending = new Map<string, Pending>();
const granted = new Set<string>();
events.addEventListener(RESPONSE, (ev: MessageEvent) => { // (2)
const { id, eos, appId, instanceId, object } = JSON.parse(ev.data).content;
const request = pending.get(id);
if (!request) {
return; // (3)
}
if (!eos) {
request.answers.push({ appId, instanceId, object });
return;
}
clearTimeout(request.timer);
pending.delete(id);
request.resolve(request.answers);
});
function post(name: string, content: object) {
return fetch("/api/v2/object", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ namespace: BASE, name, content }),
});
}
// Whether this app may send objects of `objectKey`. Asks the user the
// first time; resolves when they have answered.
export async function askGrant(objectKey: string): Promise<boolean> {
if (granted.has(objectKey)) {
return true;
}
const response = await post("GrantRequest", { objectKey }); // (4)
if (response.status == 200) {
granted.add(objectKey);
}
return response.status == 200;
}
// Sends `object` to every app that handles it and resolves with their
// answers. Rejects when the app holds no grant for the object.
export async function crossRequest(
object: { namespace: string; name: string; content: object },
timeoutMs = 10000,
): Promise<Answer[]> {
const id = crypto.randomUUID(); // (5)
const answers = new Promise<Answer[]>((resolve) => {
const timer = setTimeout(() => { // (6)
const request = pending.get(id);
pending.delete(id);
resolve(request ? request.answers : []);
}, timeoutMs);
pending.set(id, { answers: [], resolve, timer });
});
const response = await post("CrossRequest", { id, object });
if (response.status != 202) {
clearTimeout(pending.get(id)?.timer);
pending.delete(id);
throw new Error(`cross request refused: ${response.status}`);
}
return answers;
}
- One stream for the whole page. If the app already holds an
EventSourceto follow its own mutations, add the listener to that one instead of opening a second. EventSourcedispatches by event name, so this listener seesCrossResponseevents alone.- An answer to a request the page has given up on, or to one another page of the same instance sent: every open stream of the instance receives every event.
- This call stays open while the banner is up. It can take as long as the user takes.
- The id is the page's own. It is what ties answers to their request.
- Answers are delivered to the streams that are open at that moment and are not replayed after a reconnect. A request therefore needs its own timeout, and whatever has arrived by then is what there is.
The requests are posted as JSON here; MessagePack works the same way, with Content-Type: application/msgpack.
With that in place, the Invoice app's price lookup is short. In ui/src/lib/PriceLookup.svelte:
<script lang="ts">
import { askGrant, crossRequest } from "./cross";
const namespace = "https://example.com/pricelist/model/v1";
const KEY = `{${namespace}}GetPrice`;
let item = $state("");
let prices: { list: string; amount: number }[] = $state([]);
let denied = $state(false);
async function lookUp() {
if (!(await askGrant(KEY))) {
denied = true;
return;
}
denied = false;
const answers = await crossRequest({
namespace,
name: "GetPrice",
content: { item },
});
prices = answers
.filter((a) => a.object.name == "Price")
.map((a) => ({
list: a.instanceId,
amount: a.object.content.amount,
}));
}
</script>
<input bind:value={item} placeholder="Item" />
<button onclick={lookUp}>Look up price</button>
{#if denied}
<p>Invoice is not allowed to read your price lists.</p>
{/if}
<ul>
{#each prices as price}
<li>{price.list}: {price.amount}</li>
{/each}
</ul>
Each answer says which app and which instance it came from, and carries the answer under object as plain JSON: namespace, name and content, plus error when the handler failed. A user with two price lists gets two answers, one per instance. The lookup keeps the answers that are a Price and ignores the rest.
What the user sees¶
The banner appears over the app that asked, and names three things: the app, the object, and the apps that would receive it.
| Button | Effect |
|---|---|
| Allow | This instance of the app may send the object. |
| Always Allow App | Every instance of the app may send it, including ones created later. |
| Deny | Nothing is recorded. The app may ask again. |
A grant is stored in the mailbox and replicated, so it holds on all of the user's devices. The user sees every grant under Grants in the Application Manager, and removes them there; a removed grant is gone on every device, and the next GrantRequest puts the banner up again.
Getting it right¶
Ask when the user reaches for the feature. A banner that appears as the app loads has no context. Tie askGrant() to the click, the focus or the screen that needs the data, as the lookup ties it to its button.
Do not ask again after a denial on your own. askGrant() returns false for a denial and the app may ask again, but each call puts the banner back up. Wait for the user to try the feature again.
Hide the feature when nobody can answer. A GrantRequest for an object no other app in the mailbox lists is answered 404, without asking the user. The handling app is not installed; offer the feature only when it is.
Throttle requests that follow typing. Every cross request starts the answering app's backend, and an app's requests are answered one at a time, in the order it sent them: a new request waits for the one before it. Five may wait; a request sent while five are waiting is refused with 429 and is not kept. A page that sends one per keystroke queues up answers nobody wants and then starts losing requests. For search-as-you-type, wait until the user pauses, and keep only the answers whose id belongs to the newest request. The crossRequest() helper above rejects on a 429 like any other refusal; the caller can try again once an earlier request has finished.
Expect several answers, or none. Every instance of every handling app answers separately, in no promised order. Merge them. eos means all of them have run, not that any of them answered.
Check what came back. An answer whose object.name is StructuredError is a failure, with a code in object.error and text for a human in object.content. An answer of an unexpected name is another app's reading of the same object; skip it.
Mind what JSON cannot carry. The answering backend replies in MessagePack and the stream carries JSON. Binary values arrive as base64 strings, and integer map keys as decimal strings.
Trying it out¶
Both apps run in developer mode like any other (Instantiating Your First App). Instantiate the Price List and the Invoice side by side, open the Invoice, type an item and press Look up price: the banner appears, and after Allow the list shows one row per Price List instance that knows the item. Press it again and the list refreshes with no banner.
Cross requests are served by Sobamail Desktop, on the app's own origin, like the rest of the web environment.