Skip to content

Commit 295f1d3

Browse files
committed
Add explicit bounded diagnostic exports
1 parent b7e2f0a commit 295f1d3

4 files changed

Lines changed: 158 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,12 @@ agent.close();
224224

225225
Protocol: edge sends `register`; center replies `registered`; center sends `collect` (request_id, site, command, args, positional_args, format, mode); the SDK executes `opencli` locally (via `copyForLocalCliExecution()` to avoid loops) and replies `result`; plus `ping` / `pong`.
226226

227+
### Diagnostic export
228+
229+
Call `OpenCliDiagnosticExport.export(result, 512)` explicitly with an `OpenCliResult` or an exception's partial result. The byte budget applies to UTF-8 text. Output contains only status and field lengths, with a `truncated=true` marker when fields do not fit. Field lengths can disclose how much data was present.
230+
231+
The SDK returns the text in memory. Your application controls the destination and retention. SDK diagnostics omit argv values, raw content, URLs and filesystem paths. Applications that use or log raw results should protect that data. `remoteCaptureRawHttpResponse` is still opt-in.
232+
227233
<a id="9-testing--build"></a>
228234
## 9. Testing & Build
229235

‎README.zh-CN.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,12 @@ agent.close();
223223

224224
协议摘要:边缘发送 `register`;中心回执 `registered`;中心下发 `collect`(request_id、site、command、args、positional_args、format、mode);SDK 在本机执行 `opencli`(通过 `copyForLocalCliExecution()` 强制本地子进程,避免回路)并回执 `result`;另有 `ping` / `pong`。
225225

