Skip to content

Commit b27e9ff

Browse files
committed
feat(sdk-ts): export error contract, enum unions, and caller cancellation
Address Tier-1 review feedback on the TypeScript SDK public surface (PR #2122). - Errors: export SdkError and SdkErrorCode so callers can use instanceof and exhaustively switch on .code. fromConnect preserves the originating ConnectError as .cause and its status as .connectCode, maps Aborted to a new 'aborted' code for optimistic-concurrency conflicts, and maps Canceled and DeadlineExceeded to 'canceled'. errorCode() behavior is unchanged. - Enums: replace the string-typed phase, status, scope, and policySource fields with lowercase literal unions (SandboxPhaseName, HealthStatus, SettingScopeName, PolicySourceName) backed by exhaustive Record maps. The unions are a hand-maintained mirror of the generated proto enums; a new drift test pins each literal to its generated member name. - Cancellation: accept an optional AbortSignal on exec, execInteractive, and forward, threaded into both sandbox resolution and the streaming RPC. forward tears down its local listener on abort. Signed-off-by: Max Dubrinsky <mdubrinsky@nvidia.com>
1 parent 7193806 commit b27e9ff

5 files changed

Lines changed: 257 additions & 39 deletions

File tree

‎sdk/typescript/src/client.test.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import * as net from 'node:net';
1111
import type { MessageInitShape } from '@bufbuild/protobuf';
1212
import { Code, ConnectError, createRouterTransport, type ServiceImpl, type Transport } from '@connectrpc/connect';
1313
import { describe, expect, it } from 'vitest';
14-
import { errorCode, SandboxClient } from './client.js';
15-
import { OpenShell, SandboxPhase } from './gen/openshell_pb.js';
14+
import { errorCode, PHASE_NAMES, POLICY_SOURCE_NAMES, SandboxClient, SCOPE_NAMES, STATUS_NAMES } from './client.js';
15+
import { OpenShell, SandboxPhase, ServiceStatus } from './gen/openshell_pb.js';
1616
import { PolicySource, SettingScope } from './gen/sandbox_pb.js';
1717

1818
function client(impl: Partial<ServiceImpl<typeof OpenShell>>): SandboxClient {
@@ -145,6 +145,42 @@ describe('exec / execStream', () => {
145145
await expect(sandbox.exec('sb', ['x'])).rejects.toMatchObject({ code: 'rpc' });
146146
});
147147

148+
it('execStream rejects when the caller signal is already aborted', async () => {
149+
const sandbox = client({
150+
getSandbox: () => readySandbox('sb', 'sb-id-1'),
151+
// eslint-disable-next-line require-yield
152+
execSandbox: async function* () {
153+
yield { payload: { case: 'stdout', value: { data: enc('never') } } };
154+
yield { payload: { case: 'exit', value: { exitCode: 0 } } };
155+
},
156+
});
157+
const signal = AbortSignal.abort();
158+
await expect(
159+
(async () => {
160+
for await (const _event of sandbox.execStream('sb', ['x'], { signal })) {
161+
// drain to completion
162+
}
163+
})(),
164+
).rejects.toBeInstanceOf(Error);
165+
});
166+
167+
it('exec rejects when the caller signal aborts mid-stream', async () => {
168+
const controller = new AbortController();
169+
const sandbox = client({
170+
getSandbox: () => readySandbox('sb', 'sb-id-1'),
171+
execSandbox: async function* (_req, ctx) {
172+
yield { payload: { case: 'stdout', value: { data: enc('partial') } } };
173+
await new Promise<void>((_resolve, reject) => {
174+
ctx.signal.addEventListener('abort', () => reject(new ConnectError('canceled', Code.Canceled)), {
175+
once: true,
176+
});
177+
});
178+
},
179+
});
180+
setTimeout(() => controller.abort(), 10);
181+
await expect(sandbox.exec('sb', ['x'], { signal: controller.signal })).rejects.toBeInstanceOf(Error);
182+
});
183+
148184
it('maps a NotFound from get() to an SdkError not_found', async () => {
149185
const sandbox = client({
150186
getSandbox: () => {
@@ -696,3 +732,31 @@ describe('forward', () => {
696732
await handle.closed;
697733
});
698734
});
735+
736+
// The lowercase enum-name unions in client.ts are a hand-maintained mirror of
737+
// the generated proto enums. This pins every hand-written literal to its
738+
// generated member name (lowercased), so a proto enum change that slips past
739+
// the exhaustive Record type is still caught here at runtime.
740+
describe('enum name maps', () => {
741+
function numericMembers(genEnum: Record<string, unknown>): Array<[string, number]> {
742+
return Object.entries(genEnum).filter((e): e is [string, number] => typeof e[1] === 'number');
743+
}
744+
745+
const cases: Array<[string, Record<string, unknown>, Record<number, string>]> = [
746+
['SandboxPhase', SandboxPhase, PHASE_NAMES],
747+
['ServiceStatus', ServiceStatus, STATUS_NAMES],
748+
['SettingScope', SettingScope, SCOPE_NAMES],
749+
['PolicySource', PolicySource, POLICY_SOURCE_NAMES],
750+
];
751+
752+
for (const [label, genEnum, names] of cases) {
753+
it(`${label} maps every generated member to its lowercased name`, () => {
754+
const members = numericMembers(genEnum);
755+
for (const [name, value] of members) {
756+
expect(names[value]).toBe(name.toLowerCase());
757+
}
758+
// No missing or extra map entries versus the generated enum.
759+
expect(Object.keys(names).length).toBe(members.length);
760+
});
761+
}
762+
});

‎sdk/typescript/src/client.ts‎

Lines changed: 96 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,29 @@ export { errorCode };
4040

4141
// ---- Curated public types --------------------------------------------------
4242

43+
// The gateway enums (SandboxPhase, ServiceStatus, SettingScope, PolicySource)
44+
// arrive as protoc-gen-es numeric enums. The lowercase literal unions below are
45+
// a hand-maintained mirror of them so consumers get exhaustive, typo-proof
46+
// switches instead of a bare `string`. They are deliberately duplicated by
47+
// hand, not generated, and are expected to stay stable. If a proto enum ever
48+
// gains, removes, or renames a member, update the matching union AND its
49+
// `*_NAMES` map below: the exhaustive `Record` stops compiling, and the
50+
// 'enum name maps' drift test in client.test.ts fails until both sides agree.
51+
52+
/** Lowercase mirror of the generated `SandboxPhase` enum. Hand-maintained. */
53+
export type SandboxPhaseName = 'unspecified' | 'provisioning' | 'ready' | 'error' | 'deleting' | 'unknown';
54+
55+
/** Lowercase mirror of the generated `ServiceStatus` enum. Hand-maintained. */
56+
export type HealthStatus = 'unspecified' | 'healthy' | 'degraded' | 'unhealthy';
57+
58+
/** Lowercase mirror of the generated `SettingScope` enum. Hand-maintained. */
59+
export type SettingScopeName = 'unspecified' | 'sandbox' | 'global';
60+
61+
/** Lowercase mirror of the generated `PolicySource` enum. Hand-maintained. */
62+
export type PolicySourceName = 'unspecified' | 'sandbox' | 'global';
63+
4364
export interface Health {
44-
status: string;
65+
status: HealthStatus;
4566
version: string;
4667
}
4768

@@ -71,7 +92,7 @@ export interface SandboxSpec {
7192
export interface SandboxRef {
7293
id: string;
7394
name: string;
74-
phase: string;
95+
phase: SandboxPhaseName;
7596
labels: Record<string, string>;
7697
/** u64 rendered as a string — JS numbers can't hold it safely. */
7798
resourceVersion: string;
@@ -88,6 +109,8 @@ export interface ExecOptions {
88109
environment?: Record<string, string>;
89110
timeoutSecs?: number;
90111
stdin?: Buffer;
112+
/** Abort the exec (and the in-flight stream RPC) early. */
113+
signal?: AbortSignal;
91114
}
92115

93116
export interface ExecResult {
@@ -123,6 +146,8 @@ export interface ExecInteractiveOptions {
123146
cols?: number;
124147
/** Initial terminal rows (0 = server default). */
125148
rows?: number;
149+
/** Abort the interactive exec (and the in-flight stream RPC) early. */
150+
signal?: AbortSignal;
126151
}
127152

128153
// The transport half of an interactive exec: raw stdin/stdout/stderr plus
@@ -152,6 +177,8 @@ export interface ForwardOptions {
152177
localPort?: number;
153178
/** Local address to bind. Default 127.0.0.1. */
154179
localHost?: string;
180+
/** Abort forward setup and tear down the local listener early. */
181+
signal?: AbortSignal;
155182
}
156183

157184
// A process-lifetime local listener that tunnels each accepted connection into
@@ -201,7 +228,7 @@ export interface ProviderChangeOptions {
201228
export interface EffectiveSettingView {
202229
value?: SettingValue;
203230
/** 'unspecified' | 'sandbox' | 'global'. */
204-
scope: string;
231+
scope: SettingScopeName;
205232
}
206233

207234
export interface SandboxConfig {
@@ -212,7 +239,7 @@ export interface SandboxConfig {
212239
/** u64 rendered as a string. */
213240
configRevision: string;
214241
/** 'unspecified' | 'sandbox' | 'global'. */
215-
policySource: string;
242+
policySource: PolicySourceName;
216243
globalPolicyVersion: number;
217244
/** u64 rendered as a string. */
218245
providerEnvRevision: string;
@@ -237,17 +264,44 @@ export interface UpdateConfigResult {
237264

238265
// ---- enum → lowercase string -----------------------------------------------
239266

240-
function phaseName(p: SandboxPhase): string {
241-
return (SandboxPhase[p] ?? 'UNSPECIFIED').toLowerCase();
267+
// Exported for the enum-name drift test only; not re-exported from index.ts, so
268+
// they are not part of the public package API.
269+
export const PHASE_NAMES: Record<SandboxPhase, SandboxPhaseName> = {
270+
[SandboxPhase.UNSPECIFIED]: 'unspecified',
271+
[SandboxPhase.PROVISIONING]: 'provisioning',
272+
[SandboxPhase.READY]: 'ready',
273+
[SandboxPhase.ERROR]: 'error',
274+
[SandboxPhase.DELETING]: 'deleting',
275+
[SandboxPhase.UNKNOWN]: 'unknown',
276+
};
277+
export const STATUS_NAMES: Record<ServiceStatus, HealthStatus> = {
278+
[ServiceStatus.UNSPECIFIED]: 'unspecified',
279+
[ServiceStatus.HEALTHY]: 'healthy',
280+
[ServiceStatus.DEGRADED]: 'degraded',
281+
[ServiceStatus.UNHEALTHY]: 'unhealthy',
282+
};
283+
export const SCOPE_NAMES: Record<SettingScope, SettingScopeName> = {
284+
[SettingScope.UNSPECIFIED]: 'unspecified',
285+
[SettingScope.SANDBOX]: 'sandbox',
286+
[SettingScope.GLOBAL]: 'global',
287+
};
288+
export const POLICY_SOURCE_NAMES: Record<PolicySource, PolicySourceName> = {
289+
[PolicySource.UNSPECIFIED]: 'unspecified',
290+
[PolicySource.SANDBOX]: 'sandbox',
291+
[PolicySource.GLOBAL]: 'global',
292+
};
293+
294+
function phaseName(p: SandboxPhase): SandboxPhaseName {
295+
return PHASE_NAMES[p] ?? 'unspecified';
242296
}
243-
function statusName(s: ServiceStatus): string {
244-
return (ServiceStatus[s] ?? 'UNSPECIFIED').toLowerCase();
297+
function statusName(s: ServiceStatus): HealthStatus {
298+
return STATUS_NAMES[s] ?? 'unspecified';
245299
}
246-
function scopeName(s: SettingScope): string {
247-
return (SettingScope[s] ?? 'UNSPECIFIED').toLowerCase();
300+
function scopeName(s: SettingScope): SettingScopeName {
301+
return SCOPE_NAMES[s] ?? 'unspecified';
248302
}
249-
function policySourceName(s: PolicySource): string {
250-
return (PolicySource[s] ?? 'UNSPECIFIED').toLowerCase();
303+
function policySourceName(s: PolicySource): PolicySourceName {
304+
return POLICY_SOURCE_NAMES[s] ?? 'unspecified';
251305
}
252306

253307
function sandboxRef(sandbox: Sandbox | undefined): SandboxRef {
@@ -307,7 +361,8 @@ function updateConfigResult(resp: UpdateConfigResponse): UpdateConfigResult {
307361
}
308362

309363
// Optimistic-concurrency version pin: absent/empty means 0n (server uses the
310-
// current version, backward-compatible). A mismatch surfaces as Aborted → rpc.
364+
// current version, backward-compatible). A mismatch surfaces as Aborted →
365+
// SdkError code 'aborted'.
311366
function versionPin(value: string | undefined): bigint {
312367
return value ? BigInt(value) : 0n;
313368
}
@@ -560,16 +615,19 @@ export class SandboxClient {
560615
): AsyncGenerator<ExecStreamEvent, void, void> {
561616
try {
562617
// Resolve the sandbox id first, exactly like the gateway client.
563-
const sandbox = await this.get(name);
564-
const stream = this.grpc.execSandbox({
565-
sandboxId: sandbox.id,
566-
command,
567-
workdir: options?.workdir ?? '',
568-
environment: options?.environment ?? {},
569-
timeoutSeconds: options?.timeoutSecs ?? 0,
570-
stdin: options?.stdin ? new Uint8Array(options.stdin) : new Uint8Array(),
571-
tty: false,
572-
});
618+
const sandbox = await this.get(name, options?.signal ? { signal: options.signal } : undefined);
619+
const stream = this.grpc.execSandbox(
620+
{
621+
sandboxId: sandbox.id,
622+
command,
623+
workdir: options?.workdir ?? '',
624+
environment: options?.environment ?? {},
625+
timeoutSeconds: options?.timeoutSecs ?? 0,
626+
stdin: options?.stdin ? new Uint8Array(options.stdin) : new Uint8Array(),
627+
tty: false,
628+
},
629+
{ signal: options?.signal },
630+
);
573631

574632
let sawExit = false;
575633
for await (const event of stream) {
@@ -630,7 +688,7 @@ export class SandboxClient {
630688
): Promise<ExecInteractiveSession> {
631689
let sandboxId: string;
632690
try {
633-
sandboxId = (await this.get(name)).id;
691+
sandboxId = (await this.get(name, options?.signal ? { signal: options.signal } : undefined)).id;
634692
} catch (e) {
635693
throw e instanceof SdkError ? e : fromConnect(e);
636694
}
@@ -653,7 +711,7 @@ export class SandboxClient {
653711
},
654712
});
655713

656-
const stream = this.grpc.execSandboxInteractive(input);
714+
const stream = this.grpc.execSandboxInteractive(input, { signal: options?.signal });
657715
let resolveDone!: (code: number) => void;
658716
let rejectDone!: (err: unknown) => void;
659717
const done = new Promise<number>((resolve, reject) => {
@@ -725,7 +783,7 @@ export class SandboxClient {
725783

726784
let sandboxId: string;
727785
try {
728-
const ref = await this.get(name);
786+
const ref = await this.get(name, opts.signal ? { signal: opts.signal } : undefined);
729787
if (ref.phase !== 'ready') {
730788
throw new SdkError('connect', `sandbox '${name}' is not ready (phase: ${ref.phase})`);
731789
}
@@ -763,16 +821,24 @@ export class SandboxClient {
763821
});
764822
});
765823

824+
const teardown = async (): Promise<void> => {
825+
for (const socket of sockets) socket.destroy();
826+
await new Promise<void>((resolve) => server.close(() => resolve()));
827+
};
828+
829+
// Caller cancellation tears the local listener down the same way close() does.
830+
if (opts.signal) {
831+
if (opts.signal.aborted) void teardown();
832+
else opts.signal.addEventListener('abort', () => void teardown(), { once: true });
833+
}
834+
766835
const addr = server.address() as AddressInfo | null;
767836
return {
768837
localHost,
769838
localPort: addr ? addr.port : localPort,
770839
targetHost,
771840
targetPort,
772-
close: async (): Promise<void> => {
773-
for (const socket of sockets) socket.destroy();
774-
await new Promise<void>((resolve) => server.close(() => resolve()));
775-
},
841+
close: teardown,
776842
closed,
777843
};
778844
}

‎sdk/typescript/src/errors.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// Unit tests for the error taxonomy: fromConnect() status mapping, the
5+
// preserved ConnectError cause/connectCode, and the errorCode() prefix parser.
6+
7+
import { Code, ConnectError } from '@connectrpc/connect';
8+
import { describe, expect, it } from 'vitest';
9+
import { errorCode, fromConnect, SdkError, type SdkErrorCode } from './errors.js';
10+
11+
describe('fromConnect', () => {
12+
const cases: Array<[Code, SdkErrorCode]> = [
13+
[Code.NotFound, 'not_found'],
14+
[Code.AlreadyExists, 'already_exists'],
15+
[Code.Aborted, 'aborted'],
16+
[Code.Canceled, 'canceled'],
17+
[Code.DeadlineExceeded, 'canceled'],
18+
[Code.InvalidArgument, 'invalid_config'],
19+
[Code.Unauthenticated, 'auth'],
20+
[Code.PermissionDenied, 'auth'],
21+
[Code.Internal, 'rpc'],
22+
];
23+
24+
for (const [code, expected] of cases) {
25+
it(`maps Connect ${Code[code]} to '${expected}'`, () => {
26+
const ce = new ConnectError('boom', code);
27+
const err = fromConnect(ce);
28+
expect(err).toBeInstanceOf(SdkError);
29+
expect(err.code).toBe(expected);
30+
// The originating ConnectError is preserved for inspection.
31+
expect(err.cause).toBe(ce);
32+
expect(err.connectCode).toBe(code);
33+
// errorCode() still recovers the prefix from the message.
34+
expect(errorCode(err)).toBe(expected);
35+
});
36+
}
37+
38+
it('distinguishes optimistic-concurrency conflicts from generic rpc failures', () => {
39+
const aborted = fromConnect(new ConnectError('version mismatch', Code.Aborted));
40+
const generic = fromConnect(new ConnectError('boom', Code.Internal));
41+
expect(aborted.code).toBe('aborted');
42+
expect(generic.code).toBe('rpc');
43+
expect(aborted.code).not.toBe(generic.code);
44+
});
45+
});
46+
47+
describe('SdkError', () => {
48+
it('prefixes the message with [code] and exposes the union member', () => {
49+
const err = new SdkError('invalid_config', 'bad value');
50+
expect(err.message).toBe('[invalid_config] bad value');
51+
expect(err.code).toBe('invalid_config');
52+
expect(errorCode(err)).toBe('invalid_config');
53+
});
54+
55+
it('preserves the cause and connectCode when provided', () => {
56+
const ce = new ConnectError('missing', Code.NotFound);
57+
const err = new SdkError('not_found', ce.rawMessage, { cause: ce, connectCode: ce.code });
58+
expect(err.cause).toBe(ce);
59+
expect(err.connectCode).toBe(Code.NotFound);
60+
});
61+
});

0 commit comments

Comments
 (0)