Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(fleet-sdk): bound streamed HTTP responses (#7727)

Francesco Bonaccic918c7e5db96
diff --git a/libs/fleet/scripts/test-generate-sdk-bindings.sh b/libs/fleet/scripts/test-generate-sdk-bindings.sh
index 8a5e4b7935..c6ad34ff4a 100755
--- a/libs/fleet/scripts/test-generate-sdk-bindings.sh
+++ b/libs/fleet/scripts/test-generate-sdk-bindings.sh
@@ -914,12 +914,45 @@ for typescript_binding in "$node_sdk_source" "$browser_sdk_source"; do
grep -Fq -- "FfiConverterOptionalUInt64.write(value.timeoutSecs, into)" "$typescript_binding" || fail "TypeScript bindings do not write HttpRequest.timeoutSecs: $typescript_binding"
grep -Fq -- "FfiConverterOptionalUInt64.allocationSize(value.timeoutSecs)" "$typescript_binding" || fail "TypeScript bindings do not allocate HttpRequest.timeoutSecs: $typescript_binding"
grep -Fq -- "const FfiConverterOptionalUInt64 = new FfiConverterOptional" "$typescript_binding" || fail "TypeScript bindings omit the optional UInt64 converter: $typescript_binding"
+ grep -Fq -- "maxResponseBytes?: bigint" "$typescript_binding" || fail "TypeScript bindings omit HttpRequest.maxResponseBytes: $typescript_binding"
+ grep -Fq -- "maxResponseBytes: undefined" "$typescript_binding" || fail "TypeScript bindings do not default HttpRequest.maxResponseBytes to absent: $typescript_binding"
+ grep -Fq -- "maxResponseBytes: FfiConverterOptionalUInt64.read(from)" "$typescript_binding" || fail "TypeScript bindings do not read HttpRequest.maxResponseBytes: $typescript_binding"
+ grep -Fq -- "FfiConverterOptionalUInt64.write(value.maxResponseBytes, into)" "$typescript_binding" || fail "TypeScript bindings do not write HttpRequest.maxResponseBytes: $typescript_binding"
+ grep -Fq -- "FfiConverterOptionalUInt64.allocationSize(value.maxResponseBytes)" "$typescript_binding" || fail "TypeScript bindings do not allocate HttpRequest.maxResponseBytes: $typescript_binding"
done
grep -Fq -- "TimeoutSecs *uint64" "$go_sdk_source" || fail "Go bindings omit HttpRequest.TimeoutSecs"
grep -Fq -- "FfiConverterOptionalUint64INSTANCE.Read(reader)" "$go_sdk_source" || fail "Go bindings do not read HttpRequest.TimeoutSecs"
grep -Fq -- "FfiConverterOptionalUint64INSTANCE.Write(writer, value.TimeoutSecs)" "$go_sdk_source" || fail "Go bindings do not write HttpRequest.TimeoutSecs"
grep -Fq -- "FfiDestroyerOptionalUint64{}.Destroy(r.TimeoutSecs)" "$go_sdk_source" || fail "Go bindings do not destroy HttpRequest.TimeoutSecs"
+grep -Fq -- "MaxResponseBytes *uint64" "$go_sdk_source" || fail "Go bindings omit HttpRequest.MaxResponseBytes"
+go_http_request_block="$(sed -n '/^type HttpRequest struct {/,/^type FfiDestroyerHttpRequest struct/p' "$go_sdk_source")"
+[ "$(printf '%s\n' "$go_http_request_block" | grep -Fc -- "FfiConverterOptionalUint64INSTANCE.Read(reader),")" -eq 2 ] || fail "Go bindings do not read both HttpRequest request controls in field order"
+grep -Fq -- "FfiConverterOptionalUint64INSTANCE.Write(writer, value.MaxResponseBytes)" "$go_sdk_source" || fail "Go bindings do not write HttpRequest.MaxResponseBytes"
+grep -Fq -- "FfiDestroyerOptionalUint64{}.Destroy(r.MaxResponseBytes)" "$go_sdk_source" || fail "Go bindings do not destroy HttpRequest.MaxResponseBytes"
grep -Fq -- "type FfiConverterOptionalUint64 struct{}" "$go_sdk_source" || fail "Go bindings omit the optional uint64 converter"
+node - "$python_sdk_source" "$go_sdk_source" "$node_sdk_source" "$browser_sdk_source" <<'NODE'
+const fs = require("node:fs");
+
+const bindings = [
+ [process.argv[2], /uniffi_cyclops_sdk_checksum_method_httpclient_execute\(\) != (\d+):/],
+ [process.argv[3], /if checksum != (\d+) \{\n\s*\/\/ If this happens try cleaning and rebuilding your project\n\s*panic\("fleet_sdk: uniffi_cyclops_sdk_checksum_method_httpclient_execute/],
+ [process.argv[4], /uniffi_cyclops_sdk_checksum_method_httpclient_execute\(\) !== (\d+)/],
+ [process.argv[5], /ubrn_uniffi_cyclops_sdk_checksum_method_httpclient_execute\(\) !==\s*(\d+)/],
+];
+const checksums = bindings.map(([path, pattern]) => {
+ const match = fs.readFileSync(path, "utf8").match(pattern);
+ if (!match) throw new Error(`HttpClient.execute checksum is missing from ${path}`);
+ return [path, match[1]];
+});
+const expected = checksums[0][1];
+const mismatches = checksums.filter(([, checksum]) => checksum !== expected);
+if (mismatches.length > 0) {
+ throw new Error(
+ `HttpClient.execute checksum drift: expected ${expected}; ` +
+ mismatches.map(([path, checksum]) => `${path} has ${checksum}`).join(", "),
+ );
+}
+NODE
grep -Fq -- "@uniffi_handle_map = UniffiHandleMap.new" "$ruby_sdk_source" || fail "Ruby callback bindings do not retain native callback objects"
grep -Fq -- "module UniffiCallbackInterfaceHttpClient" "$ruby_sdk_source" || fail "Ruby callback bindings do not register an HTTP callback vtable"
grep -Fq -- "[VTableCallbackInterfaceHttpClient.by_ref]" "$ruby_sdk_source" || fail "Ruby callback vtable initializer has the wrong FFI signature"
diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
index b6bf906928..dc3d29801c 100644
--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
@@ -695,7 +695,7 @@ func uniffiCheckChecksums() {
checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
return C.uniffi_cyclops_sdk_checksum_method_httpclient_execute()
})
- if checksum != 38803 {
+ if checksum != 33213 {
// If this happens try cleaning and rebuilding your project
panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_httpclient_execute: UniFFI API checksum mismatch")
}
@@ -3215,6 +3215,9 @@ type HttpRequest struct {
// pre-timeout record shape keep constructing requests unchanged; absent
// falls back to the native client's 30-second default.
TimeoutSecs *uint64
+ // Maximum bytes delivered in the response body. Absent preserves the
+ // historical unbounded response behavior.
+ MaxResponseBytes *uint64
}
func (r *HttpRequest) Destroy() {
@@ -3223,6 +3226,7 @@ func (r *HttpRequest) Destroy() {
FfiDestroyerSequenceHttpHeader{}.Destroy(r.Headers)
FfiDestroyerOptionalBytes{}.Destroy(r.Body)
FfiDestroyerOptionalUint64{}.Destroy(r.TimeoutSecs)
+ FfiDestroyerOptionalUint64{}.Destroy(r.MaxResponseBytes)
}
type FfiConverterHttpRequest struct{}
@@ -3240,6 +3244,7 @@ func (c FfiConverterHttpRequest) Read(reader io.Reader) HttpRequest {
FfiConverterSequenceHttpHeaderINSTANCE.Read(reader),
FfiConverterOptionalBytesINSTANCE.Read(reader),
FfiConverterOptionalUint64INSTANCE.Read(reader),
+ FfiConverterOptionalUint64INSTANCE.Read(reader),
}
}
@@ -3257,6 +3262,7 @@ func (c FfiConverterHttpRequest) Write(writer io.Writer, value HttpRequest) {
FfiConverterSequenceHttpHeaderINSTANCE.Write(writer, value.Headers)
FfiConverterOptionalBytesINSTANCE.Write(writer, value.Body)
FfiConverterOptionalUint64INSTANCE.Write(writer, value.TimeoutSecs)
+ FfiConverterOptionalUint64INSTANCE.Write(writer, value.MaxResponseBytes)
}
type FfiDestroyerHttpRequest struct{}
diff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
index ca6bc67af7..087e84d29f 100644
--- a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
@@ -830,6 +830,8 @@ internal object IntegrityCheckingUniffiLib {
): Short
external fun uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers(
): Short
+ external fun uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes(
+ ): Short
external fun uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method(
): Short
external fun uniffi_cyclops_sdk_checksum_method_httprequestbuilder_timeout_secs(
@@ -1095,6 +1097,8 @@ external fun uniffi_cyclops_sdk_fn_method_httprequestbuilder_build(`ptr`: Long,u
): RustBuffer.ByValue
external fun uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers(`ptr`: Long,`value`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
): Long
+external fun uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes(`ptr`: Long,`value`: Long,uniffi_out_err: UniffiRustCallStatus,
+): Long
external fun uniffi_cyclops_sdk_fn_method_httprequestbuilder_method(`ptr`: Long,`value`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
): Long
external fun uniffi_cyclops_sdk_fn_method_httprequestbuilder_timeout_secs(`ptr`: Long,`value`: Long,uniffi_out_err: UniffiRustCallStatus,
@@ -1351,7 +1355,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
- if (lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 38803.toShort()) {
+ if (lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_cyclops_sdk_checksum_method_createclaimrequestbuilder_build() != 10518.toShort()) {
@@ -1438,6 +1442,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers() != 19982.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes() != 42011.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method() != 4078.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -5517,6 +5524,10 @@ public object FfiConverterTypeCyclopsTokenProviderConfigurationBuilder: FfiConve
public interface HttpClient {
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
suspend fun `execute`(`request`: HttpRequest): HttpResponse
companion object
@@ -5619,6 +5630,10 @@ open class HttpClientImpl: Disposable, AutoCloseable, HttpClient
}
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
@Throws(HttpException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
override suspend fun `execute`(`request`: HttpRequest) : HttpResponse {
@@ -5859,6 +5874,8 @@ public interface HttpRequestBuilderInterface {
fun `headers`(`value`: List<HttpHeader>): HttpRequestBuilder
+ fun `maxResponseBytes`(`value`: kotlin.ULong): HttpRequestBuilder
+
fun `method`(`value`: kotlin.String): HttpRequestBuilder
fun `timeoutSecs`(`value`: kotlin.ULong): HttpRequestBuilder
@@ -6012,6 +6029,19 @@ open class HttpRequestBuilder: Disposable, AutoCloseable, HttpRequestBuilderInte
}
+ override fun `maxResponseBytes`(`value`: kotlin.ULong): HttpRequestBuilder {
+ return FfiConverterTypeHttpRequestBuilder.lift(
+ callWithHandle {
+ uniffiRustCall() { _status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes(
+ it,
+ FfiConverterULong.lower(`value`),_status)
+}
+ }
+ )
+ }
+
+
override fun `method`(`value`: kotlin.String): HttpRequestBuilder {
return FfiConverterTypeHttpRequestBuilder.lift(
callWithHandle {
@@ -6861,6 +6891,12 @@ data class HttpRequest (
* falls back to the native client's 30-second default.
*/
var `timeoutSecs`: kotlin.ULong? = null
+ ,
+ /**
+ * Maximum bytes delivered in the response body. Absent preserves the
+ * historical unbounded response behavior.
+ */
+ var `maxResponseBytes`: kotlin.ULong? = null
){
@@ -6882,6 +6918,7 @@ public object FfiConverterTypeHttpRequest: FfiConverterRustBuffer<HttpRequest> {
FfiConverterSequenceTypeHttpHeader.read(buf),
FfiConverterOptionalByteArray.read(buf),
FfiConverterOptionalULong.read(buf),
+ FfiConverterOptionalULong.read(buf),
)
}
@@ -6890,7 +6927,8 @@ public object FfiConverterTypeHttpRequest: FfiConverterRustBuffer<HttpRequest> {
FfiConverterString.allocationSize(value.`url`) +
FfiConverterSequenceTypeHttpHeader.allocationSize(value.`headers`) +
FfiConverterOptionalByteArray.allocationSize(value.`body`) +
- FfiConverterOptionalULong.allocationSize(value.`timeoutSecs`)
+ FfiConverterOptionalULong.allocationSize(value.`timeoutSecs`) +
+ FfiConverterOptionalULong.allocationSize(value.`maxResponseBytes`)
)
override fun write(value: HttpRequest, buf: ByteBuffer) {
@@ -6899,6 +6937,7 @@ public object FfiConverterTypeHttpRequest: FfiConverterRustBuffer<HttpRequest> {
FfiConverterSequenceTypeHttpHeader.write(value.`headers`, buf)
FfiConverterOptionalByteArray.write(value.`body`, buf)
FfiConverterOptionalULong.write(value.`timeoutSecs`, buf)
+ FfiConverterOptionalULong.write(value.`maxResponseBytes`, buf)
}
}
diff --git a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
index fc60ea630c..ffc3acb155 100644
--- a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
+++ b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
@@ -628,7 +628,7 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopstokenproviderconfigurationbuilder_pool_poll_limit() != 6865:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 38803:
+ if lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_constructor_httprequestbuilder_new() != 25892:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
@@ -638,6 +638,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers() != 19982:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes() != 42011:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method() != 4078:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_timeout_secs() != 40941:
@@ -1495,6 +1497,12 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes.argtypes = (
+ ctypes.c_uint64,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes.restype = ctypes.c_uint64
_UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_method.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1786,6 +1794,9 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_build.restype =
_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method.restype = ctypes.c_uint16
@@ -2937,7 +2948,7 @@ class _UniffiFfiConverterOptionalUInt64(_UniffiConverterRustBuffer):
@dataclass
class HttpRequest:
- def __init__(self, *, method:str, url:str, headers:typing.List[HttpHeader], body:typing.Optional[bytes], timeout_secs:typing.Optional[int] = _DEFAULT):
+ def __init__(self, *, method:str, url:str, headers:typing.List[HttpHeader], body:typing.Optional[bytes], timeout_secs:typing.Optional[int] = _DEFAULT, max_response_bytes:typing.Optional[int] = _DEFAULT):
self.method = method
self.url = url
self.headers = headers
@@ -2946,12 +2957,16 @@ class HttpRequest:
self.timeout_secs = None
else:
self.timeout_secs = timeout_secs
+ if max_response_bytes is _DEFAULT:
+ self.max_response_bytes = None
+ else:
+ self.max_response_bytes = max_response_bytes
def __str__(self):
- return "HttpRequest(method={}, url={}, headers={}, body={}, timeout_secs={})".format(self.method, self.url, self.headers, self.body, self.timeout_secs)
+ return "HttpRequest(method={}, url={}, headers={}, body={}, timeout_secs={}, max_response_bytes={})".format(self.method, self.url, self.headers, self.body, self.timeout_secs, self.max_response_bytes)
def __eq__(self, other):
if self.method != other.method:
return False
@@ -2963,6 +2978,8 @@ class HttpRequest:
return False
if self.timeout_secs != other.timeout_secs:
return False
+ if self.max_response_bytes != other.max_response_bytes:
+ return False
return True
class _UniffiFfiConverterTypeHttpRequest(_UniffiConverterRustBuffer):
@@ -2974,6 +2991,7 @@ class _UniffiFfiConverterTypeHttpRequest(_UniffiConverterRustBuffer):
headers=_UniffiFfiConverterSequenceTypeHttpHeader.read(buf),
body=_UniffiFfiConverterOptionalBytes.read(buf),
timeout_secs=_UniffiFfiConverterOptionalUInt64.read(buf),
+ max_response_bytes=_UniffiFfiConverterOptionalUInt64.read(buf),
)
@staticmethod
@@ -2983,6 +3001,7 @@ class _UniffiFfiConverterTypeHttpRequest(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceTypeHttpHeader.check_lower(value.headers)
_UniffiFfiConverterOptionalBytes.check_lower(value.body)
_UniffiFfiConverterOptionalUInt64.check_lower(value.timeout_secs)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.max_response_bytes)
@staticmethod
def write(value, buf):
@@ -2991,6 +3010,7 @@ class _UniffiFfiConverterTypeHttpRequest(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceTypeHttpHeader.write(value.headers, buf)
_UniffiFfiConverterOptionalBytes.write(value.body, buf)
_UniffiFfiConverterOptionalUInt64.write(value.timeout_secs, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.max_response_bytes, buf)
class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt):
CLASS_NAME = "u16"
@@ -5799,6 +5819,10 @@ class _UniffiFfiConverterTypeCyclopsTokenProviderConfigurationBuilder:
class HttpClient():
async def execute(self, request: HttpRequest) -> HttpResponse:
+ """
+ Executes an HTTP request. Foreign implementations must enforce
+ `request.max_response_bytes` while streaming the response body.
+"""
raise NotImplementedError
class HttpClientImpl(HttpClient):
@@ -5826,6 +5850,10 @@ class HttpClientImpl(HttpClient):
inst._handle = handle
return inst
async def execute(self, request: HttpRequest) -> HttpResponse:
+ """
+ Executes an HTTP request. Foreign implementations must enforce
+ `request.max_response_bytes` while streaming the response body.
+"""
_UniffiFfiConverterTypeHttpRequest.check_lower(request)
_uniffi_lowered_args = (
@@ -5954,6 +5982,8 @@ class HttpRequestBuilderProtocol(typing.Protocol):
raise NotImplementedError
def headers(self, value: typing.List[HttpHeader]) -> HttpRequestBuilder:
raise NotImplementedError
+ def max_response_bytes(self, value: int) -> HttpRequestBuilder:
+ raise NotImplementedError
def method(self, value: str) -> HttpRequestBuilder:
raise NotImplementedError
def timeout_secs(self, value: int) -> HttpRequestBuilder:
@@ -6035,6 +6065,21 @@ class HttpRequestBuilder(HttpRequestBuilderProtocol):
*_uniffi_lowered_args,
)
return _uniffi_lift_return(_uniffi_ffi_result)
+ def max_response_bytes(self, value: int) -> HttpRequestBuilder:
+
+ _UniffiFfiConverterUInt64.check_lower(value)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterUInt64.lower(value),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeHttpRequestBuilder.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
def method(self, value: str) -> HttpRequestBuilder:
_UniffiFfiConverterString.check_lower(value)
diff --git a/libs/fleet/sdk-bindings/python/tests/test_builders.py b/libs/fleet/sdk-bindings/python/tests/test_builders.py
index 0f03de1e62..f9b1eab90a 100644
--- a/libs/fleet/sdk-bindings/python/tests/test_builders.py
+++ b/libs/fleet/sdk-bindings/python/tests/test_builders.py
@@ -74,23 +74,27 @@ class GeneratedBuilderTest(unittest.TestCase):
.url("https://run.cua.ai/v1/pools")
.headers([])
.timeout_secs(30)
+ .max_response_bytes(4096)
.build()
)
self.assertIs(type(request), fleet_sdk.HttpRequest)
self.assertIsNone(request.body)
self.assertIsNone(request.timeout_secs)
+ self.assertIsNone(request.max_response_bytes)
self.assertEqual(bounded.timeout_secs, 30)
+ self.assertEqual(bounded.max_response_bytes, 4096)
with self.assertRaises(fleet_sdk.SdkBuildError.MissingRequiredField) as error:
fleet_sdk.HttpRequestBuilder().method("GET").headers([]).build()
self.assertEqual(error.exception.record_type, "HttpRequest")
self.assertEqual(error.exception.field, "url")
- def test_http_request_constructor_treats_timeout_secs_as_optional(self):
+ def test_http_request_constructor_treats_request_controls_as_optional(self):
request = fleet_sdk.HttpRequest(
method="GET", url="https://run.cua.ai/v1/pools", headers=[], body=None
)
self.assertIsNone(request.timeout_secs)
+ self.assertIsNone(request.max_response_bytes)
def test_remaining_frontend_builders_are_generated(self):
configuration = (
diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
index 682a13a05c..00e131285c 100644
--- a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
@@ -372,6 +372,7 @@ private_constant :UniffiHandleMap
RustBuffer.check_lower_SequenceTypeHttpHeader(v.headers)
RustBuffer.check_lower_Optionalbytes(v.body)
RustBuffer.check_lower_Optionalu64(v.timeout_secs)
+ RustBuffer.check_lower_Optionalu64(v.max_response_bytes)
end
def self.alloc_from_TypeHttpRequest(v)
@@ -1246,7 +1247,8 @@ class RustBufferStream
url: readString,
headers: readSequenceTypeHttpHeader,
body: readOptionalbytes,
- timeout_secs: readOptionalu64
+ timeout_secs: readOptionalu64,
+ max_response_bytes: readOptionalu64
)
end
@@ -2017,6 +2019,7 @@ class RustBufferBuilder
self.write_SequenceTypeHttpHeader(v.headers)
self.write_Optionalbytes(v.body)
self.write_Optionalu64(v.timeout_secs)
+ self.write_Optionalu64(v.max_response_bytes)
end
# The Record type HttpResponse.
@@ -3109,6 +3112,9 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers,
[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
:uint64
+ attach_function :uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes,
+ [:uint64, :uint64, RustCallStatus.by_ref],
+ :uint64
attach_function :uniffi_cyclops_sdk_fn_method_httprequestbuilder_method,
[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
:uint64
@@ -3361,6 +3367,9 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers,
[RustCallStatus.by_ref],
:uint16
+ attach_function :uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes,
+ [RustCallStatus.by_ref],
+ :uint16
attach_function :uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method,
[RustCallStatus.by_ref],
:uint16
@@ -3736,14 +3745,15 @@ end
# Record type HttpRequest
class HttpRequest
- attr_reader :method, :url, :headers, :body, :timeout_secs
+ attr_reader :method, :url, :headers, :body, :timeout_secs, :max_response_bytes
- def initialize(method:, url:, headers:, body:, timeout_secs: nil)
+ def initialize(method:, url:, headers:, body:, timeout_secs: nil, max_response_bytes: nil)
@method = method
@url = url
@headers = headers
@body = body
@timeout_secs = timeout_secs
+ @max_response_bytes = max_response_bytes
end
def ==(other)
@@ -3762,6 +3772,9 @@ class HttpRequest
if @timeout_secs != other.timeout_secs
return false
end
+ if @max_response_bytes != other.max_response_bytes
+ return false
+ end
true
end
@@ -5262,6 +5275,12 @@ end
result = FleetSdk.rust_call(:uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers,uniffi_clone_handle(),RustBuffer.alloc_from_SequenceTypeHttpHeader(value))
return HttpRequestBuilder.uniffi_allocate(result)
end
+ def max_response_bytes(value)
+ value = FleetSdk::uniffi_in_range(value, "u64", 0, 2**64)
+
+ result = FleetSdk.rust_call(:uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes,uniffi_clone_handle(),value)
+ return HttpRequestBuilder.uniffi_allocate(result)
+ end
def method(value)
value = FleetSdk::uniffi_utf8(value)
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
index c9ace835a4..f25403eb4e 100644
--- a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
@@ -2571,6 +2571,10 @@ public func FfiConverterTypeCyclopsTokenProviderConfigurationBuilder_lower(_ val
public protocol HttpClient: AnyObject, Sendable {
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
func execute(request: HttpRequest) async throws -> HttpResponse
}
@@ -2627,6 +2631,10 @@ open class HttpClientImpl: HttpClient, @unchecked Sendable {
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
open func execute(request: HttpRequest)async throws -> HttpResponse {
return
try await uniffiRustCallAsync(
@@ -2791,6 +2799,8 @@ public protocol HttpRequestBuilderProtocol: AnyObject, Sendable {
func headers(value: [HttpHeader]) -> HttpRequestBuilder
+ func maxResponseBytes(value: UInt64) -> HttpRequestBuilder
+
func method(value: String) -> HttpRequestBuilder
func timeoutSecs(value: UInt64) -> HttpRequestBuilder
@@ -2884,6 +2894,15 @@ open func headers(value: [HttpHeader]) -> HttpRequestBuilder {
})
}
+open func maxResponseBytes(value: UInt64) -> HttpRequestBuilder {
+ return try! FfiConverterTypeHttpRequestBuilder_lift(try! rustCall() {
+ uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes(
+ self.uniffiCloneHandle(),
+ FfiConverterUInt64.lower(value),$0
+ )
+})
+}
+
open func method(value: String) -> HttpRequestBuilder {
return try! FfiConverterTypeHttpRequestBuilder_lift(try! rustCall() {
uniffi_cyclops_sdk_fn_method_httprequestbuilder_method(
@@ -3693,6 +3712,11 @@ public struct HttpRequest: Equatable, Hashable {
* falls back to the native client's 30-second default.
*/
public var timeoutSecs: UInt64?
+ /**
+ * Maximum bytes delivered in the response body. Absent preserves the
+ * historical unbounded response behavior.
+ */
+ public var maxResponseBytes: UInt64?
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -3701,12 +3725,17 @@ public struct HttpRequest: Equatable, Hashable {
* Per-request timeout. Defaults to absent so callers written against the
* pre-timeout record shape keep constructing requests unchanged; absent
* falls back to the native client's 30-second default.
- */timeoutSecs: UInt64? = nil) {
+ */timeoutSecs: UInt64? = nil,
+ /**
+ * Maximum bytes delivered in the response body. Absent preserves the
+ * historical unbounded response behavior.
+ */maxResponseBytes: UInt64? = nil) {
self.method = method
self.url = url
self.headers = headers
self.body = body
self.timeoutSecs = timeoutSecs
+ self.maxResponseBytes = maxResponseBytes
}
@@ -3729,7 +3758,8 @@ public struct FfiConverterTypeHttpRequest: FfiConverterRustBuffer {
url: FfiConverterString.read(from: &buf),
headers: FfiConverterSequenceTypeHttpHeader.read(from: &buf),
body: FfiConverterOptionData.read(from: &buf),
- timeoutSecs: FfiConverterOptionUInt64.read(from: &buf)
+ timeoutSecs: FfiConverterOptionUInt64.read(from: &buf),
+ maxResponseBytes: FfiConverterOptionUInt64.read(from: &buf)
)
}
@@ -3739,6 +3769,7 @@ public struct FfiConverterTypeHttpRequest: FfiConverterRustBuffer {
FfiConverterSequenceTypeHttpHeader.write(value.headers, into: &buf)
FfiConverterOptionData.write(value.body, into: &buf)
FfiConverterOptionUInt64.write(value.timeoutSecs, into: &buf)
+ FfiConverterOptionUInt64.write(value.maxResponseBytes, into: &buf)
}
}
@@ -5603,7 +5634,7 @@ private let initializationResult: InitializationResult = {
if (uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 38803) {
+ if (uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cyclops_sdk_checksum_method_createclaimrequestbuilder_build() != 10518) {
@@ -5690,6 +5721,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers() != 19982) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes() != 42011) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method() != 4078) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
index 5606f32ef9..4b1fbd93f3 100644
--- a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
@@ -770,6 +770,11 @@ RustBuffer uniffi_cyclops_sdk_fn_method_httprequestbuilder_build(uint64_t ptr, R
uint64_t uniffi_cyclops_sdk_fn_method_httprequestbuilder_headers(uint64_t ptr, RustBuffer value, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPREQUESTBUILDER_MAX_RESPONSE_BYTES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPREQUESTBUILDER_MAX_RESPONSE_BYTES
+uint64_t uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes(uint64_t ptr, uint64_t value, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPREQUESTBUILDER_METHOD
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPREQUESTBUILDER_METHOD
uint64_t uniffi_cyclops_sdk_fn_method_httprequestbuilder_method(uint64_t ptr, RustBuffer value, RustCallStatus *_Nonnull out_status
@@ -1497,6 +1502,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_httprequestbuilder_build(void
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPREQUESTBUILDER_HEADERS
uint16_t uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPREQUESTBUILDER_MAX_RESPONSE_BYTES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPREQUESTBUILDER_MAX_RESPONSE_BYTES
+uint16_t uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPREQUESTBUILDER_METHOD
diff --git a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
index 97030194fe..da685e1bb2 100644
--- a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
+++ b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
@@ -994,6 +994,11 @@ export type HttpRequest = {
* falls back to the native client's 30-second default.
*/
timeoutSecs?: bigint;
+ /**
+ * Maximum bytes delivered in the response body. Absent preserves the
+ * historical unbounded response behavior.
+ */
+ maxResponseBytes?: bigint;
};
/**
@@ -1002,6 +1007,7 @@ export type HttpRequest = {
export const HttpRequest = (() => {
const defaults = () => ({
timeoutSecs: undefined,
+ maxResponseBytes: undefined,
});
const create = (() => {
return uniffiCreateRecord<HttpRequest, ReturnType<typeof defaults>>(
@@ -1025,6 +1031,7 @@ const FfiConverterTypeHttpRequest = (() => {
headers: FfiConverterSequenceTypeHttpHeader.read(from),
body: FfiConverterOptionalBytes.read(from),
timeoutSecs: FfiConverterOptionalUInt64.read(from),
+ maxResponseBytes: FfiConverterOptionalUInt64.read(from),
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -1033,6 +1040,7 @@ const FfiConverterTypeHttpRequest = (() => {
FfiConverterSequenceTypeHttpHeader.write(value.headers, into);
FfiConverterOptionalBytes.write(value.body, into);
FfiConverterOptionalUInt64.write(value.timeoutSecs, into);
+ FfiConverterOptionalUInt64.write(value.maxResponseBytes, into);
}
allocationSize(value: TypeName): number {
return (
@@ -1040,7 +1048,8 @@ const FfiConverterTypeHttpRequest = (() => {
FfiConverterString.allocationSize(value.url) +
FfiConverterSequenceTypeHttpHeader.allocationSize(value.headers) +
FfiConverterOptionalBytes.allocationSize(value.body) +
- FfiConverterOptionalUInt64.allocationSize(value.timeoutSecs)
+ FfiConverterOptionalUInt64.allocationSize(value.timeoutSecs) +
+ FfiConverterOptionalUInt64.allocationSize(value.maxResponseBytes)
);
}
}
@@ -5515,6 +5524,10 @@ const FfiConverterTypeCyclopsTokenProviderConfigurationBuilder =
);
export interface HttpClient {
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
execute(
request: HttpRequest,
asyncOpts_?: { signal: AbortSignal },
@@ -5533,6 +5546,10 @@ export class HttpClientImpl extends UniffiAbstractObject implements HttpClient {
uniffiTypeHttpClientImplObjectFactory.bless(pointer);
}
+ /**
+ * Executes an HTTP request. Foreign implementations must enforce
+ * `request.max_response_bytes` while streaming the response body.
+ */
async execute(
request: HttpRequest,
asyncOpts_?: { signal: AbortSignal },
@@ -5744,6 +5761,7 @@ export interface HttpRequestBuilderLike {
body(value: ArrayBuffer): HttpRequestBuilderLike;
build() /*throws*/ : HttpRequest;
headers(value: Array<HttpHeader>): HttpRequestBuilderLike;
+ maxResponseBytes(value: bigint): HttpRequestBuilderLike;
method(value: string): HttpRequestBuilderLike;
timeoutSecs(value: bigint): HttpRequestBuilderLike;
url(value: string): HttpRequestBuilderLike;
@@ -5834,6 +5852,21 @@ export class HttpRequestBuilder
);
}
+ maxResponseBytes(value: bigint): HttpRequestBuilderLike {
+ return FfiConverterTypeHttpRequestBuilder.lift(
+ uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_httprequestbuilder_max_response_bytes(
+ uniffiTypeHttpRequestBuilderObjectFactory.clonePointer(this),
+ FfiConverterUInt64.lower(value, nativeModule().rustbuffer_alloc),
+ callStatus,
+ );
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ),
+ );
+ }
+
method(value: string): HttpRequestBuilderLike {
return FfiConverterTypeHttpRequestBuilder.lift(
uniffiCaller.rustCall(
@@ -6877,7 +6910,7 @@ function uniffiEnsureInitialized() {
}
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_httpclient_execute() !==
- 38803
+ 33213
) {
throw new UniffiInternalError.ApiChecksumMismatch(
"uniffi_cyclops_sdk_checksum_method_httpclient_execute",
@@ -6915,6 +6948,14 @@ function uniffiEnsureInitialized() {
"uniffi_cyclops_sdk_checksum_method_httprequestbuilder_headers",
);
}
+ if (
+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes() !==
+ 42011
+ ) {
+ throw new UniffiInternalError.ApiChecksumMismatch(
+ "uniffi_cyclops_sdk_checksum_method_httprequestbuilder_max_response_bytes",
+ );
+ }
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_httprequestbuilder_method() !==
4078
diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
index 4c1ded3b16..9168faa06f 100644
--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
@@ -867,7 +867,12 @@ export type HttpRequest = {
* pre-timeout record shape keep constructing requests unchanged; absent
* falls back to the native client's 30-second default.
*/
- timeoutSecs?: bigint
+ timeoutSecs?: bigint,
+ /**
+ * Maximum bytes delivered in the response body. Absent preserves the
+ * historical unbounded response behavior.
+ */
+ maxResponseBytes?: bigint
}
/**
@@ -875,7 +880,8 @@ export type HttpRequest = {
*/
export const HttpRequest = (() => {
const defaults = () => ({
- timeoutSecs: undefined
+ timeoutSecs: undefined,
+ maxResponseBytes: undefined
});
const create = (() => {
return uniffiCreateRecord<HttpRequest, ReturnType<typeof defaults>>(defaults);
@@ -896,7 +902,8 @@ const FfiConverterTypeHttpRequest = (() => {
url: FfiConverterString.read(from),
headers: FfiConverterSequenceTypeHttpHeader.read(from),
body: FfiConverterOptionalBytes.read(from),
- timeoutSecs: FfiConverterOptionalUInt64.read(from)
+ timeoutSecs: FfiConverterOptionalUInt64.read(from),
+ maxResponseBytes: FfiConverterOptionalUInt64.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -905,13 +912,15 @@ const FfiConverterTypeHttpRequest = (() => {
FfiConverterSequenceTypeHttpHeader.write(value.headers, into);
FfiConverterOptionalBytes.write(value.body, into);
FfiConverterOptionalUInt64.write(value.timeoutSecs, into);
+ FfiConverterOptionalUInt64.write(value.maxResponseBytes, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.method) +
FfiConverterString.allocationSize(value.url) +
FfiConverterSequenceTypeHttpHeader.allocationSize(value.headers) +
FfiConverterOptionalBytes.allocationSize(value.body) +
- FfiConverterOptionalUInt64.allocationSize(value.timeoutSecs);
+ FfiConverterOptionalUInt64.allocationSize(value.timeoutSecs) +
+ FfiConverterOptionalUInt64.allocationSize(value.maxResponseBytes);
}
};
@@ -4045,7 +4054,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() !== 25746) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new");
}
- if (nativeModule().uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 38803) {
+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 33213) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_httpclient_execute");
}
diff --git a/libs/fleet/sdk/Cargo.toml b/libs/fleet/sdk/Cargo.toml
index f01432d678..9b37850cd6 100644
--- a/libs/fleet/sdk/Cargo.toml
+++ b/libs/fleet/sdk/Cargo.toml
@@ -36,7 +36,7 @@ js-sys = "0.3"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-time = "1.1.0"
-web-sys = { version = "0.3", features = ["Headers", "Request", "RequestInit", "Response", "Window"] }
+web-sys = { version = "0.3", features = ["Headers", "ReadableStream", "ReadableStreamDefaultReader", "Request", "RequestInit", "Response", "Window"] }
[dev-dependencies]
camino = "1.0"
diff --git a/libs/fleet/sdk/src/claims.rs b/libs/fleet/sdk/src/claims.rs
index 48dcb2fae7..0d8f4307a9 100644
--- a/libs/fleet/sdk/src/claims.rs
+++ b/libs/fleet/sdk/src/claims.rs
@@ -283,6 +283,7 @@ fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/src/namespaces.rs b/libs/fleet/sdk/src/namespaces.rs
index eb36704f04..96adaab9c1 100644
--- a/libs/fleet/sdk/src/namespaces.rs
+++ b/libs/fleet/sdk/src/namespaces.rs
@@ -98,6 +98,7 @@ fn json_request(method: &str, url: url::Url, body: Option<Vec<u8>>) -> HttpReque
],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/src/pools.rs b/libs/fleet/sdk/src/pools.rs
index bdc1d8ff4d..eaef342c7a 100644
--- a/libs/fleet/sdk/src/pools.rs
+++ b/libs/fleet/sdk/src/pools.rs
@@ -225,6 +225,7 @@ fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/src/services.rs b/libs/fleet/sdk/src/services.rs
index d23efb6afa..9565e6c236 100644
--- a/libs/fleet/sdk/src/services.rs
+++ b/libs/fleet/sdk/src/services.rs
@@ -22,6 +22,7 @@ impl CyclopsClient {
headers: filtered_headers(request.headers),
body: request.body,
timeout_secs: request.timeout_secs,
+ max_response_bytes: request.max_response_bytes,
};
self.execute_authenticated_service(request).await
}
diff --git a/libs/fleet/sdk/src/signed_service_urls.rs b/libs/fleet/sdk/src/signed_service_urls.rs
index 3f3d6a6dc7..173b15a22f 100644
--- a/libs/fleet/sdk/src/signed_service_urls.rs
+++ b/libs/fleet/sdk/src/signed_service_urls.rs
@@ -166,6 +166,7 @@ fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
}],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/src/templates.rs b/libs/fleet/sdk/src/templates.rs
index b4eac62c70..35ffb06517 100644
--- a/libs/fleet/sdk/src/templates.rs
+++ b/libs/fleet/sdk/src/templates.rs
@@ -171,6 +171,7 @@ fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/src/transport.rs b/libs/fleet/sdk/src/transport.rs
index fc7be9c7df..651680c417 100644
--- a/libs/fleet/sdk/src/transport.rs
+++ b/libs/fleet/sdk/src/transport.rs
@@ -17,6 +17,28 @@ use web_time::Instant;
const TOKEN_EXPIRY_SKEW: Duration = Duration::from_secs(30);
const AUTHENTICATED_REQUEST_OPERATION: &str = "authenticated request";
const TOKEN_OPERATION: &str = "acquire OAuth token";
+const RESPONSE_BODY_LIMIT_ERROR: &str = "HTTP response exceeds configured size limit";
+
+fn append_response_chunk(
+ body: &mut Vec<u8>,
+ chunk: &[u8],
+ max_response_bytes: Option<u64>,
+) -> Result<(), HttpError> {
+ if let Some(limit) = max_response_bytes {
+ let current = u64::try_from(body.len()).unwrap_or(u64::MAX);
+ let chunk_len = u64::try_from(chunk.len()).unwrap_or(u64::MAX);
+ if current
+ .checked_add(chunk_len)
+ .is_none_or(|size| size > limit)
+ {
+ return Err(HttpError::Transport {
+ reason: RESPONSE_BODY_LIMIT_ERROR.into(),
+ });
+ }
+ }
+ body.extend_from_slice(chunk);
+ Ok(())
+}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum AuthenticatedRequestClass {
@@ -81,6 +103,7 @@ impl HttpClient for NativeHttpClient {
headers: request_headers,
body,
timeout_secs,
+ max_response_bytes,
} = request;
let method = reqwest::Method::from_bytes(method.as_bytes()).map_err(|error| {
HttpError::Transport {
@@ -113,7 +136,7 @@ impl HttpClient for NativeHttpClient {
reason: format!("could not create native HTTP runtime: {reason}"),
})?
.spawn(async move {
- let response = native.send().await.map_err(|error| HttpError::Transport {
+ let mut response = native.send().await.map_err(|error| HttpError::Transport {
reason: format!("native HTTP request failed: {error}"),
})?;
let status = response.status().as_u16();
@@ -134,16 +157,21 @@ impl HttpClient for NativeHttpClient {
})
})
.collect::<Result<Vec<_>, _>>()?;
- let body = response
- .bytes()
- .await
- .map_err(|error| HttpError::Transport {
- reason: format!("could not read native HTTP response body: {error}"),
- })?;
+ let mut body = Vec::new();
+ while let Some(chunk) =
+ response
+ .chunk()
+ .await
+ .map_err(|error| HttpError::Transport {
+ reason: format!("could not read native HTTP response body: {error}"),
+ })?
+ {
+ append_response_chunk(&mut body, &chunk, max_response_bytes)?;
+ }
Ok(HttpResponse {
status,
headers,
- body: body.to_vec(),
+ body,
})
})
.await
@@ -157,6 +185,8 @@ impl HttpClient for NativeHttpClient {
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
pub trait HttpClient: Send + Sync {
+ /// Executes an HTTP request. Foreign implementations must enforce
+ /// `request.max_response_bytes` while streaming the response body.
async fn execute(&self, request: HttpRequest) -> Result<HttpResponse, HttpError>;
}
@@ -170,6 +200,7 @@ impl HttpClient for BrowserHttpClient {
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
+ let max_response_bytes = request.max_response_bytes;
let init = web_sys::RequestInit::new();
init.set_method(&request.method);
if let Some(body) = request.body {
@@ -194,18 +225,59 @@ impl HttpClient for BrowserHttpClient {
.map_err(browser_transport_error)?
.dyn_into::<web_sys::Response>()
.map_err(browser_transport_error)?;
- let body = JsFuture::from(response.array_buffer().map_err(browser_transport_error)?)
- .await
- .map_err(browser_transport_error)?;
+ let body = read_browser_response_body(&response, max_response_bytes).await?;
Ok(HttpResponse {
status: response.status(),
headers: vec![],
- body: js_sys::Uint8Array::new(&body).to_vec(),
+ body,
})
}
}
+#[cfg(target_arch = "wasm32")]
+async fn read_browser_response_body(
+ response: &web_sys::Response,
+ max_response_bytes: Option<u64>,
+) -> Result<Vec<u8>, HttpError> {
+ use wasm_bindgen::{JsCast, JsValue};
+ use wasm_bindgen_futures::JsFuture;
+
+ let Some(stream) = response.body() else {
+ return Ok(Vec::new());
+ };
+ let reader = stream
+ .get_reader()
+ .dyn_into::<web_sys::ReadableStreamDefaultReader>()
+ .map_err(|error| browser_transport_error(error.into()))?;
+ let mut body = Vec::new();
+ loop {
+ let result = match JsFuture::from(reader.read()).await {
+ Ok(result) => result,
+ Err(error) => {
+ reader.release_lock();
+ return Err(browser_transport_error(error));
+ }
+ };
+ let done = js_sys::Reflect::get(&result, &JsValue::from_str("done"))
+ .map_err(browser_transport_error)?
+ .as_bool()
+ .unwrap_or(false);
+ if done {
+ reader.release_lock();
+ return Ok(body);
+ }
+ let value = js_sys::Reflect::get(&result, &JsValue::from_str("value"))
+ .map_err(browser_transport_error)?;
+ let chunk = js_sys::Uint8Array::new(&value).to_vec();
+ if let Err(error) = append_response_chunk(&mut body, &chunk, max_response_bytes) {
+ let _ = JsFuture::from(reader.cancel()).await;
+ reader.release_lock();
+ return Err(error);
+ }
+ }
+}
+
#[cfg(target_arch = "wasm32")]
fn browser_transport_error(error: wasm_bindgen::JsValue) -> HttpError {
let reason = error
@@ -486,6 +558,7 @@ impl Transport {
],
body: Some(body),
timeout_secs: None,
+ max_response_bytes: None,
})
.await
.map_err(map_http_error)?;
@@ -604,6 +677,57 @@ mod native_http_client_tests {
String::from_utf8(bytes).unwrap()
}
+ fn request(method: &str, url: String, max_response_bytes: Option<u64>) -> HttpRequest {
+ HttpRequest {
+ method: method.into(),
+ url,
+ headers: vec![],
+ body: None,
+ timeout_secs: None,
+ max_response_bytes,
+ }
+ }
+
+ async fn execute_response(
+ method: &str,
+ response: Vec<u8>,
+ max_response_bytes: Option<u64>,
+ ) -> Result<HttpResponse, HttpError> {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!(
+ "http://{}/sensitive-request?token=secret",
+ listener.local_addr().unwrap()
+ );
+ let server = thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ read_request(&mut stream);
+ stream.write_all(&response).unwrap();
+ });
+ let result = NativeHttpClient::new()
+ .unwrap()
+ .execute(request(method, url, max_response_bytes))
+ .await;
+ server.join().unwrap();
+ result
+ }
+
+ fn fixed_response(body: &[u8]) -> Vec<u8> {
+ let mut response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
+ body.len()
+ )
+ .into_bytes();
+ response.extend_from_slice(body);
+ response
+ }
+
+ fn assert_limit_error(error: HttpError) {
+ let HttpError::Transport { reason } = error;
+ assert_eq!(reason, RESPONSE_BODY_LIMIT_ERROR);
+ assert!(!reason.contains("sensitive-request"));
+ assert!(!reason.contains("secret-response"));
+ }
+
#[tokio::test]
async fn native_transport_preserves_duplicate_headers_and_error_bodies() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
@@ -632,6 +756,7 @@ mod native_http_client_tests {
],
body: None,
timeout_secs: None,
+ max_response_bytes: None,
})
.await
.unwrap();
@@ -676,6 +801,7 @@ mod native_http_client_tests {
}],
body: None,
timeout_secs: None,
+ max_response_bytes: None,
})
.await
.unwrap();
@@ -684,6 +810,74 @@ mod native_http_client_tests {
assert_eq!(response.status, 302);
assert!(matches!(redirected.accept(), Err(error) if error.kind() == ErrorKind::WouldBlock));
}
+
+ #[tokio::test]
+ async fn native_transport_enforces_limit_minus_one_exact_and_plus_one() {
+ let below = execute_response("GET", fixed_response(b"abc"), Some(4))
+ .await
+ .unwrap();
+ let exact = execute_response("GET", fixed_response(b"abcd"), Some(4))
+ .await
+ .unwrap();
+ let error = execute_response("GET", fixed_response(b"abcde"), Some(4))
+ .await
+ .unwrap_err();
+
+ assert_eq!(below.body, b"abc");
+ assert_eq!(exact.body, b"abcd");
+ assert_limit_error(error);
+ }
+
+ #[tokio::test]
+ async fn native_transport_allows_empty_but_rejects_nonempty_at_zero() {
+ let empty = execute_response("GET", fixed_response(b""), Some(0))
+ .await
+ .unwrap();
+ let error = execute_response("GET", fixed_response(b"secret-response"), Some(0))
+ .await
+ .unwrap_err();
+
+ assert!(empty.body.is_empty());
+ assert_limit_error(error);
+ }
+
+ #[tokio::test]
+ async fn native_transport_enforces_chunked_body_without_content_length() {
+ let response = b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\nconnection: close\r\n\r\n2\r\nab\r\n2\r\ncd\r\n0\r\n\r\n".to_vec();
+ let error = execute_response("GET", response, Some(3))
+ .await
+ .unwrap_err();
+
+ assert_limit_error(error);
+ }
+
+ #[tokio::test]
+ async fn native_transport_drops_an_oversized_stream_without_waiting_for_eof() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}/stream", listener.local_addr().unwrap());
+ let server = thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ read_request(&mut stream);
+ stream
+ .write_all(b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n2\r\nab\r\n")
+ .unwrap();
+ stream.flush().unwrap();
+ stream
+ .set_read_timeout(Some(Duration::from_secs(2)))
+ .unwrap();
+ let mut byte = [0; 1];
+ stream.read(&mut byte)
+ });
+
+ let error = NativeHttpClient::new()
+ .unwrap()
+ .execute(request("GET", url, Some(1)))
+ .await
+ .unwrap_err();
+
+ assert_limit_error(error);
+ assert_eq!(server.join().unwrap().unwrap(), 0);
+ }
}
#[cfg(all(test, not(target_arch = "wasm32")))]
diff --git a/libs/fleet/sdk/src/types.rs b/libs/fleet/sdk/src/types.rs
index bac3045d37..b7f896cc5e 100644
--- a/libs/fleet/sdk/src/types.rs
+++ b/libs/fleet/sdk/src/types.rs
@@ -341,6 +341,11 @@ pub struct HttpRequest {
#[serde(default)]
#[uniffi(default = None)]
pub timeout_secs: Option<u64>,
+ /// Maximum bytes delivered in the response body. Absent preserves the
+ /// historical unbounded response behavior.
+ #[serde(default)]
+ #[uniffi(default = None)]
+ pub max_response_bytes: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
diff --git a/libs/fleet/sdk/src/user_keys.rs b/libs/fleet/sdk/src/user_keys.rs
index 33ab66fcaf..1178195ab9 100644
--- a/libs/fleet/sdk/src/user_keys.rs
+++ b/libs/fleet/sdk/src/user_keys.rs
@@ -76,5 +76,6 @@ fn json_request(method: &str, url: url::Url, body: Option<Vec<u8>>) -> HttpReque
headers,
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/tests/oauth.rs b/libs/fleet/sdk/tests/oauth.rs
index d87106ab52..563ae135d7 100644
--- a/libs/fleet/sdk/tests/oauth.rs
+++ b/libs/fleet/sdk/tests/oauth.rs
@@ -341,6 +341,7 @@ async fn does_not_attach_bearer_to_cross_origin_requests() {
headers: vec![header("Authorization", "Basic external")],
body: Some(vec![0, 1, 2]),
timeout_secs: None,
+ max_response_bytes: None,
};
let response = client.execute_authenticated(external).await.unwrap();
@@ -432,6 +433,7 @@ fn request(url: &str) -> HttpRequest {
],
body: None,
timeout_secs: None,
+ max_response_bytes: None,
}
}
diff --git a/libs/fleet/sdk/tests/public_api.rs b/libs/fleet/sdk/tests/public_api.rs
index 561c0c8211..331ff480d0 100644
--- a/libs/fleet/sdk/tests/public_api.rs
+++ b/libs/fleet/sdk/tests/public_api.rs
@@ -177,6 +177,7 @@ async fn foreign_http_client_preserves_ordered_headers_and_byte_bodies() {
],
body: Some(vec![0, 255]),
timeout_secs: None,
+ max_response_bytes: None,
})
.await
.unwrap();
@@ -192,6 +193,7 @@ fn http_request_distinguishes_absent_and_empty_bodies() {
headers: vec![],
body: None,
timeout_secs: None,
+ max_response_bytes: None,
};
let empty = HttpRequest {
body: Some(vec![]),
@@ -219,16 +221,19 @@ fn http_request_builder_treats_optional_fields_as_skippable() {
assert_eq!(request.body, None);
assert_eq!(request.timeout_secs, None);
+ assert_eq!(request.max_response_bytes, None);
let bounded = HttpRequestBuilder::new()
.method("GET".into())
.url("https://run.cua.ai/v1/pools".into())
.headers(vec![])
.timeout_secs(30)
+ .max_response_bytes(4096)
.build()
.unwrap();
assert_eq!(bounded.timeout_secs, Some(30));
+ assert_eq!(bounded.max_response_bytes, Some(4096));
let missing = HttpRequestBuilder::new()
.method("GET".into())
@@ -239,7 +244,7 @@ fn http_request_builder_treats_optional_fields_as_skippable() {
}
#[test]
-fn http_request_deserializes_without_timeout_secs() {
+fn http_request_deserializes_without_optional_request_controls() {
let request: HttpRequest = serde_json::from_value(serde_json::json!({
"method": "GET",
"url": "https://run.cua.ai/v1/pools",
@@ -249,6 +254,7 @@ fn http_request_deserializes_without_timeout_secs() {
.unwrap();
assert_eq!(request.timeout_secs, None);
+ assert_eq!(request.max_response_bytes, None);
}
#[test]
diff --git a/libs/fleet/sdk/tests/service_flow.rs b/libs/fleet/sdk/tests/service_flow.rs
index 5362700cc6..2b553452bd 100644
--- a/libs/fleet/sdk/tests/service_flow.rs
+++ b/libs/fleet/sdk/tests/service_flow.rs
@@ -185,6 +185,7 @@ async fn filters_hop_by_hop_and_connection_nominated_headers_without_reordering_
],
body: Some(vec![0, 255, 1]),
timeout_secs: Some(75),
+ max_response_bytes: Some(1024),
};
client
@@ -208,6 +209,7 @@ async fn filters_hop_by_hop_and_connection_nominated_headers_without_reordering_
);
assert_eq!(request.body, Some(vec![0, 255, 1]));
assert_eq!(request.timeout_secs, Some(75));
+ assert_eq!(request.max_response_bytes, Some(1024));
}
#[tokio::test]
@@ -298,6 +300,7 @@ async fn returns_service_unauthorized_once_without_refreshing_or_replaying() {
headers: vec![header("content-type", "application/octet-stream")],
body: Some(vec![0, 255, 1]),
timeout_secs: None,
+ max_response_bytes: None,
};
let response = client
@@ -411,6 +414,7 @@ fn request(body: Option<Vec<u8>>) -> HttpRequest {
headers: vec![],
body,
timeout_secs: None,
+ max_response_bytes: None,
}
}