226+
### 诊断导出
227+
228+
如需导出诊断,请调用 `OpenCliDiagnosticExport.export(result, 512)`,传入 `OpenCliResult` 或异常中的部分结果。上限按 UTF-8 字节计算。输出只包含状态和字段长度,字段放不下时会标明 `truncated=true`。字段长度仍可能反映数据规模。
229+
230+
SDK 在内存中返回文本,由应用决定目的地和保留时间。SDK 诊断会排除命令参数、原始内容、URL 和文件路径。应用读取或记录原始结果时应自行保护这些数据。`remoteCaptureRawHttpResponse` 仍需显式开启。
231+
226232
<a id="9-testing--build"></a>
227233
## 9. 测试与构建
228234

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package io.github.easy4j.opencli.core;
2+
3+
import java.util.Objects;
4+
5+
/**
6+
* Creates an explicit, in-memory diagnostic projection of an existing invocation result.
7+
* The SDK retains no copy of the returned text. The caller controls its retention and destination.
8+
*/
9+
public final class OpenCliDiagnosticExport {
10+
11+
private static final String COMPLETE_HEADER = "policy=metadata-only\ntruncated=false\n";
12+
private static final String TRUNCATED_HEADER = "policy=metadata-only\ntruncated=true\n";
13+
14+
/** Minimum budget that can represent either export header. */
15+
public static final int MIN_EXPORT_BYTES = COMPLETE_HEADER.length();
16+
17+
private OpenCliDiagnosticExport() {
18+
}
19+
20+
/**
21+
* Exports status and character counts as UTF-8 key-value lines. Raw output, parsed values,
22+
* command arguments, URLs, and paths are excluded by construction. Lengths are UTF-16 code-unit counts
23+
* and reveal the size of the corresponding fields.
24+
*
25+
* @param result completed result or partial result from an exception
26+
* @param maxBytes maximum UTF-8 size, at least {@link #MIN_EXPORT_BYTES}
27+
* @return diagnostic text containing complete fields only, with a truncation indicator
28+
* @throws IllegalArgumentException when the budget cannot fit the header
29+
*/
30+
public static String export(OpenCliResult result, int maxBytes) {
31+
Objects.requireNonNull(result, "result");
32+
if (maxBytes < MIN_EXPORT_BYTES) {
33+
throw new IllegalArgumentException("maxBytes must fit the diagnostic export header");
34+
}
35+
36+
Integer exitCode = result.getExitCode();
37+
String[] fields = {
38+
"success=" + result.isSuccess() + "\n",
39+
Objects.isNull(exitCode) ? "" : "exitCode=" + exitCode + "\n",
40+
characterCount("stdoutChars", result.getStdout()),
41+
characterCount("stderrChars", result.getStderr()),
42+
characterCount("rawHttpChars", result.getRemoteRawHttpBody())
43+
};
44+
45+
// Every emitted character is ASCII, so the character count is also the UTF-8 byte count.
46+
int completeBytes = COMPLETE_HEADER.length();
47+
for (String field : fields) {
48+
completeBytes += field.length();
49+
}
50+
51+
boolean truncated = completeBytes > maxBytes;
52+
StringBuilder output = new StringBuilder(Math.min(completeBytes, maxBytes));
53+
output.append(truncated ? TRUNCATED_HEADER : COMPLETE_HEADER);
54+
int remainingBytes = maxBytes - COMPLETE_HEADER.length();
55+
for (String field : fields) {
56+
if (field.length() > remainingBytes) {
57+
break;
58+
}
59+
output.append(field);
60+
remainingBytes -= field.length();
61+
}
62+
return output.toString();
63+
}
64+
65+
private static String characterCount(String name, String value) {
66+
return Objects.isNull(value) ? "" : name + "=" + value.length() + "\n";
67+
}
68+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package io.github.easy4j.opencli.core;
2+
3+
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
4+
import java.nio.charset.StandardCharsets;
5+
import java.util.UUID;
6+
import org.junit.jupiter.api.Test;
7+
8+
import static org.junit.jupiter.api.Assertions.assertEquals;
9+
import static org.junit.jupiter.api.Assertions.assertFalse;
10+
import static org.junit.jupiter.api.Assertions.assertThrows;
11+
import static org.junit.jupiter.api.Assertions.assertTrue;
12+
13+
class OpenCliDiagnosticExportTest {
14+
15+
@Test
16+
void explicitProjectionExcludesPayloadsAndLeavesResultIntact() {
17+
String sensitive = "secret-" + UUID.randomUUID();
18+
String stderr = "/trace/" + sensitive;
19+
String rawHttp = "https://user:" + sensitive + "@example.test";
20+
OpenCliParsedFields parsed = OpenCliParsedFields.builder().jsonShapeHint(sensitive).build();
21+
OpenCliResult result = OpenCliResult.builder()
22+
.success(false).exitCode(7).stdout(sensitive).stderr(stderr).remoteRawHttpBody(rawHttp).parsed(parsed).build();
23+
24+
String export = OpenCliDiagnosticExport.export(result, 512);
25+
26+
assertTrue(export.startsWith("policy=metadata-only\ntruncated=false\n"));
27+
assertTrue(export.contains("success=false\n"));
28+
assertTrue(export.contains("exitCode=7\n"));
29+
assertTrue(export.contains("stdoutChars=" + sensitive.length() + "\n"));
30+
assertTrue(export.contains("stderrChars=" + stderr.length() + "\n"));
31+
assertTrue(export.contains("rawHttpChars=" + rawHttp.length() + "\n"));
32+
assertFalse(export.contains(sensitive));
33+
assertEquals(sensitive, result.getStdout());
34+
assertEquals(stderr, result.getStderr());
35+
assertEquals(rawHttp, result.getRemoteRawHttpBody());
36+
assertEquals(sensitive, result.getParsed().getJsonShapeHint());
37+
}
38+
39+
@Test
40+
void byteLimitUsesWholeFieldsAndReportsTruncation() {
41+
OpenCliResult result = OpenCliResult.builder().success(true).stdout("非 ASCII 内容").build();
42+
int maxBytes = 50;
43+
44+
String export = OpenCliDiagnosticExport.export(result, maxBytes);
45+
46+
assertTrue(export.getBytes(StandardCharsets.UTF_8).length <= maxBytes);
47+
assertEquals("policy=metadata-only\ntruncated=true\nsuccess=true\n", export);
48+
assertEquals("非 ASCII 内容", result.getStdout());
49+
}
50+
51+
@Test
52+
void exactFitAndOneByteShortUseConsistentTruncationMarkers() {
53+
OpenCliResult result = OpenCliResult.builder().success(true).build();
54+
String expected = "policy=metadata-only\ntruncated=false\nsuccess=true\n";
55+
56+
assertEquals(expected, OpenCliDiagnosticExport.export(result, expected.length()));
57+
assertEquals("policy=metadata-only\ntruncated=true\n",
58+
OpenCliDiagnosticExport.export(result, expected.length() - 1));
59+
}
60+
61+
@Test
62+
void invalidBudgetDoesNotMutateResult() {
63+
OpenCliResult result = OpenCliResult.builder().success(false).stderr("original failure").build();
64+
65+
assertThrows(IllegalArgumentException.class, () -> OpenCliDiagnosticExport.export(result, 1));
66+
assertEquals("original failure", result.getStderr());
67+
assertFalse(result.isSuccess());
68+
}
69+
70+
@Test
71+
void absentValuesAreOmittedRatherThanReportedAsEmptyData() {
72+
String export = OpenCliDiagnosticExport.export(OpenCliResult.builder().stdout("").build(), 512);
73+
assertTrue(export.contains("stdoutChars=0\n"));
74+
assertFalse(export.contains("stderrChars"));
75+
assertFalse(export.contains("rawHttpChars"));
76+
assertFalse(export.contains("exitCode"));
77+
}
78+
}

0 commit comments

Comments
 (0)