diff --git a/docs/design/mockups/design-canvas.jsx b/docs/design/mockups/design-canvas.jsx
index fa1f93e7..faf9fc03 100644
--- a/docs/design/mockups/design-canvas.jsx
+++ b/docs/design/mockups/design-canvas.jsx
@@ -1,19 +1,3 @@
-
-// DesignCanvas.jsx — Figma-ish design canvas wrapper
-// Warm gray grid bg + Sections + Artboards + PostIt notes.
-// Artboards are reorderable (grip-drag), deletable, labels/titles are
-// inline-editable, and any artboard can be opened in a fullscreen focus
-// overlay (←/→/Esc). State persists to a .design-canvas.state.json sidecar
-// via the host bridge. No assets, no deps.
-//
-// Usage:
-//
). tail/since map to the server's query
-// params (200/empty defaults; tail clamped server-side to
-// [10, 2000]).
-//
-// Errors: 404 if the named container isn't in the instance's
-// compose project; 503 if docker is unreachable.
export async function fetchContainerLogs(
instance: string,
container: string,
@@ -221,22 +163,18 @@ export async function fetchContainerLogs(
try {
body = JSON.parse(text);
} catch {
- // non-JSON; default body retained
}
throw new ApiError(resp.status, body);
}
return resp.text();
}
-// JwtRequest mirrors internal/ui/handlers/auth.go jwtRequest.
export interface JwtRequest {
role?: string;
ttl_seconds?: number;
audience?: string;
}
-// JwtResponse mirrors internal/ui/handlers/auth.go jwtResponse.
-// `token` always contains the raw LocalNet JWT.
export interface JwtResponse {
schema_version: number;
token: string;
@@ -247,8 +185,6 @@ export interface JwtResponse {
expires_in_seconds?: number;
}
-// issueJwt posts to the JWT endpoint. LocalNet returns the raw
-// dev-only token directly.
export function issueJwt(
name: string,
req: JwtRequest,
@@ -262,16 +198,8 @@ export function issueJwt(
);
}
-// AppConfigFormat is the query-param `format=` whitelist.
export type AppConfigFormat = "env" | "json" | "yaml";
-// fetchAppConfigText returns the .env or YAML body as plain
-// text — the env / yaml endpoints emit text/plain so apiFetch's
-// JSON-decode path would error. Inline a small fetch here that
-// returns the body verbatim.
-//
-// App config includes raw LocalNet JWTs so it can be copied directly
-// into a dApp's environment.
export async function fetchAppConfigText(
name: string,
format: "env" | "yaml",
@@ -286,12 +214,6 @@ export async function fetchAppConfigText(
return resp.text();
}
-// AppConfigPayload mirrors the shared apitypes.EnvExport
-// (internal/api/types/env.go) the app-config handler now emits — the
-// SAME shape `dpm localnet env --format=json` produces. `vars` carries
-// the flat CANTON_<...> key/value set: endpoint ports (incl. the
-// participant Ledger/Admin/JSON APIs and scan UI URL), per-role
-// credentials, and the real on-ledger party ids.
export interface AppConfigPayload {
schema_version: number;
instance: string;
@@ -303,21 +225,12 @@ export const fetchAppConfigJSON = (name: string) =>
`/api/instances/${encodeURIComponent(name)}/app-config?format=json`,
);
-// ── create-instance flow ──────────────────────────────────
-
-// SpliceVersionEntry mirrors internal/ui/handlers/splice_versions.go
-// SpliceVersionEntry. Status taxonomy matches the version picker
-// badges (latest / supported / available / drifted /
-// catalogued-only). Today the backend only emits latest+supported;
-// the rest are reserved for the upstream check.
export interface SpliceVersionEntry {
tag: string;
status: "latest" | "supported" | "available" | "drifted" | "catalogued-only";
major: string;
commit: string;
note?: string;
- // True when the release includes the released Token Standard V2 APIs and
- // implementation (Splice 0.6.11+).
v2_capable?: boolean;
}
@@ -327,45 +240,24 @@ export interface SpliceVersionsResponse {
versions: SpliceVersionEntry[];
}
-// fetchSpliceVersions powers the version picker in the create
-// modal. Stateless GET; safe to call on every modal open.
export const fetchSpliceVersions = () =>
apiFetch("/api/splice/versions");
-// CreateInstanceRequest mirrors handlers/instances.go upRequest.
-// version="" defers to the server's "latest" alias.
-// profiles maps to `dpm localnet up --profile ...` — currently the
-// only allowed entry is "observability" (Prometheus + Grafana).
export interface CreateInstanceRequest {
name: string;
version?: string;
allow_uncurated?: boolean;
profiles?: string[];
- // port_base > 0 pins deterministic host ports from this base
- // (`dpm localnet up --port-base`). Omit / 0 → auto-allocate.
port_base?: number;
- // observability_mode maps to `--observability-mode`: auto | shared |
- // per-instance. Omit → auto.
observability_mode?: string;
}
-// CreateInstanceAcceptedResponse is what POST /api/instances
-// returns on success (202). events_url is the relative path the
-// modal opens an EventSource on for progress streaming.
export interface CreateInstanceAcceptedResponse {
schema_version: number;
instance: string;
events_url: string;
}
-// createInstance kicks off the bring-up. The HTTP request returns
-// 202 immediately; progress arrives over the SSE stream at the
-// returned events_url. Errors here are client-side
-// (400 validation / 409 duplicate / 413 oversized / 422 preflight
-// failure / 503 disabled). 422 carries a PreflightReport body, not
-// the usual ApiError envelope — handled by createInstance via the
-// X-Preflight-Failed response header so the modal can surface the
-// findings inline instead of generic error text.
export async function createInstance(req: CreateInstanceRequest): Promise {
const resp = await fetch("/api/instances", {
method: "POST",
@@ -379,32 +271,20 @@ export async function createInstance(req: CreateInstanceRequest): Promise and as the body of
-// a 422 from POST /api/instances when the host can't satisfy the
-// chosen version's resource floor.
export interface PreflightReport {
schema_version: number;
ok: boolean;
sections: PreflightSection[];
summary?: string;
- // stable machine-readable code populated when ok=false.
- // Values: PORTS_IN_USE | DOCKER_DOWN | DOCKER_NOT_INSTALLED |
- // COMPOSE_V1_OR_MISSING | DOCKER_MEMORY_LOW | DISK_LOW |
- // PREFLIGHT_FAILED. Frontend switches on this for targeted
- // remediation panels.
error_code?: ErrorCode;
}
-// ErrorCode — wire-stable strings from internal/localnet/coded_error.go.
-// New values are non-breaking; renaming/repurposing is breaking.
-// Keep this union in sync with the Go constants.
export type ErrorCode =
| "PORTS_IN_USE"
| "DOCKER_DOWN"
@@ -428,10 +308,6 @@ export interface PreflightCheck {
remediation?: string[];
}
-// PreflightFailedError is thrown by createInstance when the server
-// rejects with a 422 preflight failure. The caller (typically the
-// create modal) catches this and renders the report inline rather
-// than the generic error envelope.
export class PreflightFailedError extends Error {
report: PreflightReport;
constructor(report: PreflightReport) {
@@ -440,31 +316,11 @@ export class PreflightFailedError extends Error {
}
}
-// fetchPreflight runs the system-requirements gate for a version
-// without queuing a bring-up. The create modal calls this on
-// version-change so the Create button can be disabled (and the
-// findings shown) BEFORE the user clicks — no need to round-trip
-// through POST /api/instances just to discover an under-provisioned
-// host. Always returns a PreflightReport (200) — `ok=false` is the
-// signal to block, not a thrown error.
export const fetchPreflight = (version: string) =>
apiFetch(
`/api/preflight?version=${encodeURIComponent(version)}`,
);
-// fetchDoctor runs the host-readiness diagnostic — the Web UI
-// counterpart of `dpm localnet doctor`. It calls the same shared
-// localnet.CollectDoctor collector the CLI uses, so it returns the
-// resource/Docker gate PLUS the two doctor-only advisories
-// (platform-support matrix + host-port availability) that
-// /api/preflight omits.
-//
-// `version` (optional) sets the Splice tag whose memory thresholds the
-// resource checks are graded against — defaults to the curated
-// "latest" alias server-side. Always returns a PreflightReport (200);
-// `ok=false` is a diagnostic result, not a thrown error — only a
-// malformed request (unknown version / non-numeric port_base) or a
-// server-side collector failure rejects.
export const fetchDoctor = (version?: string) =>
apiFetch(
version
@@ -472,13 +328,6 @@ export const fetchDoctor = (version?: string) =>
: "/api/doctor",
);
-// ── snapshot / restore ─────────────────────────────────────
-
-// downloadSnapshot POSTs to /api/instances/:name/snapshot via a
-// hidden-iframe form submit instead of fetch()+Blob: a snapshot can be
-// 100s of MB, and the form submit keeps the body entirely in the
-// browser's download pipeline instead of JS memory.
-//
// Error detection relies on an asymmetry: on success the server sends
// Content-Disposition: attachment, the body goes to the download
// manager, and the iframe never navigates (no `load` event). On
@@ -486,10 +335,6 @@ export const fetchDoctor = (version?: string) =>
// navigates to it, and `load` fires — we can't read the cross-document
// body, so we reject with a generic ApiError. Success is detected by
// absence: a settle timeout resolves once no `load` arrived.
-//
-// Resolves once the request is dispatched (the browser owns download
-// completion). The iframe is reused across downloads; each call
-// attaches a one-shot `load` listener so handlers don't accumulate.
const DOWNLOAD_SETTLE_MS = 1200;
export function downloadSnapshot(name: string): Promise {
@@ -511,9 +356,6 @@ export function downloadSnapshot(name: string): Promise {
let settled = false;
let settleTimer: ReturnType | undefined;
const onLoad = () => {
- // Iframe navigated → the server returned an inline error
- // document rather than an attachment; the snapshot did NOT
- // download.
if (settled) return;
settled = true;
if (settleTimer !== undefined) clearTimeout(settleTimer);
@@ -532,8 +374,6 @@ export function downloadSnapshot(name: string): Promise {
form.submit();
document.body.removeChild(form);
- // No `load` within the settle window → the body was taken by the
- // download manager (success).
settleTimer = setTimeout(() => {
if (settled) return;
settled = true;
@@ -548,14 +388,6 @@ export interface RestoreResponse {
restored: boolean;
}
-// restoreSnapshot uploads a snapshot tar to POST /api/instances/restore
-// via multipart/form-data. We use XMLHttpRequest (not fetch) for
-// upload progress events — fetch has no equivalent in Safari ≤17 and
-// the snapshot UX needs a progress bar for 100-MB-class uploads.
-//
-// onProgress receives a fraction in [0, 1]; callers render whatever
-// they like (bar, %, spinner with %). Resolves with the parsed
-// response body on 2xx; rejects with ApiError otherwise.
export function restoreSnapshot(
file: File,
name: string,
@@ -593,7 +425,6 @@ export function restoreSnapshot(
try {
body = JSON.parse(xhr.responseText);
} catch {
- /* non-JSON; keep default */
}
reject(new ApiError(xhr.status, body));
});
@@ -610,16 +441,6 @@ export interface ResumeAcceptedResponse {
events_url: string;
}
-// resumeInstance invokes POST /api/instances/{name}/up — the
-// "restart a stopped instance" verb. Backend kicks off the same
-// goroutine + SSE shape as the create-instance flow, so the
-// frontend can hand `response.events_url` straight to the
-// existing progress modal without a separate code path.
-//
-// The recorded Splice version + ports are reused, so a resume
-// won't silently upgrade or shuffle ports. Errors mirror the
-// create flow: 404 if unregistered, 409 if running or already
-// being brought up.
export async function resumeInstance(name: string): Promise {
const resp = await fetch(
`/api/instances/${encodeURIComponent(name)}/up`,
@@ -631,25 +452,12 @@ export async function resumeInstance(name: string): Promise {
const resp = await fetch(
`/api/instances/${encodeURIComponent(name)}/recreate`,
@@ -661,26 +469,15 @@ export async function recreateInstance(name: string): Promise`. Querying the SAME transaction
-// as different parties yields different event sets — pass `parties` to
-// project through specific parties, omit to use the JWT's own.
export interface TxReplayEvent {
kind: "created" | "exercised" | "archived";
node_id: number;
contract_id: string;
template_id?: string;
- choice?: string; // exercised only
- acting_parties?: string[]; // exercised only
- consuming?: boolean; // exercised only
- signatories?: string[]; // created only
- observers?: string[]; // created only
+ choice?: string;
+ acting_parties?: string[];
+ consuming?: boolean;
+ signatories?: string[];
+ observers?: string[];
}
export interface TxReplayResponse {
@@ -1228,20 +943,12 @@ export const fetchTxReplay = (
);
};
-// fetchMetricsSummary returns the headline panel data. Callers MUST
-// handle ApiError code "OBSERVABILITY_PROFILE_OFF" as the "raise
-// observability" empty state — a missing profile, not a hard failure.
export const fetchMetricsSummary = (name: string, signal?: AbortSignal) =>
apiFetch(
`/api/instances/${encodeURIComponent(name)}/metrics/summary`,
{ signal },
);
-// ObservabilityToggleResponse mirrors the POST
-// /api/instances/{name}/observability response. `enabled` is the
-// legacy synonym (true iff BOTH sidecars are on); the per-component
-// booleans are canonical. Ports are present only when the matching
-// sidecar is up.
export interface ObservabilityToggleResponse {
schema_version: number;
instance: string;
@@ -1253,11 +960,6 @@ export interface ObservabilityToggleResponse {
warning?: string;
}
-// setObservability toggles the Prometheus + Grafana sidecars on a
-// running instance via the per-component HTTP body. Routed through
-// apiFetch (the single chokepoint) so the envelope decoding +
-// ApiError mapping apply uniformly. The CLI mirror is
-// `dpm localnet observability enable|disable`.
export function setObservability(
name: string,
want: { prometheus: boolean; grafana: boolean },
@@ -1271,10 +973,6 @@ export function setObservability(
);
}
-// Prometheus range-query response (subset). The backend's
-// /metrics/range endpoint passes Prometheus's response through
-// verbatim, so the frontend decodes the same shape Prometheus
-// publishes.
export interface PrometheusRangeResponse {
status: string;
data?: {
@@ -1301,10 +999,6 @@ export const fetchMetricsRange = (
);
};
-// downInstance invokes POST /api/instances/{name}/down — runs
-// `docker compose down`, REMOVING containers and networks while
-// preserving Docker volumes and the registry entry (status=stopped).
-// Synchronous on the wire: blocks until the server returns 204 or 5xx.
export async function downInstance(name: string): Promise {
const resp = await fetch(
`/api/instances/${encodeURIComponent(name)}/down`,
@@ -1316,31 +1010,15 @@ export async function downInstance(name: string): Promise {
try {
body = JSON.parse(text);
} catch {
- /* non-JSON; keep default */
}
throw new ApiError(resp.status, body);
}
}
-// stopInstance invokes POST /api/instances/{name}/stop — runs
-// `docker compose stop`: a graceful halt that KEEPS the containers in
-// place for a fast `startInstance`. Distinct from downInstance (which
-// removes them). Synchronous: 204 on success. Valid only when running
-// or paused.
export async function stopInstance(name: string): Promise {
await postInstanceAction(name, "stop");
}
-// startInstance invokes POST /api/instances/{name}/start — the
-// intelligent "get it running" verb. The backend returns:
-//
-// - 204 — fast `docker compose start` completed (containers were
-// present); the caller just refetches.
-// - 202 + events_url — the containers were gone, so the backend fell
-// back to a full bring-up; the caller hands events_url to the
-// progress modal (same shape as resumeInstance).
-//
-// Returns the accepted response on 202, or null on 204.
export async function startInstance(
name: string,
): Promise {
@@ -1354,7 +1032,6 @@ export async function startInstance(
try {
body = JSON.parse(text);
} catch {
- /* non-JSON; keep default */
}
throw new ApiError(resp.status, body);
}
@@ -1364,9 +1041,6 @@ export async function startInstance(
return null;
}
-// pauseInstance / resumeInstance invoke POST /api/instances/{name}/pause
-// | /resume — docker compose pause/unpause. Near-instant; 204
-// on success. Pause is valid only when running, resume only when paused.
export async function pauseInstance(name: string): Promise {
await postInstanceAction(name, "pause");
}
@@ -1386,23 +1060,11 @@ async function postInstanceAction(name: string, action: string): Promise {
try {
body = JSON.parse(text);
} catch {
- /* non-JSON; keep default */
}
throw new ApiError(resp.status, body);
}
}
-// removeInstance invokes DELETE /api/instances/{name}. It mirrors
-// `localnet remove`: compose containers and named volumes are removed before
-// the registry entry. It also repairs zombie creating entries after a server
-// restart; when state.json is already gone, only the orphan index row can be
-// scrubbed because no compose-project identifier remains.
-//
-// A running instance is refused (409 INSTANCE_RUNNING) unless `force` is
-// set — the wire form of the CLI's confirmation prompt, which callers pass
-// only once the user has accepted the remove dialog. A job that is actively
-// creating is always refused (409 INSTANCE_CREATING — caller should cancel
-// /up first).
export async function removeInstance(name: string, force = false): Promise {
const qs = force ? "?force=true" : "";
const resp = await fetch(`/api/instances/${encodeURIComponent(name)}${qs}`, {
@@ -1414,16 +1076,11 @@ export async function removeInstance(name: string, force = false): Promise
try {
body = JSON.parse(text);
} catch {
- /* non-JSON; keep default */
}
throw new ApiError(resp.status, body);
}
}
-// cancelInstanceUp invokes DELETE /api/instances/{name}/up. 204 on
-// success; 404 if the goroutine already exited (idempotent). The
-// SSE stream carries the synthetic kind=cancelled event the
-// backend publishes before the actual cancel propagates.
export async function cancelInstanceUp(name: string): Promise {
const resp = await fetch(
`/api/instances/${encodeURIComponent(name)}/up`,
@@ -1435,16 +1092,11 @@ export async function cancelInstanceUp(name: string): Promise {
try {
body = JSON.parse(text);
} catch {
- /* non-JSON; keep default */
}
throw new ApiError(resp.status, body);
}
}
-// CreateProgressEvent — the discriminated-union of payloads
-// SSEProgress publishes (internal/ui/progress/sse_progress.go).
-// EventSource wire format: each event's `data:` line carries a
-// JSON object the modal switches on by `kind`.
export type CreateProgressEvent =
| StepStartedEvent
| StepProgressEvent
@@ -1455,8 +1107,6 @@ export type CreateProgressEvent =
| OutputEvent
| CancelledEvent;
-// step names mirror internal/localnet/progress.go Step constants.
-// The modal renders a step row per name in display order.
export type StepName =
| "resolve_version"
| "acquire_lock"
@@ -1510,11 +1160,6 @@ interface StepFailedEvent {
step: StepName;
summary?: string;
cause?: string;
- // stable machine-readable code, populated when the
- // server recognized the failure mode (PORTS_IN_USE,
- // DOCKER_DOWN, DOCKER_MEMORY_LOW, etc.). useCreateProgress
- // surfaces this in the banner so the modal can render targeted
- // remediation panels instead of generic "failed" copy.
error_code?: ErrorCode;
}
interface WarnEvent {
@@ -1535,9 +1180,6 @@ interface CancelledEvent {
reason?: string;
}
-// ── Agent Skills ─────────────────────────────────────────
-// Mirrors internal/skills.Skill + the /api/skills handler. The same
-// embedded docs back the CLI `localnet skills` command.
export interface Skill {
filename: string;
name: string;
@@ -1556,17 +1198,11 @@ export interface SkillsInstallResponse {
dir: string;
installed: string[];
count: number;
- // Files left untouched because an existing copy differs from the
- // bundled doc (server is clobber-safe by default). Re-install with
- // force=true to overwrite them. Mirrors skills.InstallResult.Skipped.
skipped: string[];
}
export const fetchSkills = () => apiFetch("/api/skills");
-// force overwrites locally-modified SKILL.md files that the server
-// would otherwise preserve. Defaults to false to match the safe-by-
-// default CLI (`skills install` without --force).
export const installSkills = (target: "claude" | "codex", force = false) =>
apiFetch("/api/skills/install", {
method: "POST",
@@ -1574,10 +1210,6 @@ export const installSkills = (target: "claude" | "codex", force = false) =>
body: JSON.stringify({ target, force }),
});
-// Tokens — Web UI client for /api/tokens. Mirrors api/types shapes;
-// every action is instance-scoped (`?instance=`) and error codes match
-// handlers.mapTokenError.
-
export interface TokenRef {
name: string;
symbol: string;
@@ -1589,9 +1221,6 @@ export interface TokenRef {
status: string;
}
-// HoldingSource: "ledger" = summed from the live ACS (real balance);
-// "registry" = pseudo-balance fallback when no participant is reachable
-// (NOT on-ledger truth — the UI labels these rows).
export type HoldingSource = "ledger" | "registry";
export interface TokenHolding {
@@ -1604,9 +1233,6 @@ export interface TokenHolding {
export interface TokensListResponse {
schema_version: number;
- // Endpoint contract: the participant host:port + role this list was
- // resolved against ("" endpoint = recorded/offline fallback). Mirrors
- // internal/api/types.ResolvedEndpoint.
endpoint: string;
role: string;
tokens: TokenRef[];
@@ -1614,23 +1240,13 @@ export interface TokensListResponse {
export interface TokenHoldingsResponse {
schema_version: number;
- // Endpoint contract: the participant host:port + role this balance was
- // read from ("" endpoint = registry pseudo-balance). Mirrors
- // internal/api/types.ResolvedEndpoint.
endpoint: string;
role: string;
- // Response-level provenance (matches every row's source); the UI
- // renders one disclaimer banner when "registry".
source: HoldingSource;
holdings: TokenHolding[];
- // true when the live ACS scan stopped at its safety cap (partial view).
truncated?: boolean;
}
-// --- V2 foundation shapes -------------------------------------------
-// Mirror internal/api/types/tokens.go; each is wrapped in a feature's
-// own versioned response when it lands.
-
export type TokenActivitySource = "event_log" | "transaction";
export interface TokenTransferLeg {
@@ -1641,7 +1257,6 @@ export interface TokenTransferLeg {
instrument_id: string;
}
-// One row of a V2 instrument's holdings-change history.
export interface TokenActivityEvent {
source: TokenActivitySource;
update_id: string;
@@ -1663,7 +1278,6 @@ export type AllocationStatus =
| "cancelled"
| "withdrawn";
-// A V2 DvP allocation detail.
export interface Allocation {
contract_id: string;
status: AllocationStatus;
@@ -1677,7 +1291,6 @@ export interface Allocation {
created_at?: string;
}
-// List-row form of an Allocation.
export interface AllocationSummary {
contract_id: string;
status: AllocationStatus;
@@ -1687,15 +1300,13 @@ export interface AllocationSummary {
committed: boolean;
}
-// One pending V2 transfer offer — a TransferInstruction the receiver has
-// not yet accepted. contract_id is the id the accept endpoint takes.
export interface TransferSummary {
contract_id: string;
sender: string;
receiver: string;
instrument_id: string;
amount: string;
- generation: string; // "v1" | "v2"
+ generation: string;
requested_at?: string;
execute_before?: string;
}
@@ -1706,20 +1317,14 @@ export interface BatchActionResult {
detail?: string;
}
-// Outcome of a BatchingUtility_ExecuteBatch exercise.
export interface BatchResult {
update_id: string;
actions: BatchActionResult[];
ok: boolean;
}
-// Matches the backend token.DefaultRole / roleFromQuery — keep in sync.
-// Explorer and DAR callers below keep their own app-user defaults.
const DEFAULT_ROLE = "app-provider";
-// tokenQuery builds `?instance=...&role=...` (role omitted when it just
-// repeats the default), so every token endpoint forwards role uniformly.
-// Selecting app-user must send role=app-user (no longer the omitted default).
function tokenQuery(instance: string, role?: string): string {
const params = new URLSearchParams({ instance });
if (role && role !== DEFAULT_ROLE) params.set("role", role);
@@ -1729,8 +1334,6 @@ function tokenQuery(instance: string, role?: string): string {
export const fetchTokens = (instance: string, role?: string) =>
apiFetch(`/api/tokens?${tokenQuery(instance, role)}`);
-// GET /api/tokens/identity: the act-as identities plus the one the
-// request used. Backs the Tokens screen's identity switcher.
export interface TokenIdentity {
schema_version: number;
instance: string;
@@ -1755,25 +1358,17 @@ export const fetchHoldings = (
);
};
-// ACS-derived lenses (instrument discovery, balance matrix, per-holding
-// UTXO rows). These hit the live ledger; with no endpoint the backend
-// falls back to the recorded token list (`instruments` may be absent).
-
-// An on-chain-discovered instrument.
export interface InstrumentRef {
admin: string;
instrument_id: string;
name?: string;
symbol?: string;
decimals?: number;
- // standard is the human label; generation ("v1"/"v2") is the machine
- // tag the UI gates mint/burn on — never gate on the display string.
standard?: string;
generation?: string;
on_ledger: boolean;
}
-// One HoldingV2 UTXO; a balance = sum of these.
export interface HoldingContract {
contract_id: string;
party: string;
@@ -1799,7 +1394,7 @@ export interface BalanceMatrix {
interface InstrumentsResponse {
schema_version: number;
instruments?: InstrumentRef[];
- tokens?: TokenRef[]; // fallback shape when no live endpoint
+ tokens?: TokenRef[];
}
interface MatrixResponse {
@@ -1807,7 +1402,6 @@ interface MatrixResponse {
matrix: BalanceMatrix;
}
-// One registered party alias → its on-ledger party id.
export interface PartyRef {
alias: string;
party_id: string;
@@ -1821,13 +1415,11 @@ interface PartiesResponse {
parties: PartyRef[];
}
-// Lists the instance's registered party aliases.
export const fetchParties = (instance: string, role = "app-provider") =>
apiFetch(
`/api/parties?instance=${encodeURIComponent(instance)}&role=${encodeURIComponent(role)}`,
).then((r) => r.parties);
-// Allocates a party under an alias and grants the role's user act/read-as.
export const createParty = (instance: string, alias: string, role = "app-provider") =>
apiFetch(`/api/parties?instance=${encodeURIComponent(instance)}`, {
method: "POST",
@@ -1835,14 +1427,12 @@ export const createParty = (instance: string, alias: string, role = "app-provide
body: JSON.stringify({ alias, role }),
});
-// removeParty forgets an alias (the on-ledger party persists).
export const removeParty = (instance: string, alias: string) =>
apiFetchVoid(
`/api/parties/${encodeURIComponent(alias)}?instance=${encodeURIComponent(instance)}`,
{ method: "DELETE" },
);
-// partyID → alias, for client-side labelling of party ids.
export type AliasMap = Record;
export const aliasMapFrom = (parties: PartyRef[]): AliasMap => {
@@ -1856,8 +1446,6 @@ interface HoldingContractsResponse {
contracts: HoldingContract[];
}
-// Returns ACS-discovered instruments, falling back to the recorded
-// TokenRef list (mapped to InstrumentRef) when the ledger is unreachable.
export async function fetchInstruments(
instance: string,
role = "app-provider",
@@ -1884,8 +1472,6 @@ export const fetchMatrix = (instance: string, role = "app-provider") =>
`/api/tokens/matrix?instance=${encodeURIComponent(instance)}&role=${encodeURIComponent(role)}`,
).then((r) => r.matrix);
-// Instrument KPI view: supply + holder/contract counts + per-holder
-// distribution, from one ACS scan.
export interface HolderRow {
party: string;
balance: string;
@@ -1897,9 +1483,6 @@ export interface InstrumentSummary {
instrument_id: string;
admin: string;
total_supply: string;
- /** Initial supply recorded at create. Creating mints nothing, so this
- * is stated intent, not an on-ledger fact — shown only while it
- * differs from total_supply. Absent for unregistered instruments. */
declared_supply?: string;
holder_count: number;
contract_count: number;
@@ -1922,9 +1505,6 @@ export const fetchInstrumentSummary = (
)}&role=${encodeURIComponent(role)}`,
).then((r) => r.summary);
-// Instrument activity feed. Each event is one movement netted into
-// senders/receivers + a kind (mint | burn | transfer), sourced from the
-// admin's EventLog events or HoldingV2 create/archive netting.
export interface PartyDelta {
party: string;
amount: string;
@@ -1945,21 +1525,14 @@ export interface ActivityEvent {
interface ActivityResponse {
schema_version: number;
events: ActivityEvent[];
- // true when the backend's ledger scan hit its safety cap
- // (maxActivityScan) before the window end — the feed is the newest
- // slice of a clipped scan, not the complete history.
truncated?: boolean;
}
-// What the Activity tab consumes: newest-first events + the truncation
-// flag, so the UI distinguishes "reached the end" from "scan was capped".
export interface ActivityPage {
events: ActivityEvent[];
truncated: boolean;
}
-// Returns an instrument's movement feed, newest-first (offset
-// descending), plus the truncation flag. `limit` caps the rows.
export const fetchActivity = (
instance: string,
symbol: string,
@@ -1997,10 +1570,6 @@ export interface TokenCreateInput {
issuer: string;
}
-// A fresh per-submission Idempotency-Key for value-moving token POSTs.
-// The server dedupes retries of the SAME key, so one key per logical
-// submission: a user-initiated retry mints a new key (a new attempt); a
-// transport-level retry of the same fetch reuses it.
function idempotencyHeader(): Record {
return { "Idempotency-Key": crypto.randomUUID() };
}
@@ -2019,8 +1588,6 @@ export const createToken = (
},
);
-// POST /api/tokens/demo result: the created instrument, issuer party,
-// and (when seeded) the funded holder.
export interface DemoResult {
token: TokenRef;
issuer: PartyRef;
@@ -2028,9 +1595,6 @@ export interface DemoResult {
seeded: boolean;
}
-// Provisions a live demo token in one call (issuer + V2 instrument whose
-// supply is minted to a holder party). Throws ApiError(412, NEEDS_V2_LOCALNET)
-// when the instance has no live V2 endpoint.
export const launchDemoToken = (
instance: string,
opts?: { symbol?: string; initial_supply?: string; decimals?: number },
@@ -2055,9 +1619,6 @@ export const mintToken = (
idempotencyHeader(),
);
-// Submits a live transfer and returns the created TransferInstruction id
-// (Offer kind) so the caller can drive the receiver-side Accept. settled
-// is true when auto-accept chained it (or a Direct/self transfer needed none).
export const transferToken = async (
instance: string,
symbol: string,
@@ -2067,13 +1628,6 @@ export const transferToken = async (
reason?: string,
role?: string,
autoAccept?: boolean,
- // atomic (with autoAccept) batches transfer+accept into one
- // all-or-nothing BatchingUtilityV2 transaction; on-ledger test tokens
- // only. EXPERIMENTAL and not yet supported on current Splice — the
- // accept leg can't reference the transfer leg's instruction within one
- // batch, so the server errors and nothing commits. Default
- // (undefined/false) keeps the working sequential offer→accept path.
- // Mirrors the CLI's --atomic flag (also experimental).
atomic?: boolean,
): Promise<{ transferInstructionId: string; settled: boolean }> => {
const resp = await fetch(
@@ -2096,7 +1650,6 @@ export const transferToken = async (
try {
parsed = await resp.json();
} catch {
- /* keep default */
}
throw new ApiError(resp.status, parsed);
}
@@ -2107,8 +1660,6 @@ export const transferToken = async (
return { transferInstructionId: body.transfer_instruction_id ?? "", settled: !!body.settled };
};
-// Funds a party from a well-known source, auto-accepted. Empty source
-// defaults to the role's funded party.
export const faucetToken = (
instance: string,
symbol: string,
@@ -2123,8 +1674,6 @@ export const faucetToken = (
idempotencyHeader(),
);
-// Dry-run coin selection: which Holding contracts a transfer consumes,
-// the change, and whether the sender can cover it. Read-only.
export interface TransferPlan {
instrument: string;
from: string;
@@ -2182,22 +1731,14 @@ export const acceptTransfer = (
idempotencyHeader(),
);
-// --- V2 DvP allocations ---------------------------------------------
-// The allocate / list / settle-withdraw-cancel endpoints; same RunX
-// orchestration the `token allocate/allocations/settle` CLI verbs call.
-
interface AllocationsListResponse {
schema_version: number;
- // Endpoint contract: participant host:port + role this scan resolved
- // against. Mirrors internal/api/types.ResolvedEndpoint.
endpoint: string;
role: string;
allocations: AllocationSummary[];
aliases: AliasMap;
}
-// Lists ready-to-settle V2 allocations (optionally filtered to one
-// authorizer), plus the alias map for labelling party ids.
export async function fetchAllocations(
instance: string,
party?: string,
@@ -2214,8 +1755,6 @@ export async function fetchAllocations(
interface PendingTransfersListResponse {
schema_version: number;
- // Endpoint contract: participant host:port + role this scan resolved
- // against. Mirrors internal/api/types.ResolvedEndpoint.
endpoint: string;
role: string;
pending_transfers: TransferSummary[];
@@ -2223,9 +1762,6 @@ interface PendingTransfersListResponse {
aliases: AliasMap;
}
-// Lists the pending V2 transfer offers visible on the participant
-// (optionally filtered to offers involving one party), plus the alias map
-// for labelling party ids and a truncated flag when the scan was capped.
export async function fetchPendingTransfers(
instance: string,
party?: string,
@@ -2253,8 +1789,6 @@ export interface AllocateInput {
committed?: boolean;
}
-// Creates a V2 allocation and returns the resulting Allocation (or
-// pending AllocationInstruction) contract id.
export async function allocateToken(
instance: string,
symbol: string,
@@ -2274,7 +1808,6 @@ export async function allocateToken(
try {
parsed = await resp.json();
} catch {
- /* keep default */
}
throw new ApiError(resp.status, parsed);
}
@@ -2282,9 +1815,6 @@ export async function allocateToken(
return { allocationId: b.allocation_id ?? "" };
}
-// withdraw / cancel exercise the matching per-allocation choice; both
-// return void on 2xx. Settlement (SettlementFactory_SettleBatch) is not yet
-// functional on LocalNet, so no settle action is exposed.
export const withdrawAllocation = (
instance: string,
allocationID: string,
@@ -2322,9 +1852,6 @@ function allocationActionURL(
)}${party ? `&party=${encodeURIComponent(party)}` : ""}`;
}
-// A thin POST wrapper for 204-returning handlers (mint/transfer/burn/
-// accept: 204 on success, ApiError on failure). extraHeaders carries the
-// Idempotency-Key so a retry or double-click can't submit twice.
async function apiFetchVoid(
path: string,
body: unknown,
@@ -2340,7 +1867,6 @@ async function apiFetchVoid(
try {
parsed = await resp.json();
} catch {
- /* keep default */
}
throw new ApiError(resp.status, parsed);
}
diff --git a/internal/cli/localnet/contracts.go b/internal/cli/localnet/contracts.go
index e063fa65..41adeef2 100644
--- a/internal/cli/localnet/contracts.go
+++ b/internal/cli/localnet/contracts.go
@@ -24,23 +24,6 @@ import (
// SchemaVersion constant in internal/api/types for HTTP shapes.
const contractsTxSchemaVersion = 1
-// buildContracts wires `dpm localnet contracts ` — the CLI
-// surface for the Daml LF v2 Ledger API, backed by the
-// internal/canton/ledger client.
-//
-// Sub-verbs:
-//
-// watch — stream Active Contract Set changes (StateService.GetActiveContracts
-// + UpdateService.GetUpdates for ongoing deltas).
-// ls — paginated snapshot of the current ACS (StateService.GetActiveContracts).
-//
-// Both default to text output (term.Table); --format json emits a
-// stable JSON shape with schema_version suitable for jq / CI
-// assertions.
-//
-// Endpoint discovery: LocalNet's participant gRPC ports are
-// network-internal (not host-published) — pass --endpoint
-// host:port explicitly.
func buildContracts() *cobra.Command {
cmd := &cobra.Command{
Use: "contracts",
@@ -92,10 +75,6 @@ func buildContractsLs() *cobra.Command {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "ledger end query failed:", err)
return localnet.AsExitError(localnet.ExitRuntimeFailure)
}
- // Default party scope: when --party is omitted, project
- // through the JWT's own act/read parties (mirrors the Web
- // UI's per-party filter) so the default filter is a shape
- // the participant accepts even for user-id tokens.
effParties, err := resolveDefaultParties(cmd.Context(), cmd.ErrOrStderr(), client, parties)
if err != nil {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), err)
@@ -189,15 +168,6 @@ func buildContractsWatch() *cobra.Command {
return cmd
}
-// buildTx wires `dpm localnet tx ` — transaction ops sister
-// command to `contracts`. Same ledger client, different lens.
-//
-// Sub-verbs:
-//
-// ls — bounded list of recent transactions (UpdateService.GetUpdates).
-// replay — fetch a single transaction by --id or --offset and render its
-// events in tree shape (UpdateService.GetUpdateById /
-// GetUpdateByOffset).
func buildTx() *cobra.Command {
cmd := &cobra.Command{
Use: "tx",
@@ -253,9 +223,6 @@ func buildTxLs() *cobra.Command {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "ledger end query failed:", err)
return localnet.AsExitError(localnet.ExitRuntimeFailure)
}
- // --from is a real offset only when the user set it:
- // an explicit --from 0 reads from genesis, while an
- // unset --from picks the default recent window.
fromSet := cmd.Flags().Changed("from")
toSet := cmd.Flags().Changed("to")
begin, endIncl, err := resolveOffsetWindow(fromOff, toOff, fromSet, toSet, end.Offset)
@@ -278,11 +245,6 @@ func buildTxLs() *cobra.Command {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "update stream failed:", err)
return localnet.AsExitError(localnet.ExitRuntimeFailure)
}
- // tx ls is a bounded LIST (not a live tail): collect the
- // NEWEST `limit` matching rows in the scanned window via a
- // ring buffer, then print the window we actually inspected
- // so a filtered query that finds nothing isn't mistaken for
- // "no such transactions" when matches sit just outside it.
return renderUpdateList(cmd.OutOrStdout(), instance, effParties, format, stream, limit, begin, *endIncl)
},
}
@@ -299,19 +261,11 @@ func buildTxLs() *cobra.Command {
return cmd
}
-// txReplayLedger is the narrow interface `tx replay` needs from the
-// ledger client. Mirrors the token package's LedgerClient seam: keeps
-// the production path on *ledger.Client while letting unit tests inject
-// a fake without dialing a real participant. Add methods only as new
-// orchestration paths come under test.
type txReplayLedger interface {
UpdateById(ctx context.Context, req *lapiv2.GetUpdateByIdRequest) (*lapiv2.GetUpdateResponse, error)
UpdateByOffset(ctx context.Context, req *lapiv2.GetUpdateByOffsetRequest) (*lapiv2.GetUpdateResponse, error)
}
-// dialTxReplayLedgerFn is the test seam buildTxReplay's RunE dials
-// through. Defaults to upcasting dialLedger's concrete *ledger.Client
-// to txReplayLedger. Tests reassign to return a fake.
var dialTxReplayLedgerFn = func(ctx context.Context, instance, endpoint, token, role string) (txReplayLedger, func(), error) {
c, cleanup, err := dialLedger(ctx, instance, endpoint, token, role)
if err != nil {
@@ -346,7 +300,6 @@ func buildTxReplay() *cobra.Command {
if err := localnet.ValidateFormat(format, "text", "json"); err != nil {
return err
}
- // Mutually exclusive: exactly one of --id / --offset.
haveID := strings.TrimSpace(updateID) != ""
haveOff := cmd.Flags().Changed("offset")
if !haveID && !haveOff {
@@ -368,10 +321,6 @@ func buildTxReplay() *cobra.Command {
}
defer cleanup()
- // Replay uses the tree (LEDGER_EFFECTS) shape so users see
- // exercised choices, not just the ACS-delta projection. The
- // EventFormat carries the --party filter; nil templates means
- // "no template restriction".
uf := &lapiv2.UpdateFormat{
IncludeTransactions: &lapiv2.TransactionFormat{
EventFormat: buildEventFormat(parties, nil, true),
@@ -415,11 +364,6 @@ func buildTxReplay() *cobra.Command {
return cmd
}
-// The per-event `tx replay` shape is shared with the Web UI replay
-// endpoint via apitypes.TxReplayEvent / TxReplayResponse, and the
-// projection itself is ledger.ProjectReplayEvents — so the two
-// surfaces can never drift on which fields a replay surfaces.
-
func renderTxReplay(out io.Writer, instance string, parties []string, format string, txn *lapiv2.Transaction) error {
summaries := ledger.ProjectReplayEvents(txn)
rows := make([]apitypes.TxReplayEvent, 0, len(summaries))
@@ -503,8 +447,6 @@ func renderTxReplayText(out io.Writer, instance string, parties []string, txn *l
return nil
}
-// identString stringifies a gRPC Identifier as pkg:Module:Entity (same
-// shape contractRow.TemplateID uses).
func identString(id *lapiv2.Identifier) string {
if id == nil {
return ""
@@ -524,19 +466,6 @@ func identString(id *lapiv2.Identifier) string {
// LocalNet.
const defaultTxWindowSpan = 10_000
-// resolveOffsetWindow computes the (beginExclusive, endInclusive]
-// offset window for `tx ls`. --limit is deliberately NOT an input:
-// it is a row cap the renderer applies, not an offset count.
-//
-// Precedence:
-// - --to set → that exact end; otherwise the current ledger end.
-// - --from set → that exact begin (`--from 0` reads from genesis).
-// - --from unset → begin = max(0, end - defaultTxWindowSpan): a
-// generous recent window independent of --limit, so sparse
-// filtered matches are still found.
-//
-// When the resulting begin > end we fail loudly rather than silently
-// producing an empty window.
func resolveOffsetWindow(fromOff, toOff int64, fromSet, toSet bool, ledgerEnd int64) (int64, *int64, error) {
end := ledgerEnd
if toSet {
@@ -557,18 +486,6 @@ func resolveOffsetWindow(fromOff, toOff int64, fromSet, toSet bool, ledgerEnd in
return begin, &end, nil
}
-// dialLedger resolves the participant endpoint + dials the ledger
-// client. Returns a (client, cleanup) pair so the caller can
-// `defer cleanup()` to close the gRPC conn.
-//
-// Resolution mirrors the Web UI Explorer handlers (CLI ↔ Web UI
-// parity): when --endpoint is empty we resolve the participant
-// ledger port AND the per-role JWT from the registry via
-// localnet.ResolveLedgerEndpoint (registry → participant_ledger_
-// port → captured JWT → SignToken fallback). --endpoint and --token
-// remain explicit overrides; an explicit --endpoint wins outright,
-// and an explicit --token overrides the resolved JWT. `role` defaults
-// to app-provider inside the resolver when empty.
func dialLedger(ctx context.Context, instance, endpoint, token, role string) (*ledger.Client, func(), error) {
if endpoint == "" {
resolved, err := localnet.ResolveLedgerEndpoint(instance, role)
@@ -576,9 +493,6 @@ func dialLedger(ctx context.Context, instance, endpoint, token, role string) (*l
return nil, func() {}, err
}
endpoint = resolved.Endpoint
- // Explicit --token always wins; otherwise use the resolved
- // per-role JWT (which may be "" for an unauthenticated
- // participant).
if token == "" {
token = resolved.Token
}
@@ -600,12 +514,6 @@ func dialLedger(ctx context.Context, instance, endpoint, token, role string) (*l
return client, cleanup, nil
}
-// resolveDefaultParties picks the party set the EventFormat is built
-// from. An explicit --party is honoured verbatim. Otherwise — including
-// a --template with no --party — we project through the JWT's own
-// act/read parties, mirroring the Web UI Explorer's resolveLedgerForRole
-// → ResolveActAndReadParties flow.
-//
// Why this matters: Splice LocalNet signs user-id JWTs by default. A
// bare FiltersForAnyParty wildcard is accepted by request validation
// but the participant then PermissionDenies the stream for a user-id
@@ -613,14 +521,6 @@ func dialLedger(ctx context.Context, instance, endpoint, token, role string) (*l
// present. Resolving the user's concrete parties and filtering by-party
// (with the template filter applied per party) is the shape that
// actually returns data — the same reason the UI does it.
-//
-// Best-effort: if the rights lookup fails or returns no parties we
-// fall back to the wildcard (empty party set). That keeps the
-// explicit --endpoint/--token admin path and unauthenticated
-// participants working, and lets buildEventFormat emit the valid
-// non-nil-empty FiltersForAnyParty wildcard. A warning is printed to
-// errw when we couldn't resolve any party so the empty result isn't
-// mistaken for "no contracts".
func resolveDefaultParties(
ctx context.Context,
errw io.Writer,
@@ -632,9 +532,6 @@ func resolveDefaultParties(
}
resolved, err := client.ResolveActAndReadParties(ctx)
if err != nil {
- // Don't fail the command — fall back to the wildcard and let
- // the participant decide. Surface the reason so a later
- // PermissionDenied is easier to diagnose.
_, _ = fmt.Fprintln(errw, term.Dimc(
"note: could not resolve the JWT's parties ("+err.Error()+
"); querying with the wildcard claim"))
@@ -649,11 +546,6 @@ func resolveDefaultParties(
return resolved, nil
}
-// The per-contract row + list response shapes are shared with the Web
-// UI ACS handler via apitypes.ContractRow / ContractsListResponse, so
-// the two surfaces emit the same JSON and the schema pin test keeps
-// them aligned with frontend/src/api.ts.
-
func renderACSStream(
out io.Writer,
instance string,
@@ -672,8 +564,6 @@ func renderACSStream(
continue
}
ev := ac.CreatedEvent
- // nilToEmpty: marshal nil slices as [] not null so the wire
- // contract is "always an array" (matches the UI handler).
sigs := ev.GetSignatories()
if sigs == nil {
sigs = []string{}
@@ -693,8 +583,6 @@ func renderACSStream(
row.CreatedAt = ev.CreatedAt.AsTime().Format(time.RFC3339)
}
if ev.CreateArguments != nil {
- // Shared decoder so the CLI and Web UI decode payloads
- // identically.
row.Payload = ledger.RecordToMap(ev.CreateArguments)
}
rows = append(rows, row)
@@ -713,9 +601,6 @@ func renderACSStream(
return renderACSText(out, instance, parties, offset, rows)
}
-// renderACSText delegates to term.Table so the column layout
-// matches the rest of the CLI surface (status, list, container
-// list).
func renderACSText(out io.Writer, instance string, parties []string, offset int64, rows []apitypes.ContractRow) error {
if len(rows) == 0 {
_, _ = fmt.Fprintln(out, term.Dimc("no active contracts"))
@@ -723,7 +608,7 @@ func renderACSText(out io.Writer, instance string, parties []string, offset int6
}
cols := []term.Column{
{Label: "contract id", Width: 24},
- {Label: "template", Width: 0}, // flex
+ {Label: "template", Width: 0},
{Label: "signatories", Width: 0},
}
body := make([][]string, 0, len(rows))
@@ -744,11 +629,6 @@ func renderACSText(out io.Writer, instance string, parties []string, offset int6
return nil
}
-// updateEventRow is the per-event JSON shape emitted under each
-// transaction by `contracts watch` / `tx ls`. Mirrors the Web UI
-// transactions handler's txEventRow so both surfaces agree on the
-// create/archive/exercise projection (shared decoder:
-// ledger.ProjectTransactionEvents).
type updateEventRow struct {
Kind string `json:"kind"`
ContractID string `json:"contract_id,omitempty"`
@@ -772,15 +652,6 @@ func eventRowsFrom(txn *lapiv2.Transaction) []updateEventRow {
return rows
}
-// renderUpdateStream prints rows for the UpdateService stream — the
-// live `contracts watch` tail. Limit caps the count (after which we
-// cancel by returning). JSON mode is NDJSON so consumers can `dpm
-// localnet contracts watch --format json | jq` stream-style.
-//
-// Each transaction is followed by one indented line PER event (kind,
-// template, contract id, witnesses) — a live tail of create/archive
-// events, similar to `kubectl get -w`, so a user watching for a
-// specific contract creation sees it as it lands.
func renderUpdateStream(
out io.Writer,
instance string,
@@ -823,9 +694,6 @@ func renderUpdateStream(
return nil
}
-// printTxnText renders one transaction header followed by one
-// indented line per event. Shared by `contracts watch` and `tx ls`
-// text output so the two surfaces look identical.
func printTxnText(out io.Writer, txn *lapiv2.Transaction, events []updateEventRow) {
_, _ = fmt.Fprintf(out, "%s offset=%d events=%d %s\n",
term.Brandc(truncTail(txn.UpdateId, 16)),
@@ -844,15 +712,6 @@ func printTxnText(out io.Writer, txn *lapiv2.Transaction, events []updateEventRo
}
}
-// renderUpdateList collects the NEWEST `limit` transactions from a
-// bounded `tx ls` stream and prints them newest-first. Unlike
-// renderUpdateStream (a live tail where stopping at the first `limit`
-// rows is correct), `tx ls` must return the most RECENT matches in
-// the scanned window — the stream arrives in ASCENDING offset order,
-// so we keep a fixed-size ring of the last `limit` rows rather than
-// the first. The scanned offset window (begin, end] is printed so a
-// filtered query that finds nothing isn't mistaken for "no such
-// transactions" when matches sit just outside the window.
func renderUpdateList(
out io.Writer,
instance string,
@@ -866,8 +725,6 @@ func renderUpdateList(
txn *lapiv2.Transaction
events []updateEventRow
}
- // Ring buffer of the newest `limit` records. limit<=0 means
- // "unbounded" — collect everything in the window.
var ring []txnRecord
ringCap := limit
if ringCap > 0 {
@@ -897,8 +754,6 @@ func renderUpdateList(
count++
}
}
- // Unwind the ring into chronological (oldest-first) order when it
- // was used.
if ringCap > 0 {
ring = ring[:0]
start := (head - count + ringCap) % ringCap
@@ -906,7 +761,6 @@ func renderUpdateList(
ring = append(ring, buf[(start+i)%ringCap])
}
}
- // Reverse to newest-first for display.
for i, j := 0, len(ring)-1; i < j; i, j = i+1, j-1 {
ring[i], ring[j] = ring[j], ring[i]
}
@@ -951,10 +805,6 @@ func renderUpdateList(
return nil
}
-// truncTail / truncMiddle keep wide IDs from blowing column
-// widths. truncTail appends "…"; truncMiddle elides the middle
-// (preserves prefix + suffix — useful for contract IDs where the
-// last chars distinguish entries with the same prefix).
func truncTail(s string, n int) string {
if len(s) <= n {
return s
diff --git a/internal/docker/compose.go b/internal/docker/compose.go
index f01d73f6..19f92153 100644
--- a/internal/docker/compose.go
+++ b/internal/docker/compose.go
@@ -13,50 +13,22 @@ import (
)
const (
- // Splice LocalNet's onboarding flow (DAML package vetting, SV keygen,
- // validator registration) routinely takes 3–5 minutes on a cold start,
- // and 18+ minutes has been observed on a resource-constrained machine
- // with no cached images. 25 minutes gives realistic headroom without
- // leaking goroutines indefinitely on a genuinely stuck daemon; the
- // caller can still ^C earlier.
readinessTimeout = 25 * time.Minute
readinessPollWait = 3 * time.Second
)
type ComposeRunner struct {
- ProjectName string
- // ComposeFiles is the ordered list of `-f` files passed to docker
- // compose. Later files override earlier ones.
+ ProjectName string
ComposeFiles []string
- // EnvFiles is the ordered list of --env-file paths. Compose
- // interpolates variables across these files (and the shell env), but
- // values are loaded literally — for cross-file `${VAR:-default}`
- // expansion the shell env must be primed before docker compose runs.
- EnvFiles []string
- // Env, when non-nil, replaces the inherited process environment for
- // every `docker compose` invocation. WorkDir is the cwd for every
- // invocation. Both must be set whenever ComposeFiles/EnvFiles use
- // relative paths, which they always do for the cached Splice project.
- Env []string
- WorkDir string
- LogWriter io.Writer
- // Profiles, when non-empty, becomes one or more `--profile P`
- // args on every compose invocation. Compose services scoped
- // under a profile via `profiles: [P]` are skipped unless that
- // profile is enabled — used by the `observability` overlay
- // to opt users into the Prometheus + Grafana stack
- // without forcing the extra ~600 MiB on the default path.
- Profiles []string
-
- // commandFn is the seam tests use to inject a fake docker. Production
- // callers leave it nil; tests set it to capture (and optionally script
- // the output of) every `docker compose ...` invocation.
+ EnvFiles []string
+ Env []string
+ WorkDir string
+ LogWriter io.Writer
+ Profiles []string
+
commandFn func(ctx context.Context, name string, arg ...string) *exec.Cmd
}
-// command constructs the *exec.Cmd for one `docker ...` invocation with
-// Dir + Env applied. Every method in this file routes through here so
-// no call site can accidentally drop WorkDir or Env.
func (c *ComposeRunner) command(ctx context.Context, args ...string) *exec.Cmd {
var cmd *exec.Cmd
if c.commandFn != nil {
@@ -71,13 +43,6 @@ func (c *ComposeRunner) command(ctx context.Context, args ...string) *exec.Cmd {
return cmd
}
-// workDirOrFallback returns dir when it exists, otherwise a neutral temp
-// dir. The label-only teardown (`compose -p down
-// --remove-orphans`) and RemainingContainers don't need the project's
-// compose files, so falling back keeps them working even after the
-// shared Splice cache dir (the recorded WorkDir) has been pruned. Without
-// the fallback the chdir fails, `down` errors, and `remove` could then
-// orphan the containers by scrubbing their registry entry.
func workDirOrFallback(dir string) string {
if dir != "" {
if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
@@ -87,13 +52,6 @@ func workDirOrFallback(dir string) string {
return os.TempDir()
}
-// RemainingContainers returns the ids of every container (running or
-// stopped) still labelled for this compose project. `remove` calls it to
-// confirm a teardown actually cleared docker BEFORE it scrubs the
-// registry — so a `down` that errored or silently no-op'd can't orphan
-// containers by deleting their only record. It shells out to plain
-// `docker ps` with the project-label filter, independent of any compose
-// file, so it works even after the shared Splice cache dir is gone.
func (c *ComposeRunner) RemainingContainers(ctx context.Context) ([]string, error) {
cmd := c.command(ctx, "ps", "-aq",
"--filter", "label=com.docker.compose.project="+c.ProjectName)
@@ -105,8 +63,6 @@ func (c *ComposeRunner) RemainingContainers(ctx context.Context) ([]string, erro
return strings.Fields(string(out)), nil
}
-// composeBase returns the leading docker-compose argv shared by Up/Down/
-// ps/etc.
func (c *ComposeRunner) composeBase() []string {
args := []string{"compose", "-p", c.ProjectName}
for _, f := range c.ComposeFiles {
@@ -116,8 +72,6 @@ func (c *ComposeRunner) composeBase() []string {
args = append(args, "--env-file", ef)
}
for _, p := range c.Profiles {
- // `--profile` is per-invocation; emitting it here keeps the
- // enabled profile set identical across `up` / `ps` / etc.
args = append(args, "--profile", p)
}
return args
@@ -127,11 +81,6 @@ func (c *ComposeRunner) Up(ctx context.Context) error {
// --wait is omitted deliberately: compose's --wait surfaces transient
// "unhealthy" states as fatal during long Splice onboarding, so
// WaitForHealthy does its own polling with a Splice-sized timeout.
- // Compose still honors `depends_on: { condition: service_healthy }`
- // during `up -d`; the overlay from
- // internal/localnet.WriteContainerRenameOverlay downgrades Splice's
- // nginx→splice condition to service_started so onboarding (which
- // exceeds the healthcheck retry budget) can't time out that wait.
args := append(c.composeBase(), "up", "-d")
cmd := c.command(ctx, args...)
@@ -148,10 +97,6 @@ func (c *ComposeRunner) WaitForHealthy(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, readinessTimeout)
defer cancel()
- // Keep the last raw `ps` snapshot so the timeout error can report
- // which services were stuck and in what state. The most common
- // stuck-state is splice in `restarting/starting` due to OOM-kill
- // from insufficient Docker memory (see docs/limitations.md).
var lastSnapshot []byte
for {
select {
@@ -192,10 +137,6 @@ func (c *ComposeRunner) WaitForHealthy(ctx context.Context) error {
}
}
-// allBlockersAreSpliceStarting returns true iff every non-ready service
-// in the snapshot is a `*-splice`-named container in state=running and
-// health=starting. The narrow gate keeps the readyz fallback from
-// masking real failures in other services (canton, postgres, nginx).
func (c *ComposeRunner) allBlockersAreSpliceStarting(raw []byte) bool {
if len(raw) == 0 {
return false
@@ -212,11 +153,9 @@ func (c *ComposeRunner) allBlockersAreSpliceStarting(raw []byte) bool {
return false
}
name, state, health := parts[0], parts[1], strings.TrimSpace(parts[2])
- // Ready-bucket entries don't block — skip.
if state == "running" && (health == "healthy" || health == "") {
continue
}
- // Anything else must be splice/running/starting.
if state != "running" || health != "starting" || !strings.HasSuffix(name, "-splice") {
return false
}
@@ -225,10 +164,6 @@ func (c *ComposeRunner) allBlockersAreSpliceStarting(raw []byte) bool {
return sawSplice
}
-// spliceReadyzOK execs into the splice container and probes
-// `http://localhost:2903/api/validator/readyz`; a 200 means ready.
-// Best-effort: any error (curl missing, network, non-200) → false,
-// which simply means "keep polling".
func (c *ComposeRunner) spliceReadyzOK(ctx context.Context, raw []byte) bool {
name := spliceContainerName(raw)
if name == "" {
@@ -236,9 +171,6 @@ func (c *ComposeRunner) spliceReadyzOK(ctx context.Context, raw []byte) bool {
}
probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- // curl is present in the splice image (verified against the
- // 0.6.5-snapshot `-dev` image). -sf keeps stdout empty and
- // returns non-zero on HTTP errors, so a successful exit means 200.
cmd := c.command(probeCtx,
"exec", name,
"curl", "-sf", "-o", "/dev/null",
@@ -246,8 +178,6 @@ func (c *ComposeRunner) spliceReadyzOK(ctx context.Context, raw []byte) bool {
return cmd.Run() == nil
}
-// spliceContainerName extracts the first `*-splice` container name from
-// the snapshot. Returns "" when none present.
func spliceContainerName(raw []byte) string {
scanner := bufio.NewScanner(bytes.NewReader(raw))
for scanner.Scan() {
@@ -263,8 +193,6 @@ func spliceContainerName(raw []byte) string {
return ""
}
-// formatHealthSnapshot turns the raw tab-separated `docker compose ps`
-// output into a tidy table for the timeout error message.
func formatHealthSnapshot(raw []byte) string {
if len(raw) == 0 {
return " (no services reported)"
@@ -287,54 +215,21 @@ func formatHealthSnapshot(raw []byte) string {
return b.String()
}
-// healthSnapshot runs `docker compose ps` once and classifies the result.
-// ready=true means every service is in a terminal-good state and the
-// poller can stop; fatal!=nil means something is irrecoverably broken
-// (e.g. a service exited non-zero) and the caller should fail fast
-// instead of polling further.
-//
-// Empty output (no services at all) is treated as not-ready rather than
-// fatal: compose may not have registered the project yet right after
-// `up` returns.
func (c *ComposeRunner) healthSnapshot(ctx context.Context) (ready bool, fatal error) {
_, ready, fatal = c.healthSnapshotRaw(ctx)
return ready, fatal
}
-// healthSnapshotRaw is the variant the WaitForHealthy loop uses so it
-// can stash the raw ps output for inclusion in a timeout error.
func (c *ComposeRunner) healthSnapshotRaw(ctx context.Context) (raw []byte, ready bool, fatal error) {
- // Tab-separated to keep parsing trivial even with whitespace in
- // future fields. Order: name, state, health.
args := append(c.composeBase(), "ps", "--all", "--format", "{{.Name}}\t{{.State}}\t{{.Health}}")
out, err := c.command(ctx, args...).Output()
if err != nil {
- // Transient errors (e.g. daemon momentarily unavailable) shouldn't
- // abort the whole wait — keep polling.
return nil, false, nil
}
ready, fatal = classifyHealth(out)
return out, ready, fatal
}
-// classifyHealth is the pure parser behind healthSnapshot. Extracted so
-// the readiness logic can be exercised by unit tests against canned
-// `docker compose ps` output without invoking docker.
-//
-// Decision table (per service):
-//
-// state=running, health=healthy → counts toward ready
-// state=running, health=starting → not ready, keep polling
-// state=running, health=unhealthy → not ready, keep polling
-// state=running, health="" → counts toward ready (no healthcheck)
-// state=exited|dead|removing|paused → fatal (service died)
-// state="" (no services yet) → not ready, keep polling
-//
-// The function returns ready=true iff at least one service was reported
-// AND every reported service is in a counts-toward-ready bucket.
-//
-// # Why `running/unhealthy` is not fatal
-//
// Splice's container healthchecks routinely report `unhealthy` for a
// stretch during onboarding before settling green. The container is
// alive and `restart: always` brings it back if it does crash — so a
@@ -343,26 +238,14 @@ func (c *ComposeRunner) healthSnapshotRaw(ctx context.Context) (raw []byte, read
// snapshot in the error message) is the actual gate; classifyHealth's
// job is just "is this snapshot good enough to stop polling?", and the
// honest answer for unhealthy is "no, wait".
-//
-// `exited`/`dead`/`removing`/`paused` ARE fatal because the container
-// is no longer running — no amount of waiting will produce a healthy
-// state from there.
func classifyHealth(raw []byte) (ready bool, fatal error) {
scanner := bufio.NewScanner(bytes.NewReader(raw))
count := 0
for scanner.Scan() {
- // Trim only \r (Windows line endings) — NOT all whitespace,
- // because the third column is a tab-delimited empty string for
- // services without a healthcheck and TrimSpace would eat the
- // preceding tab, collapsing 3 columns into 2.
line := strings.TrimRight(scanner.Text(), "\r")
if line == "" {
continue
}
- // Exactly three columns. If a future `docker compose` release
- // adds more, plain Split would smuggle them into parts[2] and
- // silently break the health-string switch; require the exact
- // shape and keep polling on anything weird.
parts := strings.Split(line, "\t")
if len(parts) != 3 {
return false, nil
@@ -376,33 +259,18 @@ func classifyHealth(raw []byte) (ready bool, fatal error) {
case "running":
switch health {
case "healthy", "":
- // good
default:
- // "starting", "unhealthy", or anything unknown — keep
- // polling. Unhealthy is deliberately not fatal; see the
- // decision-table commentary above.
return false, nil
}
case "exited", "dead", "removing", "paused":
return false, fmt.Errorf("service %q is in state %q", name, state)
default:
- // "created", "restarting", "" — not ready yet.
return false, nil
}
}
return count > 0, nil
}
-// Endpoints returns container-name → human-readable publisher string,
-// e.g. `nginx → "0.0.0.0:54321->2000/tcp, 0.0.0.0:54322->3000/tcp"`. The
-// value is intentionally a display blob — the raw {{.Publishers}}
-// template output, possibly with multiple comma-separated mappings.
-// Callers that need structured port info should use DiscoverPort()
-// instead.
-//
-// Tab is the field separator because Publishers values themselves
-// contain spaces; with a tab the right-hand side is always exactly the
-// Publishers value, however many ports it holds.
func (c *ComposeRunner) Endpoints(ctx context.Context) map[string]string {
endpoints := make(map[string]string)
args := append(c.composeBase(), "ps", "--format", "{{.Name}}\t{{.Publishers}}")
@@ -426,7 +294,6 @@ func (c *ComposeRunner) Endpoints(ctx context.Context) map[string]string {
return endpoints
}
-// Ps returns a tab-separated docker compose ps snapshot for status rendering.
func (c *ComposeRunner) Ps(ctx context.Context) ([]byte, error) {
args := append(c.composeBase(), "ps", "--all", "--format", "{{.Name}}\t{{.State}}\t{{.Health}}\t{{.Image}}\t{{.Publishers}}")
out, err := c.command(ctx, args...).Output()
@@ -436,13 +303,6 @@ func (c *ComposeRunner) Ps(ctx context.Context) ([]byte, error) {
return out, nil
}
-// DiscoverPort returns the host port that the given compose service has
-// mapped to its container port. Used when running with TEST_PORT=1 (i.e.
-// ephemeral allocation) so we can populate state.Ports with the actual
-// daemon-assigned ports.
-//
-// Returns 0 (not an error) if the service exists but doesn't publish
-// the requested container port — caller decides whether that's fatal.
func (c *ComposeRunner) DiscoverPort(ctx context.Context, service string, containerPort int) (int, error) {
args := append(c.composeBase(), "port", service, fmt.Sprintf("%d", containerPort))
out, err := c.command(ctx, args...).Output()
@@ -451,8 +311,6 @@ func (c *ComposeRunner) DiscoverPort(ctx context.Context, service string, contai
// surface as port=0 rather than an error.
return 0, nil
}
- // Output looks like "0.0.0.0:54321\n". Split on ':' and take the last
- // chunk so IPv6 (e.g. "[::]:54321") also parses.
s := strings.TrimSpace(string(out))
if s == "" {
return 0, nil
@@ -467,16 +325,6 @@ func (c *ComposeRunner) DiscoverPort(ctx context.Context, service string, contai
return port, nil
}
-// Stop runs `docker compose down`. When removeVolumes is true the call
-// is destructive — it strips named volumes and orphan containers (the
-// `localnet remove` semantics). When false it preserves volumes so a
-// follow-up `localnet up` against the same --name can resume from
-// existing state (the `localnet down` semantics).
-//
-// --remove-orphans is always set because forgetting it leaves dangling
-// containers after a compose project rename, and the user has no way to
-// find or remove them without inspecting docker directly.
-//
// TEARDOWN IS `-p`-ONLY — it deliberately omits the `-f` compose files,
// `--env-file`, and `--profile` flags (i.e. it does NOT use
// composeBase). Every Splice LocalNet service is profile-gated
@@ -495,11 +343,7 @@ func (c *ComposeRunner) Stop(ctx context.Context, removeVolumes bool) error {
if removeVolumes {
args = append(args, "--volumes")
}
- // CombinedOutput so a failure surfaces the real docker error instead
- // of a bare "exit status 1".
cmd := c.command(ctx, args...)
- // Run from a dir guaranteed to exist so a pruned Splice cache dir
- // (the recorded WorkDir) can't fail the chdir and strand containers.
cmd.Dir = workDirOrFallback(c.WorkDir)
out, err := cmd.CombinedOutput()
if err != nil {
@@ -511,15 +355,10 @@ func (c *ComposeRunner) Stop(ctx context.Context, removeVolumes bool) error {
return nil
}
-// Down is the destructive teardown, equivalent to Stop(ctx, true).
func (c *ComposeRunner) Down(ctx context.Context) error {
return c.Stop(ctx, true)
}
-// forceCommand builds a docker invocation that inherits the FULL process
-// environment (PATH for the compose plugin, etc.) and does not pin Dir or
-// Env to the cached project. Force teardown must not depend on the
-// project's recorded env/working-dir — which may be exactly what's broken.
func (c *ComposeRunner) forceCommand(ctx context.Context, args ...string) *exec.Cmd {
if c.commandFn != nil {
return c.commandFn(ctx, "docker", args...)
@@ -527,14 +366,6 @@ func (c *ComposeRunner) forceCommand(ctx context.Context, args ...string) *exec.
return exec.CommandContext(ctx, "docker", args...)
}
-// ForceStop tears the project down by PROJECT LABEL only — it deliberately
-// omits the -f compose files and --env-file. A normal, file-driven
-// `docker compose down` parses+interpolates those files first and errors
-// out (before removing anything) when the env is incomplete or a
-// container is unhealthy/OOM-restarting; the label-only form sidesteps
-// that, which is the whole point of `down --force`. `--timeout 10`
-// SIGKILLs containers that won't stop gracefully. The full docker output
-// is captured and returned on failure (no bare "exit status 1").
func (c *ComposeRunner) ForceStop(ctx context.Context, removeVolumes bool) error {
args := []string{"compose", "-p", c.ProjectName, "down", "--remove-orphans", "--timeout", "10"}
if removeVolumes {
@@ -550,11 +381,6 @@ func (c *ComposeRunner) ForceStop(ctx context.Context, removeVolumes bool) error
return nil
}
-// Pause runs `docker compose pause` — SIGSTOPs every container in the
-// project so they hold their in-memory state and stop consuming CPU
-// without losing it. Cheap to reverse with Unpause. Unlike Stop it keeps
-// the processes alive (no boot cost on resume) and unlike Restart it
-// doesn't bounce them. Published host ports stay bound.
func (c *ComposeRunner) Pause(ctx context.Context) error {
args := append(c.composeBase(), "pause")
cmd := c.command(ctx, args...)
@@ -566,9 +392,6 @@ func (c *ComposeRunner) Pause(ctx context.Context) error {
return nil
}
-// Unpause runs `docker compose unpause` — SIGCONTs the paused containers,
-// resuming them exactly where Pause froze them. No readiness wait is
-// needed (the apps never stopped), and ports are unchanged.
func (c *ComposeRunner) Unpause(ctx context.Context) error {
args := append(c.composeBase(), "unpause")
cmd := c.command(ctx, args...)
@@ -580,12 +403,6 @@ func (c *ComposeRunner) Unpause(ctx context.Context) error {
return nil
}
-// Restart runs `docker compose restart [services...]`. With no
-// services it restarts the whole project. Unlike down+up it keeps
-// containers, networks, and volumes — only the processes bounce —
-// so it's the right primitive for `localnet restart`. Containers
-// keep their identities but Docker MAY re-assign published host
-// ports on restart, so callers should re-capture ports afterward.
func (c *ComposeRunner) Restart(ctx context.Context, services ...string) error {
args := append(c.composeBase(), "restart")
args = append(args, services...)
@@ -598,12 +415,6 @@ func (c *ComposeRunner) Restart(ctx context.Context, services ...string) error {
return nil
}
-// StopContainers runs `docker compose -p stop` — a graceful
-// SIGTERM→SIGKILL shutdown that leaves the containers, networks, and
-// volumes in place (unlike Stop/Down, which remove them). Reverse with
-// Start: the processes restart from a clean boot, but no image pull or
-// container re-create is needed, so it's cheaper than up.
-//
// TEARDOWN IS `-p`-ONLY for the same reason Stop is (see Stop's godoc):
// every Splice service is profile-gated, so a `-f`-driven `compose stop`
// would apply profile filtering and no-op. Targeting by project label is
@@ -611,8 +422,6 @@ func (c *ComposeRunner) Restart(ctx context.Context, services ...string) error {
// "Docker Compose teardown must be `-p`-only".
func (c *ComposeRunner) StopContainers(ctx context.Context) error {
cmd := c.command(ctx, "compose", "-p", c.ProjectName, "stop")
- // Run from a dir guaranteed to exist so a pruned Splice cache dir
- // (the recorded WorkDir) can't fail the chdir and strand containers.
cmd.Dir = workDirOrFallback(c.WorkDir)
out, err := cmd.CombinedOutput()
if err != nil {
@@ -624,15 +433,7 @@ func (c *ComposeRunner) StopContainers(ctx context.Context) error {
return nil
}
-// Start runs `docker compose -p start` — the inverse of
-// StopContainers. It restarts the existing (stopped) containers of the
-// project without re-creating them. Errors if the containers were
-// removed (e.g. a `down` ran); callers should fall back to `up` in that
-// case.
-//
// `-p`-only for the same profile-filtering reason as StopContainers.
-// Docker MAY re-assign published host ports on start, so callers should
-// re-capture Canton's ephemeral gRPC ports afterward (as Restart does).
func (c *ComposeRunner) Start(ctx context.Context) error {
cmd := c.command(ctx, "compose", "-p", c.ProjectName, "start")
cmd.Dir = workDirOrFallback(c.WorkDir)
diff --git a/internal/localnet/overlay.go b/internal/localnet/overlay.go
index 6fcc510c..78b99f88 100644
--- a/internal/localnet/overlay.go
+++ b/internal/localnet/overlay.go
@@ -12,18 +12,6 @@ import (
"github.com/bitdynamics-ab/canton-devkit/assets"
)
-// splice610Containers lists every service that has a hardcoded
-// `container_name:` in Splice LocalNet's compose.yaml at the time of
-// writing (verified against both 0.5.18 and 0.6.4 — the list is
-// identical across both majors).
-//
-// Adding a new container name when Splice changes upstream is a 1-line
-// edit here. We keep the list explicit (rather than parsing compose.yaml
-// at runtime) for two reasons:
-// - Determinism: a renamed service is caught by the compile + test
-// pipeline rather than only at runtime.
-// - Simplicity: avoids dragging a YAML parser into the binary for
-// what is fundamentally a known-set problem.
var splice610Containers = []string{
"ans-web-ui-app-provider",
"ans-web-ui-app-user",
@@ -41,31 +29,6 @@ var splice610Containers = []string{
"wallet-web-ui-sv",
}
-// WriteContainerRenameOverlay generates a compose overlay file that
-// rewrites every `container_name:` from to
-// AND relaxes the dependency conditions that block bring-up.
-//
-// Two reasons one overlay covers both:
-//
-// 1. Container-name rename: without it, two `localnet up` invocations
-// collide on docker daemon-global container names (e.g. both want
-// to create `postgres`).
-// 2. depends_on relaxation: Splice's compose.yaml declares
-// `nginx depends_on splice (condition: service_healthy)` — but
-// splice's onboarding (DAML package vetting, SV keygen, validator
-// registration) routinely takes 5-10 min while splice's container
-// healthcheck retry budget is ~5 min. Compose times out the
-// dependency wait on `docker compose up -d` / `start` and reports
-// `dependency failed to start: container ... is unhealthy`, even
-// though the splice container is still alive and would settle.
-// We override JUST that condition to `service_started` so compose
-// stops blocking; ComposeRunner.WaitForHealthy then polls for real
-// readiness with a 15-min, Splice-sized timeout.
-//
-// The overlay file is written to /containers.yaml. Caller
-// appends it to the ComposeFiles list when invoking docker compose.
-//
-// Returns the absolute path of the written file.
func WriteContainerRenameOverlay(dataDir, prefix string) (string, error) {
if prefix == "" {
return "", fmt.Errorf("container prefix must be non-empty")
@@ -84,7 +47,6 @@ func WriteContainerRenameOverlay(dataDir, prefix string) (string, error) {
b.WriteString("# Real readiness is polled by WaitForHealthy.\n")
b.WriteString("services:\n")
- // Deterministic order makes the file easy to diff/inspect.
names := append([]string(nil), splice610Containers...)
sort.Strings(names)
for _, svc := range names {
@@ -107,34 +69,10 @@ func WriteContainerRenameOverlay(dataDir, prefix string) (string, error) {
return path, nil
}
-// SplicePortInternal lists the container ports the splice service
-// publishes. Same naming convention as CantonPortInternal — the
-// 903 pattern is from Splice's compose port block.
-//
-// These ports use the same `${TEST_PORT-N:}M` pattern as the Canton
-// participant ports, so they end up on 0.0.0.0 with Docker-assigned
-// ephemeral host ports when TEST_PORT is empty.
var SplicePortInternal = []int{2903, 3903, 4903}
-// loopbackPortServices enumerates every Splice compose service that
-// publishes host ports, along with the container-side ports and the
-// compose env-var pattern for the host side. Services whose host port
-// is an env-var (nginx, postgres, swagger-ui) use the "${VAR}" form
-// so the overlay reuses the allocated ephemeral value. Services whose
-// host port is Docker-assigned (canton, splice) use "0" so Docker
-// picks a free port.
-//
-// The data is intentionally kept as a literal table (not derived from
-// adapter.EndpointServices or CantonPortInternal) so that a Splice
-// upstream port-list change is caught by the cross-reference test
-// rather than silently masked by dynamic derivation.
type loopbackPort struct {
- // HostExpr is "0" for Docker-ephemeral, or "${VAR}" for env-driven.
- HostExpr string
- // ContainerExpr is usually a literal container port. For nginx UI
- // ports it must stay env-driven too: Splice templates nginx's
- // `listen` directives from the same vars DevKit overrides for
- // deterministic host ports.
+ HostExpr string
ContainerExpr string
}
@@ -143,9 +81,6 @@ type loopbackService struct {
Ports []loopbackPort
}
-// loopbackPortTable returns the full list of services whose ports must
-// be overridden to bind to 127.0.0.1. Returned as a function (not a
-// package-level var) so tests can call it without an init-order issue.
func loopbackPortTable() []loopbackService {
return []loopbackService{
{
@@ -154,12 +89,6 @@ func loopbackPortTable() []loopbackService {
{"0", "2901"}, {"0", "2902"}, {"0", "2975"},
{"0", "3901"}, {"0", "3902"}, {"0", "3975"},
{"0", "4901"}, {"0", "4902"}, {"0", "4975"},
- // :10013 is the built-in Prometheus reporter (JVM + canton
- // metrics). Published to loopback so the SHARED host-level
- // Prometheus can scrape it via host.docker.internal —
- // it lives in its own compose network and can't reach the
- // `canton` service name. Ephemeral host port, captured as
- // canton_metrics.
{"0", "10013"},
},
},
@@ -167,7 +96,6 @@ func loopbackPortTable() []loopbackService {
Name: "splice",
Ports: []loopbackPort{
{"0", "2903"}, {"0", "3903"}, {"0", "4903"},
- // :10013 — splice's Prometheus reporter; see canton above.
{"0", "10013"},
},
},
@@ -194,26 +122,11 @@ func loopbackPortTable() []loopbackService {
}
}
-// WriteLoopbackPortsOverlay generates a compose overlay that forces
-// every published port to bind to 127.0.0.1 (loopback only) instead
-// of the upstream default of 0.0.0.0 (all interfaces).
-//
-// Without this overlay, the canton, splice, postgres, and swagger-ui
-// containers are reachable from any host on the local network — a
-// security issue for a dev tool that exposes unauthenticated gRPC,
-// database, and HTTP endpoints.
-//
// The overlay uses the `!override` YAML tag (Docker Compose v2.24.0+,
// Compose Specification §merge) to REPLACE rather than append the
// ports list. Without `!override`, compose's default sequence-merge
// would concatenate the 127.0.0.1-bound entries onto the existing
// 0.0.0.0-bound ones, resulting in dual bindings.
-//
-// The overlay is written to /loopback-ports.yaml. Caller
-// appends it to the ComposeFiles list AFTER the container-rename
-// overlay so both take effect.
-//
-// Returns the absolute path of the written file.
func WriteLoopbackPortsOverlay(dataDir string) (string, error) {
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return "", fmt.Errorf("create data dir %s: %w", dataDir, err)
@@ -240,31 +153,14 @@ func WriteLoopbackPortsOverlay(dataDir string) (string, error) {
return path, nil
}
-// nginxVhostConfNames are the Splice nginx server-config templates
-// DevKit overrides. Each is materialized from assets/nginx/.conf
-// into the instance data dir and bind-mounted over the upstream copy so
-// the routing fix ships with the binary rather than being patched into
-// the content-hash-verified Splice cache.
var nginxVhostConfNames = []string{
"app-provider.conf",
"app-user.conf",
"sv.conf",
}
-// nginxTuningConfName is a DevKit-owned http-context snippet mounted
-// straight into conf.d (not a Splice template). It bumps
-// server_names_hash_bucket_size so nginx can boot with DevKit's longer
-// role-scoped vhosts (...localhost); the
-// default 64-byte bucket is too small and nginx aborts with a
-// "could not build server_names_hash" emerg. The "00-" prefix sorts it
-// ahead of the role server blocks in the include glob.
const nginxTuningConfName = "00-devkit-tuning.conf"
-// Splice service names for the instance-scoped nginx virtual hosts. Each
-// UI/API the localnet nginx fronts is reachable at
-// ..localhost: (see instanceVHost). The names
-// match Splice's own docs (wallet, ans, scan, sv, json-ledger-api,
-// grpc-ledger-api).
const (
VHostServiceWallet = "wallet"
VHostServiceANS = "ans"
@@ -274,74 +170,16 @@ const (
VHostServiceGRPCLedger = "grpc-ledger-api"
)
-// vhostRoles are the wallet-serving roles, in the order their
-// VHOST_WALLET_ env vars are emitted. Each maps to a role .conf on
-// its own UI port.
var vhostRoles = []string{"app-user", "app-provider", "sv"}
-// instanceVHost returns the instance-scoped nginx virtual host for a
-// service, e.g. instanceVHost("wallet", "localnet-2") ==
-// "wallet.localnet-2.localhost". This is the single source of truth for
-// the hostname shape shared by the nginx overlay (which injects the
-// values as ${VHOST_*} env vars) and every URL/env emitter.
-//
-// Instance names are already validated as DNS labels
-// (registry.ValidateName), so the result is always a valid hostname.
-//
-// *.localhost resolves to 127.0.0.1 in browsers, curl, and Go, but NOT
-// in the JVM/Node/Python resolvers (and some Rust HTTP clients) — those
-// need an explicit Host header (HTTP) / :authority pseudo-header (gRPC)
-// or an /etc/hosts entry.
func instanceVHost(service, instance string) string {
return service + "." + instance + ".localhost"
}
-// instanceVHostRole is instanceVHost for services that exist once per
-// role/participant (wallet, ans, json-ledger-api, grpc-ledger-api). The
-// role becomes its own subdomain label so the URL self-describes which
-// participant it hits, e.g.
-// instanceVHostRole("wallet", "app-user", "localnet-2") ==
-// "wallet.app-user.localnet-2.localhost". Single-per-instance services
-// (scan, sv) keep the shorter instanceVHost shape.
-//
-// Same resolution caveat as instanceVHost — one extra label doesn't
-// change browser/curl/Go behavior, but the stricter JVM/Node/Python
-// resolvers still need an explicit Host header / :authority or an
-// /etc/hosts entry.
func instanceVHostRole(service, role, instance string) string {
return service + "." + role + "." + instance + ".localhost"
}
-// WriteNginxVhostOverlay rewrites the hostnames DevKit's nginx serves so
-// each UI/API is reachable at an instance-scoped virtual host of the
-// form ..localhost (e.g. wallet.localnet-2.localhost).
-//
-// Splice's nginx routes by Host header, defining several `server_name`
-// blocks per listen port. DevKit ships its own copies of the role .conf
-// files (assets/nginx/*.conf) whose server_name is a ${VHOST_*} env var;
-// this overlay injects the per-instance value for each var via a compose
-// `environment:` block, and bind-mounts the DevKit copies over Splice's
-// upstream templates.
-//
-// Only the instance-scoped names are served — the flat Splice names
-// (wallet.localhost, scan.localhost, ...) are intentionally dropped so
-// URLs stay unambiguous across concurrently running localnets. DevKit's
-// own scan-registry client threads the same instance-scoped Host header
-// (see internal/localnet/token.resolveRegistryURL).
-//
-// The upstream .conf files live in the content-hash-verified Splice
-// cache (shared across instances), so we do NOT edit them. nginx.conf
-// and the includes/ dir are unchanged upstream, so the overlay still
-// points those at ${LOCALNET_DIR}/conf/nginx (the cache). Compose merges
-// `volumes` by appending, so the whole mount list is re-declared under
-// `!override` (same tactic as WriteLoopbackPortsOverlay).
-//
-// The overlay is written to /nginx-vhosts.yaml. Caller appends
-// it to the ComposeFiles list AFTER the loopback overlay. warnw receives
-// a drift notice for any materialized .conf an operator has edited; it
-// may be nil.
-//
-// Returns the absolute path of the written overlay.
func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (string, error) {
if dataDir == "" {
return "", fmt.Errorf("WriteNginxVhostOverlay: empty dataDir")
@@ -354,8 +192,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
return "", fmt.Errorf("create nginx overlay dir %s: %w", nginxDir, err)
}
- // Materialize the embedded templates (edit-preserving so an operator
- // who tweaks a vhost keeps it across `localnet up`).
for _, name := range nginxVhostConfNames {
data, err := fs.ReadFile(assets.FS, "nginx/"+name)
if err != nil {
@@ -366,9 +202,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
}
}
- // The http-context tuning snippet is a DevKit invariant (nginx won't
- // boot without the bigger bucket), so it is NOT edit-preserving —
- // always overwrite with the bundled copy.
tuning, err := fs.ReadFile(assets.FS, "nginx/"+nginxTuningConfName)
if err != nil {
return "", fmt.Errorf("read embedded nginx/%s: %w", nginxTuningConfName, err)
@@ -384,12 +217,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
// nginx.conf and includes/ stay on the upstream cache paths. The
// destination keeps Splice's `${..._PROFILE}` gating so a disabled
// profile still parks the file at an inactive `.coff.template` name.
- //
- // Per-role services (wallet, ans, json/grpc-ledger-api) get a
- // role-suffixed env var per role .conf (VHOST_WALLET_APP_USER, …) so
- // each conf can carry a distinct role-scoped hostname while sharing
- // the one nginx env namespace. Single-per-instance services (scan,
- // sv) keep a plain VHOST_SCAN / VHOST_SV.
var b strings.Builder
b.WriteString("# Generated by canton-devkit.\n")
b.WriteString("# Serves each Splice UI/API at an instance-scoped virtual host:\n")
@@ -400,8 +227,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
b.WriteString("services:\n")
b.WriteString(" nginx:\n")
b.WriteString(" environment:\n")
- // Wallet is served for every role; ans and the ledger APIs only by
- // the app-user / app-provider confs (sv.conf has no such blocks).
for _, role := range vhostRoles {
seg := normalizeEnvSegment(role)
fmt.Fprintf(&b, " VHOST_WALLET_%s: %q\n", seg, instanceVHostRole(VHostServiceWallet, role, instanceName))
@@ -412,7 +237,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
fmt.Fprintf(&b, " VHOST_JSON_LEDGER_%s: %q\n", seg, instanceVHostRole(VHostServiceJSONLedger, role, instanceName))
fmt.Fprintf(&b, " VHOST_GRPC_LEDGER_%s: %q\n", seg, instanceVHostRole(VHostServiceGRPCLedger, role, instanceName))
}
- // Single-per-instance services (the SV node's scan / sv UIs).
fmt.Fprintf(&b, " VHOST_SCAN: %q\n", instanceVHost(VHostServiceScan, instanceName))
fmt.Fprintf(&b, " VHOST_SV: %q\n", instanceVHost(VHostServiceSV, instanceName))
b.WriteString(" volumes: !override\n")
@@ -420,10 +244,6 @@ func WriteNginxVhostOverlay(dataDir, instanceName string, warnw io.Writer) (stri
fmt.Fprintf(&b, " - %s/app-provider.conf:/etc/nginx/templates/app-provider.c${APP_PROVIDER_PROFILE}f.template\n", filepath.ToSlash(nginxDir))
fmt.Fprintf(&b, " - %s/app-user.conf:/etc/nginx/templates/app-user.c${APP_USER_PROFILE}f.template\n", filepath.ToSlash(nginxDir))
fmt.Fprintf(&b, " - %s/sv.conf:/etc/nginx/templates/sv.c${SV_PROFILE}f.template\n", filepath.ToSlash(nginxDir))
- // http-context tuning snippet: mount straight into conf.d (bypassing
- // the templates/envsubst step, since it has no ${VHOST_*} vars) so
- // `include /etc/nginx/conf.d/*.conf` picks it up ahead of the
- // envsubst-rendered role blocks.
fmt.Fprintf(&b, " - %s/%s:/etc/nginx/conf.d/%s\n", filepath.ToSlash(nginxDir), nginxTuningConfName, nginxTuningConfName)
b.WriteString(" - ${LOCALNET_DIR}/conf/nginx/swagger-ui:/etc/nginx/includes\n")
diff --git a/internal/localnet/token/actions.go b/internal/localnet/token/actions.go
index 70007063..0f3bcbcf 100644
--- a/internal/localnet/token/actions.go
+++ b/internal/localnet/token/actions.go
@@ -14,23 +14,10 @@ import (
lapiv2 "github.com/digital-asset/dazl-client/v8/go/api/com/daml/ledger/api/v2"
)
-// ErrNeedsV2LocalNet signals that the requested action needs the V2
-// Splice LocalNet to be up with the splice-test-token-v2 DAR vetted.
-// CLI maps to ExitUserError; HTTP handler maps to 412 Precondition
-// Failed so the Web UI can render a meaningful remediation.
var ErrNeedsV2LocalNet = errors.New(
"V2 ledger action needs a running Splice 0.6.11 or newer LocalNet; " +
"bring one up with `localnet up --version 0.6.12`, then re-run")
-// ErrUnsupportedOnInstrument signals that the asset implementing the
-// instrument doesn't expose a standard mint or burn choice. Amulet is
-// the most common case — it doesn't implement BurnMintFactoryV1, and
-// the V2 Token Standard has no generic mint/burn interface. Real
-// tokens that want these operations either implement BurnMintFactoryV1
-// or expose asset-specific choices on the issuer's TokenRules contract.
-// CLI maps to ExitUserError; HTTP handler maps to 422 Unprocessable
-// Entity so the UI can render "this instrument doesn't support that
-// operation — use the asset's wallet UI" instead of a wiring error.
var ErrUnsupportedOnInstrument = errors.New(
"this instrument doesn't implement the V2 standard's mint/burn surface " +
"(Amulet has no BurnMintFactoryV1, and V2 defines no generic mint/burn). " +
@@ -38,17 +25,8 @@ var ErrUnsupportedOnInstrument = errors.New(
"splice-test-token-v2 instrument via `localnet token create` for a token " +
"that implements asset-specific mint via TokenRules_OfferMint")
-// ErrUnresolvedLedgerEndpoint signals that a live on-ledger action could
-// not resolve a participant host:port for the instance+role. Distinct
-// from ErrUnsupportedOnInstrument so a missing captured port is never
-// misreported as "this instrument doesn't support mint/burn". HTTP
-// maps to 503 PARTICIPANT_PORT_NOT_RECORDED; CLI prints the wrapped
-// remediation (instance, role, restart, --endpoint).
var ErrUnresolvedLedgerEndpoint = errors.New("unresolved ledger endpoint")
-// unresolvedLedgerEndpoint builds the actionable missing-port error
-// required by the endpoint contract: instance, role, restart remedy,
-// and the --endpoint override.
func unresolvedLedgerEndpoint(instance, role string) error {
return fmt.Errorf(
"%w: instance %q role %q has no recorded participant ledger port — "+
@@ -57,21 +35,12 @@ func unresolvedLedgerEndpoint(instance, role string) error {
ErrUnresolvedLedgerEndpoint, instance, role, instance, instance)
}
-// MintOptions / TransferOptions / BurnOptions / BalanceOptions are the
-// input shapes for each action. In the orchestration layer (not the CLI
-// package) so the HTTP handler can populate them from a JSON body.
type MintOptions struct {
- Instance string // required
- Instrument string // symbol OR raw instrument id; symbol resolves via ResolveBySymbol
- To string // recipient party
- Amount string // decimal string
-
- // Endpoint, when set (or auto-resolved from Instance+Role), runs the
- // live asset-specific mint (TokenRules_OfferMint) for a
- // splice-test-token-v2 instrument the issuer created on-ledger. An
- // unresolvable endpoint yields ErrUnresolvedLedgerEndpoint; an
- // instrument with no asset-specific mint path (e.g. Amulet) yields
- // ErrUnsupportedOnInstrument.
+ Instance string
+ Instrument string
+ To string
+ Amount string
+
Endpoint string
Role string
Insecure bool
@@ -82,55 +51,27 @@ type TransferOptions struct {
From string
To string
Amount string
- NoWait bool // if true, return the TransferInstruction id without waiting for accept
+ NoWait bool
Reason string
- // AutoAccept chains the receiver-side accept onto the
- // transfer when the receiver is locally controlled — the common
- // LocalNet case where you own both parties. The transfer produces a
- // pending TransferInstruction; with AutoAccept the same flow then
- // exercises Accept as the receiver, so a transfer lands in one step.
- // Ignored when NoWait is set (the two are contradictory).
AutoAccept bool
- // Atomic routes an AutoAccept on-ledger transfer through the wallet's
- // BatchingUtilityV2 so the transfer + receiver-accept commit in ONE
- // all-or-nothing transaction (see batch.go). Default (false) keeps the
- // sequential offer→accept path, which preserves partial-recovery: a
- // committed offer whose accept later fails is retryable, whereas a
- // failed batch rolls back entirely. Only takes effect for on-ledger
- // instruments with AutoAccept set and NoWait clear.
Atomic bool
- // Live-submit fields. When Endpoint is set, RunTransfer performs
- // the full V2 flow: ACS query → POST /transfer-factory → ledger
- // exercise. Empty Endpoint surfaces the legacy ErrNeedsV2LocalNet
- // stub for callers that haven't been updated to provide one.
Endpoint string
Token string
Role string
Insecure bool
- RegistryURL string // off-ledger token registry base URL (asset-specific)
+ RegistryURL string
}
type AcceptOptions struct {
Instance string
TransferInstructionID string
- // Party is the receiver acting on the instruction. Optional —
- // empty falls back to the first Act-As party granted to the JWT
- // (correct for single-party participants). Set explicitly when the
- // participant hosts several parties and the receiver isn't the
- // alphabetically-first one.
Party string
- // Gen is the instruction's token-standard generation when the caller
- // already knows it (e.g. the in-process auto-accept after a transfer).
- // Zero means "derive it" — runAcceptLive inspects the instruction
- // contract rather than guessing from the vetted surfaces, which would
- // misroute a V1 instruction on a participant that also vets V2.
Gen Generation
- // Same live-submit envelope as TransferOptions.
Endpoint string
Token string
Role string
@@ -140,13 +81,9 @@ type AcceptOptions struct {
type BurnOptions struct {
Instance string
Instrument string
- From string // party whose holding is burned
+ From string
Amount string
- // Endpoint, when set, runs the live burn for an on-ledger
- // test-token instrument: a transfer of the holder's tokens to the
- // instrument's special burn account. Amulet / registry-only
- // instruments yield ErrUnsupportedOnInstrument.
Endpoint string
Token string
Role string
@@ -154,76 +91,34 @@ type BurnOptions struct {
}
type BalanceOptions struct {
Instance string
- Party string // optional; empty = every party visible on the participant
- Instrument string // optional; empty = every instrument
-
- // Endpoint, Token, Role, Insecure are the live-ACS path. When
- // Endpoint is set, RunBalance ACS-queries the participant for
- // every HoldingInterfaceV2 contract and sums the views per
- // (party, instrument). Empty Endpoint falls back to the
- // registry-derived pseudo-balances.
- //
- // Token is optional: empty triggers per-role JWT auto-issuance
- // via registry.State.Credentials → splice.SignToken (see
- // dialLedger's token resolution chain). Role defaults to
- // "app-provider" — pass "sv" or "app-user" to dial a different
- // participant.
+ Party string
+ Instrument string
+
Endpoint string
Token string
Role string
Insecure bool
- // Limit caps result counts on paged read paths (e.g. the activity
- // feed). Zero means the caller's default applies.
Limit int
}
-// maxHoldingsScan caps how many ACS contracts runBalanceLive consumes
-// before declaring the result truncated — a guard against a runaway
-// ledger OOM-ing us via the unbounded gRPC stream. On overflow the caller
-// gets truncated=true so the UI can show "showing N of many".
const maxHoldingsScan = 10_000
-// BalanceRow is one row of the balance response — instrument + party +
-// summed amount across the participant's visible ACS holdings.
-//
-// MIRRORS internal/api/types.TokenHolding byte-for-byte (same JSON tags);
-// a local copy so this package doesn't depend on api/types. Adding a
-// field requires updating both.
type BalanceRow struct {
- InstrumentSymbol string `json:"instrument_symbol,omitempty"`
- InstrumentID string `json:"instrument_id"`
- Party string `json:"party"`
- Amount string `json:"amount"`
- // Source records whether this row was summed from the live ACS
- // ("ledger") or synthesized from the registry pseudo-balance
- // ("registry"). Every row carries its provenance so neither surface
- // can present the fallback as a real holding.
- Source HoldingSource `json:"source"`
+ InstrumentSymbol string `json:"instrument_symbol,omitempty"`
+ InstrumentID string `json:"instrument_id"`
+ Party string `json:"party"`
+ Amount string `json:"amount"`
+ Source HoldingSource `json:"source"`
}
-// HoldingSource is the provenance of a BalanceRow. Mirrors
-// api/types.HoldingSource — the wire values ("ledger"/"registry") must
-// match. Defined here too so this package stays free of an api/types
-// import (which would create a cycle as shared types grow).
type HoldingSource string
const (
- // SourceLedger — summed from the participant's live ACS.
- SourceLedger HoldingSource = "ledger"
- // SourceRegistry — the registry-derived pseudo-balance fallback
- // (issuer holds InitialSupply, everyone else 0). NOT on-ledger
- // truth; surfaced only when no live participant endpoint is
- // reachable.
+ SourceLedger HoldingSource = "ledger"
SourceRegistry HoldingSource = "registry"
)
-// RunMint mints supply of an on-ledger test-token instrument via its
-// asset-specific TokenRules_OfferMint choice (requires Endpoint and a
-// TokenRef with status "on-ledger"). Amulet and registry-only
-// instruments return ErrUnsupportedOnInstrument. A missing captured
-// ledger port returns ErrUnresolvedLedgerEndpoint before any instrument
-// capability check — never mislabeled as unsupported.
func RunMint(ctx context.Context, out io.Writer, opts MintOptions) error {
if err := requireFields("mint", "instance", opts.Instance, "instrument", opts.Instrument,
"recipient party", opts.To, "amount", opts.Amount); err != nil {
@@ -239,9 +134,6 @@ func RunMint(ctx context.Context, out io.Writer, opts MintOptions) error {
if opts.Role == "" {
opts.Role = DefaultRole
}
- // Auto-discover the endpoint from the instance's captured ledger port
- // when none was passed, so a live mint (and its self-mint guard) works
- // flag-free on a running LocalNet. Explicit --endpoint wins.
if opts.Endpoint == "" {
opts.Endpoint = ResolveLedgerEndpoint(opts.Instance, opts.Role)
}
@@ -253,8 +145,6 @@ func RunMint(ctx context.Context, out io.Writer, opts MintOptions) error {
return unresolvedLedgerEndpoint(opts.Instance, opts.Role)
}
ref := instrumentRefOrRaw(opts.Instance, opts.Instrument)
- // Live mint only for on-ledger test-token instruments. Amulet and
- // registry-only instruments have no asset-specific mint.
if ref.Status == "on-ledger" {
if err := enforceSupplyCap(ctx, opts, ref); err != nil {
return err
@@ -268,10 +158,6 @@ func RunMint(ctx context.Context, out io.Writer, opts MintOptions) error {
return ErrUnsupportedOnInstrument
}
-// RunTransfer dispatches: if opts.Endpoint is set, run the live V2
-// transfer flow (ACS → registry → exercise). Otherwise surface
-// ErrNeedsV2LocalNet so callers that haven't been updated to thread
-// through the endpoint get a clear remediation.
func RunTransfer(ctx context.Context, out io.Writer, opts TransferOptions) error {
if err := requireFields("transfer", "instance", opts.Instance, "instrument", opts.Instrument,
"sender party", opts.From, "recipient party", opts.To, "amount", opts.Amount); err != nil {
@@ -292,9 +178,6 @@ func RunTransfer(ctx context.Context, out io.Writer, opts TransferOptions) error
if opts.Role == "" {
opts.Role = DefaultRole
}
- // Auto-discover the endpoint from the instance's captured ledger port
- // when none was passed. Explicit --endpoint wins; if still empty (no
- // live participant) fall through to the ErrNeedsV2LocalNet remediation.
if opts.Endpoint == "" {
opts.Endpoint = ResolveLedgerEndpoint(opts.Instance, opts.Role)
}
@@ -324,11 +207,6 @@ func RunTransfer(ctx context.Context, out io.Writer, opts TransferOptions) error
return runTransferOffLedgerFn(ctx, out, opts)
}
-// runTransferOffLedger is the off-ledger (Amulet / external-registry)
-// transfer flow: POST to the asset's scan registry for a factory + choice
-// context, exercise it on-ledger, then optionally chain the receiver-side
-// accept. Split out so tests can pin it via the runTransferOffLedgerFn
-// seam.
func runTransferOffLedger(ctx context.Context, out io.Writer, opts TransferOptions) error {
instructionID, gen, err := runTransferLive(ctx, out, opts)
if err != nil {
@@ -338,23 +216,17 @@ func runTransferOffLedger(ctx context.Context, out io.Writer, opts TransferOptio
"transfer_instruction_id": instructionID,
})
- // Auto-accept chains the receiver-side accept (on LocalNet you own the
- // receiver). NoWait opts out; an empty instructionID means the
- // transfer already settled — nothing to accept.
if opts.AutoAccept && !opts.NoWait && instructionID != "" {
acc := AcceptOptions{
Instance: opts.Instance,
TransferInstructionID: instructionID,
Party: opts.To,
- // Thread the transfer's generation so the accept routes the
- // same way — never re-derived from surfaces, which would
- // misroute a V1 instruction on a dual-surface participant.
- Gen: gen,
- Endpoint: opts.Endpoint,
- Token: opts.Token,
- Role: opts.Role,
- Insecure: opts.Insecure,
- RegistryURL: opts.RegistryURL,
+ Gen: gen,
+ Endpoint: opts.Endpoint,
+ Token: opts.Token,
+ Role: opts.Role,
+ Insecure: opts.Insecure,
+ RegistryURL: opts.RegistryURL,
}
if err := RunAccept(ctx, out, acc); err != nil {
return fmt.Errorf("auto-accept transfer %s: %w", instructionID, err)
@@ -372,16 +244,10 @@ func RunAccept(ctx context.Context, out io.Writer, opts AcceptOptions) error {
"transfer instruction id", opts.TransferInstructionID); err != nil {
return err
}
- // Resolve a --party alias to its full party id: both the on-ledger
- // detection (which puts the receiver in an ACS party filter) and the
- // off-ledger path need a real party id, not an alias.
opts.Party = ResolveAlias(aliasMapForInstance(opts.Instance), opts.Party)
if opts.Role == "" {
opts.Role = DefaultRole
}
- // Auto-discover the endpoint from the instance's captured ledger port
- // when none was passed. Explicit --endpoint wins; if still empty fall
- // through to the ErrNeedsV2LocalNet remediation.
if opts.Endpoint == "" {
opts.Endpoint = ResolveLedgerEndpoint(opts.Instance, opts.Role)
}
@@ -391,20 +257,12 @@ func RunAccept(ctx context.Context, out io.Writer, opts AcceptOptions) error {
})
return ErrNeedsV2LocalNet
}
- // An issuer-administered test-token offer is accepted on-ledger; only
- // Amulet / external-registry instructions go through the off-ledger
- // choice-context endpoint (runAcceptOnLedgerIfTestToken reports
- // handled=false for those).
if handled, err := runAcceptOnLedgerFn(ctx, out, opts); handled || err != nil {
return err
}
return runAcceptOffLedgerFn(ctx, out, opts)
}
-// RunBurn burns supply of an on-ledger test-token instrument by
-// transferring the holder's tokens to the instrument's special burn
-// account. Amulet / registry-only instruments have no such path and
-// yield ErrUnsupportedOnInstrument.
func RunBurn(ctx context.Context, out io.Writer, opts BurnOptions) error {
if err := requireFields("burn", "instance", opts.Instance, "instrument", opts.Instrument,
"holder party", opts.From, "amount", opts.Amount); err != nil {
@@ -420,8 +278,6 @@ func RunBurn(ctx context.Context, out io.Writer, opts BurnOptions) error {
if opts.Role == "" {
opts.Role = DefaultRole
}
- // Auto-discover the endpoint from the instance's captured ledger port
- // when none was passed. Explicit --endpoint wins.
if opts.Endpoint == "" {
opts.Endpoint = ResolveLedgerEndpoint(opts.Instance, opts.Role)
}
@@ -443,29 +299,17 @@ func RunBurn(ctx context.Context, out io.Writer, opts BurnOptions) error {
return ErrUnsupportedOnInstrument
}
-// RunBalance returns per-(party, instrument) balances. When a live
-// participant endpoint is available (explicit or auto-discovered from
-// the registry) it sums the ACS holdings; otherwise it falls back to
-// registry-derived pseudo-balances (Amount = InitialSupply when
-// --party matches the issuer, zero otherwise), tagged SourceRegistry
-// so no caller can present them as on-ledger truth. The bool result
-// reports whether the live scan was truncated at maxHoldingsScan.
func RunBalance(ctx context.Context, out io.Writer, opts BalanceOptions) ([]BalanceRow, bool, error) {
if opts.Instance == "" {
return nil, false, errors.New("instance is required")
}
opts.Party = ResolveAlias(aliasMapForInstance(opts.Instance), opts.Party)
- // Auto-discover the endpoint from the registry when none was passed,
- // so both surfaces get the live ACS by default. Explicit wins.
if opts.Endpoint == "" {
opts.Endpoint = ResolveLedgerEndpoint(opts.Instance, opts.Role)
}
if opts.Endpoint != "" {
return runBalanceLive(ctx, opts)
}
- // Registry fallback: no live participant. Rows are pseudo-balances
- // (issuer holds InitialSupply, everyone else 0), tagged SourceRegistry
- // so the caller can flag them as not-on-ledger.
state, err := registry.Read(opts.Instance)
if err != nil {
return nil, false, fmt.Errorf("read instance state: %w", err)
@@ -494,11 +338,6 @@ func RunBalance(ctx context.Context, out io.Writer, opts BalanceOptions) ([]Bala
return rows, false, nil
}
-// BalanceSource reports which path RunBalance will take for opts —
-// "ledger" when a participant endpoint is available (explicit or
-// auto-discovered), "registry" otherwise. Callers set the response-level
-// provenance from it. Pure: endpoint availability, not reachability,
-// decides the path — matching RunBalance's own branch.
func BalanceSource(opts BalanceOptions) HoldingSource {
if opts.Endpoint != "" || ResolveLedgerEndpoint(opts.Instance, opts.Role) != "" {
return SourceLedger
@@ -506,22 +345,13 @@ func BalanceSource(opts BalanceOptions) HoldingSource {
return SourceRegistry
}
-// runBalanceLive streams every vetted-generation Holding from the
-// participant, parses the view, and sums amounts per (party, instrument).
-// Symbols come from the local registry when a streamed instrument matches
-// a recorded TokenRef; otherwise the row carries the raw `(admin, id)`
-// pair. addDecimal sums the textual Daml Decimals without precision loss.
func runBalanceLive(ctx context.Context, opts BalanceOptions) ([]BalanceRow, bool, error) {
- // Cancel on every return path so an early break (cap, decode error)
- // doesn't leak the gRPC stream pump goroutine.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
state, err := registry.Read(opts.Instance)
if err != nil {
return nil, false, fmt.Errorf("read instance state: %w", err)
}
- // Resolve the optional --instrument filter (symbol or raw
- // InstrumentID) into the (admin, id) pair we match streamed views on.
var wantAdmin, wantID string
if opts.Instrument != "" {
if ref, ok := state.Tokens[opts.Instrument]; ok {
@@ -568,8 +398,6 @@ func runBalanceLive(ctx context.Context, opts BalanceOptions) ([]BalanceRow, boo
// nothing to report anyway.
return nil, false, nil
}
- // Query every vetted holding surface so a V1 token like Amulet is
- // summed on a stable release, not just V2.
surfaces, err := discoverTokenSurfaces(ctx, client)
if err != nil {
return nil, false, err
@@ -607,8 +435,6 @@ func runBalanceLive(ctx context.Context, opts BalanceOptions) ([]BalanceRow, boo
if !ok || entry.ActiveContract == nil {
continue
}
- // One holding per contract (prefers the richer V2 view) — never
- // double-counted.
hv, ok := extractBestHoldingView(entry.ActiveContract.GetCreatedEvent().GetInterfaceViews())
if !ok || hv.Owner == "" {
continue
@@ -627,7 +453,6 @@ func runBalanceLive(ctx context.Context, opts BalanceOptions) ([]BalanceRow, boo
bucket[k] = sum
}
- // Join back to the local symbol table for friendly rendering.
symByID := make(map[string]string, len(state.Tokens))
for _, t := range state.Tokens {
symByID[t.IssuerParty+"\x00"+t.InstrumentID] = t.Symbol
@@ -645,40 +470,23 @@ func runBalanceLive(ctx context.Context, opts BalanceOptions) ([]BalanceRow, boo
return rows, truncated, nil
}
-// addDecimal returns a + b for two Daml Decimal strings. Empty is treated
-// as "0". Aligns fractional widths ("1.0" + "1" → "2.0") and adds as
-// big.Ints so we don't depend on a big-decimal library.
-// ErrSupplyCapExceeded is returned when a mint would push an instrument's
-// circulating supply past the initial supply declared at create. CLI maps
-// it to a user error; the HTTP handler maps it to 422 so the Web UI can
-// render the numbers rather than a generic failure.
var ErrSupplyCapExceeded = errors.New("mint exceeds the instrument's declared supply")
-// enforceSupplyCap rejects a mint that would take total supply past the
-// figure recorded at `token create`. The declared supply is devkit-side
-// bookkeeping, not a ledger invariant — the test token's TokenRules has no
-// cap, so a client minting against it directly still can — but it makes
-// the number the operator typed at create actually mean something.
-//
-// Skipped when the instrument has no declared supply (Amulet and anything
-// not created here), or when either figure isn't a decimal we can compare.
-// A scan failure is not treated as a violation: the mint proceeds rather
-// than being blocked by an unrelated read error.
func enforceSupplyCap(ctx context.Context, opts MintOptions, ref registry.TokenRef) error {
declared, ok := new(big.Rat).SetString(ref.InitialSupply)
if !ok {
- return nil // nothing declared (or unparseable) — no cap to enforce
+ return nil
}
want, ok := new(big.Rat).SetString(opts.Amount)
if !ok {
- return nil // validateAmount already vetted this; be permissive here
+ return nil
}
sum, err := RunInstrumentSummary(ctx, BalanceOptions{
Instance: opts.Instance, Role: opts.Role, Insecure: opts.Insecure,
Endpoint: opts.Endpoint, Instrument: ref.InstrumentID,
})
if err != nil {
- return nil // can't measure supply — don't block the mint on a read error
+ return nil
}
minted, ok := new(big.Rat).SetString(zeroIfEmpty(sum.TotalSupply))
if !ok {
@@ -698,8 +506,6 @@ func enforceSupplyCap(ctx context.Context, opts MintOptions, ref registry.TokenR
trimDecimal(minted), trimDecimal(headroom))
}
-// trimDecimal renders a Rat without trailing-zero noise, so an error reads
-// "2001" rather than "2001.0000000000".
func trimDecimal(r *big.Rat) string {
if r.IsInt() {
return r.Num().String()
@@ -747,10 +553,6 @@ func splitDecimal(s string) (intPart, fracPart string) {
return s, ""
}
-// instrumentRefOrRaw resolves the --instrument string to a recorded
-// TokenRef, falling back to a bare ref carrying the string as the
-// InstrumentID (Amulet and other unregistered instruments have no
-// `token create` record).
func instrumentRefOrRaw(instance, ident string) registry.TokenRef {
ref, err := resolveInstrument(instance, ident)
if err != nil {
@@ -759,9 +561,6 @@ func instrumentRefOrRaw(instance, ident string) registry.TokenRef {
return ref
}
-// resolveInstrument turns the --instrument string into a full TokenRef.
-// It may be the symbol (the common path) or the raw InstrumentID (the
-// escape hatch the HTTP handler uses with already-resolved IDs).
func resolveInstrument(instance, ident string) (registry.TokenRef, error) {
if ident == "" {
return registry.TokenRef{}, errors.New("--instrument is required")
@@ -773,7 +572,6 @@ func resolveInstrument(instance, ident string) (registry.TokenRef, error) {
if t, ok := state.Tokens[ident]; ok {
return t, nil
}
- // Fall back to InstrumentID match when the caller passed the raw id.
for _, t := range state.Tokens {
if t.InstrumentID == ident {
return t, nil
@@ -784,12 +582,6 @@ func resolveInstrument(instance, ident string) (registry.TokenRef, error) {
ident, instance)
}
-// requireFields surfaces the same "field X is required" wording as
-// the create wizard so every error in the token surface looks alike.
-// requireFields reports the first missing field by name. Callers pass
-// name/value pairs ("recipient party", opts.To) so the error tells the
-// operator which input to fill — this text surfaces directly in the Web
-// UI's form, where an internal field index means nothing.
func requireFields(verb string, nameValuePairs ...string) error {
for i := 0; i+1 < len(nameValuePairs); i += 2 {
if nameValuePairs[i+1] == "" {
@@ -799,9 +591,6 @@ func requireFields(verb string, nameValuePairs ...string) error {
return nil
}
-// validateAmount rejects an --amount that isn't a positive Daml decimal
-// before any action logic, so a plain input error is never mislabelled as
-// ErrNeedsV2LocalNet.
func validateAmount(verb, amount string) error {
if !looksLikeDecimal(amount) {
return fmt.Errorf(
@@ -814,8 +603,6 @@ func validateAmount(verb, amount string) error {
return nil
}
-// isZeroDecimal reports whether a looksLikeDecimal-valid string is zero
-// (only 0s and an optional dot). Cheap and allocation-free.
func isZeroDecimal(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] >= '1' && s[i] <= '9' {
@@ -825,13 +612,11 @@ func isZeroDecimal(s string) bool {
return true
}
-// emit writes a ": {json}" progress line, JSON-encoded for a
-// consistent surface across CLI and HTTP.
func emit(out io.Writer, verb string, payload map[string]any) {
if out == nil {
return
}
_, _ = fmt.Fprintf(out, "%s: ", verb)
enc := json.NewEncoder(out)
- _ = enc.Encode(payload) // includes trailing newline
+ _ = enc.Encode(payload)
}
diff --git a/internal/localnet/up.go b/internal/localnet/up.go
index 2a4ed493..cd961a94 100644
--- a/internal/localnet/up.go
+++ b/internal/localnet/up.go
@@ -1,7 +1,3 @@
-// Package localnet orchestrates `canton-devkit localnet ...` subcommands.
-// The actual Canton/Splice processes run in containers — this package
-// only composes preflight + Splice fetcher + docker-compose runner +
-// per-major adapter + state registry into a coherent UX.
package localnet
import (
@@ -32,22 +28,10 @@ const (
ExitRuntimeFailure = 4
)
-// ExitCodeError carries a deterministic process exit code through a
-// Cobra `RunE` return. Cobra's default behavior collapses every error
-// into exit 1; we wrap our codes in this type so the App.Run layer can
-// extract them via errors.As.
-//
-// The string form is only used when something accidentally treats this
-// as a normal error — App.Run intercepts ExitCodeError before its
-// generic stderr-print path runs, so subcommands own all human-visible
-// stderr output.
type ExitCodeError int
func (e ExitCodeError) Error() string { return fmt.Sprintf("exit code %d", int(e)) }
-// AsExitError converts a non-zero process exit code returned by one of
-// our Run* functions into an error suitable for Cobra's RunE return.
-// Zero returns nil so the happy path doesn't allocate.
func AsExitError(code int) error {
if code == 0 {
return nil
@@ -55,83 +39,29 @@ func AsExitError(code int) error {
return ExitCodeError(code)
}
-// composeOps is the subset of *docker.ComposeRunner that RunUp drives.
-// Extracted as an interface (and matched implicitly by ComposeRunner)
-// so a fake-driven happy-path test can swap in a no-op stub. Two
-// methods is the floor — adding more here means rewiring RunUp first,
-// keeping the seam honest.
type composeOps interface {
Up(ctx context.Context) error
WaitForHealthy(ctx context.Context) error
}
-// UpOptions captures the parsed `localnet up` flags. Cobra binds the
-// flags directly to the corresponding `cmd.Flags().StringVar` targets in
-// internal/cli/localnet/up.go; this struct exists so the Run* function
-// has a single typed entry point.
type UpOptions struct {
Name string
- Version string // "" or "latest" → splice.LatestAlias
-
- // AllowUncurated opts the user into layer 2 of the two-layer
- // version model: if --version is not in the curated
- // catalogue, RunUp consults the upstream Splice GitHub repo to
- // resolve a commit SHA, prints a one-line "uncurated" warning, and
- // proceeds. Without this flag, an uncurated --version fails fast
- // with ErrUncuratedTag. Default false keeps the audited path the
- // safe default for first-time users.
+ Version string
+
AllowUncurated bool
- // Profiles is the docker compose profile set to enable on this
- // bring-up. `--profile observability` adds Prometheus +
- // Grafana via the assets/compose/observability.yaml overlay.
- // Empty (default) means "no opt-in profiles" — same behavior
- // as before this field existed.
Profiles []string
- // ObservabilityMode selects shared vs per-instance sidecars when an
- // observability profile is enabled: auto (default) prefers the
- // host-shared stack and skips the per-instance overlay when it is
- // reachable, shared forces shared-only, per-instance forces the
- // overlay. Empty == auto.
ObservabilityMode ObservabilityMode
- // PortBase, when > 0, switches host-port assignment from automatic
- // (ephemeral, stable-reuse) to DETERMINISTIC: each service is pinned
- // to PortBase+N (see DeriveUIPorts). Used for reproducible
- // multi-instance / CI layouts where a fixed, predictable port map
- // matters. Every derived port must be free, or RunUp fails with a
- // PortBaseConflict (no silent fallback). 0 (default) keeps the
- // auto-allocation behavior.
PortBase int
- // SkipPreflight bypasses the docker.RunPreflight call. This is a
- // test-only knob — unit tests for the `up` orchestration can't run
- // Docker checks in CI. Not exposed as a CLI flag.
SkipPreflight bool
- // Test-only seams. When nil, RunUp uses the real
- // splice.Fetch and *docker.ComposeRunner. The fake-driven happy-
- // path test in up_test.go injects no-op stubs so we can prove the
- // orchestration sequence without docker / network.
- //
- // FetchFn replaces splice.Fetch — return a directory that contains
- // (at minimum) an env/ subdir with role auth files; nil err means
- // "happy path."
- FetchFn func(ctx context.Context, v splice.Version, cacheRoot string, out io.Writer) (string, error)
- // NewRunner replaces the *docker.ComposeRunner constructor —
- // receives the same plumbing fields the real runner gets so the
- // test can assert on them. Returning a stub that succeeds on
- // Up+WaitForHealthy drives RunUp to the success path.
+ FetchFn func(ctx context.Context, v splice.Version, cacheRoot string, out io.Writer) (string, error)
NewRunner func(projectName string, composeFiles, envFiles, env []string, workDir string, logw io.Writer) composeOps
}
-// ValidateName returns an error if the supplied --name is empty or
-// fails the DNS-label rule. Thin wrapper over registry.ValidateName
-// so CLI and registry validation share a single rule (otherwise we
-// maintain two policies that drift). The empty-string check is
-// hoisted here so the CLI error message can mention `--name` rather
-// than the generic ErrInvalidName phrasing.
func ValidateName(name string) error {
if name == "" {
return fmt.Errorf("--name is required")
@@ -142,50 +72,17 @@ func ValidateName(name string) error {
return nil
}
-// RunUp orchestrates the full bring-up sequence. Each phase calls into
-// the `prog` Progress interface (StepResolveVersion through
-// StepCaptureJWTs in progress.go): the CLI's TextProgress emits
-// terminal lines while the Web UI's SSEProgress impl ships typed step
-// events to the browser.
-//
-// 1. Resolve --version against the curated list + look up the per-major
-// adapter for that Splice tag.
-// 2. Acquire the per-instance lock so concurrent ups on the same name
-// fail fast.
-// 3. Run preflight (Docker CLI, daemon, Compose v2, ports the adapter
-// demands, disk, memory, host prereqs) with platform-specific
-// remediation.
-// 4. Fetch + verify Splice LocalNet compose project (cache-hit fast
-// path).
-// 5. Persist initial state.json so a crash mid-bring-up leaves enough
-// metadata for `localnet down` to clean up.
-// 6. `docker compose up -d --wait` with the adapter-supplied compose
-// files / env files / profiles, and shell-exported overlay env.
-// 7. Mark state running, print endpoints + state file paths.
-//
-// SIGINT/SIGTERM cancel the in-flight `docker compose` call. RunUp never
-// modifies the host outside ~/.canton/.
func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer stop()
- // Reject unknown --profile values up front (pure input check —
- // before the lock / any side effect). Shared with the Web UI create
- // handler via ValidateProfiles so a typo'd `--profile observabilty`
- // fails fast instead of silently producing a metric-less instance.
if err := ValidateProfiles(opts.Profiles); err != nil {
prog.FailStep(StepResolveVersion, err.Error(), nil)
return ExitUserError
}
- // Wall-clock start for the welcome screen's "ready in Nm Ns" line.
- // Captured here so it includes resolve+preflight time, not just
- // compose-up time — a realistic cold-start cost.
startedAt := time.Now()
- // 1. Resolve version + adapter. Layer-1 (curated) is the default;
- // AllowUncurated opts into layer-2 (upstream resolution) — see
- // internal/splice/resolver.go.
prog.StartStep(StepResolveVersion, "")
version, fromUpstream, err := splice.ResolveOrUpstream(ctx, opts.Version, opts.AllowUncurated)
if err != nil {
@@ -193,17 +90,10 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
return ExitUserError
}
if fromUpstream {
- // One-line caveat so the user is never surprised that the bits
- // they're running weren't reviewed by a DevKit maintainer.
prog.Warn(fmt.Sprintf(
"using uncurated Splice tag %q (resolved upstream to commit %s); not tested by DevKit",
version.Tag, shortSHA(version.Commit)))
}
- // Alpha-channel warning. Catalogue entries marked `channel: "alpha"`
- // are opt-in pre-releases (e.g. the Token Standard V2 snapshot) —
- // images come from a different ghcr registry and the upstream
- // branch can be reset on a weekly cadence. Surface this once at
- // startup so it shows up in CI logs alongside the version banner.
if version.IsAlpha() {
prog.Warn(fmt.Sprintf(
"selecting alpha-channel Splice %q (pre-release; expect upstream resets and additional configuration — see docs/versions.md)",
@@ -217,12 +107,9 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
prog.FinishStep(StepResolveVersion,
fmt.Sprintf("splice %s · adapter %s", version.Tag, adapter.MajorVersion()))
- // Banner line. TextProgress writes it verbatim; SSEProgress gets it
- // as a console-style event so the browser sees the same banner.
_, _ = fmt.Fprintf(prog.Out(), "Starting Canton LocalNet %q (Splice %s, adapter %s)...\n",
opts.Name, version.Tag, adapter.MajorVersion())
- // 2. Per-instance lock. Released on any return path.
prog.StartStep(StepAcquireLock, "")
release, err := registry.Lock(opts.Name)
if err != nil {
@@ -232,15 +119,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
defer release()
prog.FinishStep(StepAcquireLock, "")
- // Re-up profile continuity. On a plain `down` → `up` with no
- // explicit --profile, re-enable the opt-in profiles the instance was
- // last brought up with, so observability / tokens-v2 don't silently
- // vanish on a CLI restart (the Web UI Restart already preserves them).
- // state.Profiles persists the FULL set (adapter base + opt-ins), so we
- // subtract the adapter base to recover just the opt-ins — enabledProfiles
- // re-adds the base below, so there's no double-counting. An explicit
- // --profile still wins (overrides, never merges). Best-effort: a
- // missing/old state.json leaves opts.Profiles empty.
if prior, rerr := registry.Read(opts.Name); rerr == nil {
if len(opts.Profiles) == 0 {
if optIns := subtractProfiles(prior.Profiles, adapter.Profiles()); len(optIns) > 0 {
@@ -256,39 +134,18 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
}
- // 3. Preflight (Docker CLI / daemon / Compose v2 / disk / memory).
- // Host TCP ports are NOT preflight-checked — DevKit allocates them
- // ephemerally (step 8) so port availability is never a precondition.
- // SkipPreflight is honored for unit tests; in production code paths
- // the flag is always false.
if !opts.SkipPreflight {
prog.StartStep(StepPreflight, "")
- // Memory floor is version-aware (CLI ↔ Web UI parity:
- // matches GET /api/preflight). splice.MinMemoryFor() is
- // guaranteed to return >= docker.DefaultMinMemoryBytes
- // by TestThresholdParity_VersionMinAtLeastDefault — a
- // per-version override can only RAISE the gate, never
- // weaken it, so the `doctor && up` contract holds:
- // every host that passes doctor still passes up's floor
- // for the lightest catalogued version.
report := docker.RunPreflight(ctx, docker.Options{
DataDir: registry.Root(),
MinDiskBytes: docker.DefaultMinDiskBytes,
MinMemoryBytes: splice.MinMemoryFor(version),
RecommendedMemoryBytes: splice.RecommendedMemoryFor(version),
})
- // Anonymous telemetry (no-op unless enabled): the docker engine
- // flavor + compose-version bucket discovered by preflight. No host,
- // path, or version string is recorded — only the allow-listed bucket.
telemetry.Inc("dpm/docker_engine", telemetry.NormEngine(report.DockerEngine))
telemetry.Inc("dpm/compose_version_bucket", telemetry.ComposeBucket(report.ComposeVersion))
report.Write(prog.Out())
if !report.OK() {
- // Stamp the most-specific code we can infer from the
- // failed checks so the UI can render a
- // targeted remediation panel (Docker not running vs
- // memory too low vs disk full, etc.) instead of a
- // generic "preflight failed" wall of text.
prog.FailStep(StepPreflight,
"\nPreflight failed. Address the items above and re-run.",
WithCode(fmt.Errorf("preflight failed"), PreflightCodeFromReport(report)))
@@ -297,8 +154,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
prog.FinishStep(StepPreflight, "")
}
- // 4. Fetch + verify compose project. FetchFn is a test seam;
- // in production it's nil and we call splice.Fetch directly.
prog.StartStep(StepFetchSplice, "")
cacheRoot := splice.CacheRoot()
fetch := opts.FetchFn
@@ -317,10 +172,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
prog.FinishStep(StepFetchSplice, "")
- // 5. Persist state — generate per-instance container-rename
- // overlay, write the (creating) state.json. Every Splice service
- // has a hardcoded container_name; without renaming, two instances
- // collide daemon-wide regardless of project name.
prog.StartStep(StepPersistState, "")
dataDir := registry.DataDirFor(opts.Name)
containerPrefix := opts.Name + "-"
@@ -331,14 +182,8 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
composeFiles := append([]string(nil), adapter.ComposeFiles()...)
- composeFiles = append(composeFiles, overlayPath) // absolute path; not relative to projectDir
-
- // Force all published ports to bind to 127.0.0.1 (loopback only).
- // The upstream Splice compose.yaml binds ports without a host IP,
- // so Docker defaults to 0.0.0.0 — exposing unauthenticated gRPC,
- // database, and HTTP endpoints to the local network. This overlay
- // uses Compose's !override tag (v2.24.0+) to replace the port
- // lists with 127.0.0.1-prefixed bindings.
+ composeFiles = append(composeFiles, overlayPath)
+
loopbackPath, err := WriteLoopbackPortsOverlay(dataDir)
if err != nil {
prog.FailStep(StepPersistState, "Failed to write loopback-ports overlay", err)
@@ -346,12 +191,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
composeFiles = append(composeFiles, loopbackPath)
- // Serve each Splice UI/API at an instance-scoped virtual host
- // (..localhost). Splice's nginx routes by Host
- // header; this overlay bind-mounts DevKit-owned copies of the role
- // .conf files (server_name = ${VHOST_*}) over the upstream ones and
- // injects the per-instance vhost values as nginx container env,
- // without touching the content-hash-verified Splice cache.
nginxPath, err := WriteNginxVhostOverlay(dataDir, opts.Name, prog.Err())
if err != nil {
prog.FailStep(StepPersistState, "Failed to write nginx-vhost overlay", err)
@@ -359,19 +198,9 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
composeFiles = append(composeFiles, nginxPath)
- // Observability profile(s) materialize the embedded Prometheus +
- // Grafana overlay and append its compose file. Per-component
- // profiles (`prometheus`, `grafana`) and the legacy umbrella
- // (`observability` = both) all funnel through
- // ExpandObservabilityProfiles so the rest of the bring-up logic
- // only deals with two booleans.
wantPrometheus, wantGrafana := ExpandObservabilityProfiles(opts.Profiles)
hasObservabilityProfile := wantPrometheus || wantGrafana
if wantGrafana && !wantPrometheus {
- // Grafana without a bundled Prometheus is valid (user may
- // point it at an external scrape source) but is a common
- // mistake — surface a warning so an empty dashboard is
- // expected rather than mysterious.
prog.Warn("--profile grafana enabled without --profile prometheus: " +
"Grafana will start with no bundled data source. Add " +
"--profile prometheus, or configure an external Prometheus " +
@@ -401,11 +230,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
}
- // tokens-v2 profile materializes the alpha-protocol
- // Canton config overlay. Required when running the Token Standard
- // V2 snapshot (alpha catalogue entry); a stable Splice version
- // with this profile on is harmless — it just injects an env that
- // the stable Canton ignores.
hasTokensV2Profile := slices.Contains(opts.Profiles, TokensV2ProfileName)
if hasTokensV2Profile {
overlay, err := MaterializeTokensV2Overlay(dataDir, prog.Err())
@@ -416,11 +240,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
composeFiles = append(composeFiles, overlay)
} else if version.IsAlpha() {
- // Alpha version selected without the matching profile — Canton
- // won't carry the protocol-35 flags V2 requires and the bring-up
- // is highly likely to fail. WARN loudly rather than refuse, so
- // users who pin alpha for non-V2 reasons (e.g. previewing other
- // changes on the snapshot) aren't blocked.
prog.Warn(fmt.Sprintf(
"alpha Splice %q selected without --profile %s — Canton "+
"will not enable initial-protocol-version=35; V2 features "+
@@ -428,28 +247,9 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
version.Tag, TokensV2ProfileName, TokensV2ProfileName))
}
- // Read any pre-existing state so we can reuse the
- // previously assigned UI host ports — stable URLs across an
- // up/down/up cycle is the whole point of persisting them. If no
- // prior state exists (first run, or it was deleted), priorPorts
- // stays nil and ReuseOrAllocateUIPorts falls back to full
- // ephemeral allocation.
- //
- // We also stash the prior run's recorded image digests so the
- // post-up capture can WARN if a republished ghcr tag changed what
- // runs. Only meaningful when the SAME version is being
- // brought back up — a version change legitimately swaps images, so
- // we skip the comparison in that case.
var priorPorts map[string]int
var priorImageDigests map[string]string
if prior, err := registry.Read(opts.Name); err == nil {
- // Refuse to re-up an instance that is already running. Without
- // this guard RunUp overwrites the live state with
- // Status=creating and then fails port allocation (the published
- // host ports are still held), stranding the healthy instance as
- // a permanent `creating` zombie the reconciler won't heal and
- // `scrub` would orphan. Mirrors the Web UI's 409 INSTANCE_RUNNING
- // guard.
if prior.Status == registry.StatusRunning {
prog.FailStep(StepPersistState, fmt.Sprintf(
"instance %q is already running — stop it first with "+
@@ -463,12 +263,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
}
- // The enabled profile set: the adapter's base profiles (which gate
- // every core Splice service) plus the user's `--profile` opt-ins.
- // Persisted in state and re-used for the `up` runner below so the
- // recorded set is byte-identical to what we actually bring up;
- // `restart`/`pause`/`status` replay it (teardown does not need it —
- // see ComposeRunner.Stop).
enabledProfiles := append(adapter.Profiles(), opts.Profiles...)
state := registry.NewState(opts.Name, version.Tag)
@@ -482,7 +276,7 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
state.ContainerPrefix = containerPrefix
state.ProjectDir = projectDir
state.DataDir = dataDir
- state.Ports = adapter.EndpointMap() // overwritten post-up if ephemeral
+ state.Ports = adapter.EndpointMap()
state.AlphaProtocolEnabled = adapter.SupportsAlphaProtocol()
state.Status = registry.StatusCreating
if err := registry.Write(state); err != nil {
@@ -493,17 +287,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
// Pre-allocate UI host ports. Splice's nginx/swagger/postgres
// services don't honor TEST_PORT — they only consume the per-service
// env vars (APP_USER_UI_PORT etc).
- //
- // On first run priorPorts is nil → all ports allocated ephemerally.
- // On re-up after a clean `down`, ReuseOrAllocateUIPorts hands back
- // the same ports the user previously had (stable-URL contract)
- // unless one is busy, in which case we surface ErrPortBusy as
- // a user error and stop — silently picking a new port would
- // defeat the contract.
- //
- // When --profile observability is on, allocate Prometheus +
- // Grafana host ports alongside the rest so they go through the
- // stable-reuse contract too.
portEnvVars := UIPortEnvVars()
if wantPrometheus {
portEnvVars = append(portEnvVars, "PROMETHEUS_HOST_PORT")
@@ -511,9 +294,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
if wantGrafana {
portEnvVars = append(portEnvVars, "GRAFANA_HOST_PORT")
}
- // Explicit-port mode (--port-base) pins deterministic ports and
- // fails on any conflict; default mode auto-allocates with stable
- // reuse across re-ups.
var uiOverrides map[string]int
if opts.PortBase > 0 {
uiOverrides, err = DeriveUIPorts(portEnvVars, opts.PortBase)
@@ -523,9 +303,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
if err != nil {
var conflict *PortBaseConflict
if errors.Is(err, ErrPortBusy) || errors.As(err, &conflict) {
- // Stamp PORTS_IN_USE so the frontend can
- // render the "free the port" remediation panel
- // instead of the generic failure dialog.
prog.FailStep(StepPersistState,
fmt.Sprintf("%s\nFree the conflicting process (lsof -i :), pick a different --port-base, or tear down the "+
"other instance and re-run `localnet up %s`.", err, opts.Name),
@@ -548,10 +325,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
prog.FinishStep(StepPersistState, "")
- // 6. Starting services. Build the compose env files and run
- // `up -d --wait`. Ephemeral is always true: canton participant
- // ports get TEST_PORT="" and UI/postgres ports come from
- // uiOverrides.
params := splice.InstanceParams{
Name: opts.Name,
Version: version,
@@ -561,22 +334,14 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
overlayVars := adapter.OverlayEnv(params)
- // Persist the overlay env to a .env file so downstream commands
- // (down, logs, pause, restart, remove) replay the exact same
- // compose environment via --env-file — no adapter re-derivation
- // needed. The file is written to DataDir alongside state.json.
overlayEnvPath, err := WriteOverlayEnv(dataDir, overlayVars)
if err != nil {
prog.FailStep(StepPersistState, "Failed to write overlay env", err)
return ExitRuntimeFailure
}
- // Env files: adapter base files + the generated overlay (last wins).
envFiles := append(adapter.EnvFiles(), overlayEnvPath)
- // NewRunner is a test seam. Production: build the
- // real *docker.ComposeRunner (which satisfies composeOps
- // implicitly).
var runner composeOps
if opts.NewRunner != nil {
runner = opts.NewRunner(state.ComposeProject, composeFiles, envFiles, nil, projectDir, prog.Out())
@@ -612,7 +377,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
prog.FinishStep(StepStartServices, "")
- // 7. Wait for services to become healthy.
prog.StartStep(StepWaitHealthy, "")
if err := runner.WaitForHealthy(ctx); err != nil {
markFailed(state, prog.Err())
@@ -620,14 +384,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
prog.FailStep(StepWaitHealthy, "Timed out waiting for services", nil)
return ExitTimeout
}
- // Try to diagnose the failure by inspecting the
- // unhealthy containers' recent logs. Most common cause on
- // first-run with default Docker memory: canton JVM OOM-loop
- // — its logs include "exceeds half of the container's
- // total memory". If we spot that pattern, stamp
- // CANTON_OOM so the UI renders the memory-raise
- // remediation card; otherwise stamp CONTAINER_UNHEALTHY
- // so the UI can at least offer a "see logs" affordance.
diagCtx, cancelDiag := context.WithTimeout(ctx, 15*time.Second)
code := diagnoseUnhealthy(diagCtx, state.ComposeProject)
cancelDiag()
@@ -640,29 +396,13 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
prog.FinishStep(StepWaitHealthy, "")
- // 8. Capture Canton participant ports. The Canton container
- // exposes Ledger/Admin/JSON APIs per party role on Docker-ephemeral
- // host ports — ask docker what they ended up as and persist them so
- // consumers (Web UI Explorer, DAR Manager, token tooling) can dial
- // without a manual `--admin-host=localhost:` flag.
- // Best-effort: any port that fails to query is silently omitted,
- // not stamped as 0.
for key, port := range CaptureCantonPorts(ctx, state.ComposeProject) {
state.Ports[key] = port
}
- // Capture the canton/splice :10013 metrics ports too, so the shared
- // host-level Prometheus can scrape this instance via
- // host.docker.internal: once it's registered.
for key, port := range CaptureMetricsPorts(ctx, state.ComposeProject) {
state.Ports[key] = port
}
- // 8b. Capture the content digests of the images that actually ran
- // and persist them. The catalogue pins the source tree but ghcr
- // image tags are mutable; recording digests lets a later up/restart
- // detect a republished tag. Best-effort — a capture failure
- // just skips drift detection, never fails the bring-up. If the same
- // version was up before with recorded digests, warn on any change.
if digests := CaptureImageDigests(ctx, state.ComposeProject); len(digests) > 0 {
if changed := DiffImageDigests(priorImageDigests, digests); len(changed) > 0 {
prog.Warn(fmt.Sprintf(
@@ -673,9 +413,6 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
state.ImageDigests = digests
}
- // 9. Capture JWTs and persist running state. (UI ports were
- // pre-allocated in step 5; Canton participant gRPC/JSON API
- // ports were just captured in step 8.)
prog.StartStep(StepCaptureJWTs, "")
if creds := captureCredentials(projectDir, prog.Err()); creds != nil {
state.Credentials = creds
@@ -686,48 +423,24 @@ func RunUp(ctx context.Context, prog Progress, opts *UpOptions) int {
}
prog.FinishStep(StepCaptureJWTs, "")
- // Register this instance with the shared host-level observability
- // stack and ensure the stack is up, so one Prometheus+Grafana
- // scrapes every instance. Register+ensure run atomically under the
- // shared-stack lock so a concurrent teardown can't race us. Best-effort
- // — a failure here is a warning, never a failed bring-up. (The
- // per-instance overlay still runs alongside the shared stack; gating it
- // off is a deferred decision — see docs/observability.md.)
if hasObservabilityProfile {
if _, err := RegisterInstanceAndEnsureStack(ctx, state, prog.Err()); err != nil {
prog.Warn("shared observability: " + err.Error())
}
}
- // Welcome screen (endpoints + try-next cheat sheet). The renderer
- // auto-degrades to a plain-text variant on non-TTY writers so
- // `localnet up | tee log` stays grep-clean.
renderWelcome(prog.Out(), opts.Name, version.Tag, state, time.Since(startedAt))
- // Emit the terminal `done` event. On the CLI (TextProgress) Done("")
- // is a no-op — renderWelcome already printed the success box. On the
- // Web UI (SSEProgress) this is the ONLY signal that flips the create/
- // resume/restart modal out of its "running" state: without it the
- // modal hangs forever on every successful bring-up, never refreshes
- // the dashboard, and can't be dismissed via Esc/backdrop.
prog.Done("")
return ExitSuccess
}
-// captureCredentials reads the per-role auth env files from the cached
-// project and signs a JWT for each role. Returns nil + a warning on the
-// error path — JWT capture failure shouldn't fail an otherwise-healthy
-// bring-up.
func captureCredentials(projectDir string, errw io.Writer) map[string]registry.Credential {
inputs, err := splice.LoadCredentialInputs(projectDir)
if err != nil {
_, _ = fmt.Fprintf(errw, "Warning: could not read auth env files: %s\n", err)
return nil
}
- // One-shot dev-secret warning to the injected stderr. SignToken
- // itself is pure (no global writes) — the orchestrator owns the
- // output channel. RunCreds emits the same warning when re-issuing
- // tokens from a previously-captured instance.
if len(inputs) > 0 {
_, _ = fmt.Fprintln(errw, splice.DevSecretWarning)
}
@@ -755,27 +468,13 @@ func markFailed(state *registry.State, errw io.Writer) {
}
}
-// renderWelcome composes the post-ready welcome screen using the term
-// package's WelcomeScreen primitive (see internal/ui/term/welcome.go).
-//
-// Bridges registry-shaped data (state.Ports, the orderedEndpointKeys
-// scheme map) into the term-package's renderer-shaped data (Endpoint
-// records grouped by Category). Kept in this package rather than the
-// term package because the endpoint→category mapping is domain
-// knowledge (Splice's UI structure), not a generic terminal primitive.
func renderWelcome(out io.Writer, name, spliceVersion string, state *registry.State, elapsed time.Duration) {
- // Group endpoints by purpose. The order here drives display
- // order in the welcome screen — keep the most-clicked surfaces
- // (wallet, scan) at the top.
endpoints := []term.Endpoint{}
for _, e := range orderedEndpointKeys() {
port, ok := state.Ports[e.key]
if !ok {
continue
}
- // Wallet UIs are served at the role-scoped wallet vhost;
- // everything else (swagger, postgres) stays on the bare loopback
- // host.
host := "localhost"
if vh := walletVHostForKey(e.key, name); vh != "" {
host = vh
@@ -807,17 +506,6 @@ func renderWelcome(out io.Writer, name, spliceVersion string, state *registry.St
}.Render(out)
}
-// diagnoseUnhealthy inspects the project's containers for the
-// known failure patterns we can give targeted remediation for.
-// Called from RunUp's wait_healthy fail path.
-//
-// Returns "" when no recognized pattern matches; caller falls
-// back to ErrCodeContainerUnhealthy. Best-effort — if the docker
-// probe itself fails (daemon down, project gone), returns "" and
-// the wait_healthy failure surfaces with the generic code.
-//
-// # Why not just the JVM "-Xmx exceeds half" warning
-//
// The JVM logs that warning on EVERY startup of a memory-tight
// canton container — it's a JVM config-time advisory, not an OOM
// event. Pattern-matching it would false-positive on every boot
@@ -825,23 +513,6 @@ func renderWelcome(out io.Writer, name, spliceVersion string, state *registry.St
// actually OOM-kills (the kernel kills the JVM before it can log
// anything; the container restarts and the new JVM's startup log
// has no OOM trace).
-//
-// True OOM detection signals (any ONE is sufficient):
-//
-// 1. docker inspect: State.OOMKilled == true on the last
-// terminated state. This is the kernel's own OOM-killer
-// event, not derived from logs.
-// 2. State.ExitCode == 137 (SIGKILL) AND State.Status == "exited"
-// — Linux kernel OOM-kill manifests as SIGKILL.
-// 3. container is restarting AND its RestartCount is > 0 AND
-// the JVM warning is present in the most recent boot's logs
-// — the warning by itself isn't proof, but COMBINED with an
-// observed restart cycle it strongly suggests OOM-loop.
-//
-// We use signal (3) here as the cheapest reliable indicator
-// (signals 1+2 would need a richer `docker inspect` parse than
-// `compose ps` gives us). Wired so the JVM warning alone never
-// fires a code — only "warning AND restart-loop" does.
func diagnoseUnhealthy(ctx context.Context, project string) string {
infos, err := containers.List(ctx, project)
if err != nil {
@@ -854,11 +525,6 @@ func diagnoseUnhealthy(ctx context.Context, project string) string {
Health: c.Health,
Status: c.Status,
}
- // Only spend a docker logs subprocess when the cheap
- // signal (Status) already suggests a kernel kill.
- // diagnoseFromObs without LogTail can short-circuit
- // in the common "container is healthy" / "container
- // is just slow-starting" cases.
if diagnoseFromObs(obs) == "" && !isRestartingOOM(c.Status) {
continue
}
@@ -873,21 +539,7 @@ func diagnoseUnhealthy(ctx context.Context, project string) string {
return ""
}
-// PreflightCodeFromReport extracts the most specific error code from a
-// failed docker.Report. Priority order matches "what's the most
-// actionable diagnosis the user can fix first":
-//
-// Docker CLI missing → ErrCodeDockerNotInstalled (install Docker)
-// Docker daemon down → ErrCodeDockerDown (start Docker)
-// Docker Compose v1/missing → ErrCodeComposeMissing (install compose v2)
-// Docker memory below floor → ErrCodeMemoryLow (raise Resources → Memory)
-// Disk space low → ErrCodeDiskLow (free space)
-// anything else → ErrCodePreflightFailed (catch-all)
-//
-// Exported so internal/ui/handlers/preflight.go can call it for the
-// HTTP-422 response — single source of truth.
func PreflightCodeFromReport(r *docker.Report) string {
- // Walk in priority order — the first FAIL we hit wins.
for _, c := range r.Results {
if c.Status != docker.StatusFail {
continue
@@ -908,11 +560,6 @@ func PreflightCodeFromReport(r *docker.Report) string {
return ErrCodePreflightFailed
}
-// orderedEndpointKeys returns the endpoint pretty-print order — stable
-// regardless of map iteration order. Carries the welcome-screen
-// metadata (Category, External) alongside the registry key so the
-// renderer can group rows by purpose and render hyperlinks only for
-// browsable URLs (not for sockets like postgres).
func orderedEndpointKeys() []endpointDisplay {
return []endpointDisplay{
{key: "app_user_ui", label: "Wallet (username: app-user)", scheme: "http", category: "WEB UIs", external: true},
@@ -927,25 +574,16 @@ type endpointDisplay struct {
key string
label string
scheme string
- category string // welcome-screen section header — "WEB UIs", "INFRASTRUCTURE"
- external bool // browsable URL → render "↗" + OSC 8 hyperlink
+ category string
+ external bool
}
-// walletUIRoleByKey maps a state.json UI port key to the Splice role
-// whose wallet is served behind that port. The wallet vhost is
-// role-scoped (wallet...localhost), so URL builders and
-// the reachability probe resolve the role from the port key here.
-// Shared by the welcome-screen, status, and probe code so they all
-// scope wallet URLs the same way.
var walletUIRoleByKey = map[string]string{
"app_user_ui": "app-user",
"app_provider_ui": "app-provider",
"sv_ui": "sv",
}
-// walletVHostForKey returns the role-scoped wallet vhost for a UI port
-// key, e.g. walletVHostForKey("app_user_ui", "localnet-2") ==
-// "wallet.app-user.localnet-2.localhost". Empty for non-wallet keys.
func walletVHostForKey(key, instance string) string {
role, ok := walletUIRoleByKey[key]
if !ok {
@@ -954,8 +592,6 @@ func walletVHostForKey(key, instance string) string {
return instanceVHostRole(VHostServiceWallet, role, instance)
}
-// shortSHA returns the first 7 characters of a git SHA (or the whole
-// string if shorter). Used only for the uncurated-tag warning.
func shortSHA(s string) string {
if len(s) <= 7 {
return s
diff --git a/internal/ui/handlers/instances.go b/internal/ui/handlers/instances.go
index 2a267e41..014c6b42 100644
--- a/internal/ui/handlers/instances.go
+++ b/internal/ui/handlers/instances.go
@@ -1,10 +1,3 @@
-// Package handlers implements the REST endpoints mounted at /api/*.
-// Each file in this package owns one resource.
-//
-// The CLI status command and Web UI detail endpoint share
-// localnet.CollectStatus so JSON shape, Docker soft-fail handling,
-// endpoint projection, and credential projection do not drift. See
-// CONTRIBUTING.md "CLI ↔ Web UI parity".
package handlers
import (
@@ -30,40 +23,12 @@ import (
"github.com/bitdynamics-ab/canton-devkit/internal/ui/stream"
)
-// upBodyMax caps the POST /api/instances request body. Defence-in-
-// depth against a malicious-or-buggy client feeding us a 100 MiB
-// JSON blob — the handler only needs a tiny request shape.
-const upBodyMax = 4 << 10 // 4 KiB
-
-// upJobTimeout is the hard ceiling on a single create-instance
-// goroutine. It must outlast the internal docker readinessTimeout
-// (25 min, see internal/docker/compose.go WaitForHealthy) plus
-// Splice fetch (~5 min fresh) and compose up — a first-run bring-up
-// with no cached images can take 18+ minutes; a shorter cap fires
-// before WaitForHealthy's own deadline and surfaces a misleading
-// timeout while containers are still progressing.
-//
-// This is NOT the HTTP request timeout — the POST returns 202
-// immediately; the goroutine runs on its own context, cancellable
-// via DELETE.
+const upBodyMax = 4 << 10
+
const upJobTimeout = 30 * time.Minute
-// progressBufferCap is the per-instance topic ring size. Sized
-// for a normal up: 8 step.started + 8 step.finished + a few
-// step.progress + a few warnings + the done event = ~32 events.
-// 128 leaves headroom for verbose compose-log forwarding without
-// the oldest events evicting during a 90-second up.
const progressBufferCap = 128
-// MountInstances installs the instance-resource routes on mux.
-// hub may be nil for callers that don't want the create-instance
-// flow (e.g. read-only deployments); in that case POST and the
-// SSE endpoint return 503.
-//
-// Path prefix is fixed at /api/instances. The GET handlers are
-// stateless — every call re-reads from registry. The POST handler
-// spawns a long-running goroutine that publishes progress events
-// to a per-instance topic on hub.
func MountInstances(mux *http.ServeMux, hub *stream.Hub) {
mux.HandleFunc("GET /api/instances", handleList)
mux.HandleFunc("GET /api/instances/{name}", handleDetail)
@@ -77,9 +42,6 @@ func MountInstances(mux *http.ServeMux, hub *stream.Hub) {
mux.HandleFunc("POST /api/instances/{name}/recreate", handleRecreateInstance(hub))
mux.HandleFunc("POST /api/instances/{name}/observability", handleObservabilityToggle())
} else {
- // Stub so a misconfigured deployment fails loudly
- // rather than 404 (which the frontend would mistake
- // for a missing endpoint).
stub := func(w http.ResponseWriter, _ *http.Request) {
writeErrorWithCode(w, http.StatusServiceUnavailable,
"SSE_DISABLED",
@@ -94,21 +56,12 @@ func MountInstances(mux *http.ServeMux, hub *stream.Hub) {
mux.HandleFunc("POST /api/instances/{name}/up", stub)
mux.HandleFunc("POST /api/instances/{name}/recreate", stub)
}
- // Container probe + log tail + restart are hub-independent
- // (pure docker calls) — mount them for every deployment.
mux.HandleFunc("GET /api/instances/{name}/containers", handleInstanceContainers())
mux.HandleFunc("GET /api/instances/{name}/containers/{container}/logs", handleContainerLogs())
mux.HandleFunc("POST /api/instances/{name}/containers/{container}/restart", handleContainerRestart())
- // Pause / resume — docker compose pause/unpause; hub-
- // independent. CLI counterpart: `localnet pause` / `localnet resume`.
mux.HandleFunc("POST /api/instances/{name}/pause", handlePauseInstance(true))
mux.HandleFunc("POST /api/instances/{name}/resume", handlePauseInstance(false))
- // Stop — docker compose stop; hub-independent, synchronous
- // (near-instant, containers kept). CLI counterpart: `localnet stop`.
mux.HandleFunc("POST /api/instances/{name}/stop", handleStopInstance())
- // Start — the fast compose-start path is synchronous (204), but a
- // fall-through to a full bring-up needs the hub's SSE machinery,
- // so it's only mounted when the hub is present (stubbed above).
if hub != nil {
mux.HandleFunc("POST /api/instances/{name}/start", handleStartInstance(hub))
} else {
@@ -121,10 +74,6 @@ func MountInstances(mux *http.ServeMux, hub *stream.Hub) {
}
}
-// handleStopInstance: POST /api/instances/{name}/stop.
-// Synchronous wrapper around localnet.RunStop (docker compose stop) —
-// containers are kept for a fast `start`. 204 on success; mapped error
-// codes on failure. CLI counterpart: `localnet stop`.
func handleStopInstance() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -157,30 +106,12 @@ func handleStopInstance() http.HandlerFunc {
}
}
-// Indirected so tests can drive the bring-up paths without booting a
-// real Canton stack: RunUp outlives the request on a detached context.
var (
listContainers = containers.List
runStart = localnet.RunStart
runUp = localnet.RunUp
)
-// handleStartInstance: POST /api/instances/{name}/start.
-//
-// Mirrors the CLI's intelligent `localnet start`:
-//
-// - stopped + containers present → fast `docker compose start`,
-// synchronous, returns 204
-// - stopped + containers removed, or failed/partial → falls back to a
-// full bring-up, returns 202 + an events_url the UI subscribes to
-// (reusing the resume/create SSE machinery)
-// - not registered → 404 (the UI's Start button only shows for
-// registered rows; use POST /api/instances to create)
-// - running → 204 (idempotent no-op)
-// - paused → 409 (use /resume)
-//
-// The 204-vs-202 split lets the frontend branch: 204 → just refetch;
-// 202 → open the existing create-progress modal.
func handleStartInstance(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -203,7 +134,7 @@ func handleStartInstance(hub *stream.Hub) http.HandlerFunc {
}
switch state.Status {
case registry.StatusRunning:
- w.WriteHeader(http.StatusNoContent) // idempotent
+ w.WriteHeader(http.StatusNoContent)
return
case registry.StatusPaused:
writeErrorWithCode(w, http.StatusConflict, "INSTANCE_PAUSED",
@@ -212,18 +143,11 @@ func handleStartInstance(hub *stream.Hub) http.HandlerFunc {
return
}
- // stopped / failed / partial: fast-start iff the containers
- // still exist; otherwise fall back to a full bring-up.
existing, listErr := listContainers(r.Context(), state.ComposeProject)
if listErr == nil && len(existing) > 0 {
ctx, cancel := context.WithTimeout(r.Context(), downTimeout)
defer cancel()
var outBuf, errBuf bytes.Buffer
- // SkipWait: return quickly; the reconciler promotes to
- // running once healthy (same precedent as restart no-wait).
- // The Progress sink is only used on RunStart's up-fallback
- // path, which the containers-present branch can't reach, so
- // a discard sink is safe here.
exit := runStart(ctx,
localnet.NewTextProgress(io.Discard, io.Discard),
&outBuf, &errBuf,
@@ -247,15 +171,10 @@ func handleStartInstance(hub *stream.Hub) http.HandlerFunc {
return
}
- // Containers gone → full bring-up via the async SSE path.
startBringUp(w, name, state.SpliceVersion, state.Profiles, hub)
}
}
-// startBringUp kicks off a full `up` for an existing (registered but
-// container-less) instance and returns 202 + events_url. Extracted so
-// handleStartInstance can reuse the same job/SSE machinery the resume
-// and create handlers use.
func startBringUp(w http.ResponseWriter, name, version string, profiles []string, hub *stream.Hub) {
jobCtx, cancelJob := context.WithTimeout(context.Background(), upJobTimeout)
if !jobs.Register(name, cancelJob) {
@@ -287,10 +206,6 @@ func startBringUp(w http.ResponseWriter, name, version string, profiles []string
})
}
-// handlePauseInstance: POST /api/instances/{name}/pause|resume.
-// Synchronous wrapper around localnet.RunPause / RunResume — both are
-// near-instant (a SIGSTOP/SIGCONT signal to the containers), so no async
-// job is needed. 204 on success; the run's stderr is surfaced on failure.
func handlePauseInstance(pause bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -329,11 +244,6 @@ func handlePauseInstance(pause bool) http.HandlerFunc {
}
}
-// handleList: GET /api/instances → types.ListResponse.
-//
-// Output shape mirrors `localnet list --json` exactly; the Web UI
-// dashboard reads this on initial load before subscribing to SSE
-// updates.
func handleList(w http.ResponseWriter, _ *http.Request) {
idx, err := registry.ReadIndex()
if err != nil {
@@ -352,8 +262,6 @@ func handleList(w http.ResponseWriter, _ *http.Request) {
SpliceVersion: e.SpliceVersion,
StartedAgo: localnet.InstanceStartedAgo(e.CreatedAt, e.Status),
}
- // Best-effort, matching `localnet list`: a corrupt state
- // file becomes a response warning, not a fatal error.
if s, err := registry.Read(e.Name); err == nil {
row.Ports = formatPortRange(s.Ports)
} else {
@@ -372,11 +280,6 @@ func handleList(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// handleDetail: GET /api/instances/{name} → types.Instance.
-//
-// Returns 404 if the instance isn't registered. The 400 vs 404
-// distinction matters for the frontend: 400 = malformed name (user
-// typed garbage); 404 = well-formed name not currently known.
func handleDetail(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
if err := registry.ValidateName(name); err != nil {
@@ -395,10 +298,6 @@ func handleDetail(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, inst)
}
-// formatPortRange compresses a Ports map (logical → host) into the
-// "min–max" shape the dashboard expects. Mirrors
-// internal/cli/localnet/list.go's formatPortRange — see the godoc
-// there for the allowlist rationale.
func formatPortRange(ports map[string]int) string {
if len(ports) == 0 {
return "—"
@@ -431,14 +330,6 @@ func formatPortRange(ports map[string]int) string {
return strconv.Itoa(lo) + "–" + strconv.Itoa(hi)
}
-// writeJSON is the shared JSON-response helper. Indented for
-// human-readability (browsers and `curl | jq` both prefer it).
-//
-// Every API JSON response carries no-store: without it, browsers and
-// HTTP proxies can cache responses that include credentials (the
-// JWT endpoint, app-config) or that change frequently (instance
-// list). The Vite bundle (assets.go) opts into hashed-file caching
-// separately.
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
@@ -448,21 +339,6 @@ func writeJSON(w http.ResponseWriter, status int, body any) {
_ = enc.Encode(body)
}
-// errorBody is the canonical error response shape — aligned with the
-// FriendlyError taxonomy in internal/localnet/friendly_errors.go.
-//
-// The CLI's friendly_errors carries (Code, Summary, Remediation[]) and
-// the frontend already knows how to render that triple. Mirroring keeps
-// one error taxonomy across CLI and UI surfaces.
-//
-// Fields:
-// - Code: stable token scripts/frontends branch on (e.g.
-// "INSTANCE_NOT_FOUND"). Never renamed once shipped.
-// - Error: one-line human summary (toast).
-// - Detail: cause string for the dev-tools view; populated only
-// for 5xx (server-side) so 4xx (client-input) errors don't
-// echo attacker-controlled strings.
-// - Remediation: ordered action list ("try X then Y").
type errorBody struct {
Code string `json:"code"`
Error string `json:"error"`
@@ -484,27 +360,8 @@ const (
ErrCodeRequestTooLarge = "REQUEST_TOO_LARGE"
)
-// writeError emits a structured error.
-//
-// The cause string is never shipped to the client for 5xx errors:
-// including it would leak filesystem paths (e.g.
-// "read /home/user/.canton-devkit/...") into the response body — visible
-// to anyone on the loopback AND to anyone who can screenshot a JS error.
-// Instead:
-// - 4xx: code + summary only (no cause)
-// - 5xx: code + summary only AS WELL — the cause is LOGGED
-// server-side via log.Default so the operator can diagnose,
-// but never leaves the box. A correlation ID would be
-// better than the implicit log/wire pairing; tracked for
-// a future observability pass.
-//
-// `summary` is the human-facing label (rendered as a toast);
-// it must not include attacker-controlled strings — the caller's
-// responsibility, but the helper enforces "no Detail" so a
-// careless cause.Error() can't leak.
func writeError(w http.ResponseWriter, status int, summary string, cause error) {
if cause != nil && status >= 500 {
- // Log server-side, don't ship to client.
log.Printf("handler error: status=%d code=%s summary=%q cause=%v",
status, codeForStatus(status), summary, cause)
}
@@ -514,10 +371,6 @@ func writeError(w http.ResponseWriter, status int, summary string, cause error)
})
}
-// writeErrorWithCode is the variant used when the handler wants
-// to pin a specific stable code rather than the status-derived
-// default. Used across this and sibling handlers (snapshots,
-// metrics, …).
func writeErrorWithCode(w http.ResponseWriter, status int, code, summary string, remediation ...string) {
writeJSON(w, status, errorBody{
Code: code,
@@ -526,8 +379,6 @@ func writeErrorWithCode(w http.ResponseWriter, status int, code, summary string,
})
}
-// codeForStatus is the default code mapping. Handlers wanting a
-// more specific code use writeErrorWithCode.
func codeForStatus(status int) string {
switch {
case status == http.StatusNotFound:
@@ -545,27 +396,15 @@ func codeForStatus(status int) string {
}
}
-// ── async create-instance flow ────────────────────────────
-
-// upRequest is the body shape for POST /api/instances. Mirrors
-// `dpm localnet up` flags exactly so CLI and Web UI surface the
-// same controls.
type upRequest struct {
- Name string `json:"name"`
- Version string `json:"version,omitempty"` // empty → "latest" server-side
- AllowUncurated bool `json:"allow_uncurated,omitempty"` // resolve unknown tags upstream
- Profiles []string `json:"profiles,omitempty"` // docker-compose profiles; e.g. ["observability"]
- PortBase int `json:"port_base,omitempty"` // >0 → deterministic ports from this base (CLI --port-base parity)
- // ObservabilityMode is the CLI --observability-mode parity: auto | shared | per-instance. Empty == auto.
- ObservabilityMode string `json:"observability_mode,omitempty"`
+ Name string `json:"name"`
+ Version string `json:"version,omitempty"`
+ AllowUncurated bool `json:"allow_uncurated,omitempty"`
+ Profiles []string `json:"profiles,omitempty"`
+ PortBase int `json:"port_base,omitempty"`
+ ObservabilityMode string `json:"observability_mode,omitempty"`
}
-// allowedProfiles is derived from localnet.KnownProfiles() so it can
-// never drift from the CLI's set — the create handler validates through
-// localnet.ValidateProfiles directly; this map is a lookup the
-// handler-package tests pin the accepted set against. A single source
-// of truth lives in internal/localnet (CONTRIBUTING.md "mirror the
-// guards").
var allowedProfiles = func() map[string]bool {
m := make(map[string]bool, len(localnet.KnownProfiles()))
for _, p := range localnet.KnownProfiles() {
@@ -574,33 +413,14 @@ var allowedProfiles = func() map[string]bool {
return m
}()
-// upAcceptedResponse is the 202 body the POST returns. The frontend
-// uses events_url to open the EventSource for progress streaming;
-// instance is echoed so a client that auto-navigated can pick
-// it up from the response without parsing the URL.
type upAcceptedResponse struct {
SchemaVersion int `json:"schema_version"`
Instance string `json:"instance"`
EventsURL string `json:"events_url"`
}
-// handleCreate: POST /api/instances → 202 + spawns goroutine.
-//
-// Validation runs cheapest-first (body decode + size cap, DNS-label
-// name, duplicate-name check against both the registry and in-flight
-// jobs) before any work; then the handler enables SSE buffering,
-// registers a cancellable job context, spawns the RunUp goroutine,
-// and returns 202 with {instance, events_url}.
-//
-// The goroutine's deferred cleanup runs Unregister BEFORE ClearBuffer
-// so a fast-reconnecting browser that races the cleanup sees either
-// (a) the buffer still present and replays final events, or
-// (b) the registry already cleared and gets a fresh 404 from
-// the SSE endpoint — never an inconsistent state where the
-// buffer is gone but the job is still listed.
func handleCreate(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
- // Body cap first.
r.Body = http.MaxBytesReader(w, r.Body, upBodyMax)
var req upRequest
@@ -638,13 +458,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
return
}
- // Reject duplicates against BOTH the registry (an
- // already-running instance) AND the jobs registry (a
- // bring-up that hasn't finished yet). The two failure
- // modes are distinct UX cases — the frontend renders
- // "instance exists, switch to it" vs "instance is
- // being created, watch progress" — but both serve as a
- // reason to refuse the new POST.
if _, err := registry.Read(req.Name); err == nil {
writeErrorWithCode(w, http.StatusConflict,
"INSTANCE_EXISTS",
@@ -660,15 +473,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
return
}
- // Resolve the version up front so the synchronous preflight
- // gate uses the same Splice version RunUp will. Curated tags
- // resolve offline; uncurated tags (allow_uncurated) resolve
- // against upstream so the gate can apply the Major-aware
- // memory floor (see splice.MinMemoryFor) — otherwise the Web
- // UI could 202 a host that then OOM-loops mid bring-up. If
- // upstream resolution itself fails (network blip, bad tag) we
- // DON'T fail the create here — RunUp surfaces that in-stream
- // with the proper error code.
if gateVersion, ok := resolveForGate(r.Context(), req.Version, req.AllowUncurated); ok {
report := runPreflightForVersion(r.Context(), gateVersion)
if !report.OK {
@@ -677,8 +481,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
return
}
} else if !req.AllowUncurated {
- // Curated resolution failed and the caller didn't opt into
- // uncurated — same shape RunUp would produce for this input.
writeErrorWithCode(w, http.StatusBadRequest,
ErrCodeInvalidRequest,
"unknown splice version: "+req.Version,
@@ -689,14 +491,8 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
topic := progress.TopicFor(req.Name)
hub.EnableBuffering(topic, progressBufferCap)
- // Detached context: the request returns 202 immediately,
- // but the goroutine runs until RunUp completes (or the
- // upJobTimeout ceiling fires).
jobCtx, cancelJob := context.WithTimeout(context.Background(), upJobTimeout)
- // Register BEFORE spawning so a racing second POST
- // loses (sees the entry already present).
if !jobs.Register(req.Name, cancelJob) {
- // Lost the race with another POST that just won.
cancelJob()
hub.ClearBuffer(topic)
writeErrorWithCode(w, http.StatusConflict,
@@ -706,12 +502,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
return
}
- // Validate any caller-supplied profiles against the shared
- // allowlist (localnet.ValidateProfiles — the SAME guard RunUp
- // enforces, so the two surfaces can't drift; CONTRIBUTING.md
- // "mirror the guards"). Unknown profiles are an explicit 400
- // rather than a silent drop — a typo'd "observabilty" should
- // NOT quietly produce an instance without Prometheus.
if err := localnet.ValidateProfiles(req.Profiles); err != nil {
cancelJob()
hub.ClearBuffer(topic)
@@ -723,12 +513,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
return
}
- // port_base, when supplied, must fit a usable block (0 = auto).
- // Validate the FULL range up front with a 400 — both too-low and
- // too-high — rather than letting a bad value fail later inside
- // DeriveUIPorts. The upper bound mirrors up.go's effective
- // env-var block (the observability profile adds two ports), so
- // the gate matches exactly what RunUp will try to allocate.
if req.PortBase != 0 {
nPorts := len(localnet.UIPortEnvVars())
for _, p := range req.Profiles {
@@ -759,7 +543,6 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
}
go func() {
- // Cleanup order matters — see handler godoc.
defer cancelJob()
defer hub.ClearBuffer(topic)
defer jobs.Unregister(req.Name)
@@ -777,35 +560,10 @@ func handleCreate(hub *stream.Hub) http.HandlerFunc {
}
}
-// downTimeout caps a single down operation. `docker compose down`
-// is usually fast (10-30s) but a stuck container can extend it
-// well past the default 10s SIGTERM grace per container × N
-// services. 3 minutes is generous.
const downTimeout = 3 * time.Minute
-// downRequest is the body shape (currently empty; reserved for
-// future per-instance down options).
type downRequest struct{}
-// handleResumeInstance: POST /api/instances/{name}/up.
-//
-// Brings a previously-stopped instance back up, reusing its
-// recorded Splice version and ports. Symmetric counterpart to
-// `POST /api/instances/{name}/down`. The general create flow
-// (`POST /api/instances`) refuses when the name already exists,
-// so the UI needs this dedicated verb to surface a "Start"
-// button on the stopped row.
-//
-// Path-existence semantics:
-//
-// - 404 — name not in the registry (user typoed)
-// - 409 INSTANCE_RUNNING — already running; use /down first
-// - 409 INSTANCE_CREATING — a bring-up is in flight; subscribe
-// to the existing events stream instead
-// - 202 — kicked off; events stream at /api/instances/{name}/events
-//
-// Uses the same goroutine / SSE shape as handleCreate so the
-// frontend reuses its create-progress modal verbatim.
func handleResumeInstance(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -815,14 +573,6 @@ func handleResumeInstance(hub *stream.Hub) http.HandlerFunc {
"invalid instance name: "+err.Error())
return
}
- // Invert read-then-acquire order to close a TOCTOU race.
- // Reading state, deciding to proceed, then registering the
- // job leaves a window where a concurrent /up could register
- // first, get the lock, and flip the instance to running —
- // leaving us racing to start a duplicate. Instead: reserve
- // the job slot FIRST, then read state, recheck status. If
- // anything changed after we won the slot we release and
- // surface the right 409.
jobCtx, cancelJob := context.WithTimeout(context.Background(), upJobTimeout)
if !jobs.Register(name, cancelJob) {
cancelJob()
@@ -860,9 +610,6 @@ func handleResumeInstance(hub *stream.Hub) http.HandlerFunc {
topic := progress.TopicFor(name)
hub.EnableBuffering(topic, progressBufferCap)
- // Reuse the recorded Splice version so a resume doesn't
- // silently upgrade. The user explicitly upgrades by going
- // through the create flow with a new --version.
opts := &localnet.UpOptions{
Name: name,
Version: prior.SpliceVersion,
@@ -885,24 +632,10 @@ func handleResumeInstance(hub *stream.Hub) http.HandlerFunc {
}
}
-// profilesFromComposeFiles infers the docker-compose profile set
-// the instance was originally created with by inspecting its
-// recorded ComposeFiles. The observability and tokens-v2 overlays
-// each ship a distinctive filename; presence of the overlay path
-// in state.ComposeFiles is a reliable signal the corresponding
-// profile is in effect.
-//
-// Used by the restart flow so a down → up cycle re-enables the
-// same `--profile ` flags the original `localnet up` was
-// invoked with. Without this, restarting an instance that was
-// created with `--profile observability` would silently lose its
-// Prometheus + Grafana sidecars.
func profilesFromComposeFiles(files []string) []string {
var out []string
seen := map[string]bool{}
for _, f := range files {
- // Match by basename so changes to the overlay's parent
- // dir layout don't break detection.
base := f
if i := strings.LastIndexByte(f, '/'); i >= 0 {
base = f[i+1:]
@@ -923,46 +656,6 @@ func profilesFromComposeFiles(files []string) []string {
return out
}
-// handleRecreateInstance: POST /api/instances/{name}/recreate.
-//
-// Full down → up cycle for an existing instance, reusing the
-// recorded SpliceVersion + inferred profile set. The UI surfaces
-// this as a single "Restart" button so users don't have to
-// manually compose a Stop followed by a Start.
-//
-// Verb semantics:
-//
-// - 404 — name not in the registry
-// - 400 — invalid name (DNS-label validation)
-// - 409 INSTANCE_CREATING — a bring-up / down / restart goroutine
-// is already in flight for this name (jobs.Register loses the
-// race); caller should subscribe to the existing events stream
-// - 202 — kicked off; events stream at /api/instances/{name}/events
-//
-// Concurrency model:
-//
-// The handler reserves the per-name slot in `jobs` BEFORE doing
-// any state read (same ordering as handleResumeInstance —
-// inverting read-then-acquire avoids a window where a concurrent
-// /up/restart could win the lock between our read and our spawn).
-// Once registered, the goroutine runs RunDown then RunUp serially;
-// each of those takes the per-instance `registry.Lock` internally,
-// so the restart never bypasses the lock pattern the down/up
-// handlers depend on.
-//
-// Idempotency: a second POST while the first is running loses the
-// jobs.Register race and gets 409 INSTANCE_CREATING — it does NOT
-// double-execute the down/up cycle.
-//
-// What the restart preserves:
-//
-// - SpliceVersion (read from state.json before the down call)
-// - Profiles (derived from ComposeFiles via profilesFromComposeFiles)
-// - Overlay env, credentials, DSO state, ports — all preserved
-// because RunDown leaves them on disk and RunUp re-reads them
-//
-// What it does NOT do: regenerate credentials, recreate the
-// registry entry, allocate new ports, or upgrade the Splice version.
func handleRecreateInstance(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -973,10 +666,6 @@ func handleRecreateInstance(hub *stream.Hub) http.HandlerFunc {
return
}
- // Reserve the job slot first (same ordering as resume).
- // Outer context is detached so the goroutine survives the
- // HTTP response cycle; the timeout combines down (3min) +
- // up (30min) with some slack.
jobCtx, cancelJob := context.WithTimeout(context.Background(),
upJobTimeout+downTimeout)
if !jobs.Register(name, cancelJob) {
@@ -988,9 +677,6 @@ func handleRecreateInstance(hub *stream.Hub) http.HandlerFunc {
return
}
- // Read state AFTER claiming the job slot. If the name isn't
- // registered or read fails, release the slot before we
- // surface the error.
prior, err := registry.Read(name)
if err != nil {
jobs.Unregister(name)
@@ -1009,13 +695,7 @@ func handleRecreateInstance(hub *stream.Hub) http.HandlerFunc {
topic := progress.TopicFor(name)
hub.EnableBuffering(topic, progressBufferCap)
- // Capture identity values BEFORE the goroutine spawns so we
- // don't race the goroutine reading `prior` after the HTTP
- // response has already returned.
recordedVersion := prior.SpliceVersion
- // Prefer the authoritative persisted profile set; fall
- // back to sniffing the compose overlay filenames for instances
- // created before the Profiles field existed.
recordedProfiles := prior.Profiles
if len(recordedProfiles) == 0 {
recordedProfiles = profilesFromComposeFiles(prior.ComposeFiles)
@@ -1036,41 +716,21 @@ func handleRecreateInstance(hub *stream.Hub) http.HandlerFunc {
}
}
-// recreateWork runs the down→up cycle for a restart. It's a package
-// var, not an inline closure, so tests can substitute a deterministic
-// fake and assert the jobs.Register idempotency contract without the
-// detached goroutine shelling out to a real `docker compose`.
-// Production wiring is realRecreateWork.
var recreateWork = realRecreateWork
-// realRecreateWork is the production restart worker: RunDown then RunUp,
-// reusing the recorded version + profiles so a restart neither upgrades
-// nor sheds overlays.
func realRecreateWork(ctx context.Context, hub *stream.Hub, name, version string, profiles []string) {
prog := progress.New(hub, name)
- // Phase 1: down. RunDown takes the per-instance lock itself; we
- // don't pre-acquire one here or we'd deadlock. Capture stderr so a
- // down failure can be logged (the user sees the failure event via
- // SSE progress; this is for the operator-side log only).
var downOut, downErr bytes.Buffer
downExit := localnet.RunDown(ctx, &downOut, &downErr,
&localnet.DownOptions{Name: name})
if downExit != localnet.ExitSuccess {
log.Printf("restart instance %q: down phase failed exit=%d err=%s",
name, downExit, downErr.String())
- // Surface as a synthetic warning on the progress stream so the
- // UI sees something even though RunDown writes its own stderr to
- // buffers, not the hub.
prog.Warn("down phase failed during restart: " +
firstNonWarningLine(downErr.String()))
- // Continue to up anyway — RunDown is idempotent and a
- // partial-down state still lets RunUp try to reconcile.
}
- // Phase 2: up. Reuses the recorded version + profiles so the restart
- // doesn't silently upgrade or shed overlays. RunUp emits the full
- // step-event sequence to prog that the create flow uses.
upOpts := &localnet.UpOptions{
Name: name,
Version: version,
@@ -1081,20 +741,6 @@ func realRecreateWork(ctx context.Context, hub *stream.Hub, name, version string
name, downExit, exitCode)
}
-// handleDownInstance: POST /api/instances/{name}/down.
-//
-// Synchronous wrapper around localnet.RunDown. Down is fast
-// enough that streaming progress over SSE is overkill — the
-// modal would barely have time to render before completion.
-// (Compare to /up which is minutes-long; that one warrants the
-// full SSE choreography.)
-//
-// Returns 204 on success, 5xx with the captured output on
-// failure. Body is application/json; an empty body is valid.
-//
-// Refuses on `creating` (409) — a goroutine is mid-up; the
-// caller should DELETE /up to cancel first, then this endpoint
-// can scrub what's left.
func handleDownInstance() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1105,7 +751,6 @@ func handleDownInstance() http.HandlerFunc {
return
}
- // Body parse. Empty body is fine — treat as defaults.
r.Body = http.MaxBytesReader(w, r.Body, upBodyMax)
var req downRequest
dec := json.NewDecoder(r.Body)
@@ -1129,8 +774,6 @@ func handleDownInstance() http.HandlerFunc {
ctx, cancel := context.WithTimeout(r.Context(), downTimeout)
defer cancel()
- // Capture out/err for the failure-response body. The
- // success path discards them — 204 has no body.
var outBuf, errBuf bytes.Buffer
exit := localnet.RunDown(ctx, &outBuf, &errBuf, &localnet.DownOptions{
Name: name,
@@ -1142,9 +785,6 @@ func handleDownInstance() http.HandlerFunc {
return
}
- // Non-zero exit → 5xx with the cause from stderr.
- // RunDown writes friendly errors to errw; surface those
- // directly so the frontend can render them.
status := http.StatusInternalServerError
switch exit {
case localnet.ExitUserError:
@@ -1157,9 +797,6 @@ func handleDownInstance() http.HandlerFunc {
cause = "down failed with exit code " + strconv.FormatUint(uint64(exit), 10)
}
log.Printf("down instance %q: exit=%d err=%s", name, exit, cause)
- // RunDown emits non-fatal `Warning:` lines before the actual
- // fatal cause; firstNonWarningLine skips them so the summary
- // reflects the real failure. Full output stays in the server log.
writeErrorWithCode(w, status,
"DOWN_FAILED",
"failed to stop "+name+": "+firstNonWarningLine(cause),
@@ -1168,8 +805,6 @@ func handleDownInstance() http.HandlerFunc {
}
}
-// firstLine returns just the first line of s. Used to keep error
-// summaries one-line-y; the full output goes to the server log.
func firstLine(s string) string {
for i := 0; i < len(s); i++ {
if s[i] == '\n' {
@@ -1179,21 +814,11 @@ func firstLine(s string) string {
return s
}
-// firstNonWarningLine returns the first line of s that does not
-// look like a `Warning:` / `WARN:` notice. RunDown emits warning
-// lines for non-fatal side issues before the actual fatal cause,
-// so a naive firstLine would surface a Warning as the failure
-// summary. CRLF safe. If every line is a warning OR the string is
-// empty, returns the raw first line so the caller still has
-// *something* to show.
func firstNonWarningLine(s string) string {
start := 0
for i := 0; i <= len(s); i++ {
if i == len(s) || s[i] == '\n' {
line := s[start:i]
- // Trim a trailing \r so CRLF line endings (Windows
- // docker-compose stderr) don't defeat the prefix
- // match below.
if len(line) > 0 && line[len(line)-1] == '\r' {
line = line[:len(line)-1]
}
@@ -1206,13 +831,7 @@ func firstNonWarningLine(s string) string {
return firstLine(s)
}
-// looksLikeWarningLine matches lines to skip when looking for the
-// surfaced failure cause. Recognizes the fixed set of case variants
-// RunDown and docker actually emit (Warning/warning/WARNING/WARN/
-// warn/Warn) rather than matching truly case-insensitively.
func looksLikeWarningLine(line string) bool {
- // Trim leading whitespace defensively — docker-compose's
- // formatted output sometimes indents continuation lines.
for len(line) > 0 && (line[0] == ' ' || line[0] == '\t') {
line = line[1:]
}
@@ -1225,66 +844,30 @@ func looksLikeWarningLine(line string) bool {
return false
}
-// ContainerHealth is one row in the per-instance container
-// table the UI's ContainerHealth panel renders. Mirrors what
-// `docker compose ps --all --format json` emits, narrowed to the
-// fields the UI actually needs.
-//
-// State + Health are the high-leverage diagnostic pair:
-//
-// State = docker container state — running, restarting,
-// exited, dead, created, paused
-// Health = docker healthcheck verdict — healthy, unhealthy,
-// starting, "" (no healthcheck defined)
-//
-// The registry's hard-coded `running|stopped|failed|...` enum hides
-// truth like "canton is in a restart loop while postgres is healthy";
-// this list lets the UI render the per-container truth.
type ContainerHealth struct {
Name string `json:"name"`
Service string `json:"service"`
State string `json:"state"`
Health string `json:"health,omitempty"`
- Status string `json:"status"` // raw human string from docker (e.g. "Up 4 minutes (health: starting)")
+ Status string `json:"status"`
Image string `json:"image,omitempty"`
}
type ContainersResponse struct {
- SchemaVersion int `json:"schema_version"`
- Instance string `json:"instance"`
- Containers []ContainerHealth `json:"containers"`
- // Counters the frontend uses for a one-glance summary pill.
- HealthyCount int `json:"healthy_count"`
- StartingCount int `json:"starting_count"`
- UnhealthyCount int `json:"unhealthy_count"`
- RestartingCount int `json:"restarting_count"`
- ExitedCount int `json:"exited_count"`
-
- // Aggregate live resource use from `docker stats`, summed across the
- // project's containers. Pointers because docker stats is best-effort:
- // nil means "not sampled" (the UI renders an em-dash, never a zero).
- // Sourced from docker, so present whenever the instance is running —
- // independent of the observability profile that gates ledger metrics.
+ SchemaVersion int `json:"schema_version"`
+ Instance string `json:"instance"`
+ Containers []ContainerHealth `json:"containers"`
+ HealthyCount int `json:"healthy_count"`
+ StartingCount int `json:"starting_count"`
+ UnhealthyCount int `json:"unhealthy_count"`
+ RestartingCount int `json:"restarting_count"`
+ ExitedCount int `json:"exited_count"`
+
CPUPercent *float64 `json:"cpu_percent,omitempty"`
MemUsedBytes *int64 `json:"mem_used_bytes,omitempty"`
MemLimitBytes *int64 `json:"mem_limit_bytes,omitempty"`
}
-// handleInstanceContainers: GET /api/instances/{name}/containers.
-//
-// Runs `docker compose -p ps --all --format json`
-// against the registered compose project, parses each line as a
-// container record, and returns the narrow shape the
-// ContainerHealth panel renders.
-//
-// 200 with empty containers list if the project name resolves
-// but docker has no containers (the instance was scrubbed at the
-// docker level but state.json still names a project) — better
-// than 404 because the frontend can show "no containers" and
-// offer cleanup actions.
-//
-// Caching: no-store (covered by writeJSON). The frontend polls
-// every ~3s while a CreatingPanel or stuck-state row is visible.
func handleInstanceContainers() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1312,10 +895,6 @@ func handleInstanceContainers() http.HandlerFunc {
health, runErr := containersList(ctx, state.ComposeProject)
if runErr != nil {
- // Docker call failed (daemon down? project label
- // doesn't exist?). Surface the failure as a 503
- // with the underlying error so the UI can render a
- // degraded-mode message.
writeErrorWithCode(w, http.StatusServiceUnavailable,
"DOCKER_PROBE_FAILED",
"could not query docker for compose project "+state.ComposeProject,
@@ -1345,10 +924,6 @@ func handleInstanceContainers() http.HandlerFunc {
}
}
- // Best-effort live CPU/memory via `docker stats`, summed across the
- // project. Short timeout + swallowed error so a slow/failed sample
- // never blocks or fails the container list; the fields stay nil and
- // the UI shows an em-dash for that poll.
if len(health) > 0 {
names := make([]string, len(health))
for i, c := range health {
@@ -1364,11 +939,6 @@ func handleInstanceContainers() http.HandlerFunc {
}
}
-// aggregateContainerStats sums per-container docker-stats samples across a
-// project's containers. Returns nil pointers (never a fabricated zero) when
-// no container in health had a matching sample — e.g. the docker stats call
-// raced a container that just exited. MemLimitBytes stays nil if the summed
-// limit is 0 (no container reported one).
func aggregateContainerStats(health []ContainerHealth, stats map[string]containers.Stat) (cpu *float64, used, limit *int64) {
var cpuSum float64
var usedSum, limitSum int64
@@ -1392,12 +962,6 @@ func aggregateContainerStats(health []ContainerHealth, stats map[string]containe
return cpu, used, limit
}
-// containersList wraps the shared containers.List (called from
-// both the CLI's `dpm localnet container list` and this handler)
-// and re-shapes Info → ContainerHealth so the API responses keep
-// their stable JSON tags. The docker-side logic lives once in
-// internal/localnet/containers — see CONTRIBUTING.md "CLI ↔ Web UI
-// parity" rule.
func containersList(ctx context.Context, project string) ([]ContainerHealth, error) {
infos, err := containers.List(ctx, project)
if err != nil {
@@ -1417,27 +981,6 @@ func containersList(ctx context.Context, project string) ([]ContainerHealth, err
return out, nil
}
-// handleContainerLogs: GET /api/instances/{name}/containers/{container}/logs.
-//
-// Returns the last N lines (default 200, capped at 2000) of the
-// named container's logs as text/plain. The frontend renders
-// the body in a with terminal styling.
-//
-// Container name is path-param-validated against the live
-// docker-compose-ps output for the instance's project, so
-// arbitrary names can't be passed in (defence-in-depth against
-// a misconfigured proxy that forwards untrusted path segments).
-//
-// Query params:
-//
-// tail= — max lines to return; clamped to [10, 2000].
-// Default 200.
-// since= — docker --since flag, e.g. "5m", "30s".
-// Default empty (whole log).
-//
-// 404 if the named container isn't in the instance's compose
-// project (or doesn't exist in docker at all).
-// 503 if docker itself can't be reached.
func handleContainerLogs() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1468,12 +1011,6 @@ func handleContainerLogs() http.HandlerFunc {
return
}
- // Verify the container actually belongs to this
- // instance's project. Without this check, anyone could
- // fetch logs from any container on the host by passing
- // a foreign name. The check is cheap (one
- // docker compose ps) and the defence-in-depth is worth
- // the extra round trip.
probeCtx, cancelProbe := context.WithTimeout(r.Context(), 5*time.Second)
belongsErr := containers.BelongsToProject(probeCtx, state.ComposeProject, container)
cancelProbe()
@@ -1490,7 +1027,6 @@ func handleContainerLogs() http.HandlerFunc {
return
}
- // tail / since query params with sane bounds.
tail := 200
if t := r.URL.Query().Get("tail"); t != "" {
if n, err := parseClampedInt(t, 10, 2000); err == nil {
@@ -1498,9 +1034,6 @@ func handleContainerLogs() http.HandlerFunc {
}
}
since := r.URL.Query().Get("since")
- // Validate `since` against a strict subset of docker's
- // duration format (digits + h/m/s) to avoid passing
- // shell-y characters through to the docker CLI.
if since != "" && !validDuration(since) {
writeErrorWithCode(w, http.StatusBadRequest,
ErrCodeInvalidRequest,
@@ -1521,8 +1054,6 @@ func handleContainerLogs() http.HandlerFunc {
"could not tail container logs", err.Error())
return
}
- // Plain-text response so the frontend can render in a
- // without a JSON decode + escape round-trip.
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusOK)
@@ -1530,21 +1061,6 @@ func handleContainerLogs() http.HandlerFunc {
}
}
-// handleContainerRestart: POST /api/instances/{name}/containers/{container}/restart.
-//
-// Runs `docker restart ` against the named container.
-// Synchronous (docker restart blocks until container exits then
-// starts again). 30s timeout — docker's default stop grace is
-// 10s plus startup, so most containers are well under this.
-//
-// Same path-param validation as the logs endpoint: container
-// name regex + verified against the instance's compose project
-// via docker compose ps so arbitrary host containers can't be
-// poked.
-//
-// 204 on success. 5xx with the docker error on failure (most
-// likely cause: the container is gone between the ps probe and
-// the restart call).
func handleContainerRestart() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1574,10 +1090,6 @@ func handleContainerRestart() http.HandlerFunc {
return
}
- // Verify container belongs to this instance's project.
- // Defence-in-depth: without this, a malicious client
- // could restart arbitrary containers on the host by
- // passing a foreign container name.
probeCtx, cancelProbe := context.WithTimeout(r.Context(), 5*time.Second)
belongsErr := containers.BelongsToProject(probeCtx, state.ComposeProject, container)
cancelProbe()
@@ -1608,9 +1120,6 @@ func handleContainerRestart() http.HandlerFunc {
}
}
-// validContainerName allows alphanumeric, dot, underscore,
-// hyphen — the character set docker actually uses for container
-// names. Rejects path separators, shell metachars, spaces.
func validContainerName(s string) bool {
if s == "" || len(s) > 253 {
return false
@@ -1628,9 +1137,6 @@ func validContainerName(s string) bool {
return true
}
-// validDuration accepts the narrow docker --since format:
-// one-or-more digits followed by exactly one unit letter (h/m/s).
-// Rejects compound expressions ("1h30m") and shell metachars.
func validDuration(s string) bool {
if len(s) < 2 || len(s) > 6 {
return false
@@ -1647,10 +1153,6 @@ func validDuration(s string) bool {
return true
}
-// parseClampedInt parses s as an integer and clamps to [lo, hi].
-// Returns an error only on non-integer input — out-of-range
-// values get silently clamped because the caller's intent is
-// clearer that way ("tail=99999" → return the max we'll allow).
func parseClampedInt(s string, lo, hi int) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
@@ -1667,22 +1169,6 @@ func parseClampedInt(s string, lo, hi int) (int, error) {
type runRemoveFunc func(context.Context, io.Writer, io.Writer, *localnet.RemoveOptions) int
-// handleRemoveInstance: DELETE /api/instances/{name}.
-//
-// Destructive cleanup equivalent to `localnet remove`: removes the compose
-// project's containers and named volumes before deleting state.json and the
-// registry entry. This distinction is load-bearing: `down` preserves volumes
-// for a later resume, while `remove` must not leave an old ledger database to
-// be attached to a future instance that reuses the same name.
-//
-// Orphaned index entries with no state.json are still scrubbed. Without state
-// there is no trustworthy compose-project identifier, so that repair path can
-// only remove the index entry. Active create jobs are refused; the caller must
-// cancel creation first.
-//
-// A RUNNING instance requires `?force=true` — the wire form of the CLI's
-// confirmation prompt, set by the Web UI only once the user accepts the
-// remove dialog, so an unconfirmed click cannot destroy a live ledger.
func handleRemoveInstance(hub *stream.Hub) http.HandlerFunc {
return handleRemoveInstanceWithRunner(hub, localnet.RunRemove)
}
@@ -1697,8 +1183,6 @@ func handleRemoveInstanceWithRunner(hub *stream.Hub, runRemove runRemoveFunc) ht
return
}
- // Refuse if a job is actively creating — the goroutine
- // would race our cleanup. Caller should DELETE /up first.
if jobs.Active(name) {
writeErrorWithCode(w, http.StatusConflict,
"INSTANCE_CREATING",
@@ -1710,18 +1194,6 @@ func handleRemoveInstanceWithRunner(hub *stream.Hub, runRemove runRemoveFunc) ht
state, err := registry.Read(name)
if err != nil {
if errors.Is(err, registry.ErrNotFound) {
- // Two flavours of "not found":
- // 1. The name is unknown entirely — neither
- // a state.json nor an index entry exists.
- // Return 404; nothing to clean.
- // 2. ORPHAN: state.json is missing but the
- // index.json still references the name —
- // a previous interrupted teardown or a
- // manual filesystem wipe. The Web UI shows
- // this in `localnet list` and the user
- // clicks Remove with no way to repair it.
- // Treat Delete as idempotent here: scrub
- // the index entry so list reflects truth.
idx, ierr := registry.ReadIndex()
if ierr != nil {
writeError(w, http.StatusInternalServerError, "read registry index", ierr)
@@ -1748,9 +1220,6 @@ func handleRemoveInstanceWithRunner(hub *stream.Hub, runRemove runRemoveFunc) ht
force := r.URL.Query().Get("force") == "true"
- // Block on `running` unless the caller confirmed via ?force=true —
- // the CLI's prompt equivalent, so an accidental unconfirmed request
- // cannot destroy a live ledger.
if state != nil && state.Status == registry.StatusRunning && !force {
writeErrorWithCode(w, http.StatusConflict,
"INSTANCE_RUNNING",
@@ -1791,36 +1260,6 @@ func handleRemoveInstanceWithRunner(hub *stream.Hub, runRemove runRemoveFunc) ht
}
}
-// handleInstanceEvents: GET /api/instances/{name}/events.
-//
-// SSE endpoint for the per-instance progress stream. Subscribes
-// to instance: via SubscribeWithReplay so a late client
-// (browser opening the EventSource ~50ms after POST returns)
-// receives the events that were published before its connection
-// completed.
-//
-// When no buffer exists for the topic — the up finished (and
-// ClearBuffer ran) OR the name was never the target of a POST —
-// the stream simply opens with nothing to replay. The frontend
-// distinguishes "instance finished" from "instance never existed"
-// via a registry.Read follow-up.
-//
-// 30s heartbeat (matches the global /events handler). On the
-// goroutine's done event the client closes the EventSource;
-// idle connections beyond that survive on the heartbeat until
-// the user navigates away.
-//
-// # Origin gate (parity with the global /events handler)
-//
-// EventSource issues a GET, so this stream is exempt from the
-// router's state-changing CSRF middleware — but a tab on another
-// origin can still open EventSource("http://127.0.0.1:7777/api/
-// instances/x/events") and READ the bring-up progress (instance
-// name, Splice version, step status, RunUp error text). The global
-// /events handler (internal/ui/sse.go) hardens against exactly this;
-// we mirror the guard here so the two SSE surfaces are consistent.
-// Origin is absent on direct curl, so we only enforce when it is
-// present and only fail on mismatch.
func handleInstanceEvents(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1831,10 +1270,6 @@ func handleInstanceEvents(hub *stream.Hub) http.HandlerFunc {
return
}
- // Mirror sse.go's Origin/Host check. Host-level rebinding is
- // blocked by the router's withHostCheck; this catches the
- // cross-origin EventSource read where Host is loopback but
- // Origin is the attacker's site.
if origin := r.Header.Get("Origin"); origin != "" {
if err := httpsec.CheckOriginAgainstHost(
origin, r.Header.Get("Referer"), r.Host); err != nil {
@@ -1851,7 +1286,6 @@ func handleInstanceEvents(hub *stream.Hub) http.HandlerFunc {
return
}
- // SSE headers — same shape as the global /events handler.
h := w.Header()
h.Set("Content-Type", "text/event-stream; charset=utf-8")
h.Set("Cache-Control", "no-cache, no-transform")
@@ -1886,22 +1320,12 @@ func handleInstanceEvents(hub *stream.Hub) http.HandlerFunc {
}
}
-// writeInstanceEventFrame is a minimal SSE encoder for the
-// per-instance handler.
-//
// We DO NOT emit an `event:` line. The hub's Topic field is
// internal routing data (e.g. "instance:test"); when emitted on
// the wire it becomes a NAMED SSE event, which EventSource's
// onmessage handler ignores by spec (only the default-type events
// fire onmessage; named events require addEventListener(name, …)).
//
-// Since the per-instance handler ALWAYS serves a single topic
-// (the {name} path param IS the topic), the topic is redundant on
-// the wire — the consumer already knows what stream they opened.
-// Omitting the event: line means events arrive as the default
-// type and the frontend's onmessage catches them as the spec
-// intends.
-//
// Per spec, multi-line data needs one "data:" prefix per line; we
// strip a trailing newline so the payload doesn't gain a trailing
// empty data: line.
@@ -1920,35 +1344,6 @@ func writeInstanceEventFrame(w http.ResponseWriter, e stream.Event) {
_, _ = w.Write([]byte("\n"))
}
-// ── cancel an in-flight create-instance goroutine ─────────
-
-// handleCancelUp: DELETE /api/instances/{name}/up.
-//
-// The CSRF middleware in router.go protects DELETE against
-// cross-origin invocations (DELETE isn't a CORS simple method,
-// so a browser preflight would fire and be rejected by the
-// Origin check). Loopback bind is the outer defence.
-//
-// Sequence:
-// 1. validate name
-// 2. lookup the job; 404 if no in-flight goroutine
-// 3. publish a synthetic kind=cancelled event so SSE consumers
-// see the user-initiated cancellation BEFORE the natural
-// step.failed events RunUp emits when it notices ctx.Err()
-// 4. invoke the registered cancel func — the goroutine's
-// ctx.Done() fires, RunUp returns ExitTimeout via its
-// existing path, the deferred ClearBuffer + Unregister run
-//
-// 204 No Content on success. The frontend doesn't need a body —
-// the SSE stream carries the actual cancellation marker, and
-// the registry change becomes visible to /api/instances on the
-// goroutine's next state write.
-//
-// Idempotency: a second DELETE for the same name (after the
-// goroutine has already exited) returns 404, NOT 200/204. The
-// frontend's "cancel" button should debounce so this only
-// matters for genuine retries; the 404 is the right signal that
-// there's nothing to cancel.
func handleCancelUp(hub *stream.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -1967,20 +1362,8 @@ func handleCancelUp(hub *stream.Hub) http.HandlerFunc {
return
}
- // Publish cancellation marker BEFORE invoking cancel.
- // Order matters: a fast subscriber reading the SSE in
- // real-time should see kind=cancelled THEN the
- // step.failed events RunUp emits as ctx.Err() propagates
- // through the orchestrator. Reverse order would surface
- // the natural failure ("Interrupted while …") without
- // the user-initiated marker, which the frontend would
- // mis-render as a generic failure.
progress.PublishCancelled(hub, name, "user requested via DELETE")
- // Cancel returns false if the job vanished between
- // Active() and Cancel(). Treat as success — the goal
- // was achieved (no in-flight work). Don't 404 on a
- // race the user can't observe.
jobs.Cancel(name)
log.Printf("cancel instance %q via DELETE", name)
@@ -1988,31 +1371,14 @@ func handleCancelUp(hub *stream.Hub) http.HandlerFunc {
}
}
-// observabilityToggleTimeout caps how long the toggle handler will
-// wait on docker compose. Prometheus + Grafana cold-start in <10s
-// typically; 90s leaves room for the first image pull (~250 MB)
-// on a fresh machine.
const observabilityToggleTimeout = 90 * time.Second
-// observabilityToggleRequest is the body for
-// POST /api/instances/{name}/observability.
-//
-// Per-component flags (`prometheus` / `grafana`) are the canonical
-// form so users can flip the two sidecars independently. The legacy
-// `enabled` flag is retained as a compatibility synonym: when
-// present (non-nil), it sets BOTH components to the same value so
-// clients that haven't been updated keep working. Per-component
-// flags win over `enabled` when both are sent in the same body.
type observabilityToggleRequest struct {
Prometheus *bool `json:"prometheus,omitempty"`
Grafana *bool `json:"grafana,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
}
-// resolveTargets folds the three optional fields into the
-// (prometheus, grafana) target booleans. Returns the resolved
-// targets plus a flag indicating whether any field was set. The
-// per-component flags take precedence over `enabled`.
func (r observabilityToggleRequest) resolveTargets() (prom, graf bool, ok bool) {
if r.Enabled != nil {
prom = *r.Enabled
@@ -2030,42 +1396,6 @@ func (r observabilityToggleRequest) resolveTargets() (prom, graf bool, ok bool)
return
}
-// handleObservabilityToggle: POST /api/instances/{name}/observability.
-//
-// Toggles the Prometheus + Grafana sidecars on a RUNNING instance
-// without disturbing canton/splice. The endpoint exists so users
-// who created an instance without `--profile observability` (or
-// without the checkbox in the Create modal) can flip metrics on
-// after the fact instead of having to down + up.
-//
-// CLI parity: mirrored by `dpm localnet observability enable|disable|
-// status` (internal/cli/localnet/observability.go) — both surfaces call
-// the SAME neutral localnet.SetObservability, so there is no per-surface
-// docker-compose drift. The sidecars are still PER-INSTANCE rather than
-// a single host-level stack (see docs/limitations.md "Shared
-// observability stack").
-//
-// Body: {"enabled": true|false}
-//
-// enabled=true → MaterializeObservabilityOverlay into dataDir,
-// append the overlay to state.ComposeFiles if
-// absent, then bring up each requested sidecar with
-// its own `docker compose ... up -d --no-deps `
-// under the profile set the service needs (grafana
-// also activates the prometheus profile so its
-// `depends_on: prometheus` resolves). Discover the
-// new host port, persist into state.Ports[...].
-// enabled=false → `docker compose ... stop prometheus grafana`
-// then `... rm -f prometheus grafana`. Clear the
-// port from state.json. Canton + splice are
-// untouched.
-//
-// Failure modes:
-//
-// 404 INSTANCE_NOT_FOUND — name unknown
-// 409 INSTANCE_NOT_RUNNING — toggle requires a live stack
-// 409 INSTANCE_BUSY — another op holds the lock
-// 502 OBSERVABILITY_TOGGLE_FAIL — docker compose returned non-zero
func handleObservabilityToggle() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
@@ -2095,9 +1425,6 @@ func handleObservabilityToggle() http.HandlerFunc {
return
}
- // Per-instance lock so we can't race a concurrent down/up
- // or another toggle. The lock is the same one
- // `localnet up` / snapshot / restore hold — uniform CAS.
release, lerr := registry.Lock(name)
if lerr != nil {
writeErrorWithCode(w, http.StatusConflict,
@@ -2130,12 +1457,6 @@ func handleObservabilityToggle() http.HandlerFunc {
ctx, cancel := context.WithTimeout(r.Context(), observabilityToggleTimeout)
defer cancel()
- // Delegate the docker-compose orchestration + port persistence
- // to the NEUTRAL localnet.SetObservability so the CLI verb
- // (`dpm localnet observability`) and this handler share one
- // code path (CONTRIBUTING.md "share the business logic"). We
- // hold the per-instance lock for the whole handler, satisfying
- // SetObservability's caller contract.
var logBuf bytes.Buffer
res, err := localnet.SetObservability(ctx, state, wantProm, wantGraf, &logBuf)
if logBuf.Len() > 0 {
@@ -2143,10 +1464,6 @@ func handleObservabilityToggle() http.HandlerFunc {
}
if err != nil {
log.Printf("observability toggle %q failed: %v", name, err)
- // Point the docker-logs hint at the container that actually
- // failed (prometheus vs grafana) instead of always naming
- // prometheus — SetObservability wraps the failure with a
- // component-specific prefix we can key off.
svc := failedObservabilityService(err)
writeErrorWithCode(w, http.StatusBadGateway,
"OBSERVABILITY_TOGGLE_FAIL",
@@ -2160,8 +1477,7 @@ func handleObservabilityToggle() http.HandlerFunc {
"instance": name,
"prometheus": res.Prometheus,
"grafana": res.Grafana,
- // `enabled` retained for legacy clients: true iff BOTH are on.
- "enabled": res.Prometheus && res.Grafana,
+ "enabled": res.Prometheus && res.Grafana,
}
if res.PrometheusPort != 0 {
resp["prometheus_ui"] = res.PrometheusPort
@@ -2176,15 +1492,6 @@ func handleObservabilityToggle() http.HandlerFunc {
}
}
-// failedObservabilityService maps a SetObservability error to the
-// sidecar the remediation hint should name. SetObservability wraps every
-// component failure with a leading "enable|disable : ..."
-// prefix, so we match that PREFIX rather than searching the whole error:
-// the wrapped docker output (the "...\noutput:\n" tail) can
-// mention the other component (e.g. a compose error listing both
-// services), which a substring match would mis-attribute. A grafana
-// prefix yields "grafana"; the prometheus path and any non-component
-// error fall back to "prometheus".
func failedObservabilityService(err error) string {
if err != nil {
msg := err.Error()
@@ -2195,10 +1502,6 @@ func failedObservabilityService(err error) string {
return "prometheus"
}
-// truncateForUser keeps error messages from leaking the full docker
-// compose stderr (sometimes 10+ KB) into the user-facing response.
-// 400 chars is enough for the typical "no such service" / "address
-// already in use" lines without dumping the entire trace.
func truncateForUser(s string) string {
const max = 400
if len(s) <= max {
diff --git a/internal/ui/handlers/reconciler.go b/internal/ui/handlers/reconciler.go
index d47347e5..e2c349d5 100644
--- a/internal/ui/handlers/reconciler.go
+++ b/internal/ui/handlers/reconciler.go
@@ -11,35 +11,12 @@ import (
"github.com/bitdynamics-ab/canton-devkit/internal/registry"
)
-// captureCantonPorts is a test seam wrapping localnet.CaptureCantonPorts.
-// Tests override this var to feed deterministic port maps without
-// shelling out to docker. Production uses the real implementation.
var captureCantonPorts = localnet.CaptureCantonPorts
-// reconcileContainersList is the test seam wrapping containersList so
-// reconciler tests can drive ReconcileOne end-to-end without exec'ing
-// docker. Production keeps the real wrapper.
var reconcileContainersList = containersList
-// coreServicesFor resolves an instance's core compose service names
-// via the splice adapter. Exposed as a var so the
-// reconciler tests can swap in a deterministic list without dragging
-// the splice catalogue into the test setup. Returns nil when the
-// version isn't resolvable; evalStatus treats nil as "skip the core
-// check," preserving back-compat with registry entries whose
-// splice_version has been renamed or removed.
var coreServicesFor = localnet.CoreServicesFor
-// cantonPortsCacheTTL caps how long the reconciler will reuse a
-// cached port-capture result. Each `CaptureCantonPorts` call shells
-// out to `docker compose port` 9 times — without the cache, the 15s
-// reconcile loop would fire 9 docker subprocesses every cycle for
-// every running instance, even though host ports only change when
-// the canton container is recreated. A TTL slightly shorter than
-// the reconcile interval means: cached result for the common
-// "everything stable" case (one cycle uses cache from the previous),
-// fresh probe at most once per interval. Tests set this to zero via
-// resetCantonPortsCache to bypass the cache deterministically.
var cantonPortsCacheTTL = 14 * time.Second
type cantonPortsCacheEntry struct {
@@ -52,13 +29,6 @@ var (
cantonPortsCache = map[string]cantonPortsCacheEntry{}
)
-// cachedCaptureCantonPorts wraps captureCantonPorts with a per-project
-// TTL cache. Returns the cached map on a hit; on miss / expiry,
-// calls through and stores the fresh result. The cache holds maps
-// returned by callers BY VALUE-via-shared-reference — callers must
-// treat the returned map as read-only (the reconciler does: it only
-// diffs against state.Ports, then merges deltas into the freshly
-// re-read state under the registry lock).
func cachedCaptureCantonPorts(ctx context.Context, project string) map[string]int {
cantonPortsCacheMu.Lock()
entry, ok := cantonPortsCache[project]
@@ -68,10 +38,6 @@ func cachedCaptureCantonPorts(ctx context.Context, project string) map[string]in
}
fresh := captureCantonPorts(ctx, project)
if len(fresh) == 0 {
- // Don't poison the cache with a probe failure — keep
- // the prior entry (if any) so a transient docker hiccup
- // doesn't force 9 subprocesses on every cycle until the
- // daemon recovers.
return fresh
}
cantonPortsCacheMu.Lock()
@@ -80,65 +46,16 @@ func cachedCaptureCantonPorts(ctx context.Context, project string) map[string]in
return fresh
}
-// resetCantonPortsCache clears the TTL cache. Exposed for tests that
-// need to assert pre/post probe behaviour without waiting out the
-// TTL. Not used in production.
func resetCantonPortsCache() {
cantonPortsCacheMu.Lock()
cantonPortsCache = map[string]cantonPortsCacheEntry{}
cantonPortsCacheMu.Unlock()
}
-// Reconciler — adopt/resync registry status from docker.
-//
-// The registry's `Status` field is set ONCE per lifecycle event:
-// RunUp writes `running` on success or `failed`/`partial` on
-// timeout/cancel; RunDown writes `stopped`. After that, nothing
-// updates it. Result: the dashboard's status pill can lie for
-// hours — e.g. a bring-up that timed out at "wait_healthy" stamps
-// `failed`, the user fixes the underlying cause (raises Docker
-// memory, restarts splice), the containers go healthy, but the
-// registry still says `failed` until the next destructive op.
-//
-// The container-health panel polls docker live and shows truth,
-// but the dashboard row + ActionButton key off the cached status.
-//
-// This reconciler closes that gap. A background ticker probes
-// `docker compose ps` for every registered instance and rewrites
-// the registry status when it diverges from docker. The handler
-// surfaces are unchanged — they still read the registry — but the
-// registry is now eventually-consistent with docker (within one
-// reconcileInterval).
-
-// reconcileInterval is how often we sweep every registered
-// instance. 15s strikes a balance: fast enough that a user who
-// just fixed an OOM and restarted splice sees the dashboard catch
-// up within one rotation, slow enough that the per-instance
-// `docker compose ps` probes don't peg a laptop CPU. Each probe
-// itself is bounded to reconcilePerInstanceTimeout.
const reconcileInterval = 15 * time.Second
-// reconcilePerInstanceTimeout caps a single docker probe so a
-// stuck daemon can't pin the reconciler goroutine forever. Matches
-// the per-instance timeout in handleInstanceContainers (5s — the
-// "live" panel uses the same number, so the reconciler's load is
-// at most equivalent to one extra Container Health panel polling
-// at 1/15 the rate).
const reconcilePerInstanceTimeout = 5 * time.Second
-// StartReconciler launches the background sweep. Returns
-// immediately; the goroutine runs until ctx is cancelled. Pass
-// the same shutdown context the HTTP server uses so a Ctrl-C
-// in `dpm localnet ui` stops the reconciler cleanly.
-//
-// The first sweep happens after one interval — NOT immediately on
-// start. Reason: on cold start the registry may have entries from
-// a previous run whose containers were torn down out-of-band
-// (e.g. `docker compose down` from a terminal). The first sweep
-// would correctly flip those to `stopped`, but doing it before
-// the operator has any chance to see the dashboard's pre-sweep
-// state is confusing — better to give them 15s of "what the
-// registry remembers" before reality overrides it.
func StartReconciler(ctx context.Context) {
go func() {
ticker := time.NewTicker(reconcileInterval)
@@ -154,17 +71,9 @@ func StartReconciler(ctx context.Context) {
}()
}
-// reconcileAll iterates every entry in the index and reconciles
-// each in serial. Serial (not parallel) because the typical user
-// has 1–3 instances, the per-instance probe is 5s worst case, and
-// a parallel fan-out would burst N docker subprocesses which is
-// worse for laptop CPU than spreading them across the interval.
func reconcileAll(parent context.Context) {
idx, err := registry.ReadIndex()
if err != nil {
- // Registry unreadable — log once per sweep and skip. The
- // registry layer's own diagnostics surface the underlying
- // cause (permission, missing file, malformed JSON).
log.Printf("reconciler: read index: %v", err)
return
}
@@ -180,34 +89,14 @@ func reconcileAll(parent context.Context) {
}
}
-// ReconcileOne probes docker for the named instance and writes
-// the registry back if the status disagrees. Idempotent; safe to
-// call repeatedly. Logs only when an actual flip happens, to keep
-// the access log readable.
-//
-// Returns (oldStatus, newStatus, changed) so callers like the CLI
-// `dpm localnet refresh` command can render per-flip output. When
-// nothing changed, both old and new are equal and changed is
-// false. Probe errors are NOT propagated — a transient docker
-// hiccup is treated as "leave stale" rather than flipping noisily;
-// the only signal a caller gets is changed=false.
func ReconcileOne(ctx context.Context, name string) (old, neu registry.Status, changed bool) {
- // Skip instances with an in-flight create — the create
- // goroutine owns the status during its lifetime and a
- // reconciler write would race it.
if jobs.Active(name) {
return "", "", false
}
state, err := registry.Read(name)
if err != nil {
- // Vanished between ReadIndex and Read — registry deleted
- // or corrupted. Either way nothing to reconcile.
return "", "", false
}
- // Transitional states are owned by their respective goroutines
- // (creating = RunUp, stopping = RunDown). The reconciler must
- // not write to them — only the orchestrator knows when the
- // transition is complete.
switch state.Status {
case registry.StatusCreating, registry.StatusStopping:
return state.Status, state.Status, false
@@ -215,47 +104,15 @@ func ReconcileOne(ctx context.Context, name string) (old, neu registry.Status, c
probed, probeErr := reconcileContainersList(ctx, state.ComposeProject)
if probeErr != nil {
- // Daemon down, project missing, transient error. Leave
- // the cached status alone — better to render stale than
- // to flip on a transient probe failure.
return state.Status, state.Status, false
}
- // Pull the splice adapter's core-services list so
- // evalStatus can distinguish "core stack missing" (failed) from
- // "core stack running but degraded" (partial). Resolution
- // failures (e.g. an old splice_version no longer in the
- // catalogue) yield nil, which evalStatus interprets as "skip
- // the core check" — preserves back-compat with stale entries.
coreServices := coreServicesFor(state.SpliceVersion)
newStatus := evalStatus(state.Status, probed, coreServices)
- // When canton is up (or going up), re-capture the 9
- // participant ports the screens dial. If `canton` was recreated
- // since the last bring-up (clean restart, OOM restart, etc.)
- // docker reassigned its ephemeral host ports — but the
- // capture-on-WaitForHealthy never gets a second chance to update
- // state.Ports. Without this the Explorer / DAR / contracts
- // handlers happily 502 against a port that's been closed for
- // minutes while the reconciler reports `running`.
- //
- // We refresh ports BEFORE the status-changed early return so the
- // common case (cached=running, newStatus=running, only ports
- // drifted) gets the fix too.
- //
// Gate also includes `partial` — the V2 Token Standard image set
// has a perpetually-`starting` splice healthcheck that pegs the
// reconciler at `partial` forever (see assets/compose/tokens-v2.yml).
- // Those are the instances where canton most often restarts AND
- // the screens most need a working port set; gating on `running`
- // alone would never fire for them. The capture is best-effort —
- // missing probes leave cached values intact — so probing during
- // `partial` is safe (probe failure ⇒ no diff ⇒ no write).
- // Probe ports OUTSIDE the registry lock — the docker subprocesses
- // can take seconds, and we don't want to block concurrent writers
- // (e.g. `localnet down`) on a slow daemon. We only diff against
- // state.Ports here; the authoritative apply-and-write happens
- // below under the lock against a freshly-re-read state.
var livePorts map[string]int
if state.ComposeProject != "" &&
(newStatus == registry.StatusRunning || newStatus == registry.StatusPartial) {
@@ -266,27 +123,16 @@ func ReconcileOne(ctx context.Context, name string) (old, neu registry.Status, c
return state.Status, state.Status, false
}
- // Acquire the registry lock and re-read fresh state before
- // applying changes. Mirrors the lock+re-read pattern in
- // internal/cli/localnet/down.go — without it a concurrent
- // `localnet down` (or a future Web UI POST) could clobber our
- // stale snapshot's Credentials / DSO / Tokens fields when we
- // Write(state) here.
release, lockErr := registry.Lock(name)
if lockErr != nil {
- // Lock contention or fs error — treat like a probe failure
- // and leave the cached status alone for this cycle.
return state.Status, state.Status, false
}
defer release()
fresh, rerr := registry.Read(name)
if rerr != nil {
- // Vanished between probe and lock — nothing to write.
return state.Status, state.Status, false
}
- // Re-evaluate transitional states after re-read: a concurrent
- // `down` may have flipped to stopping while we were probing.
switch fresh.Status {
case registry.StatusCreating, registry.StatusStopping:
return fresh.Status, fresh.Status, false
@@ -312,10 +158,6 @@ func ReconcileOne(ctx context.Context, name string) (old, neu registry.Status, c
return oldStatus, fresh.Status, statusChanged || portsChanged
}
-// portMapDiffers reports whether `live` contains any port that
-// disagrees with `cached`. A missing key in `live` is "I don't know"
-// (per CaptureCantonPorts contract) and does NOT count as a diff.
-// Returns false when live is empty (probe failure / not gated).
func portMapDiffers(cached, live map[string]int) bool {
if len(live) == 0 {
return false
@@ -328,12 +170,6 @@ func portMapDiffers(cached, live map[string]int) bool {
return false
}
-// applyPortDelta writes only the changed keys from `live` into
-// fresh.Ports, preserving every other key (including non-canton
-// ports like app_user_ui). Returns true when at least one port
-// changed. It operates on the freshly-re-read state held under the
-// registry lock — so a concurrent down's Credentials/DSO/Tokens
-// writes are preserved rather than clobbered by a stale snapshot.
func applyPortDelta(fresh *registry.State, live map[string]int, name string) bool {
if len(live) == 0 {
return false
@@ -356,76 +192,22 @@ func applyPortDelta(fresh *registry.State, live map[string]int, name string) boo
return true
}
-// refreshCantonPorts probes `docker compose port` for the 9 canonical
-// canton participant ports and updates state.Ports in place with any
-// diff. Returns true when at least one port changed.
-//
-// Probe failures are tolerated — `localnet.CaptureCantonPorts` is
-// best-effort (a port that fails to query is OMITTED from the result
-// rather than returned as 0). Missing keys leave the cached value
-// alone, matching that contract — better to render stale than to
-// blank out ports on a transient docker hiccup.
-//
-// ReconcileOne does not call this — it splits the probe and the
-// in-place write so the write can happen under the registry lock
-// against a freshly-re-read state. This function is a stable
-// unit-test seam for the in-place diff/merge logic.
func refreshCantonPorts(ctx context.Context, state *registry.State, name string) bool {
live := captureCantonPorts(ctx, state.ComposeProject)
return applyPortDelta(state, live, name)
}
-// evalStatus maps a docker-compose-ps snapshot to the registry
-// status the UI should display.
-//
-// Decision table (containers = docker compose ps output):
-//
-// cached=stopped + no containers → stopped (no change)
-// cached=running + no containers → stopped (compose down ran elsewhere)
-// cached=failed + no containers → failed (no change; orchestrator gave up cleanly)
-// cached=partial + no containers → failed (everything's gone; collapse to failed)
-// any core service missing from snapshot → failed
-// cached=* + all healthy/running → running (the happy path)
-// cached=* + any restarting/unhealthy/exited → partial
-//
-// "Healthy" is generous: a container without a HEALTHCHECK in its
-// image (e.g. nginx, swagger-ui in Splice's compose) but in state
-// `running` is treated as healthy — same convention the UI's
-// signalFor uses. Otherwise the reconciler would never call any
-// Splice instance `running` because two of the standard
-// containers have no healthcheck and would forever drag the
-// aggregate into `partial`.
-//
-// coreServices is the contract from splice.Adapter: the
-// compose service names whose absence collapses the snapshot to
-// `failed` regardless of how the surviving containers look. Pass
-// nil to skip the core check (back-compat for callers that don't
-// know the adapter, e.g. older registry entries with an
-// unresolvable splice_version).
func evalStatus(cached registry.Status, containers []ContainerHealth, coreServices []string) registry.Status {
if len(containers) == 0 {
- // No project / all containers removed. If we thought it
- // was running, demote to stopped — the only way we'd see
- // this is someone ran `docker compose down` directly.
if cached == registry.StatusRunning {
return registry.StatusStopped
}
- // partial with no containers is just failed — there's
- // nothing live to be partial about.
if cached == registry.StatusPartial {
return registry.StatusFailed
}
return cached
}
- // Distinguish "core stack missing" from "core stack
- // running but degraded". If even one core service has no
- // container in the snapshot, the instance can't serve a
- // Ledger API call regardless of how the sidecars look. The
- // motivating bug: an instance whose core stack was torn down
- // but whose `--profile observability` containers (prometheus
- // + grafana) survived would happily report `running` because
- // the surviving sidecars were all healthy.
if len(coreServices) > 0 {
seen := make(map[string]bool, len(containers))
for _, c := range containers {
@@ -438,13 +220,6 @@ func evalStatus(cached registry.Status, containers []ContainerHealth, coreServic
}
}
- // `localnet stop` (docker compose stop) leaves the containers in
- // place but `exited`. If we already recorded the instance as
- // `stopped` and NOTHING is running, that's the expected resting
- // state — keep it `stopped` instead of demoting to `partial`
- // (which would make a cleanly-stopped instance look broken and
- // hide the Start button). A running/restarting container means it
- // was started out-of-band, so fall through to the normal eval.
if cached == registry.StatusStopped {
anyRunning := false
for _, c := range containers {
@@ -469,11 +244,8 @@ func evalStatus(cached registry.Status, containers []ContainerHealth, coreServic
case "unhealthy":
anyBad = true
case "starting":
- // In-flight; not bad, but not "healthy" yet.
allHealthy = false
case "healthy", "":
- // healthy or no-healthcheck-defined — both count
- // toward "healthy enough" iff state == running.
if c.State != "running" {
allHealthy = false
}
@@ -488,10 +260,5 @@ func evalStatus(cached registry.Status, containers []ContainerHealth, coreServic
if allHealthy {
return registry.StatusRunning
}
- // Mixed: nothing failing, but not everything healthy yet.
- // Most common case: containers up, healthchecks still
- // `starting`. Don't flip a cached `failed` to running until
- // the healthchecks actually go green; keep partial as the
- // "we know docker has it but it's not fully ready" signal.
return registry.StatusPartial
}
diff --git a/internal/ui/stream/hub.go b/internal/ui/stream/hub.go
index 25315303..4bf7c0c0 100644
--- a/internal/ui/stream/hub.go
+++ b/internal/ui/stream/hub.go
@@ -1,28 +1,3 @@
-// Package stream implements the SSE (Server-Sent Events) broadcaster that
-// powers the Web UI's live-update channel at /events.
-//
-// # The slow-client problem
-//
-// A naive SSE hub — write blocks the publisher — lets a single slow
-// browser tab back up the publisher and freeze the docker poller or
-// ledger client. This hub instead uses bounded per-subscriber channels
-// with drop-oldest: when a subscriber's buffer is full, the OLDEST
-// event is discarded and a `dropped` event is queued so the client
-// knows to refetch state. The publisher never blocks on a subscriber.
-//
-// # Topics
-//
-// Subscribers register for one or more named topics ("services",
-// "logs:demo", …); only events published on a matching topic are
-// delivered. Topic names are opaque strings — handlers define their
-// own taxonomy.
-//
-// # Lifecycle
-//
-// New() returns a Hub ready to publish. The hub has no goroutines of
-// its own; Subscribe() returns a channel that the HTTP handler reads
-// from. When the handler closes (client disconnect), it MUST call the
-// returned cancel func to free the subscription.
package stream
import (
@@ -33,16 +8,6 @@ import (
"time"
)
-// Event is a single broadcast payload. Topic routes the event; Data
-// is the opaque body the SSE handler serialises to the wire. ID is
-// optional and appears as the SSE `id:` line for client-side
-// last-event tracking.
-//
-// SchemaVersion mirrors internal/api/types.SchemaVersion. Every
-// wire-level message the Web UI consumes carries a schema-version field
-// so a frontend bundled for v1 can refuse to decode a v2 event with a
-// clear error; the event-level field also lets a long-running
-// EventSource detect a server upgrade mid-session.
type Event struct {
SchemaVersion int `json:"schema_version"`
Topic string `json:"topic"`
@@ -50,42 +15,21 @@ type Event struct {
Data []byte `json:"data,omitempty"`
}
-// EventSchemaVersion is the canonical value Event.SchemaVersion takes
-// today. Mirrors types.SchemaVersion (duplicated rather than imported
-// so the dependency direction stays handlers→types, not stream→types).
const EventSchemaVersion = 1
-// defaultBuffer is the per-subscriber channel capacity: large enough
-// to absorb a few seconds of normal docker-poll traffic, small enough
-// that drop-oldest kicks in promptly when a client genuinely stalls.
const defaultBuffer = 64
-// Hub is the publisher. Goroutine-safe; methods are intended to be
-// called from many goroutines (one publisher per data source, one
-// subscriber per HTTP handler).
type Hub struct {
mu sync.RWMutex
subs map[*subscription]struct{}
bufLen int
- // Per-topic event buffers for the replay-on-subscribe contract,
- // populated only for topics opted in via EnableBuffering. The
- // create-flow SSE stream relies on this: the up goroutine
- // publishes its first step events before the browser's
- // EventSource opens, and SubscribeWithReplay drains the buffer
- // so those events aren't lost. Buffers are removed on
- // ClearBuffer(topic).
topicBuffers map[string]*topicBuffer
- // stats — atomically updated, read by Stats() for observability.
published atomic.Uint64
dropped atomic.Uint64
}
-// topicBuffer is a fixed-size ring of recent events for one topic.
-// A full buffer evicts the oldest event silently — unlike the live
-// drop-oldest path there is no "dropped" sentinel, because the lost
-// events were published before the subscriber existed.
type topicBuffer struct {
mu sync.Mutex
events []Event
@@ -102,9 +46,6 @@ func newTopicBuffer(cap int) *topicBuffer {
}
}
-// append adds an event to the ring, evicting the oldest when full.
-// The shift-left copy is bounded by `cap`, negligible at the
-// human-paced rate of step events.
func (b *topicBuffer) append(e Event) {
b.mu.Lock()
defer b.mu.Unlock()
@@ -115,8 +56,6 @@ func (b *topicBuffer) append(e Event) {
b.events = append(b.events, e)
}
-// snapshot returns a copy of the current buffer contents. Safe to
-// hand to subscribers — no aliasing with future appends.
func (b *topicBuffer) snapshot() []Event {
b.mu.Lock()
defer b.mu.Unlock()
@@ -125,29 +64,14 @@ func (b *topicBuffer) snapshot() []Event {
return out
}
-// subscription is the per-subscriber state the publisher writes to.
-// One per active /events HTTP request.
-//
-// mu serialises BOTH close(ch) (in cancel) AND the deliverTo body.
-// A plain Mutex (not RWMutex) is deliberate: concurrent deliverTo
-// calls could both drain the same channel, double-counting drops and
-// racing the retry. The Mutex is per-subscription, so other
-// subscribers still proceed in parallel; the hub-level RWMutex (h.mu)
-// keeps the SET of subscribers safe for concurrent iteration.
type subscription struct {
- topics map[string]struct{} // empty = subscribe-all
- ch chan Event
- mu sync.Mutex
- closed bool // protected by mu
- // droppedSinceWarn counts events lost to drop-oldest for THIS
- // subscriber. When non-zero the next successful send is preceded
- // by a synthetic "dropped" event so the client can react.
- // Read+reset via Swap(0) under mu so concurrent increments
- // inside deliverTo are safe.
+ topics map[string]struct{}
+ ch chan Event
+ mu sync.Mutex
+ closed bool
droppedSinceWarn atomic.Uint64
}
-// New constructs a Hub with the default per-subscriber buffer.
func New() *Hub {
return &Hub{
subs: make(map[*subscription]struct{}),
@@ -156,8 +80,6 @@ func New() *Hub {
}
}
-// NewWithBuffer is the variant tests use to dial the per-subscriber
-// buffer size. Production callers should stay on New().
func NewWithBuffer(buf int) *Hub {
if buf < 1 {
buf = 1
@@ -169,14 +91,6 @@ func NewWithBuffer(buf int) *Hub {
}
}
-// EnableBuffering opts a topic into the replay buffer. Subsequent
-// Publish calls for `topic` append to a fixed-size ring of `cap`
-// events (clamped to at least 1); SubscribeWithReplay drains the ring
-// into new subscribers before live event flow begins.
-//
-// Idempotent — re-enabling with the same cap is a no-op; a different
-// cap resizes the existing buffer (truncating oldest-first if
-// smaller). The matching ClearBuffer call frees the ring.
func (h *Hub) EnableBuffering(topic string, cap int) {
if cap < 1 {
cap = 1
@@ -188,8 +102,6 @@ func (h *Hub) EnableBuffering(topic string, cap int) {
h.topicBuffers[topic] = newTopicBuffer(cap)
return
}
- // Already buffering. Resize only if cap differs to avoid
- // dropping queued events on a no-op re-enable.
if existing.cap == cap {
return
}
@@ -197,28 +109,16 @@ func (h *Hub) EnableBuffering(topic string, cap int) {
defer existing.mu.Unlock()
existing.cap = cap
if len(existing.events) > cap {
- // Keep the most recent `cap` events; older ones evict.
existing.events = append([]Event(nil), existing.events[len(existing.events)-cap:]...)
}
}
-// ClearBuffer removes the topic's replay buffer, freeing memory
-// eagerly. Subsequent Publish calls for `topic` still reach live
-// subscribers — they just no longer accumulate in a replay ring.
-// Safe to call on a topic that was never buffered.
func (h *Hub) ClearBuffer(topic string) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.topicBuffers, topic)
}
-// Subscribe registers a new subscriber. topics may be empty to
-// receive every event regardless of topic; otherwise only events
-// whose Topic matches one of the registered names are delivered.
-//
-// Returns a receive-only channel and a cancel func. The handler
-// MUST call cancel when the client disconnects, otherwise the
-// subscription leaks.
func (h *Hub) Subscribe(topics ...string) (<-chan Event, func()) {
s := &subscription{
topics: make(map[string]struct{}, len(topics)),
@@ -232,20 +132,14 @@ func (h *Hub) Subscribe(topics ...string) (<-chan Event, func()) {
h.mu.Unlock()
cancel := func() {
- // Remove from the publisher's set FIRST under h.mu, so no
- // new Publish call will pick this subscription up.
h.mu.Lock()
if _, ok := h.subs[s]; !ok {
h.mu.Unlock()
- return // already cancelled — idempotent
+ return
}
delete(h.subs, s)
h.mu.Unlock()
- // Then close the channel under the subscription's own mutex
- // so it serialises with deliverTo. Without this, a Publish
- // that picked up the sub before the delete could race close
- // → panic on send-to-closed-channel.
s.mu.Lock()
s.closed = true
close(s.ch)
@@ -254,33 +148,16 @@ func (h *Hub) Subscribe(topics ...string) (<-chan Event, func()) {
return s.ch, cancel
}
-// Publish broadcasts an event to every interested subscriber.
-// NEVER blocks on a slow subscriber: if a subscriber's buffer is
-// full, the oldest queued event is discarded and a count is
-// incremented. The subscriber's NEXT successful delivery is
-// preceded by a synthetic Event{Topic: "dropped"} so the client
-// knows it missed some updates and can refetch.
-//
-// Returns the count of subscribers that received the event (or
-// had drop-oldest applied — both count). 0 means no interested
-// subscriber, which is normal during quiet periods.
func (h *Hub) Publish(e Event) int {
h.mu.RLock()
defer h.mu.RUnlock()
- // If the topic has a replay buffer, append BEFORE live delivery.
- // Order matters: a late SubscribeWithReplay (one that races
- // Publish) sees the event in either the snapshot (if we appended
- // before they snapshotted) OR the live channel (if we appended
- // after) — never both, because subscribe holds h.mu.Lock for the
- // add+snapshot and we hold h.mu.RLock here.
if buf, ok := h.topicBuffers[e.Topic]; ok {
buf.append(e)
}
delivered := 0
for s := range h.subs {
- // Topic filter: empty topic set = match-all.
if len(s.topics) > 0 {
if _, ok := s.topics[e.Topic]; !ok {
continue
@@ -293,28 +170,7 @@ func (h *Hub) Publish(e Event) int {
return delivered
}
-// SubscribeWithReplay is the variant the per-instance SSE handler
-// uses. Under a single hub lock it:
-//
-// 1. Snapshots each requested topic's replay buffer
-// 2. Pre-fills the subscription's channel with the snapshot
-// 3. Registers the subscription so live events start flowing
-//
-// The pre-fill happens BEFORE the subscription enters h.subs, so
-// no publisher can interleave a live event into the channel during
-// the drain. Ordering guarantee: replay events appear in
-// publish-order, immediately followed by any live events published
-// after Subscribe returns.
-//
-// The channel is sized max(h.bufLen, total replay events) so the
-// pre-fill can never block.
-//
-// Returns the channel + cancel func, same as Subscribe.
func (h *Hub) SubscribeWithReplay(topics ...string) (<-chan Event, func()) {
- // Everything happens under h.mu.Lock: Publish holds h.mu.RLock,
- // so no event can land in a topic buffer between our snapshot
- // and the subscription becoming visible — each event ends up in
- // either the snapshot or the live channel, never both or neither.
h.mu.Lock()
defer h.mu.Unlock()
@@ -340,16 +196,12 @@ func (h *Hub) SubscribeWithReplay(topics ...string) (<-chan Event, func()) {
s.topics[t] = struct{}{}
}
- // Pre-fill BEFORE registering. No publisher can send to s.ch
- // yet because s isn't in h.subs. Iterate topics in the order
- // the caller gave them so cross-topic replay is deterministic.
for _, t := range topics {
for _, ev := range snapshots[t] {
- s.ch <- ev // never blocks: chanSize ≥ totalReplay
+ s.ch <- ev
}
}
- // NOW make the subscription visible to publishers.
h.subs[s] = struct{}{}
cancel := func() {
@@ -368,19 +220,6 @@ func (h *Hub) SubscribeWithReplay(topics ...string) (<-chan Event, func()) {
return s.ch, cancel
}
-// deliverTo handles the drop-oldest semantics for one subscriber.
-// Tries a non-blocking send; if the buffer is full, drains the
-// oldest event, increments droppedSinceWarn, and retries.
-//
-// Holds s.mu for the entire duration: it serialises with the cancel
-// path (no close(s.ch) between our fullness check and the send) and
-// with other publishers (two concurrent drains on the same channel
-// would double-count drops). If the subscription is already closed,
-// the function is a no-op.
-//
-// Drop accounting uses Swap(0): a Load + Store pair would be racy — a
-// concurrent Publish could increment droppedSinceWarn between the Load
-// and Store, losing the increment.
func (h *Hub) deliverTo(s *subscription, e Event) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -388,10 +227,6 @@ func (h *Hub) deliverTo(s *subscription, e Event) {
return
}
- // Prepend the dropped-warning event if we owe one. The payload
- // is just the count, for the client to decide whether to
- // refetch. Try non-blocking; if it doesn't fit either, restore
- // the count and let the next call handle it.
if lost := s.droppedSinceWarn.Swap(0); lost > 0 {
select {
case s.ch <- Event{SchemaVersion: EventSchemaVersion,
@@ -401,39 +236,29 @@ func (h *Hub) deliverTo(s *subscription, e Event) {
}
}
- // Drain + retry up to once.
for i := 0; i < 2; i++ {
select {
case s.ch <- e:
return
default:
- // Full — drop the oldest, then retry.
select {
case <-s.ch:
s.droppedSinceWarn.Add(1)
h.dropped.Add(1)
default:
- // Subscriber drained the channel between our
- // fullness check and the drain attempt. The
- // channel is empty now; retry will succeed.
}
}
}
- // Two failures in a row — count and drop.
s.droppedSinceWarn.Add(1)
h.dropped.Add(1)
}
-// Stats returns counters useful for /healthz-style introspection
-// and tests. NOT atomic across fields — callers shouldn't rely on
-// a coherent snapshot.
type Stats struct {
Subscribers int
Published uint64
Dropped uint64
}
-// Stats reports current counters.
func (h *Hub) Stats() Stats {
h.mu.RLock()
n := len(h.subs)
@@ -445,20 +270,13 @@ func (h *Hub) Stats() Stats {
}
}
-// Close shuts down the hub. Every active subscriber is closed,
-// the hub's set is cleared, and subsequent Publish calls become
-// no-ops returning 0. Idempotent — calling Close twice is safe.
-//
-// The server's shutdown path calls this so in-flight EventSource
-// connections disconnect immediately instead of leaking until each
-// connection dies on its own.
func (h *Hub) Close() {
h.mu.Lock()
subs := make([]*subscription, 0, len(h.subs))
for s := range h.subs {
subs = append(subs, s)
}
- h.subs = make(map[*subscription]struct{}) // clear; Publish becomes no-op
+ h.subs = make(map[*subscription]struct{})
h.mu.Unlock()
for _, s := range subs {
s.mu.Lock()
@@ -470,10 +288,6 @@ func (h *Hub) Close() {
}
}
-// WaitForSubscribers polls Stats().Subscribers until it reaches
-// n or ctx expires, returning true when the count is reached.
-// Tests use this instead of a flaky time.Sleep to deterministically
-// wait for an SSE handler to register its subscription.
func (h *Hub) WaitForSubscribers(ctx context.Context, n int) bool {
tick := time.NewTicker(time.Millisecond)
defer tick.Stop()