Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions crates/registry-breg-client-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,20 @@ cache; `await provider.bearerToken()` uses that separate client-credentials
cache. Neither method logs or persists the returned credential. The application
must protect it and pass it explicitly to a resource client. The resource server
still validates the signed authority and bounds.

## Exact JSON Proposal transitions and listing

Use `prepareProposalJson(proposal, operation, bodyJson, key)` when an edit
contains integers outside JavaScript's safe integer range, including nested
values that satisfy BReg's binary64 mutation model. Exact reads retain all
signed and unsigned 64-bit integers, while mutation preparation still refuses
integers that model cannot represent exactly. Decimal text such as `"0.7500"` stays a string with its lexical form.
The exact JSON decoder refuses duplicate members and lossy numeric literals.
The structured `prepareProposal` method continues to refuse unsafe numbers.

`listProposalsJson(collection, queryJson)` accepts the same query contract as
`listProposals`, with explicit pagination and a metadata-selected collection.
Both methods delegate to the canonical Rust client. They retain the same
pre-I/O checks, lifecycle conditions, source binding, and caller-chosen key.
Persist and recover the returned `BRegPreparedProposal` through
`recoverProposal` before executing after a restart, just as for an object body.
8 changes: 8 additions & 0 deletions crates/registry-breg-client-node/__test__/facade.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
BRegRecoveredCreate,
BRegProposal,
BRegProposalGetBinding,
BRegProposalCollection,
BRegPreparedProposal,
BRegTombstoneBinding,
AsOfListContinuation,
Expand Down Expand Up @@ -59,6 +60,13 @@ declare const preparedAction: BRegPreparedAction
declare const preparedCreate: BRegPreparedCreate
declare const proposal: BRegProposal
declare const proposalGet: BRegProposalGetBinding
declare const proposalCollection: BRegProposalCollection
client.listProposalsJson(proposalCollection, '{"limit":1}')
client.prepareProposalJson(proposal, 'edit', '{"input":{"wide":9223372036854775807}}', 'exact-key')
// @ts-expect-error Exact Proposal methods require JSON text.
client.prepareProposalJson(proposal, 'edit', {input: {}}, 'exact-key')
// @ts-expect-error Exact Proposal listing requires JSON text.
client.listProposalsJson(proposalCollection, {})
declare const preparedProposal: BRegPreparedProposal
declare const recoveredAction: BRegRecoveredAction
declare const recoveredCreate: BRegRecoveredCreate
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
'use strict';
const assert = require('node:assert/strict');
const http = require('node:http');
const { test } = require('node:test');
const { BaseRegistryClient, BRegPreparedProposal } = process.env.BREG_CLIENT_PACKAGE
? require(process.env.BREG_CLIENT_PACKAGE).breg : require('..');

const id = '00000000-0000-4000-8000-000000000001';
const revision = `sha256:${'a'.repeat(64)}`;
const metadata = {id: 'proposal-json', version: '1', revision, metadataVersion: '2', recordTypes: [], operations: [],
proposals: {method: 'GET', path: '/v1/proposals', accessProfiles: ['author'],
actions: [{actionId: 'correct', accessProfile: 'author', operations: ['get', 'list'], readableInputs: [], readableContextFields: []}],
get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['author']}}};
const proposal = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', links: {
self: {method: 'GET', path: `/v1/proposals/${id}`, accessProfile: 'author', operation: 'get'},
edit: {method: 'POST', path: `/v1/proposals/${id}/edit`, accessProfile: 'author', operation: 'edit', ifMatch: '"draft-condition"'},
}};
const inputJson = '{"nullable":null,"nested":{"wide":9223372036854775807,"decimal":"0.7500","values":[9223372036854775807,null,{"amount":"0.7500"}]}}';

