everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
186 lines (184 loc) • 9.14 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_http_client = require("../../utils/http-client.cjs");
const require_keys = require("./keys.cjs");
const require_client = require("./client.cjs");
let effect = require("effect");
//#region src/services/registry/fastkv.ts
function getFastKvBaseUrlForNetwork(network) {
return require_client.registryBaseUrlForNetwork(network);
}
function buildRegistryConfigUrl(accountId, gatewayId, registry) {
return require_client.latestUrlFor(configKey(accountId, gatewayId), { registry });
}
function buildRegistryConfigUrlForNetwork(network, accountId, gatewayId, registry) {
const base = require_client.registryBaseUrlForNetwork(network);
const namespace = require_client.registryNamespaceForNetwork(network, registry);
const key = encodeURIComponent(require_keys.keyPathOf(configKey(accountId, gatewayId)));
return `${base}/v0/latest/${encodeURIComponent(namespace)}/${encodeURIComponent(accountId)}/${key}`;
}
function getRegistryNamespaceForAccount(accountId, registry) {
return registry ?? require_client.registryNamespaceForNetwork(require_client.networkIdForAccount(accountId));
}
function getRegistryNamespaceForNetwork(network, registry) {
return require_client.registryNamespaceForNetwork(network, registry);
}
function configKey(accountId, gatewayId, pathSegments = []) {
return {
kind: "runtimeConfig",
ref: runtimeRefOf(accountId, gatewayId),
...pathSegments.length > 0 ? { path: pathSegments } : {}
};
}
function getRegistryConfigKey(accountId, gatewayId, pathSegments = []) {
return require_keys.keyPathOf(configKey(accountId, gatewayId, pathSegments));
}
function runtimeRefOf(accountId, gatewayId) {
return `bos://${accountId}/${gatewayId}`;
}
function parseBosUrl(bosUrl) {
const parsed = require_keys.parseRuntimeRef(bosUrl);
return {
accountId: parsed.accountId,
gatewayId: parsed.gatewayId,
pathSegments: parsed.path
};
}
async function fetchBosConfigFromFastKv(bosUrl, registry) {
const { accountId, gatewayId, pathSegments } = parseBosUrl(bosUrl);
try {
return await require_client.registryClientShape.read(configKey(accountId, gatewayId, pathSegments), registry !== void 0 ? { registry } : void 0);
} catch (error) {
if (error instanceof require_client.RegistryError && error.kind === "absent") throw new Error(`No config found for ${bosUrl}`);
throw error;
}
}
/**
* Read an arbitrary registry key under `apps/<account>/<gateway>/` — the
* well-known-slot seam (ADR 0034's `platform.json` lives beside the config).
* Absent key (404) → null; a network failure throws so callers can distinguish
* "the slot is empty" from "the slot is unreachable" (a swallowed error here
* would silently tighten a compat floor).
*/
async function fetchRegistryKey(accountId, gatewayId, keyPath, registry) {
const key = encodeURIComponent(`apps/${accountId}/${gatewayId}/${keyPath}`);
const value = (await fetchJson(`${require_client.registryBaseUrlForNetwork(require_client.networkIdForAccount(accountId))}/v0/latest/${encodeURIComponent(getRegistryNamespaceForAccount(accountId, registry))}/${encodeURIComponent(accountId)}/${key}`))?.entries?.find(Boolean)?.value;
if (!value) return null;
if (typeof value === "string") return JSON.parse(value);
return value;
}
/** Tolerant variant of {@link fetchRegistryKey} — any failure collapses to null. */
async function fetchRegistryKeyOrNull(accountId, gatewayId, keyPath, registry) {
try {
return await fetchRegistryKey(accountId, gatewayId, keyPath, registry);
} catch {
return null;
}
}
/** Read a published config from an already-built registry URL
* (`buildRegistryConfigUrlForNetwork`). Unlike {@link fetchBosConfigFromFastKv}
* this takes the URL directly, so the read key is exactly the one the publish
* writes, and a network failure is reported as such instead of collapsing
* into "No config found" (fetchJsonOrNull swallows errors into null). */
async function fetchPublishedConfigFromFastKv(url) {
const response = await require_http_client.fetchRaw(url, { headers: { accept: "application/json" } });
if (!response.ok) {
if (response.status === 404) throw new Error(`No config found for ${url}`);
throw new Error(`HTTP ${response.status} fetching ${url}`);
}
return parseFastKvConfigValue(await response.json(), url);
}
function parseFastKvConfigValue(payload, label) {
const value = payload?.entries?.find(Boolean)?.value;
if (!value) throw new Error(`No config found for ${label}`);
if (typeof value === "string") return JSON.parse(value);
if (typeof value !== "object") throw new Error(`Invalid config value for ${label}`);
return value;
}
const FASTKV_HISTORY_MAX_LIMIT = 200;
/**
* Publish history for the registry config key (atomic-deploys 11): the
* exact-key variant of FastData's history endpoint, newest-first. The API
* caps a page at 200 rows; a config key's write history fits well inside
* that, so a single request is the whole story (the limit param is clamped).
*/
async function fetchConfigHistory(opts) {
const key = encodeURIComponent(opts.keyPath ?? getRegistryConfigKey(opts.accountId, opts.gatewayId));
const limit = Math.max(1, Math.min(opts.limit ?? 20, FASTKV_HISTORY_MAX_LIMIT));
return ((await fetchJson(`${require_client.registryBaseUrlForNetwork(require_client.networkIdForAccount(opts.accountId))}/v0/history/${encodeURIComponent(getRegistryNamespaceForAccount(opts.accountId, opts.registry))}/${encodeURIComponent(opts.accountId)}/${key}?limit=${limit}`))?.entries ?? []).filter(Boolean).map((entry) => ({
blockHeight: entry.block_height ?? 0,
blockTimestampNs: String(entry.block_timestamp ?? ""),
...entry.tx_hash ? { txHash: entry.tx_hash } : {},
value: typeof entry.value === "string" && entry.value.length > 0 ? JSON.parse(entry.value) : entry.value
})).sort((a, b) => b.blockHeight - a.blockHeight);
}
/**
* The per-deploy audit trail (atomic-deploys 03/12): every publish writes
* `apps/<account>/<gateway>/manifests/<ts>.json` atomically with the pointer
* swap — this lists that key family newest-first via the history-by-prefix
* endpoint.
*/
async function fetchDeployManifests(opts) {
const keyPrefix = encodeURIComponent(`${getRegistryConfigKey(opts.accountId, opts.gatewayId).replace(/bos\.config\.json$/, "")}manifests/`);
return ((await fetchJson(`${require_client.registryBaseUrlForNetwork(require_client.networkIdForAccount(opts.accountId))}/v0/history/${encodeURIComponent(getRegistryNamespaceForAccount(opts.accountId, opts.registry))}/${encodeURIComponent(opts.accountId)}`, {
method: "POST",
body: JSON.stringify({
key_prefix: decodeURIComponent(keyPrefix),
asc: false,
limit: Math.max(1, Math.min(opts.limit ?? 20, FASTKV_HISTORY_MAX_LIMIT))
})
}))?.entries ?? []).filter(Boolean).map((entry) => ({
key: entry.key ?? "",
blockHeight: entry.block_height ?? 0,
blockTimestampNs: String(entry.block_timestamp ?? ""),
value: typeof entry.value === "string" && entry.value.length > 0 ? JSON.parse(entry.value) : entry.value
})).sort((a, b) => b.blockHeight - a.blockHeight);
}
async function fetchRemotePluginManifest(cdnUrl) {
const baseUrl = cdnUrl.replace(/\/$/, "");
return require_http_client.fetchJsonOrNull(`${baseUrl}/plugin.manifest.json`, { retries: 2 });
}
async function fetchJson(url, init) {
const headers = {
accept: "application/json",
"content-type": "application/json",
...init?.headers
};
return require_http_client.fetchJsonOrNull(url, {
method: init?.method,
headers,
body: init?.body ?? void 0,
retries: 3
});
}
/**
* The FastKV registry as a Context.Service (#425): reads (config, published
* config, history, deploy manifests) and the bos:// URL algebra behind one
* tag. The registry WRITE is a signing concern — it rides the signer
* services (#423), not this tag. Callers may keep using the plain
* functions — the module is the implementation; the tag is the seam.
*/
var FastKVRegistryService = class extends effect.Context.Service()("everything-dev/registry/fastkv") {
static Live = effect.Layer.succeed(this, this.of({
fetchBosConfigFromFastKv,
fetchPublishedConfigFromFastKv,
fetchConfigHistory,
fetchDeployManifests
}));
};
//#endregion
exports.FastKVRegistryService = FastKVRegistryService;
exports.buildRegistryConfigUrl = buildRegistryConfigUrl;
exports.buildRegistryConfigUrlForNetwork = buildRegistryConfigUrlForNetwork;
exports.fetchBosConfigFromFastKv = fetchBosConfigFromFastKv;
exports.fetchConfigHistory = fetchConfigHistory;
exports.fetchDeployManifests = fetchDeployManifests;
exports.fetchPublishedConfigFromFastKv = fetchPublishedConfigFromFastKv;
exports.fetchRegistryKey = fetchRegistryKey;
exports.fetchRegistryKeyOrNull = fetchRegistryKeyOrNull;
exports.fetchRemotePluginManifest = fetchRemotePluginManifest;
exports.getFastKvBaseUrlForNetwork = getFastKvBaseUrlForNetwork;
exports.getRegistryNamespaceForAccount = getRegistryNamespaceForAccount;
exports.getRegistryNamespaceForNetwork = getRegistryNamespaceForNetwork;
exports.parseBosUrl = parseBosUrl;
exports.parseFastKvConfigValue = parseFastKvConfigValue;
//# sourceMappingURL=fastkv.cjs.map