test('exact Proposal JSON methods preserve nested values and recovery authority through native HTTP', async () => {
const requests = [];
let current = JSON.stringify(proposal).replace('"links":', `"input":${inputJson},"links":`);
const server = http.createServer(async (request, response) => {
let body = ''; for await (const chunk of request) body += chunk;
requests.push({url: request.url, body, headers: request.headers});
response.writeHead(200, {'content-type': 'application/json', 'cache-control': 'no-store', vary: 'authorization, accept',
traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'});
if (request.url.startsWith('/tenant/v1/registry')) return response.end(JSON.stringify(metadata));
if (request.url.startsWith('/tenant/v1/proposals?')) return response.end(`{"items":[${current}],"nextCursor":"next-page"}`);
if (request.url.includes('/edit?')) {
current = current.replace('"revision":1', '"revision":2').replace(inputJson, body.slice('{"input":'.length, -1));
}
response.end(current);
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/tenant/`});
assert.equal(typeof client.prepareProposalJson, 'function');
assert.equal(typeof client.listProposalsJson, 'function');
const contract = await client.registryContract('author');
const collection = contract.selectProposals('author');
const page = await client.listProposalsJson(collection, '{"action":"correct","limit":1}');
assert.equal(page.nextCursor, 'next-page');
assert.match(page.items[0].inputJson, /9223372036854775807/);
assert.match(page.items[0].inputJson, /"decimal":"0.7500"/);
const url = new URL(requests.at(-1).url, 'http://fixture.invalid');
assert.equal(url.pathname, '/tenant/v1/proposals');
assert.equal(url.searchParams.get('accessProfile'), 'author');
assert.equal(url.searchParams.get('action'), 'correct');
assert.equal(url.searchParams.get('limit'), '1');
const draft = page.items[0];
const before = requests.length;
for (const body of ['{"input":{"wide":1,"wide":2}}', '{"input":{"wide":1e9999}}', '{"input":[]}', '[]']) {
assert.throws(() => client.prepareProposalJson(draft, 'edit', body, 'invalid'), error => error.kind === 'invalid-request' && !error.outcomeUnknown);
}
assert.throws(() => client.prepareProposalJson(draft, 'apply', '{}', 'illegal-transition'), error => error.kind === 'invalid-request');
assert.throws(() => client.prepareProposal(draft, 'edit', {input: {wide: Number.MAX_SAFE_INTEGER + 1}}, 'unsafe'), error => error.kind === 'invalid-request');
for (const query of ['{"limit":1,"limit":2}', '{"limit":0}', '{"unknown":true}', '{"limit":"one"}']) {
await assert.rejects(client.listProposalsJson(collection, query), error => error.kind === 'invalid-request', query);
}
assert.equal(requests.length, before, 'invalid JSON, query, structured unsafe numbers and transitions fail before I/O');
assert.throws(() => client.prepareProposalJson(draft, 'edit', `{"input":${inputJson}}`, 'inexact-binary64'), error => error.kind === 'invalid-request');
const exactEditInputJson = inputJson.replaceAll('9223372036854775807', '9007199254740992');
const attempt = client.prepareProposalJson(draft, 'edit', `{"input":${exactEditInputJson}}`, 'exact-edit-key');
const bytes = attempt.toBytes();
const restored = BRegPreparedProposal.fromBytes(bytes);
await assert.rejects(client.executeProposal(restored), error => error.kind === 'invalid-request');
assert.equal(requests.length, before, 'persisted evidence requires fresh matching Proposal authority');
const recovered = client.recoverProposal(await client.readProposal(draft), restored);
assert.deepEqual(recovered.toBytes(), bytes);
const edited = await client.executeProposal(recovered);
assert.match(edited.inputJson, /9007199254740992/);
const sent = requests.at(-1);
assert.equal(sent.url, `/tenant/v1/proposals/${id}/edit?accessProfile=author`);
assert.equal(sent.headers['idempotency-key'], 'exact-edit-key');
assert.equal(sent.headers['if-match'], '"draft-condition"');
assert.match(sent.body, /"wide":9007199254740992/);
assert.match(sent.body, /"decimal":"0.7500"/);
assert.match(sent.body, /"values":\[9007199254740992,null,\{"amount":"0.7500"\}\]/);
assert.equal(JSON.parse(sent.body).input.nullable, null);
assert.ok(!Object.hasOwn(JSON.parse(sent.body).input, 'absent'));
} finally { await new Promise(resolve => server.close(resolve)); }
});
4 changes: 4 additions & 0 deletions crates/registry-breg-client-node/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,8 @@ export declare class BaseRegistryClient {
/** Read one retained submission version under the access profile of the Proposal's self link. */
readProposalSubmission(proposal: BRegProposal, version: number): Promise<CompleteOutcome<BRegProposalSubmission>>
listProposals(collection: BRegProposalCollection, query: JsonObject): Promise<BRegProposalPage>
/** Exact JSON query; retains the metadata-selected collection and bounded pagination. */
listProposalsJson(collection: BRegProposalCollection, queryJson: string): Promise<BRegProposalPage>
/**
* Bind an available transition without I/O. Throws locally when the operation
* is not a legal transition from the Proposal's observed state; `cancel` is
Expand All @@ -895,6 +897,8 @@ export declare class BaseRegistryClient {
* exercise the server's terminal-state refusal.
*/
prepareProposal(proposal: BRegProposal, operation: BRegProposalTransition, body: JsonObject, key: string): BRegPreparedProposal
/** Exact JSON body; preserves integer values and the same lifecycle authority and recovery contract. */
prepareProposalJson(proposal: BRegProposal, operation: BRegProposalTransition, bodyJson: string, key: string): BRegPreparedProposal
recoverProposal(proposal: BRegProposal, attempt: BRegPreparedProposal): BRegPreparedProposal
executeProposal(attempt: BRegPreparedProposal): Promise<BRegProposal>
constructor(config: BaseRegistryClientConfig)
Expand Down
4 changes: 2 additions & 2 deletions crates/registry-breg-client-node/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ for (const [method, jsonIndexes, requiredIndexes] of [
['invokeAction', [1], [1]],
['executeRecoveredAction'], ['executeRecoveredProposalStart'], ['executeRecoveredCreate'],
['patchRecord', [3], [3]], ['batchRecords', [1], [1]], ['tombstoneRecord'],
['startProposal', [1], [1]], ['readProposal'], ['readProposalSubmission'], ['getProposal'], ['listProposals', [1], [1]], ['executeProposal'],
['startProposal', [1], [1]], ['readProposal'], ['readProposalSubmission'], ['getProposal'], ['listProposals', [1], [1]], ['executeProposal'], ['listProposalsJson'],
['downloadProposalAttachment'], ['uploadProposalAttachment'], ['deleteProposalAttachment'],
['readProposalReviewStatus'], ['readProposalReviewContext'],
['readProposalReviewContextBatch', [1], [1]],
Expand All @@ -256,7 +256,7 @@ for (const [method, jsonIndexes, requiredIndexes] of [
['prepareAction', [1], [1]], ['prepareActionJson'],
['recoverAction', [2], [2]], ['recoverActionJson'],
['prepareCreate', [1], [1]], ['prepareCreateJson'], ['recoverCreate'],
['prepareProposal', [2], [2]], ['recoverProposal'],
['prepareProposal', [2], [2]], ['prepareProposalJson'], ['recoverProposal'],
]) {
const original = native.BaseRegistryClient.prototype[method];
native.BaseRegistryClient.prototype[method] = function (...args) {
Expand Down
4 changes: 4 additions & 0 deletions crates/registry-breg-client-node/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export declare class BaseRegistryClient {
deleteProposalAttachment(proposal: BRegProposal, slot: string, key: string): Promise<BRegProposal>
listProposals(collection: BRegProposalCollection, query: any): Promise<ProposalPage>
prepareProposal(proposal: BRegProposal, operation: string, body: any, key: string): BRegPreparedProposal
/** Prepare a transition from exact JSON through the same lifecycle authority. */
prepareProposalJson(proposal: BRegProposal, operation: string, bodyJson: string, key: string): BRegPreparedProposal
/** List through the same metadata-selected collection with an exact JSON query. */
listProposalsJson(collection: BRegProposalCollection, queryJson: string): Promise<ProposalPage>
recoverProposal(proposal: BRegProposal, attempt: BRegPreparedProposal): BRegPreparedProposal
executeProposal(attempt: BRegPreparedProposal): Promise<BRegProposal>
/** Fetch opaque target conditions for one metadata-selected action. */
Expand Down
23 changes: 23 additions & 0 deletions crates/registry-breg-client-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3393,6 +3393,29 @@ impl BaseRegistryClient {
.map_err(client_error)
}

/// Prepare a transition from exact JSON through the same lifecycle authority.
#[napi]
pub fn prepare_proposal_json(
&self,
proposal: &Proposal,
operation: String,
body_json: String,
key: String,
) -> Result<PreparedProposal> {
self.prepare_proposal(proposal, operation, exact_input(&body_json)?, key)
}

/// List through the same metadata-selected collection with an exact JSON query.
#[napi]
pub async fn list_proposals_json(
&self,
collection: &ProposalCollection,
query_json: String,
) -> Result<ProposalPage> {
self.list_proposals(collection, exact_input(&query_json)?)
.await
}

#[napi]
pub fn recover_proposal(
&self,
Expand Down
5 changes: 5 additions & 0 deletions crates/registry-breg-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ client's configured credential unchanged. Each derived value owns its token, so
different callers can use the same base client concurrently without a mutable
credential slot. Keep it within the inbound request that supplied the token.

Use `client.with_maximum_response_bytes(limit)?` to derive a client with a
separate response-body budget for a particular exchange. It reuses the same
credential provider, connection pool and source binding, and leaves the original
client's response limit unchanged. The limit must be greater than zero.

## Read records

```rust,no_run
Expand Down
14 changes: 14 additions & 0 deletions crates/registry-breg-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ impl BaseRegistryClient {
}
}

/// Derive a client with a different finite response-body limit, reusing the
/// same credential provider, connection pool, and source binding. The
/// original client and all other transport policy remain unchanged.
pub fn with_maximum_response_bytes(
&self,
maximum: u64,
) -> Result<Self, BaseRegistryClientError> {
let config = self.config.clone().with_maximum_response_bytes(maximum);
config.validate()?;
let mut transport = self.transport.clone();
transport.maximum_response_bytes = maximum;
Ok(Self { config, transport })
}

/// Unauthenticated liveness probe. Configured bearer credentials are never
/// acquired or sent.
pub async fn health(&self) -> Result<BRegComplete<BRegProbeStatus>, BaseRegistryClientError> {
Expand Down
5 changes: 4 additions & 1 deletion crates/registry-breg-client/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1796,7 +1796,10 @@ fn action_field_type(value: Value) -> Result<(), BRegMetadataError> {
}
"vocabulary-code" => {
bounded_string(required(&mut field_type, "vocabulary")?)?;
let values = identifier_array(required(&mut field_type, "values")?)?;
let values = array(required(&mut field_type, "values")?)?
.into_iter()
.map(bounded_short_text)
.collect::<Result<Vec<_>, _>>()?;
if values.is_empty() || ensure_unique(values.iter().map(String::as_str)).is_err() {
return Err(metadata_error(BRegMetadataErrorKind::Shape));
}
Expand Down
51 changes: 51 additions & 0 deletions crates/registry-breg-client/src/metadata_vocabulary_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,57 @@ fn action_field_type_vocabulary_accepts_every_bounded_engine_string() {
}
}

#[test]
fn action_vocabulary_codes_follow_engine_code_grammar() {
for codes in [
json!(["A-report", "B-report", "C-report"]),
json!(["123", "two words", "สถานะ/許可"]),
json!(["x".repeat(128), "é".repeat(64)]),
] {
let mut value = metadata("status");
value["actions"][0]["inputs"][0]["fieldType"]["values"] = codes.clone();
value["actions"][0]["inputs"][0]["schema"]["enum"] = codes.clone();
let parsed = parse(&value).unwrap();
let action = parsed.select_action("update-status", "writer").unwrap();
assert_eq!(action.inputs()[0].field_type()["values"], codes);
for code in codes.as_array().unwrap() {
crate::BRegActionInvocationRequest::new(
&action,
Map::from_iter([("status".to_owned(), code.clone())]),
None,
)
.unwrap();
}
}
}

#[test]
fn invalid_action_vocabulary_codes_never_promote_to_authority() {
for codes in [
json!([]),
json!([""]),
json!(["A-report", "A-report"]),
json!(["line one\nline two"]),
json!(["nul\0"]),
json!(["x".repeat(129)]),
json!(["é".repeat(65)]),
json!([17]),
json!("A-report"),
] {
let mut value = metadata("status");
value["actions"][0]["inputs"][0]["fieldType"]["values"] = codes;
let parsed = parse(&value).unwrap();
assert_eq!(parsed.actions().len(), 1);
assert_eq!(
parsed
.select_action("update-status", "writer")
.unwrap_err()
.kind(),
BRegMetadataSelectionErrorKind::ContractMismatch
);
}
}

#[test]
fn vocabulary_strings_retain_the_metadata_string_bound() {
let maximum = "v".repeat(64 * 1024);
Expand Down
Loading
Loading