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.

feat(cyclops-cs): add UniFFI multi-language SDK (#5905)

r33drichards47ea8c92dea6
diff --git a/libs/fleet/sdk-bindings/rust/Cargo.lock b/libs/fleet/Cargo.lock
similarity index 54%
rename from libs/fleet/sdk-bindings/rust/Cargo.lock
rename to libs/fleet/Cargo.lock
index 0799a4583f..28a6b66719 100644
--- a/libs/fleet/sdk-bindings/rust/Cargo.lock
+++ b/libs/fleet/Cargo.lock
@@ -3,16 +3,86 @@
version = 4
[[package]]
-name = "adler2"
-version = "2.0.1"
+name = "anstyle"
+version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anyhow"
-version = "1.0.103"
+version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "askama"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bf825125edd887a019d0a3a837dcc5499a68b0d034cc3eb594070c3e18addc"
+dependencies = [
+ "askama_macros",
+ "itoa",
+ "percent-encoding",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "askama_derive"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1c7065972a130eafa84215f21352ae15b4a7393da48c1f5e103904490736738"
+dependencies = [
+ "askama_parser",
+ "basic-toml",
+ "glob",
+ "memchr",
+ "proc-macro2",
+ "quote",
+ "rustc-hash",
+ "serde",
+ "serde_derive",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "askama_macros"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e23b1d2c4bd39a41971f6124cef4cc6fd0540913ecb90919b69ab3bbe44ae1a"
+dependencies = [
+ "askama_derive",
+]
+
+[[package]]
+name = "askama_parser"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7db09fde9143e7ac4513358fb32ee32847125b63b18ea715afd487956da715da"
+dependencies = [
+ "rustc-hash",
+ "serde",
+ "serde_derive",
+ "unicode-ident",
+ "winnow",
+]
+
+[[package]]
+name = "async-trait"
+version = "0.1.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.0",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
@@ -20,6 +90,21 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "basic-toml"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
[[package]]
name = "bitflags"
version = "2.13.1"
@@ -33,13 +118,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
-name = "cc"
-version = "1.2.67"
+name = "camino"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f2d30e4173c4026932d51d31d6b0613b1fd3014bf3f9f8943d4ba139c437ba0"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "cargo-platform"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
+checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
dependencies = [
- "find-msvc-tools",
- "shlex",
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror",
]
[[package]]
@@ -49,232 +157,260 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
-name = "cookie"
-version = "0.18.1"
+name = "clap"
+version = "4.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
+checksum = "dd059f9da4f5c36b3787f65d38ccaab1cc315f07b01f89abc8359ee6a8205011"
dependencies = [
- "percent-encoding",
- "time",
- "version_check",
+ "clap_builder",
+ "clap_derive",
]
[[package]]
-name = "cookie_store"
-version = "0.22.1"
+name = "clap_builder"
+version = "4.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206"
+checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"
dependencies = [
- "cookie",
- "document-features",
- "idna",
- "indexmap",
- "log",
- "serde",
- "serde_derive",
- "serde_json",
- "time",
- "url",
+ "anstyle",
+ "clap_lex",
+ "strsim",
]
[[package]]
-name = "crc32fast"
-version = "1.5.0"
+name = "clap_derive"
+version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
dependencies = [
- "cfg-if",
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "cyclops-sdk-core"
+name = "clap_lex"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+
+[[package]]
+name = "cyclops-sdk"
version = "0.1.0"
dependencies = [
+ "async-trait",
+ "camino",
+ "cyclops-sdk-schema",
+ "futures-timer",
"serde",
"serde_json",
"thiserror",
+ "tokio",
+ "uniffi",
"url",
- "wit-bindgen",
]
[[package]]
-name = "cyclops-sdk-host"
+name = "cyclops-sdk-bindgen"
version = "0.1.0"
dependencies = [
- "cyclops-sdk-core",
+ "anyhow",
"serde_json",
- "ureq",
+ "uniffi",
]
[[package]]
-name = "deranged"
-version = "0.5.8"
+name = "cyclops-sdk-schema"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "k8s-openapi",
+ "kube",
+ "schemars",
+ "serde",
+ "serde_json",
+ "serde_yaml",
+ "tempfile",
+ "thiserror",
+ "uniffi",
+]
+
+[[package]]
+name = "darling"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
[[package]]
-name = "displaydoc"
-version = "0.2.6"
+name = "darling_core"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
dependencies = [
+ "ident_case",
"proc-macro2",
"quote",
- "syn",
+ "strsim",
+ "syn 2.0.119",
]
[[package]]
-name = "document-features"
-version = "0.2.12"
+name = "darling_macro"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
dependencies = [
- "litrs",
+ "darling_core",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "equivalent"
-version = "1.0.2"
+name = "defmt"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
+dependencies = [
+ "bitflags 1.3.2",
+ "defmt-macros",
+]
[[package]]
-name = "find-msvc-tools"
-version = "0.1.9"
+name = "defmt-macros"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
+dependencies = [
+ "defmt-parser",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
[[package]]
-name = "flate2"
-version = "1.1.9"
+name = "defmt-parser"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
dependencies = [
- "crc32fast",
- "miniz_oxide",
+ "thiserror",
]
[[package]]
-name = "foldhash"
-version = "0.1.5"
+name = "derive_more"
+version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
[[package]]
-name = "form_urlencoded"
-version = "1.2.2"
+name = "derive_more-impl"
+version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
- "percent-encoding",
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
]
[[package]]
-name = "futures"
-version = "0.3.32"
+name = "displaydoc"
+version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
dependencies = [
- "futures-channel",
- "futures-core",
- "futures-executor",
- "futures-io",
- "futures-sink",
- "futures-task",
- "futures-util",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "futures-channel"
-version = "0.3.32"
+name = "dyn-clone"
+version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
-dependencies = [
- "futures-core",
- "futures-sink",
-]
+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
-name = "futures-core"
-version = "0.3.32"
+name = "equivalent"
+version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
-name = "futures-executor"
-version = "0.3.32"
+name = "errno"
+version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
- "futures-core",
- "futures-task",
- "futures-util",
+ "libc",
+ "windows-sys",
]
[[package]]
-name = "futures-io"
-version = "0.3.32"
+name = "fastrand"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
-name = "futures-macro"
-version = "0.3.32"
+name = "form_urlencoded"
+version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
- "proc-macro2",
- "quote",
- "syn",
+ "percent-encoding",
]
[[package]]
-name = "futures-sink"
-version = "0.3.32"
+name = "fs-err"
+version = "3.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
+checksum = "b91aa448ca50d7e79433bdf3ee8d99215430d2ec02ade5aefab2a073a1822e8a"
+dependencies = [
+ "autocfg",
+]
[[package]]
-name = "futures-task"
-version = "0.3.32"
+name = "futures-timer"
+version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
-
-[[package]]
-name = "futures-util"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
-dependencies = [
- "futures-channel",
- "futures-core",
- "futures-io",
- "futures-macro",
- "futures-sink",
- "futures-task",
- "memchr",
- "pin-project-lite",
- "slab",
-]
+checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
[[package]]
name = "getrandom"
-version = "0.2.17"
+version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
- "wasi",
+ "r-efi",
]
[[package]]
-name = "hashbrown"
-version = "0.15.5"
+name = "glob"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
+
+[[package]]
+name = "goblin"
+version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"
dependencies = [
- "foldhash",
+ "log",
+ "plain",
+ "scroll",
]
[[package]]
@@ -299,12 +435,6 @@ dependencies = [
"itoa",
]
-[[package]]
-name = "httparse"
-version = "1.10.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
-
[[package]]
name = "icu_collections"
version = "2.2.0"
@@ -388,10 +518,10 @@ dependencies = [
]
[[package]]
-name = "id-arena"
-version = "2.3.0"
+name = "ident_case"
+version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
@@ -421,7 +551,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
- "hashbrown 0.17.1",
+ "hashbrown",
"serde",
"serde_core",
]
@@ -433,10 +563,95 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
-name = "leb128fmt"
+name = "jiff"
+version = "0.2.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc43d6fb25860892c78ef7ce2ffed572087a6853ecb60f587f499329717ed7da"
+dependencies = [
+ "defmt",
+ "jiff-core",
+ "jiff-static",
+ "log",
+ "portable-atomic",
+ "portable-atomic-util",
+ "serde_core",
+]
+
+[[package]]
+name = "jiff-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09"
+dependencies = [
+ "defmt",
+]
+
+[[package]]
+name = "jiff-static"
+version = "0.2.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96fb828bff41eeb269a9665f950cb359e8018f7288b8f34db24937ff54ed8fc5"
+dependencies = [
+ "jiff-core",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "k8s-openapi"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c6922f6afe80418dd6019818af5d0d34584c371780ff09b9752370c25b4abb"
+dependencies = [
+ "base64",
+ "jiff",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "kube"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bb9108095346a7096d11feeaff419c75dddcac1b2f59acb38d7bf3d13c3e146"
+dependencies = [
+ "k8s-openapi",
+ "kube-core",
+ "kube-derive",
+]
+
+[[package]]
+name = "kube-core"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1b02f5933ba06140d58c7d6727f6c319f0962ec6a344aa5e21e475e891deaa8"
+dependencies = [
+ "derive_more",
+ "form_urlencoded",
+ "http",
+ "jiff",
+ "k8s-openapi",
+ "schemars",
+ "serde",
+ "serde-value",
+ "serde_json",
+ "thiserror",
+]
+
+[[package]]
+name = "kube-derive"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe171898707dadf1818ef94e81ef57f6beb7edf9ba87b9e814c045dad356c7aa"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "syn 2.0.119",
+]
[[package]]
name = "libc"
@@ -445,16 +660,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
-name = "litemap"
-version = "0.8.2"
+name = "linux-raw-sys"
+version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
-name = "litrs"
-version = "1.0.0"
+name = "litemap"
+version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "log"
@@ -469,20 +684,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
-name = "miniz_oxide"
-version = "0.8.9"
+name = "minimal-lexical"
+version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
- "adler2",
- "simd-adler32",
+ "memchr",
+ "minimal-lexical",
]
[[package]]
-name = "num-conv"
-version = "0.2.2"
+name = "num-traits"
+version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
[[package]]
name = "once_cell"
@@ -490,6 +714,15 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "ordered-float"
+version = "2.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -502,6 +735,27 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "portable-atomic"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
+dependencies = [
+ "portable-atomic",
+]
+
[[package]]
name = "potential_utf"
version = "0.1.5"
@@ -512,86 +766,126 @@ dependencies = [
]
[[package]]
-name = "powerfmt"
-version = "0.2.0"
+name = "proc-macro2"
+version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
[[package]]
-name = "prettyplease"
-version = "0.2.37"
+name = "quote"
+version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
- "syn",
]
[[package]]
-name = "proc-macro2"
-version = "1.0.106"
+name = "r-efi"
+version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "ref-cast"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d"
dependencies = [
- "unicode-ident",
+ "ref-cast-impl",
]
[[package]]
-name = "quote"
-version = "1.0.46"
+name = "ref-cast-impl"
+version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
+checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"
dependencies = [
"proc-macro2",
+ "quote",
+ "syn 3.0.0",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
]
[[package]]
-name = "ring"
-version = "0.17.14"
+name = "rustix"
+version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
- "cc",
- "cfg-if",
- "getrandom",
+ "bitflags 2.13.1",
+ "errno",
"libc",
- "untrusted",
+ "linux-raw-sys",
"windows-sys",
]
[[package]]
-name = "rustls"
-version = "0.23.42"
+name = "ryu"
+version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "schemars"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
dependencies = [
- "log",
- "once_cell",
- "ring",
- "rustls-pki-types",
- "rustls-webpki",
- "subtle",
- "zeroize",
+ "dyn-clone",
+ "ref-cast",
+ "schemars_derive",
+ "serde",
+ "serde_json",
]
[[package]]
-name = "rustls-pki-types"
-version = "1.15.0"
+name = "schemars_derive"
+version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"
+checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"
dependencies = [
- "zeroize",
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 2.0.119",
]
[[package]]
-name = "rustls-webpki"
-version = "0.103.13"
+name = "scroll"
+version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"
dependencies = [
- "ring",
- "rustls-pki-types",
- "untrusted",
+ "scroll_derive",
+]
+
+[[package]]
+name = "scroll_derive"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
@@ -599,35 +893,60 @@ name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
[[package]]
name = "serde"
-version = "1.0.228"
+version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
+[[package]]
+name = "serde-value"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
+dependencies = [
+ "ordered-float",
+ "serde",
+]
+
[[package]]
name = "serde_core"
-version = "1.0.228"
+version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.228"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.0",
+]
+
+[[package]]
+name = "serde_derive_internals"
+version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
]
[[package]]
@@ -644,22 +963,32 @@ dependencies = [
]
[[package]]
-name = "shlex"
-version = "2.0.1"
+name = "serde_spanned"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
[[package]]
-name = "simd-adler32"
-version = "0.3.10"
+name = "serde_yaml"
+version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
[[package]]
-name = "slab"
-version = "0.4.12"
+name = "siphasher"
+version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
[[package]]
name = "smallvec"
@@ -668,13 +997,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
-name = "spdx"
-version = "0.10.9"
+name = "smawk"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3"
-dependencies = [
- "smallvec",
-]
+checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
[[package]]
name = "stable_deref_trait"
@@ -683,10 +1009,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
-name = "subtle"
-version = "2.6.1"
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
@@ -700,64 +1032,67 @@ dependencies = [
]
[[package]]
-name = "synstructure"
-version = "0.13.2"
+name = "syn"
+version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+checksum = "f2fac314a64dc9a36e61a9eb4261a5e9bbfbc922b27e518af97bc32b926cf967"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "unicode-ident",
]
[[package]]
-name = "thiserror"
-version = "2.0.18"
+name = "synstructure"
+version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
- "thiserror-impl",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "thiserror-impl"
-version = "2.0.18"
+name = "tempfile"
+version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
- "proc-macro2",
- "quote",
- "syn",
+ "fastrand",
+ "getrandom",
+ "once_cell",
+ "rustix",
+ "windows-sys",
]
[[package]]
-name = "time"
-version = "0.3.53"
+name = "textwrap"
+version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50"
+checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"
dependencies = [
- "deranged",
- "num-conv",
- "powerfmt",
- "serde_core",
- "time-core",
- "time-macros",
+ "smawk",
]
[[package]]
-name = "time-core"
-version = "0.1.9"
+name = "thiserror"
+version = "2.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
+dependencies = [
+ "thiserror-impl",
+]
[[package]]
-name = "time-macros"
-version = "0.2.31"
+name = "thiserror-impl"
+version = "2.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f"
+checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
dependencies = [
- "num-conv",
- "time-core",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.0",
]
[[package]]
@@ -771,310 +1106,247 @@ dependencies = [
]
[[package]]
-name = "unicode-ident"
-version = "1.0.24"
+name = "tokio"
+version = "1.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
-
-[[package]]
-name = "untrusted"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
-
-[[package]]
-name = "ureq"
-version = "3.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
+checksum = "d988bcd52dbe076d3d46903332f58c912b87a2c49b1428419a5845154762ffee"
dependencies = [
- "base64",
- "cookie_store",
- "flate2",
- "log",
- "percent-encoding",
- "rustls",
- "rustls-pki-types",
- "serde",
- "serde_json",
- "ureq-proto",
- "utf8-zero",
- "webpki-roots",
+ "pin-project-lite",
+ "tokio-macros",
]
[[package]]
-name = "ureq-proto"
-version = "0.6.0"
+name = "tokio-macros"
+version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
+checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"
dependencies = [
- "base64",
- "http",
- "httparse",
- "log",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "url"
-version = "2.5.8"
+name = "toml"
+version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"
dependencies = [
- "form_urlencoded",
- "idna",
- "percent-encoding",
- "serde",
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
]
[[package]]
-name = "utf8-zero"
-version = "0.8.1"
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
[[package]]
-name = "utf8_iter"
-version = "1.0.4"
+name = "toml_parser"
+version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
+dependencies = [
+ "winnow",
+]
[[package]]
-name = "version_check"
-version = "0.9.5"
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]]
-name = "wasi"
-version = "0.11.1+wasi-snapshot-preview1"
+name = "unicode-ident"
+version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
-name = "wasm-encoder"
-version = "0.225.0"
+name = "uniffi"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f7eac0445cac73bcf09e6a97f83248d64356dccf9f2b100199769b6b42464e5"
+checksum = "a782a48d72cfd7a2d65cfc7c691dbf5375c43104b3c195f7eccc716dcc3540c8"
dependencies = [
- "leb128fmt",
- "wasmparser",
+ "anyhow",
+ "camino",
+ "cargo_metadata",
+ "clap",
+ "uniffi_bindgen",
+ "uniffi_core",
+ "uniffi_macros",
+ "uniffi_pipeline",
]
[[package]]
-name = "wasm-metadata"
-version = "0.225.0"
+name = "uniffi_bindgen"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1d20d0bf2c73c32a5114cf35a5c10ccf9f9aa37a3a2c0114b3e11cbf6faac12"
+checksum = "533b0312c73e3b54eb78a4b257ceae390962dd4767995778309a74644643f9ac"
dependencies = [
"anyhow",
+ "askama",
+ "camino",
+ "cargo_metadata",
+ "fs-err",
+ "glob",
+ "goblin",
+ "heck",
"indexmap",
+ "once_cell",
"serde",
- "serde_derive",
- "serde_json",
- "spdx",
- "url",
- "wasm-encoder",
- "wasmparser",
+ "tempfile",
+ "textwrap",
+ "toml",
+ "uniffi_internal_macros",
+ "uniffi_meta",
+ "uniffi_pipeline",
+ "uniffi_udl",
]
[[package]]
-name = "wasmparser"
-version = "0.225.0"
+name = "uniffi_core"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36e5456165f81e64cb9908a0fe9b9d852c2c74582aa3fe2be3c2da57f937d3ae"
+checksum = "8e32e261c5b0dfaba6488f536e71957dddd6b1a498ac7eb791bee56b60a086be"
dependencies = [
- "bitflags",
- "hashbrown 0.15.5",
- "indexmap",
- "semver",
+ "anyhow",
+ "bytes",
+ "once_cell",
+ "static_assertions",
]
[[package]]
-name = "webpki-roots"
-version = "1.0.8"
+name = "uniffi_internal_macros"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
+checksum = "84ae78069a5e6772ef694fd5bdb628532c88d2c2f0e7142bf6a384636eadb1af"
dependencies = [
- "rustls-pki-types",
+ "anyhow",
+ "indexmap",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "windows-sys"
-version = "0.52.0"
+name = "uniffi_macros"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+checksum = "330be6770532e86320df31f54c70bb0be67588594e8e77fa56e9083a3fed5d0d"
dependencies = [
- "windows-targets",
+ "camino",
+ "fs-err",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 2.0.119",
+ "toml",
+ "uniffi_meta",
]
[[package]]
-name = "windows-targets"
-version = "0.52.6"
+name = "uniffi_meta"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+checksum = "78de021f5547e56ab16c665a49d67d4fd3d31e77422f7739a2e9359d328cd9e7"
dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_gnullvm",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
+ "anyhow",
+ "siphasher",
+ "uniffi_internal_macros",
+ "uniffi_pipeline",
]
[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
-
-[[package]]
-name = "windows_i686_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.52.6"
+name = "uniffi_pipeline"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+checksum = "3f8201bb1907ed8a42d80e11cbc25c8a033e7a31c3cff1d911f56eedb81d4948"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "tempfile",
+ "uniffi_internal_macros",
+]
[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.52.6"
+name = "uniffi_udl"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+checksum = "a6e57996bc58009cc29bf04845d627ae313c2547b87171c1c349d6c51a1656c0"
+dependencies = [
+ "anyhow",
+ "textwrap",
+ "uniffi_meta",
+ "weedle2",
+]
[[package]]
-name = "windows_x86_64_msvc"
-version = "0.52.6"
+name = "unsafe-libyaml"
+version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]]
-name = "wit-bindgen"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e4dd9a372b25d6f35456b0a730d2adabeb0c4878066ba8f8089800349be6ecb5"
-dependencies = [
- "wit-bindgen-rt",
- "wit-bindgen-rust-macro",
-]
-
-[[package]]
-name = "wit-bindgen-core"
-version = "0.39.0"
+name = "url"
+version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f108fa9b77a346372858b30c11ea903680e7e2b9d820b1a5883e9d530bf51c7e"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
- "anyhow",
- "heck",
- "wit-parser",
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
]
[[package]]
-name = "wit-bindgen-rt"
-version = "0.39.0"
+name = "utf8_iter"
+version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
-dependencies = [
- "bitflags",
- "futures",
- "once_cell",
-]
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
-name = "wit-bindgen-rust"
-version = "0.39.0"
+name = "weedle2"
+version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5ba5b852e976d35dbf6cb745746bf1bd4fc26782bab1e0c615fc71a7d8aac05"
+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"
dependencies = [
- "anyhow",
- "heck",
- "indexmap",
- "prettyplease",
- "syn",
- "wasm-metadata",
- "wit-bindgen-core",
- "wit-component",
+ "nom",
]
[[package]]
-name = "wit-bindgen-rust-macro"
-version = "0.39.0"
+name = "windows-link"
+version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "401529c9af9304a20ed99fa01799e467b7d37727126f0c9a958895471268ad7a"
-dependencies = [
- "anyhow",
- "prettyplease",
- "proc-macro2",
- "quote",
- "syn",
- "wit-bindgen-core",
- "wit-bindgen-rust",
-]
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
-name = "wit-component"
-version = "0.225.0"
+name = "windows-sys"
+version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2505c917564c1d74774563bbcd3e4f8c216a6508050862fd5f449ee56e3c5125"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
- "anyhow",
- "bitflags",
- "indexmap",
- "log",
- "serde",
- "serde_derive",
- "serde_json",
- "wasm-encoder",
- "wasm-metadata",
- "wasmparser",
- "wit-parser",
+ "windows-link",
]
[[package]]
-name = "wit-parser"
-version = "0.225.0"
+name = "winnow"
+version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebefaa234e47224f10ce60480c5bfdece7497d0f3b87a12b41ff39e5c8377a78"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
- "anyhow",
- "id-arena",
- "indexmap",
- "log",
- "semver",
- "serde",
- "serde_derive",
- "serde_json",
- "unicode-xid",
- "wasmparser",
+ "memchr",
]
[[package]]
@@ -1102,7 +1374,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
"synstructure",
]
@@ -1123,16 +1395,10 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
"synstructure",
]
-[[package]]
-name = "zeroize"
-version = "1.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
-
[[package]]
name = "zerotrie"
version = "0.2.4"
@@ -1163,7 +1429,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
]
[[package]]
diff --git a/libs/fleet/Cargo.toml b/libs/fleet/Cargo.toml
new file mode 100644
index 0000000000..db14fb737c
--- /dev/null
+++ b/libs/fleet/Cargo.toml
@@ -0,0 +1,23 @@
+[workspace]
+members = ["sdk-schema", "sdk", "bindgen-cli"]
+resolver = "2"
+
+[workspace.package]
+edition = "2024"
+license = "MIT"
+rust-version = "1.97.0"
+
+[workspace.dependencies]
+anyhow = "1.0"
+async-trait = "0.1"
+futures-timer = "3.0.4"
+k8s-openapi = { version = "0.28.0", features = ["v1_32"] }
+kube = { version = "4.0.0", default-features = false, features = ["derive"] }
+schemars = "1.2.1"
+serde = { version = "1.0", features = ["derive", "rc"] }
+serde_json = "1.0"
+serde_yaml = "0.9"
+thiserror = "2.0"
+tokio = { version = "1.0", features = ["macros", "rt-multi-thread", "sync"] }
+uniffi = "0.32.0"
+url = "2.5"
diff --git a/libs/fleet/bindgen-cli/Cargo.toml b/libs/fleet/bindgen-cli/Cargo.toml
new file mode 100644
index 0000000000..bb0dcdef5e
--- /dev/null
+++ b/libs/fleet/bindgen-cli/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "cyclops-sdk-bindgen"
+version = "0.1.0"
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[[bin]]
+name = "cyclops-sdk-bindgen"
+path = "main.rs"
+
+[dependencies]
+anyhow.workspace = true
+serde_json.workspace = true
+uniffi = { workspace = true, features = ["cli"] }
diff --git a/libs/fleet/bindgen-cli/main.rs b/libs/fleet/bindgen-cli/main.rs
new file mode 100644
index 0000000000..ed8cb3d7d3
--- /dev/null
+++ b/libs/fleet/bindgen-cli/main.rs
@@ -0,0 +1,345 @@
+use std::{
+ collections::HashSet,
+ env, fs,
+ path::{Path, PathBuf},
+ process,
+};
+
+use anyhow::{Context, Result, bail};
+use serde_json::Value;
+
+fn main() {
+ let command = env::args().nth(1);
+ let result = match command.as_deref() {
+ Some("resolve-cdylib") => resolve_cdylib_command(),
+ Some("resolve-build-messages") => resolve_build_messages_command(),
+ _ => {
+ uniffi::uniffi_bindgen_main();
+ return;
+ }
+ };
+
+ if let Err(error) = result {
+ eprintln!("error: {error:#}");
+ process::exit(1);
+ }
+}
+
+fn resolve_cdylib_command() -> Result<()> {
+ let arguments = ResolverArguments::parse(true)?;
+ let sdk_manifest = fs::canonicalize(&arguments.sdk_manifest).with_context(|| {
+ format!(
+ "could not canonicalize SDK manifest {}",
+ arguments.sdk_manifest.display()
+ )
+ })?;
+ let metadata = fs::read_to_string(&arguments.metadata).with_context(|| {
+ format!(
+ "could not read Cargo metadata {}",
+ arguments.metadata.display()
+ )
+ })?;
+ let build_messages = fs::read_to_string(&arguments.build_messages).with_context(|| {
+ format!(
+ "could not read Cargo build messages {}",
+ arguments.build_messages.display()
+ )
+ })?;
+
+ let package_id = resolve_package_id(&metadata, &sdk_manifest)?;
+ let library = resolve_cdylib_from_messages(&build_messages, &package_id)?;
+ println!("{}", library.display());
+ Ok(())
+}
+
+fn resolve_build_messages_command() -> Result<()> {
+ let arguments = ResolverArguments::parse(false)?;
+ let package_id = arguments
+ .package_id
+ .as_deref()
+ .expect("required by ResolverArguments::parse");
+ let build_messages = fs::read_to_string(&arguments.build_messages).with_context(|| {
+ format!(
+ "could not read Cargo build messages {}",
+ arguments.build_messages.display()
+ )
+ })?;
+
+ let library = resolve_cdylib_from_messages(&build_messages, package_id)?;
+ println!("{}", library.display());
+ Ok(())
+}
+
+struct ResolverArguments {
+ sdk_manifest: PathBuf,
+ metadata: PathBuf,
+ build_messages: PathBuf,
+ package_id: Option<String>,
+}
+
+impl ResolverArguments {
+ fn parse(require_metadata: bool) -> Result<Self> {
+ let mut sdk_manifest = None;
+ let mut metadata = None;
+ let mut build_messages = None;
+ let mut package_id = None;
+ let mut arguments = env::args().skip(2);
+
+ while let Some(argument) = arguments.next() {
+ let value = arguments
+ .next()
+ .with_context(|| format!("missing value for {argument}"))?;
+ match argument.as_str() {
+ "--sdk-manifest" => sdk_manifest = Some(PathBuf::from(value)),
+ "--metadata" => metadata = Some(PathBuf::from(value)),
+ "--build-messages" => build_messages = Some(PathBuf::from(value)),
+ "--package-id" => package_id = Some(value),
+ _ => bail!("unknown resolver option {argument}"),
+ }
+ }
+
+ let build_messages = build_messages.context("missing required --build-messages")?;
+ if require_metadata {
+ Ok(Self {
+ sdk_manifest: sdk_manifest.context("missing required --sdk-manifest")?,
+ metadata: metadata.context("missing required --metadata")?,
+ build_messages,
+ package_id,
+ })
+ } else {
+ Ok(Self {
+ sdk_manifest: PathBuf::new(),
+ metadata: PathBuf::new(),
+ build_messages,
+ package_id: Some(package_id.context("missing required --package-id")?),
+ })
+ }
+ }
+}
+
+fn resolve_package_id(metadata_json: &str, sdk_manifest: &Path) -> Result<String> {
+ let metadata: Value =
+ serde_json::from_str(metadata_json).context("could not parse Cargo metadata JSON")?;
+ let workspace_members = metadata
+ .get("workspace_members")
+ .and_then(Value::as_array)
+ .context("Cargo metadata did not contain workspace_members")?
+ .iter()
+ .filter_map(Value::as_str)
+ .collect::<HashSet<_>>();
+ let packages = metadata
+ .get("packages")
+ .and_then(Value::as_array)
+ .context("Cargo metadata did not contain packages")?;
+
+ let canonical_packages = packages
+ .iter()
+ .filter_map(|package| {
+ let id = package.get("id")?.as_str()?;
+ let manifest_path = package.get("manifest_path")?.as_str()?;
+ (Path::new(manifest_path) == sdk_manifest).then_some(id)
+ })
+ .collect::<Vec<_>>();
+ if canonical_packages.is_empty() {
+ bail!(
+ "Cargo metadata did not contain the canonical SDK package manifest {}",
+ sdk_manifest.display()
+ );
+ }
+
+ let workspace_candidates = canonical_packages
+ .iter()
+ .copied()
+ .filter(|package_id| workspace_members.contains(package_id))
+ .collect::<Vec<_>>();
+ match workspace_candidates.as_slice() {
+ [package_id] => Ok((*package_id).to_owned()),
+ [] => bail!(
+ "Cargo package with canonical SDK manifest {} is not a workspace member",
+ sdk_manifest.display()
+ ),
+ _ => bail!(
+ "Cargo metadata identified multiple workspace packages with canonical SDK manifest {}",
+ sdk_manifest.display()
+ ),
+ }
+}
+
+fn resolve_cdylib_from_messages(messages_jsonl: &str, package_id: &str) -> Result<PathBuf> {
+ let artifacts = messages_jsonl
+ .lines()
+ .enumerate()
+ .filter(|(_, line)| !line.trim().is_empty())
+ .map(|(line_number, line)| {
+ serde_json::from_str::<Value>(line).with_context(|| {
+ format!(
+ "could not parse Cargo build JSON at line {}",
+ line_number + 1
+ )
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let matching_artifacts = artifacts
+ .iter()
+ .filter(|artifact| is_matching_cdylib_artifact(artifact, package_id))
+ .collect::<Vec<_>>();
+
+ let artifact = match matching_artifacts.as_slice() {
+ [] => bail!("no matching compiler-artifact record for cyclops-sdk package {package_id}"),
+ [artifact] => *artifact,
+ _ => bail!(
+ "multiple matching compiler-artifact records for cyclops-sdk package {package_id}"
+ ),
+ };
+ let filenames = artifact
+ .get("filenames")
+ .and_then(Value::as_array)
+ .context("matching compiler-artifact record did not contain filenames")?;
+ let libraries = filenames
+ .iter()
+ .filter_map(Value::as_str)
+ .filter(|filename| is_supported_cdylib_filename(filename))
+ .collect::<Vec<_>>();
+
+ match libraries.as_slice() {
+ [] => bail!(
+ "matching compiler-artifact record has no host library filename (.so, .dylib, or .dll)"
+ ),
+ [library] => Ok(PathBuf::from(library)),
+ _ => bail!(
+ "matching compiler-artifact record has multiple host library filenames (.so, .dylib, or .dll)"
+ ),
+ }
+}
+
+fn is_matching_cdylib_artifact(artifact: &Value, package_id: &str) -> bool {
+ artifact.get("reason").and_then(Value::as_str) == Some("compiler-artifact")
+ && artifact.get("package_id").and_then(Value::as_str) == Some(package_id)
+ && artifact
+ .get("target")
+ .and_then(|target| target.get("name"))
+ .and_then(Value::as_str)
+ == Some("cyclops_sdk")
+ && artifact
+ .get("target")
+ .and_then(|target| target.get("crate_types"))
+ .and_then(Value::as_array)
+ .is_some_and(|crate_types| {
+ crate_types
+ .iter()
+ .any(|kind| kind.as_str() == Some("cdylib"))
+ })
+}
+
+fn is_supported_cdylib_filename(filename: &str) -> bool {
+ matches!(
+ Path::new(filename)
+ .extension()
+ .and_then(|extension| extension.to_str()),
+ Some("so" | "dylib" | "dll")
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use std::path::Path;
+
+ use super::{resolve_cdylib_from_messages, resolve_package_id};
+
+ const SDK_MANIFEST: &str = "/workspace/cyclops-cs/sdk/Cargo.toml";
+
+ #[test]
+ fn requires_the_canonical_manifest_to_be_a_workspace_member() {
+ let exact_member = include_str!("tests/fixtures/metadata-exact-workspace-member.json");
+ assert_eq!(
+ resolve_package_id(exact_member, Path::new(SDK_MANIFEST)).unwrap(),
+ "exact 0.1.0"
+ );
+
+ let canonical_absent = include_str!("tests/fixtures/metadata-canonical-absent.json");
+ let error = resolve_package_id(canonical_absent, Path::new(SDK_MANIFEST))
+ .unwrap_err()
+ .to_string();
+ assert!(
+ error.contains("did not contain the canonical SDK package"),
+ "{error}"
+ );
+
+ let canonical_not_member =
+ include_str!("tests/fixtures/metadata-canonical-not-member.json");
+ let error = resolve_package_id(canonical_not_member, Path::new(SDK_MANIFEST))
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("not a workspace member"), "{error}");
+
+ let ambiguous = include_str!("tests/fixtures/metadata-ambiguous-canonical-members.json");
+ let error = resolve_package_id(ambiguous, Path::new(SDK_MANIFEST))
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("multiple workspace packages"), "{error}");
+ }
+
+ #[test]
+ fn resolves_the_exact_package_after_unrelated_artifacts_and_diagnostics() {
+ let metadata = r#"{
+ "workspace_members": ["wrong 0.1.0", "exact 0.1.0"],
+ "packages": [
+ {"id":"wrong 0.1.0","name":"cyclops-sdk","manifest_path":"/workspace/other/Cargo.toml"},
+ {"manifest_path":"/workspace/cyclops-cs/sdk/Cargo.toml","name":"cyclops-sdk","id":"exact 0.1.0"}
+ ]
+ }"#;
+ let messages = r#"
+{"reason":"compiler-message","package_id":"dependency 0.1.0"}
+{"target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/wrong/libcyclops_sdk.so"],"package_id":"wrong 0.1.0","reason":"compiler-artifact"}
+{"reason":"build-script-executed","package_id":"dependency 0.1.0"}
+{"filenames":["/tmp/exact/libcyclops_sdk.rlib","/tmp/exact/libcyclops_sdk\u002eso"],"reason":"compiler-artifact","package_id":"exact 0.1.0","target":{"crate_types":["lib","cdylib"],"name":"cyclops_sdk"}}
+"#;
+
+ let package_id = resolve_package_id(metadata, Path::new(SDK_MANIFEST)).unwrap();
+ let library = resolve_cdylib_from_messages(messages, &package_id).unwrap();
+
+ assert_eq!(package_id, "exact 0.1.0");
+ assert_eq!(library, Path::new("/tmp/exact/libcyclops_sdk.so"));
+ }
+
+ #[test]
+ fn rejects_ambiguous_artifacts_and_library_filenames() {
+ let multiple_artifacts = r#"
+{"reason":"compiler-artifact","package_id":"exact","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/one/libcyclops_sdk.so"]}
+{"reason":"compiler-artifact","package_id":"exact","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/two/libcyclops_sdk.so"]}
+"#;
+ assert!(
+ resolve_cdylib_from_messages(multiple_artifacts, "exact")
+ .unwrap_err()
+ .to_string()
+ .contains("multiple matching compiler-artifact records")
+ );
+
+ let multiple_filenames = r#"
+{"reason":"compiler-artifact","package_id":"exact","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/exact/libcyclops_sdk.so","/tmp/exact/cyclops_sdk.dll"]}
+"#;
+ assert!(
+ resolve_cdylib_from_messages(multiple_filenames, "exact")
+ .unwrap_err()
+ .to_string()
+ .contains("multiple host library filenames")
+ );
+ }
+
+ #[test]
+ fn rejects_missing_artifacts_and_accepts_cross_abi_extensions() {
+ let no_match = r#"{"reason":"compiler-message","package_id":"exact"}"#;
+ assert!(
+ resolve_cdylib_from_messages(no_match, "exact")
+ .unwrap_err()
+ .to_string()
+ .contains("no matching compiler-artifact record")
+ );
+
+ let windows_cdylib = r#"{"reason":"compiler-artifact","package_id":"exact","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["C:\\target\\release\\cyclops_sdk.dll"]}"#;
+ assert_eq!(
+ resolve_cdylib_from_messages(windows_cdylib, "exact").unwrap(),
+ Path::new(r"C:\target\release\cyclops_sdk.dll")
+ );
+ }
+}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/metadata-ambiguous-canonical-members.json b/libs/fleet/bindgen-cli/tests/fixtures/metadata-ambiguous-canonical-members.json
new file mode 100644
index 0000000000..ac8c098574
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/metadata-ambiguous-canonical-members.json
@@ -0,0 +1,15 @@
+{
+ "workspace_members": ["exact-a 0.1.0", "exact-b 0.1.0"],
+ "packages": [
+ {
+ "id": "exact-a 0.1.0",
+ "name": "cyclops-sdk",
+ "manifest_path": "/workspace/cyclops-cs/sdk/Cargo.toml"
+ },
+ {
+ "id": "exact-b 0.1.0",
+ "name": "cyclops-sdk",
+ "manifest_path": "/workspace/cyclops-cs/sdk/Cargo.toml"
+ }
+ ]
+}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-absent.json b/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-absent.json
new file mode 100644
index 0000000000..67fda128f6
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-absent.json
@@ -0,0 +1,10 @@
+{
+ "packages": [
+ {
+ "name": "cyclops-sdk",
+ "manifest_path": "/workspace/other/Cargo.toml",
+ "id": "wrong 0.1.0"
+ }
+ ],
+ "workspace_members": ["wrong 0.1.0"]
+}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-not-member.json b/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-not-member.json
new file mode 100644
index 0000000000..658ffb6962
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/metadata-canonical-not-member.json
@@ -0,0 +1,15 @@
+{
+ "workspace_members": ["wrong 0.1.0"],
+ "packages": [
+ {
+ "id": "exact 0.1.0",
+ "manifest_path": "/workspace/cyclops-cs/sdk/Cargo.toml",
+ "name": "cyclops-sdk"
+ },
+ {
+ "manifest_path": "/workspace/other/Cargo.toml",
+ "id": "wrong 0.1.0",
+ "name": "cyclops-sdk"
+ }
+ ]
+}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/metadata-exact-workspace-member.json b/libs/fleet/bindgen-cli/tests/fixtures/metadata-exact-workspace-member.json
new file mode 100644
index 0000000000..f2e00b361a
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/metadata-exact-workspace-member.json
@@ -0,0 +1,15 @@
+{
+ "packages": [
+ {
+ "manifest_path": "/workspace/other/Cargo.toml",
+ "name": "cyclops-sdk",
+ "id": "wrong 0.1.0"
+ },
+ {
+ "name": "cyclops-sdk",
+ "id": "exact 0.1.0",
+ "manifest_path": "/workspace/cyclops-cs/sdk/Cargo.toml"
+ }
+ ],
+ "workspace_members": ["wrong 0.1.0", "exact 0.1.0"]
+}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-artifacts.jsonl b/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-artifacts.jsonl
new file mode 100644
index 0000000000..2cf7dc33f4
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-artifacts.jsonl
@@ -0,0 +1,2 @@
+{"reason":"compiler-artifact","package_id":"exact 0.1.0","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/one/libcyclops_sdk.so"]}
+{"reason":"compiler-artifact","package_id":"exact 0.1.0","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/two/libcyclops_sdk.so"]}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-libraries.jsonl b/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-libraries.jsonl
new file mode 100644
index 0000000000..4c631bb441
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/resolver-multiple-libraries.jsonl
@@ -0,0 +1 @@
+{"reason":"compiler-artifact","package_id":"exact 0.1.0","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/exact/libcyclops_sdk.so","/tmp/exact/cyclops_sdk.dll"]}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/resolver-no-match.jsonl b/libs/fleet/bindgen-cli/tests/fixtures/resolver-no-match.jsonl
new file mode 100644
index 0000000000..dfb45ac69f
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/resolver-no-match.jsonl
@@ -0,0 +1,2 @@
+{"reason":"compiler-message","package_id":"exact 0.1.0","message":{"rendered":"only a diagnostic"}}
+{"reason":"compiler-artifact","package_id":"wrong 0.1.0","target":{"name":"cyclops_sdk","crate_types":["cdylib"]},"filenames":["/tmp/wrong/libcyclops_sdk.so"]}
diff --git a/libs/fleet/bindgen-cli/tests/fixtures/resolver-valid-reordered.jsonl b/libs/fleet/bindgen-cli/tests/fixtures/resolver-valid-reordered.jsonl
new file mode 100644
index 0000000000..76cc78f115
--- /dev/null
+++ b/libs/fleet/bindgen-cli/tests/fixtures/resolver-valid-reordered.jsonl
@@ -0,0 +1,5 @@
+{"reason":"compiler-message","package_id":"dependency 0.1.0","message":{"rendered":"diagnostic before"}}
+{"filenames":["/tmp/wrong/libcyclops_sdk.so"],"target":{"crate_types":["cdylib"],"name":"cyclops_sdk"},"package_id":"wrong 0.1.0","reason":"compiler-artifact"}
+{"message":{"rendered":"diagnostic between"},"reason":"compiler-message","package_id":"dependency 0.1.0"}
+{"target":{"name":"cyclops_sdk","crate_types":["lib","cdylib"]},"reason":"compiler-artifact","filenames":["/tmp/exact/libcyclops_sdk.rlib","/tmp/exact/libcyclops_sdk\u002eso"],"package_id":"exact 0.1.0"}
+{"reason":"build-finished","success":true}
diff --git a/libs/fleet/docs/sdk-schema-flow.svg b/libs/fleet/docs/sdk-schema-flow.svg
deleted file mode 100644
index 93700aab75..0000000000
--- a/libs/fleet/docs/sdk-schema-flow.svg
+++ /dev/null
@@ -1,59 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1080" viewBox="0 0 1600 1080" role="img" aria-labelledby="title desc">
- <title id="title">Cyclops multi-language SDK schema and runtime flow</title>
- <desc id="desc">Kubernetes CRDs generate shared plumbing types for WIT, Rust, TypeScript, Python, and Go. Handwritten porcelain operations use those types. Language bindings call the Rust core, which constructs Kubernetes resources, authenticates requests, and waits for claims to bind into sandboxes.</desc>
- <defs>
- <linearGradient id="background" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f7f1e6"/><stop offset="0.56" stop-color="#edf3e8"/><stop offset="1" stop-color="#e7eff0"/></linearGradient>
- <linearGradient id="sourceFill" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#182724"/><stop offset="1" stop-color="#29483f"/></linearGradient>
- <linearGradient id="coreFill" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#d9633b"/><stop offset="1" stop-color="#bd3f2a"/></linearGradient>
- <pattern id="grid" width="28" height="28" patternUnits="userSpaceOnUse"><path d="M 28 0 L 0 0 0 28" fill="none" stroke="#17352f" stroke-opacity="0.05" stroke-width="1"/></pattern>
- <filter id="shadow" x="-20%" y="-20%" width="140%" height="150%"><feDropShadow dx="0" dy="8" stdDeviation="10" flood-color="#18332e" flood-opacity="0.13"/></filter>
- <marker id="arrowDark" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#24433b"/></marker>
- <marker id="arrowOrange" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#cf5335"/></marker>
- <style>
- .display { font-family: Georgia, 'Times New Roman', serif; }
- .sans { font-family: 'Trebuchet MS', 'Segoe UI', sans-serif; }
- .mono { font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; }
- .eyebrow { font-size: 14px; font-weight: 700; }
- .section { font-size: 14px; font-weight: 700; }
- .card-title { font-size: 23px; font-weight: 700; }
- .body { font-size: 16px; }
- .small { font-size: 14px; }
- .tiny { font-size: 12px; }
- .muted { fill: #60716c; }
- .ink { fill: #182724; }
- .cream { fill: #fffaf1; }
- .line { fill: none; stroke: #24433b; stroke-width: 3; marker-end: url(#arrowDark); }
- .line-orange { fill: none; stroke: #cf5335; stroke-width: 3; marker-end: url(#arrowOrange); }
- .dash { stroke-dasharray: 8 8; }
- </style>
- </defs>
- <rect width="1600" height="1080" fill="url(#background)"/><rect width="1600" height="1080" fill="url(#grid)"/>
- <circle cx="1480" cy="104" r="190" fill="#d9633b" opacity="0.08"/><circle cx="92" cy="990" r="220" fill="#497b68" opacity="0.08"/>
- <g class="sans">
- <text x="76" y="62" class="eyebrow" fill="#bd4c31">Cyclops SDK architecture</text>
- <text x="76" y="118" class="display ink" font-size="46" font-weight="700">One schema. Many languages. One core.</text>
- <text x="78" y="151" class="body muted">Generated plumbing stays synchronized with Kubernetes; handwritten porcelain owns behavior.</text>
- <g transform="translate(1258 55)"><rect width="266" height="88" rx="20" fill="#fffaf1" stroke="#d6cbbc"/><circle cx="35" cy="31" r="8" fill="#d9633b"/><text x="55" y="36" class="small ink" font-weight="700">Generated plumbing</text><line x1="27" y1="62" x2="43" y2="62" stroke="#24433b" stroke-width="3" stroke-dasharray="5 4"/><text x="55" y="67" class="small muted">Handwritten porcelain</text></g>
- <text x="76" y="216" class="section" fill="#526660">Build time · schema flow</text><line x1="76" y1="229" x2="1524" y2="229" stroke="#72847e" stroke-opacity="0.35"/>
- <g transform="translate(76 262)"><rect width="292" height="248" rx="26" fill="url(#sourceFill)"/><rect x="22" y="22" width="132" height="28" rx="14" fill="#f1b14d"/><text x="88" y="41" class="tiny" text-anchor="middle" fill="#182724" font-weight="700">SOURCE OF TRUTH</text><text x="24" y="87" class="card-title cream">Kubernetes CRDs</text><text x="24" y="119" class="mono small" fill="#d4e3dc">clusters/base/osgym/</text><text x="24" y="141" class="mono small" fill="#d4e3dc">crd.yaml</text><line x1="24" y1="164" x2="268" y2="164" stroke="#fffaf1" stroke-opacity="0.2"/><text x="24" y="194" class="small" fill="#fffaf1">Pool <tspan fill="#91c5ae">spec schema</tspan></text><text x="24" y="219" class="small" fill="#fffaf1">Claim <tspan fill="#91c5ae">spec schema</tspan></text></g>
- <path d="M 368 386 C 402 386, 414 386, 444 386" class="line-orange"/><text x="406" y="368" class="tiny" text-anchor="middle" fill="#bd4c31" font-weight="700">READ</text>
- <g transform="translate(444 283)"><rect width="286" height="206" rx="26" fill="#fffaf1" stroke="#d6cbbc"/><rect x="22" y="20" width="104" height="28" rx="14" fill="#f2d28f"/><text x="74" y="39" class="tiny ink" text-anchor="middle" font-weight="700">GENERATOR</text><text x="24" y="82" class="card-title ink">Schema generator</text><text x="24" y="111" class="mono small muted">sdk-schema-generator</text><text x="24" y="146" class="small ink">Parses OpenAPI v3 schema</text><text x="24" y="171" class="small ink">Preserves fields, enums, lists, maps</text></g>
- <path d="M 730 386 C 765 386, 770 386, 800 386" class="line-orange"/><text x="765" y="368" class="tiny" text-anchor="middle" fill="#bd4c31" font-weight="700">EMIT</text>
- <g transform="translate(800 251)"><rect width="724" height="270" rx="26" fill="#fffaf1" stroke="#d6cbbc"/><text x="26" y="48" class="card-title ink">Generated plumbing</text><text x="26" y="73" class="small muted">The same PoolSpec and ClaimSpec shape everywhere.</text>
- <g transform="translate(26 96)"><rect width="206" height="139" rx="18" fill="#e3eee8" stroke="#a9c5b7"/><text x="18" y="31" class="small ink" font-weight="700">WIT types</text><text x="18" y="58" class="mono tiny muted">generated-crd.wit</text><text x="18" y="90" class="mono small ink">pool-spec</text><text x="18" y="115" class="mono small ink">claim-spec</text></g>
- <g transform="translate(252 96)"><rect width="210" height="139" rx="18" fill="#eef1dc" stroke="#c7cc9d"/><text x="18" y="31" class="small ink" font-weight="700">Rust core models</text><text x="18" y="58" class="mono tiny muted">generated_crd.rs</text><text x="18" y="90" class="mono tiny muted">generated_crd_</text><text x="18" y="110" class="mono tiny muted">component.rs</text></g>
- <g transform="translate(482 96)"><rect width="216" height="139" rx="18" fill="#f7e3d8" stroke="#dfb7a4"/><text x="18" y="31" class="small ink" font-weight="700">Language types</text><text x="18" y="61" class="small ink">TypeScript</text><text x="18" y="86" class="small ink">Python</text><text x="18" y="111" class="small ink">Go</text></g>
- </g>
- <g transform="translate(76 550)"><rect width="1448" height="88" rx="22" fill="#fffaf1" fill-opacity="0.72" stroke="#b8c5bd" stroke-dasharray="8 8"/><text x="24" y="35" class="section" fill="#526660">Handwritten porcelain WIT</text><text x="24" y="62" class="mono small ink">create-pool({ namespace, spec }) · create-claim({ pool, spec? }) · CRUD · wait-claim</text><text x="1418" y="51" class="small" text-anchor="end" fill="#60716c">Stable intent, generated data</text></g>
- <text x="76" y="696" class="section" fill="#526660">Runtime · request flow</text><line x1="76" y1="709" x2="1524" y2="709" stroke="#72847e" stroke-opacity="0.35"/>
- <g transform="translate(76 749)"><rect width="250" height="226" rx="26" fill="#fffaf1" stroke="#d6cbbc"/><text x="24" y="42" class="card-title ink">Your application</text><text x="24" y="74" class="small muted">Choose any binding</text><g transform="translate(24 96)"><rect width="89" height="36" rx="18" fill="#dce9e2"/><text x="44.5" y="23" class="small ink" text-anchor="middle">Python</text><rect x="99" width="103" height="36" rx="18" fill="#f3e2c2"/><text x="150.5" y="23" class="small ink" text-anchor="middle">TypeScript</text><rect y="48" width="89" height="36" rx="18" fill="#e4ebcd"/><text x="44.5" y="71" class="small ink" text-anchor="middle">Go</text><rect x="99" y="48" width="103" height="36" rx="18" fill="#f2d9ce"/><text x="150.5" y="71" class="small ink" text-anchor="middle">Rust</text></g><text x="24" y="202" class="mono tiny muted">PoolSpec / ClaimSpec</text></g>
- <path d="M 326 862 C 352 862, 363 862, 387 862" class="line"/><text x="356" y="843" class="tiny" text-anchor="middle" fill="#526660" font-weight="700">CALL</text>
- <g transform="translate(387 749)"><rect width="410" height="226" rx="26" fill="url(#coreFill)"/><text x="24" y="42" class="card-title cream">Rust core · porcelain</text><text x="24" y="72" class="small" fill="#ffe6da">Native runner or WASM component</text><line x1="24" y1="91" x2="386" y2="91" stroke="#fffaf1" stroke-opacity="0.25"/><text x="24" y="122" class="small cream">Adds apiVersion, kind, metadata</text><text x="24" y="148" class="small cream">Derives claim namespace + template ref</text><text x="24" y="174" class="small cream">Builds URLs · OAuth · 401 retry</text><text x="24" y="200" class="small cream">CRUD + claim polling</text></g>
- <path d="M 797 862 C 823 862, 834 862, 858 862" class="line"/><text x="827" y="843" class="tiny" text-anchor="middle" fill="#526660" font-weight="700">HTTP</text>
- <g transform="translate(858 749)"><rect width="274" height="226" rx="26" fill="#fffaf1" stroke="#d6cbbc"/><text x="24" y="42" class="card-title ink">Cyclops API</text><text x="24" y="73" class="mono small muted">/api/k8s/{path}</text><line x1="24" y1="93" x2="250" y2="93" stroke="#d6cbbc"/><text x="24" y="124" class="small ink">Authenticated proxy</text><text x="24" y="150" class="small ink">Resource CRUD</text><text x="24" y="176" class="small ink">Returns live status</text><rect x="24" y="191" width="127" height="23" rx="11" fill="#e3eee8"/><text x="87.5" y="207" class="tiny ink" text-anchor="middle">generic endpoint</text></g>
- <path d="M 1132 862 C 1157 862, 1169 862, 1193 862" class="line"/>
- <g transform="translate(1193 749)"><rect width="331" height="226" rx="26" fill="#203a34"/><text x="24" y="42" class="card-title cream">Kubernetes + OSGym</text><g transform="translate(24 72)"><rect width="283" height="43" rx="14" fill="#31554a"/><text x="16" y="27" class="small cream">OSGymWorkspacePool</text><rect y="54" width="283" height="43" rx="14" fill="#31554a"/><text x="16" y="81" class="small cream">OSGymSandboxClaim</text><path d="M 142 102 L 142 121" stroke="#f1b14d" stroke-width="3" marker-end="url(#arrowOrange)"/><rect y="127" width="283" height="43" rx="14" fill="#f1b14d"/><text x="141.5" y="154" class="small ink" text-anchor="middle" font-weight="700">Bound → Sandbox</text></g></g>
- <path d="M 1340 986 C 1340 1024, 592 1034, 592 986" class="line-orange dash"/><rect x="797" y="1005" width="337" height="36" rx="18" fill="#fffaf1" stroke="#dfb7a4"/><text x="965.5" y="1028" class="small" text-anchor="middle" fill="#9d3c28" font-weight="700">wait_claim polls until status.phase = Bound</text>
- <text x="76" y="1043" class="tiny muted">Generated files are checked for drift in CI. Edit the CRDs, rerun the generator, and every language follows.</text><text x="1524" y="1043" class="tiny muted" text-anchor="end">Protocol v5</text>
- </g>
-</svg>
diff --git a/libs/fleet/sdk-core/rust-toolchain.toml b/libs/fleet/rust-toolchain.toml
similarity index 59%
rename from libs/fleet/sdk-core/rust-toolchain.toml
rename to libs/fleet/rust-toolchain.toml
index 75ee9179c2..c10b12e6bb 100644
--- a/libs/fleet/sdk-core/rust-toolchain.toml
+++ b/libs/fleet/rust-toolchain.toml
@@ -1,4 +1,4 @@
[toolchain]
channel = "1.97.0"
-targets = ["wasm32-wasip2"]
profile = "minimal"
+components = ["clippy", "rustfmt"]
diff --git a/libs/fleet/scripts/build-sdk-bindings-native.sh b/libs/fleet/scripts/build-sdk-bindings-native.sh
new file mode 100755
index 0000000000..de4838eb82
--- /dev/null
+++ b/libs/fleet/scripts/build-sdk-bindings-native.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+workspace="$repo_root/cyclops-cs"
+target_dir="${CYCLOPS_SDK_NATIVE_TARGET_DIR:-$workspace/target/sdk-bindings-native}"
+
+cargo build --locked --manifest-path "$workspace/Cargo.toml" --package cyclops-sdk --target-dir "$target_dir" >&2
+case "$(uname -s)" in
+ Darwin) library="$target_dir/debug/libcyclops_sdk.dylib" ;;
+ Linux) library="$target_dir/debug/libcyclops_sdk.so" ;;
+ *) echo "unsupported host for Cyclops SDK bindings: $(uname -s)" >&2; exit 1 ;;
+esac
+[ -f "$library" ] || { echo "native Cyclops SDK library was not built: $library" >&2; exit 1; }
+printf '%s\n' "$library"
diff --git a/libs/fleet/scripts/check-sdk-binding-contract-sources.sh b/libs/fleet/scripts/check-sdk-binding-contract-sources.sh
new file mode 100755
index 0000000000..7c7afa58a6
--- /dev/null
+++ b/libs/fleet/scripts/check-sdk-binding-contract-sources.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+exec python3 "$repo_root/cyclops-cs/scripts/check_sdk_binding_contract_sources.py" "$@"
diff --git a/libs/fleet/scripts/check_sdk_binding_contract_sources.py b/libs/fleet/scripts/check_sdk_binding_contract_sources.py
new file mode 100755
index 0000000000..64a2f8f79b
--- /dev/null
+++ b/libs/fleet/scripts/check_sdk_binding_contract_sources.py
@@ -0,0 +1,380 @@
+#!/usr/bin/env python3
+"""Validate executable Task 11 binding-contract fixture structure."""
+
+from __future__ import annotations
+
+import argparse
+import io
+import re
+import sys
+import tempfile
+import tokenize
+from pathlib import Path
+
+
+class ContractFailure(RuntimeError):
+ pass
+
+
+KOTLIN_BUILD_CHECKS = [
+ ("Kotlin test source set", r"sourceSets\.test\s*\{\s*kotlin\.srcDirs\(\"tests\"\)"),
+ ("Kotlin example source set", r"sourceSets\.creating\s*\{\s*kotlin\.srcDir\(\"\.\./examples/kotlin\"\)"),
+ ("Kotlin example compile main output", r"compileClasspath\s*\+=\s*sourceSets\.main\.get\(\)\.output"),
+ ("Kotlin example runtime main output", r"runtimeClasspath\s*\+=\s*sourceSets\.main\.get\(\)\.output"),
+ ("Kotlin example implementation inheritance", r"configurations\[example\.implementationConfigurationName\]\.extendsFrom\(\s*configurations\[sourceSets\.main\.get\(\)\.implementationConfigurationName\]"),
+ ("Kotlin example runtime inheritance", r"configurations\[example\.runtimeOnlyConfigurationName\]\.extendsFrom\(\s*configurations\[sourceSets\.main\.get\(\)\.runtimeOnlyConfigurationName\]"),
+ ("Kotlin example classes dependency", r"dependsOn\(example\.classesTaskName\)"),
+ ("Kotlin example runtime classpath", r"classpath\s*=\s*example\.runtimeClasspath"),
+]
+
+
+def strip_python_comments_and_strings(text: str) -> str:
+ tokens = []
+ for token in tokenize.generate_tokens(io.StringIO(text).readline):
+ if token.type in {tokenize.COMMENT, tokenize.STRING}:
+ token = tokenize.TokenInfo(token.type, "\n" * token.string.count("\n"), token.start, token.end, token.line)
+ tokens.append(token)
+ return tokenize.untokenize(tokens)
+
+
+def strip_c_like_comments(text: str) -> str:
+ output = []
+ index = 0
+ state = "code"
+ block_comment_depth = 0
+ while index < len(text):
+ if state == "code" and text.startswith("//", index):
+ state = "line_comment"
+ index += 2
+ elif state == "code" and text.startswith("/*", index):
+ state = "block_comment"
+ block_comment_depth = 1
+ index += 2
+ elif state == "code" and text.startswith('\"\"\"', index):
+ state = "triple_string"
+ output.append('\"\"\"')
+ index += 3
+ elif state == "triple_string" and text.startswith('\"\"\"', index):
+ state = "code"
+ output.append('\"\"\"')
+ index += 3
+ elif state == "code" and text[index] in {'\"', "'"}:
+ state = text[index]
+ output.append(text[index])
+ index += 1
+ elif state in {'\"', "'"}:
+ output.append(text[index])
+ if text[index] == "\\" and index + 1 < len(text):
+ output.append(text[index + 1])
+ index += 2
+ elif text[index] == state:
+ state = "code"
+ index += 1
+ else:
+ index += 1
+ elif state == "line_comment":
+ if text[index] == "\n":
+ output.append("\n")
+ state = "code"
+ index += 1
+ elif state == "block_comment":
+ if text.startswith("/*", index):
+ block_comment_depth += 1
+ index += 2
+ elif text.startswith("*/", index):
+ block_comment_depth -= 1
+ index += 2
+ if block_comment_depth == 0:
+ state = "code"
+ else:
+ if text[index] == "\n":
+ output.append("\n")
+ index += 1
+ else:
+ output.append(text[index])
+ index += 1
+ return "".join(output)
+
+
+def strip_ruby_comments(text: str) -> str:
+ output = []
+ in_block_comment = False
+ for line in text.splitlines(keepends=True):
+ if re.match(r"^\s*=begin\s*$", line):
+ in_block_comment = True
+ continue
+ if in_block_comment:
+ if re.match(r"^\s*=end\s*$", line):
+ in_block_comment = False
+ continue
+ quote = None
+ escaped = False
+ kept = []
+ for character in line:
+ if quote is None and character == "#":
+ break
+ kept.append(character)
+ if quote is None and character in {"'", '\"'}:
+ quote = character
+ elif quote is not None:
+ if escaped:
+ escaped = False
+ elif character == "\\":
+ escaped = True
+ elif character == quote:
+ quote = None
+ output.append("".join(kept))
+ return "".join(output)
+
+
+def executable_source(path: Path) -> str:
+ text = path.read_text(encoding="utf-8")
+ if path.suffix == ".py":
+ return strip_python_comments_and_strings(text)
+ if path.suffix in {".kt", ".kts", ".swift"}:
+ return strip_c_like_comments(text)
+ if path.suffix == ".rb":
+ return strip_ruby_comments(text)
+ return text
+
+
+def require(source: str, description: str, pattern: str, path: Path) -> None:
+ if not re.search(pattern, source, flags=re.MULTILINE | re.DOTALL):
+ raise ContractFailure(f"binding contract check failed: {description} ({path})")
+
+
+def require_all(source: str, path: Path, checks: list[tuple[str, str]]) -> None:
+ for description, pattern in checks:
+ require(source, description, pattern, path)
+
+
+def forbid(source: str, description: str, pattern: str, path: Path) -> None:
+ if re.search(pattern, source, flags=re.MULTILINE | re.DOTALL):
+ raise ContractFailure(f"binding contract check failed: {description} ({path})")
+
+
+def require_kotlin_build(path: Path) -> None:
+ require_all(executable_source(path), path, KOTLIN_BUILD_CHECKS)
+
+
+def require_lifecycle(source: str, path: Path, label: str, queue_marker: str, calls: list[str], exhausted: str) -> None:
+ checks = [(f"{label} request queue", queue_marker)]
+ checks.extend((f"{label} lifecycle {call}", call) for call in calls)
+ checks.append((f"{label} queue exhaustion", exhausted))
+ require_all(source, path, checks)
+
+
+def check(root: Path) -> None:
+ bindings = root / "cyclops-cs/sdk-bindings"
+ files = {
+ "kotlin_test": bindings / "kotlin/tests/TestAsyncClient.kt",
+ "kotlin_example": bindings / "examples/kotlin/AppControlled.kt",
+ "kotlin_live": bindings / "examples/kotlin/LiveAppControlled.kt",
+ "swift_test": bindings / "swift/tests/TestAsyncClient.swift",
+ "swift_example": bindings / "examples/swift/AppControlled.swift",
+ "swift_live": bindings / "examples/swift/LiveAppControlled.swift",
+ "ruby_test": bindings / "ruby/tests/test_async_client.rb",
+ "ruby_example": bindings / "examples/ruby/app_controlled.rb",
+ "ruby_live": bindings / "examples/ruby/live_app_controlled.rb",
+ "python_test": bindings / "python/tests/test_async_client.py",
+ "python_fixture": bindings / "python/contract_fixture.py",
+ "python_example": bindings / "examples/python/app_controlled.py",
+ "python_live": bindings / "examples/python/live_app_controlled.py",
+ "kotlin_build": bindings / "kotlin/build.gradle.kts",
+ "swift_runner": root / "cyclops-cs/scripts/run-swift-sdk-binding.sh",
+ "ruby_runner": root / "cyclops-cs/scripts/run-ruby-sdk-binding.sh",
+ }
+ source = {name: executable_source(path) for name, path in files.items()}
+
+ require_all(source["kotlin_build"], files["kotlin_build"], KOTLIN_BUILD_CHECKS)
+ require_all(source["swift_runner"], files["swift_runner"], [
+ ("Swift runner module name", r"-module-name\s+CyclopsSdk"),
+ ("Swift runner Swift include directory", r"-I\s+\"\$swift_dir\""),
+ ("Swift runner SDK FFI module map", r"-Xcc\s+\"-fmodule-map-file=\$swift_dir/CyclopsSdkFFI\.modulemap\""),
+ ("Swift runner schema FFI module map", r"-Xcc\s+\"-fmodule-map-file=\$swift_dir/CyclopsSdkSchemaFFI\.modulemap\""),
+ ("Swift runner generated SDK source", r"\"\$swift_dir/CyclopsSdk\.swift\""),
+ ("Swift runner generated schema source", r"\"\$swift_dir/CyclopsSdkSchema\.swift\""),
+ ("Swift runner library rpath", r"-Xlinker\s+-rpath\s+-Xlinker\s+\"\$library_dir\""),
+ ("Swift runner array-safe invocation", r"swiftc\s+\"\$\{swiftc_args\[@\]\}\""),
+ ])
+ require_all(source["ruby_runner"], files["ruby_runner"], [
+ ("Ruby runner native library directory", r"library_dir=\"\$runtime/cyclops_sdk\""),
+ ("Ruby runner Linux loader path", r"LD_LIBRARY_PATH=\"\$library_dir\$\{LD_LIBRARY_PATH:\+:[^}]+\}\""),
+ ("Ruby runner macOS loader path", r"DYLD_LIBRARY_PATH=\"\$library_dir\$\{DYLD_LIBRARY_PATH:\+:[^}]+\}\""),
+ ("Ruby runner Windows loader path", r"PATH=\"\$library_dir:\$PATH\""),
+ ])
+
+ require_all(source["kotlin_live"], files["kotlin_live"], [
+ ("Kotlin live HTTP callback", r"class\s+JavaHttpClient\s*:\s*HttpClient"),
+ ("Kotlin live typed pool", r"PoolSpec\(.*SandboxService\(\"mcp\",\s*3000u"),
+ ("Kotlin live typed claim", r"CreateClaimRequest\(pool,\s*null\)"),
+ ("Kotlin live MCP retry", r"response\.status\.toInt\(\)\s+in\s+setOf\(502,\s*503,\s*504\)"),
+ ("Kotlin live cleanup", r"client\.deleteClaim.*client\.deletePool"),
+ ])
+
+ require_all(source["kotlin_test"], files["kotlin_test"], [
+ ("Kotlin synchronized scripted callback", r"private\s+val\s+lock\s*=\s*Any\(\)"),
+ ("Kotlin request headers comparison", r"request\.headers\.map\s*\{\s*it\.name\s+to\s+it\.value\s*}\s*==\s*item\.headers"),
+ ("Kotlin optional binary body comparison", r"request\.body\.contentEquals\(item\.body\)"),
+ ("Kotlin callback transport constructor", r"throw\s+HttpException\.Transport\("),
+ ("Kotlin SDK transport assertion", r"catch\s*\(\s*error\s*:\s*SdkException\.Transport\s*\)"),
+ ("Kotlin concurrent SDK calls", r"async\s*\{\s*concurrentClient\.serviceRequest"),
+ ])
+ require_all(source["swift_live"], files["swift_live"], [
+ ("Swift live URLSession callback", r"final\s+class\s+UrlSessionHttpClient\s*:\s*HttpClient"),
+ ("Swift live typed pool", r"PoolSpec\(.*SandboxService\(name:\s*\"mcp\",\s*targetPort:\s*3000"),
+ ("Swift live typed claim", r"CreateClaimRequest\(pool:\s*pool,\s*spec:\s*nil\)"),
+ ("Swift live MCP retry", r"\[502,\s*503,\s*504\]\.contains\(Int\(response\.status\)\)"),
+ ("Swift live portable duration", r"advanced\(by:\s*\.seconds\(300\)\)"),
+ ("Swift live cleanup", r"client\.deleteClaim.*client\.deletePool"),
+ ])
+
+ require_all(source["swift_test"], files["swift_test"], [
+ ("Swift actor callback", r"actor\s+ScriptedHttpClient\s*:\s*HttpClient"),
+ ("Swift generated callback label", r"func\s+execute\(request:\s*HttpRequest\)\s+async\s+throws\s*->\s*HttpResponse"),
+ ("Swift exact headers comparison", r"request\.headers\s*==\s*item\.headers"),
+ ("Swift optional Data body comparison", r"request\.body\s*==\s*item\.body"),
+ ("Swift callback transport constructor", r"throw\s+HttpError\.Transport\("),
+ ("Swift SDK transport assertion", r"catch\s+SdkError\.Transport\(let\s+reason\)"),
+ ("Swift concurrent SDK calls", r"async\s+let\s+first\s*=\s*concurrentClient\.serviceRequest"),
+ ])
+ require_all(source["ruby_live"], files["ruby_live"], [
+ ("Ruby live Net HTTP callback", r"class\s+NetHttpClient\s*<\s*CyclopsSdk::HttpClient"),
+ ("Ruby live typed pool", r"CyclopsSdk::PoolSpec\.new.*CyclopsSdk::SandboxService\.new\(name:\s*\x27mcp\x27,\s*target_port:\s*3000"),
+ ("Ruby live typed claim", r"CreateClaimRequest\.new\(pool:\s*pool,\s*spec:\s*nil\)"),
+ ("Ruby live MCP retry", r"\[502,\s*503,\s*504\]\.include\?\(response\.status\)"),
+ ("Ruby live cleanup", r"client\.delete_claim.*client\.delete_pool"),
+ ])
+ forbid(source["ruby_live"], "Ruby live byte arrays", r"\.bytes\b", files["ruby_live"])
+ forbid(source["ruby_live"], "Ruby live future wrapper", r"\)\.value\b", files["ruby_live"])
+
+ require_all(source["ruby_test"], files["ruby_test"], [
+ ("Ruby mutex-safe callback", r"@mutex\s*=\s*Mutex\.new"),
+ ("Ruby mutex queue access", r"@mutex\.synchronize\s+do"),
+ ("Ruby exact headers and body comparison", r"actual\s*==\s*\[item\.method,\s*item\.url,\s*item\.headers,\s*item\.body\]"),
+ ("Ruby callback transport constructor", r"raise\s+CyclopsSdk::HttpError::Transport\.new\("),
+ ("Ruby future transport assertion", r"rescue\s+CyclopsSdk::SdkError::Transport\s*=>\s*error"),
+ ("Ruby concurrent SDK threads", r"Thread\.new\s+do"),
+ ])
+ require_all(source["python_test"], files["python_test"], [
+ ("Python native body queue", r"expected_service_calls\("),
+ ("Python absent body assertion", r"assertIsNone\(transport\.requests\[1\]\.body\)"),
+ ("Python binary response assertion", r"response\.body\s+for\s+response\s+in\s+responses"),
+ ("Python one-client concurrent SDK calls", r"asyncio\.gather\(\s*sdk\.service_request"),
+ ("Python one-client queue recording", r"len\(transport\.requests\)"),
+ ("Python concurrent queue exhaustion", r"transport\.assert_exhausted\(\)"),
+ ])
+ require_all(source["python_fixture"], files["python_fixture"], [
+ ("Python asyncio callback lock", r"self\.lock\s*=\s*asyncio\.Lock\(\)"),
+ ("Python locked callback", r"async\s+with\s+self\.lock"),
+ ("Python exact headers and body comparison", r"actual_headers.*request\.body.*item\.headers.*item\.body"),
+ ("Python service call queue", r"def\s+expected_service_calls\("),
+ ("Python absent optional body helper", r"def\s+service_request\(body\)"),
+ ])
+ require(files["python_live"].read_text(encoding="utf-8"), "Python live environment", r"os\.environ\[\"CUA_CLIENT_ID\"\].*os\.environ\[\"CUA_IMAGE\"\]", files["python_live"])
+ require_all(source["python_live"], files["python_live"], [
+ ("Python live HTTP callback", r"class\s+UrlLibHttpClient\(HttpClient\).*async\s+def\s+execute"),
+ ("Python live typed pool", r"PoolSpec\(.*SandboxService\(.*target_port=3000"),
+ ("Python live typed claim", r"CreateClaimRequest\(pool=pool,\s*spec=None\)"),
+ ("Python live MCP retry", r"response\.status\s+in\s+\(502,\s*503,\s*504\)"),
+ ("Python live cleanup", r"await\s+client\.delete_claim.*await\s+client\.delete_pool"),
+ ])
+
+ lifecycle_calls = {
+ "kotlin_test": (r"lifecycleQueue\(", [r"createPool\(", r"createClaim\(", r"waitClaim\(", r"serviceRequest\(", r"deleteClaim\(", r"deletePool\("], r"transport\.assertExhausted\("),
+ "kotlin_example": (r"Expected\(", [r"createPool\(", r"createClaim\(", r"waitClaim\(", r"serviceRequest\(", r"deleteClaim\(", r"deletePool\("], r"transport\.assertExhausted\("),
+ "swift_test": (r"lifecycleQueue\(", [r"createPool\(", r"createClaim\(", r"waitClaim\(", r"serviceRequest\(", r"deleteClaim\(", r"deletePool\("], r"transport\.assertExhausted\("),
+ "swift_example": (r"private\s+var\s+expected", [r"createPool\(", r"createClaim\(", r"waitClaim\(", r"serviceRequest\(", r"deleteClaim\(", r"deletePool\("], r"transport\.assertExhausted\("),
+ "ruby_test": (r"Expected\.new", [r"create_pool\(", r"create_claim\(", r"wait_claim\(", r"service_request\(", r"delete_claim\(", r"delete_pool\("], r"transport\.assert_exhausted!"),
+ "ruby_example": (r"Expected\.new", [r"create_pool\(", r"create_claim\(", r"wait_claim\(", r"service_request\(", r"delete_claim\(", r"delete_pool\("], r"transport\.assert_exhausted!"),
+ "python_fixture": (r"def\s+expected_lifecycle\(", [r"create_pool\(", r"create_claim\(", r"wait_claim\(", r"service_request\(", r"delete_claim\(", r"delete_pool\("], r"transport\.assert_exhausted\("),
+ "python_test": (r"expected_lifecycle\(", [r"run_lifecycle\(", r"ScriptedHttpClient\("], r"transport\.assert_exhausted\("),
+ "python_example": (r"expected_lifecycle\(", [r"run_lifecycle\(", r"ScriptedHttpClient\("], r"run_lifecycle\("),
+ }
+ for name, (queue, calls, exhausted) in lifecycle_calls.items():
+ require_lifecycle(source[name], files[name], name.replace("_", " "), queue, calls, exhausted)
+
+ for name in ("ruby_test", "ruby_example"):
+ require_all(source[name], files[name], [
+ ("Ruby anchored pool collection route", r"pool_url\.sub\(%r\{/default\\z\}"),
+ ("Ruby anchored claim collection route", r"claim_url\.sub\(%r\{/default\\z\}"),
+ ])
+ forbid(source[name], "Ruby byte arrays instead of binary strings", r"\.bytes\b", files[name])
+ forbid(source[name], "Ruby future wrapper on resolved async result", r"\)\.value\b", files[name])
+
+
+def kotlin_build_fixture() -> str:
+ return """\
+sourceSets.test { kotlin.srcDirs(\"tests\") }
+val example by sourceSets.creating {
+ kotlin.srcDir(\"../examples/kotlin\")
+ compileClasspath += sourceSets.main.get().output
+ runtimeClasspath += sourceSets.main.get().output
+}
+configurations[example.implementationConfigurationName].extendsFrom(
+ configurations[sourceSets.main.get().implementationConfigurationName],
+)
+configurations[example.runtimeOnlyConfigurationName].extendsFrom(
+ configurations[sourceSets.main.get().runtimeOnlyConfigurationName],
+)
+tasks.register<JavaExec>(\"example\") {
+ dependsOn(example.classesTaskName)
+ classpath = example.runtimeClasspath
+}
+"""
+
+
+def self_test() -> None:
+ samples = {
+ "kotlin": (strip_c_like_comments, "/* throw HttpException.Transport() */\n", r"HttpException\.Transport"),
+ "swift": (strip_c_like_comments, "// actor ScriptedHttpClient: HttpClient\n", r"actor\s+ScriptedHttpClient"),
+ "ruby": (strip_ruby_comments, "=begin\nThread.new do\n=end\n# Mutex.new\n", r"Thread\.new|Mutex\.new"),
+ "python": (strip_python_comments_and_strings, '\"\"\" asyncio.gather(sdk.service_request()) \"\"\"\n# expected_service_calls()\n', r"asyncio\.gather|expected_service_calls"),
+ }
+ for language, (stripper, comment_only, pattern) in samples.items():
+ if re.search(pattern, stripper(comment_only), flags=re.DOTALL):
+ raise ContractFailure(f"comment-only negative self-test failed for {language}")
+
+ with tempfile.TemporaryDirectory() as directory:
+ fixture = Path(directory) / "build.gradle.kts"
+ fixture.write_text(kotlin_build_fixture(), encoding="utf-8")
+ require_kotlin_build(fixture)
+
+ wiring = kotlin_build_fixture().splitlines()
+ fixture.write_text(
+ "// " + wiring[0] + "\n"
+ "/* outer Gradle comment\n"
+ " /* nested Gradle comment\n"
+ + "\n".join(" " + line for line in wiring[1:-1])
+ + "\n */\n"
+ "*/\n"
+ "// " + wiring[-1] + "\n",
+ encoding="utf-8",
+ )
+ try:
+ require_kotlin_build(fixture)
+ except ContractFailure: # lint-ignore: swallowed-exception
+ pass
+ else:
+ raise ContractFailure("comment-only .kts Gradle wiring unexpectedly passed")
+ print("SDK binding source checker comment-only self-test passed.")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--self-test", action="store_true", help="prove comment-only evidence is ignored")
+ args = parser.parse_args()
+ root = Path(__file__).resolve().parents[2]
+ try:
+ check(root)
+ if args.self_test:
+ self_test()
+ except (ContractFailure, tokenize.TokenError) as error:
+ print(error, file=sys.stderr)
+ return 1
+ print("SDK binding source contract checks passed.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/libs/fleet/scripts/cleanup-live-sdk-example.sh b/libs/fleet/scripts/cleanup-live-sdk-example.sh
new file mode 100755
index 0000000000..f650f72ed2
--- /dev/null
+++ b/libs/fleet/scripts/cleanup-live-sdk-example.sh
@@ -0,0 +1,47 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+curl_bin="${CURL_BIN:-curl}"
+for variable in CUA_BASE_URL CUA_TOKEN_URL CUA_CLIENT_ID CUA_CLIENT_SECRET CYCLOPS_NAMESPACE; do
+ [[ -n "${!variable:-}" ]] || { echo "$variable is required" >&2; exit 1; }
+done
+
+token="$($curl_bin --fail-with-body --silent --show-error -X POST "$CUA_TOKEN_URL" \
+ -d grant_type=client_credentials \
+ --data-urlencode "client_id=$CUA_CLIENT_ID" \
+ --data-urlencode "client_secret=$CUA_CLIENT_SECRET" | jq -er .access_token)"
+cleanup_failed=0
+
+delete_url() {
+ local url="$1" status
+ status="$($curl_bin --silent --show-error -o /dev/null --write-out '%{http_code}' \
+ -H "Authorization: Bearer $token" -X DELETE "$url")" || status=000
+ case "$status" in
+ 200|202|204|404) ;;
+ *) echo "Failed to delete $url: HTTP $status" >&2; cleanup_failed=1 ;;
+ esac
+}
+
+delete_collection() {
+ local collection="$1" body_file status
+ body_file="$(mktemp)"
+ status="$($curl_bin --silent --show-error -o "$body_file" --write-out '%{http_code}' \
+ -H "Authorization: Bearer $token" "$collection")" || status=000
+ case "$status" in
+ 200)
+ while IFS= read -r name; do
+ [[ -n "$name" ]] && delete_url "$collection/$name"
+ done < <(jq -r '.items[]?.metadata.name' "$body_file")
+ ;;
+ 404) ;;
+ *) echo "Failed to list $collection: HTTP $status" >&2; cleanup_failed=1 ;;
+ esac
+ rm -f "$body_file"
+}
+
+claims="$CUA_BASE_URL/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/$CYCLOPS_NAMESPACE/osgymsandboxclaims"
+pools="$CUA_BASE_URL/api/k8s/apis/cua.ai/v1/namespaces/$CYCLOPS_NAMESPACE/osgymworkspacepools"
+delete_collection "$claims"
+delete_collection "$pools"
+delete_url "$CUA_BASE_URL/api/namespaces/$CYCLOPS_NAMESPACE"
+exit "$cleanup_failed"
diff --git a/libs/fleet/scripts/generate-sdk-bindings.sh b/libs/fleet/scripts/generate-sdk-bindings.sh
new file mode 100755
index 0000000000..8a2293da4d
--- /dev/null
+++ b/libs/fleet/scripts/generate-sdk-bindings.sh
@@ -0,0 +1,637 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+usage() {
+ cat >&2 <<'USAGE'
+Usage: generate-sdk-bindings.sh [--check]
+
+Generate checked-in UniFFI Python, Kotlin, Swift, and Ruby bindings. --check
+compares fresh output to the checked-in generated source without modifying it.
+USAGE
+}
+
+case "${1:-}" in
+ "") check_only=false ;;
+ --check) check_only=true ;;
+ *) usage; exit 2 ;;
+esac
+
+if [ "$#" -gt 1 ]; then
+ usage
+ exit 2
+fi
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+workspace_dir="$repo_root/cyclops-cs"
+workspace="$workspace_dir/Cargo.toml"
+bindings_dir="$workspace_dir/sdk-bindings"
+languages="python kotlin swift ruby"
+manifest_name=".cyclops-sdk-generated-files"
+
+if cargo_bin="$(command -v cargo)" && [ -n "$cargo_bin" ]; then
+ :
+else
+ echo "error: cargo must be available on PATH" >&2
+ exit 127
+fi
+
+if rustc_bin="$(command -v rustc)" && [ -n "$rustc_bin" ]; then
+ :
+else
+ echo "error: rustc must be available on PATH" >&2
+ exit 127
+fi
+
+host_triple="$("$rustc_bin" -vV | sed -n 's/^host: //p')"
+if [ -z "$host_triple" ]; then
+ echo "error: could not determine the Rust host target" >&2
+ exit 1
+fi
+
+temporary_output="$(mktemp -d "$workspace_dir/.generate-sdk-bindings.XXXXXX")"
+replacement_root=""
+backup_container=""
+backup_root=""
+transaction_state="preparing"
+mode_for() {
+ if stat -f '%Lp' "$1" >/dev/null 2>&1; then
+ stat -f '%Lp' "$1"
+ else
+ stat -c '%a' "$1"
+ fi
+}
+
+reject_symlinks() {
+ root="$1"
+ label="$2"
+ symlink_list="$temporary_output/symlinks-$label"
+
+ if [ -L "$root" ]; then
+ echo "generated symlink is not allowed: $label" >&2
+ return 1
+ fi
+ if [ ! -d "$root" ]; then
+ echo "generated root is missing or not a directory: $label" >&2
+ return 1
+ fi
+
+ find -P "$root" -type l -print > "$symlink_list"
+ if [ -s "$symlink_list" ]; then
+ while IFS= read -r path; do
+ echo "generated symlink is not allowed: $label/${path#"$root"/}" >&2
+ done < "$symlink_list"
+ return 1
+ fi
+ return 0
+}
+write_manifest() {
+ root="$1"
+ manifest="$2"
+ (
+ cd "$root"
+ {
+ find -P . -mindepth 1 -type d -print | sed 's#^\./#d #'
+ find -P . -mindepth 1 -type f -print | sed 's#^\./#f #'
+ } | LC_ALL=C sort
+ ) > "$manifest"
+}
+
+validate_manifest_path() {
+ path="$1"
+ case "$path" in
+ ""|/*|.|..|../*|*/../*|*/..) return 1 ;;
+ *) return 0 ;;
+ esac
+}
+
+grep_matches_or_empty() {
+ pattern="$1"
+ source_file="$2"
+ if grep -Eo "$pattern" "$source_file"; then
+ return 0
+ else
+ status="$?"
+ [ "$status" -eq 1 ] && return 0
+ return "$status"
+ fi
+}
+
+ruby_method_names() {
+ source_file="$1"
+ method_prefix="$2"
+ grep_matches_or_empty "${method_prefix}_Type[A-Za-z0-9_]+" "$source_file" | LC_ALL=C sort -u
+}
+
+ruby_defined_method_names() {
+ source_file="$1"
+ method_prefix="$2"
+ sed -n -E "s/^[[:space:]]*def (self\\.)?(${method_prefix}_Type[A-Za-z0-9_]+).*/\\2/p" "$source_file" | LC_ALL=C sort -u
+}
+
+write_ruby_method_array() {
+ array_name="$1"
+ methods_file="$2"
+ facade_file="$3"
+ printf ' %s = %%i[\n' "$array_name" >> "$facade_file"
+ while IFS= read -r method_name; do
+ [ -n "$method_name" ] || continue
+ printf ' %s\n' "$method_name" >> "$facade_file"
+ done < "$methods_file"
+ printf ' ].freeze\n' >> "$facade_file"
+}
+
+write_ruby_facade() {
+ sdk_file="$1"
+ schema_file="$2"
+ facade_file="$3"
+ for method_prefix in check_lower read write; do
+ references="$temporary_output/ruby-$method_prefix-references"
+ definitions="$temporary_output/ruby-$method_prefix-definitions"
+ schema_definitions="$temporary_output/ruby-schema-$method_prefix-definitions"
+ missing="$temporary_output/ruby-$method_prefix-external"
+ ruby_method_names "$sdk_file" "$method_prefix" > "$references"
+ ruby_defined_method_names "$sdk_file" "$method_prefix" > "$definitions"
+ ruby_defined_method_names "$schema_file" "$method_prefix" > "$schema_definitions"
+ comm -23 "$references" "$definitions" > "$missing"
+ unresolved="$temporary_output/ruby-$method_prefix-unresolved"
+ comm -23 "$missing" "$schema_definitions" > "$unresolved"
+ if [ -s "$unresolved" ]; then
+ echo "error: generated Ruby SDK references methods missing from schema: $method_prefix" >&2
+ cat "$unresolved" >&2
+ return 1
+ fi
+ done
+
+ cat > "$facade_file" <<'RUBY_FACADE_HEADER'
+require_relative "cyclops_sdk/schema"
+require_relative "cyclops_sdk/sdk"
+
+module CyclopsSdk
+ CyclopsSdkSchema.constants(false).each do |name|
+ const_set(name, CyclopsSdkSchema.const_get(name)) unless const_defined?(name, false)
+ end
+RUBY_FACADE_HEADER
+ write_ruby_method_array "SCHEMA_CHECK_LOWER_METHODS" "$temporary_output/ruby-check_lower-external" "$facade_file"
+ write_ruby_method_array "SCHEMA_READ_METHODS" "$temporary_output/ruby-read-external" "$facade_file"
+ write_ruby_method_array "SCHEMA_WRITE_METHODS" "$temporary_output/ruby-write-external" "$facade_file"
+ cat >> "$facade_file" <<'RUBY_FACADE_FOOTER'
+
+ schema_rust_buffer = CyclopsSdkSchema::RustBuffer
+ schema_stream = CyclopsSdkSchema.const_get(:RustBufferStream, false)
+
+ SCHEMA_CHECK_LOWER_METHODS.each do |method_name|
+ RustBuffer.define_singleton_method(method_name) do |value|
+ schema_rust_buffer.public_send(method_name, value)
+ end
+ end
+
+ SCHEMA_READ_METHODS.each do |method_name|
+ RustBufferStream.define_method(method_name) do
+ schema_buffer = schema_rust_buffer.new(@rbuf.pointer)
+ external_stream = schema_stream.new(schema_buffer)
+ external_stream.instance_variable_set(:@offset, @offset)
+ value = external_stream.public_send(method_name)
+ @offset = external_stream.instance_variable_get(:@offset)
+ value
+ end
+ end
+
+ SCHEMA_WRITE_METHODS.each do |method_name|
+ RustBufferBuilder.define_method(method_name) do |value|
+ buffer = schema_rust_buffer.public_send(method_name.to_s.sub("write_", "alloc_from_"), value)
+ begin
+ write(buffer.data.read_bytes(buffer.len))
+ ensure
+ buffer.free
+ end
+ end
+ end
+
+ private_constant :SCHEMA_CHECK_LOWER_METHODS, :SCHEMA_READ_METHODS, :SCHEMA_WRITE_METHODS
+end
+RUBY_FACADE_FOOTER
+}
+
+write_python_facade() {
+ sdk_file="$1"
+ schema_file="$2"
+ facade_file="$3"
+ private_exports="$temporary_output/python-schema-private-exports"
+
+ grep_matches_or_empty 'cyclops_sdk\._[A-Za-z_][A-Za-z0-9_]*' "$sdk_file" \
+ | sed 's/^cyclops_sdk\.//' | LC_ALL=C sort -u > "$private_exports"
+
+ cat > "$facade_file" <<'PYTHON_FACADE_HEADER'
+from . import _schema as _schema_component
+from ._schema import *
+PYTHON_FACADE_HEADER
+ while IFS= read -r symbol; do
+ [ -n "$symbol" ] || continue
+ if ! grep -Eq "^(class|def) ${symbol}|^${symbol}[[:space:]]*=" "$schema_file"; then
+ echo "error: generated Python SDK references missing schema symbol: $symbol" >&2
+ return 1
+ fi
+ printf '%s = _schema_component.%s\n' "$symbol" "$symbol" >> "$facade_file"
+ done < "$private_exports"
+ cat >> "$facade_file" <<'PYTHON_FACADE_FOOTER'
+
+from . import _sdk as _sdk_component
+from ._sdk import *
+
+__all__ = [*_schema_component.__all__, *_sdk_component.__all__]
+
+del _schema_component
+del _sdk_component
+PYTHON_FACADE_FOOTER
+}
+
+normalize_generated_text() {
+ for language in $languages; do
+ find -P "$temporary_output/generated/$language" -type f -print | while IFS= read -r file; do
+ normalized="$file.normalized"
+ awk '
+ {
+ sub(/[[:space:]]+$/, "")
+ if ($0 == "") {
+ blank_lines++
+ next
+ }
+ while (blank_lines > 0) {
+ print ""
+ blank_lines--
+ }
+ print
+ }
+ ' "$file" > "$normalized"
+ mv "$normalized" "$file"
+ done
+ done
+}
+
+set_generated_modes() {
+ source_root="$1"
+ destination_root="$2"
+ manifest="$source_root/$manifest_name"
+
+ chmod "$(mode_for "$source_root")" "$destination_root"
+ while IFS=' ' read -r type path; do
+ if ! validate_manifest_path "$path"; then
+ echo "error: invalid generated manifest path: $path" >&2
+ return 1
+ fi
+ case "$type" in
+ d|f) chmod "$(mode_for "$source_root/$path")" "$destination_root/$path" ;;
+ *) echo "error: invalid generated manifest entry: $type $path" >&2; return 1 ;;
+ esac
+ done < "$manifest"
+ chmod "$(mode_for "$manifest")" "$destination_root/$manifest_name"
+}
+
+remove_previous_generated_files() {
+ destination_root="$1"
+ previous_manifest="$2"
+
+ [ -f "$previous_manifest" ] || return 0
+
+ while IFS=' ' read -r type path; do
+ if ! validate_manifest_path "$path"; then
+ echo "error: invalid checked-in generated manifest path: $path" >&2
+ return 1
+ fi
+ case "$type" in
+ d|f) ;;
+ *) echo "error: invalid checked-in generated manifest entry: $type $path" >&2; return 1 ;;
+ esac
+ done < "$previous_manifest"
+
+ # Remove manifest-owned files (including file symlinks) before their parents.
+ while IFS=' ' read -r type path; do
+ if [ "$type" = "f" ]; then
+ rm -f "$destination_root/$path"
+ fi
+ done < "$previous_manifest"
+
+ # Remove manifest-owned directories deepest-first, preserving unlisted children.
+ while IFS= read -r path; do
+ # Nonempty directories contain unlisted files that must be preserved.
+ rmdir "$destination_root/$path" 2>/dev/null || true # lint-ignore: error-masking
+ done < <(
+ LC_ALL=C awk '
+ substr($0, 1, 2) == "d " {
+ path = substr($0, 3)
+ depth_path = path
+ depth = gsub(/\//, "/", depth_path)
+ printf "%08d %s%c", depth, path, 10
+ }
+ ' "$previous_manifest" | LC_ALL=C sort -r | sed 's/^[0-9][0-9]* //'
+ )
+
+ rm -f "$destination_root/$manifest_name"
+}
+
+prepare_replacement_root() {
+ language="$1"
+ source_root="$bindings_dir/$language"
+ generated_root="$temporary_output/generated/$language"
+ destination_root="$replacement_root/$language"
+
+ if [ -e "$source_root" ] || [ -L "$source_root" ]; then
+ reject_symlinks "$source_root" "$language"
+ remove_previous_generated_files "$destination_root" "$source_root/$manifest_name"
+ else
+ mkdir -p "$destination_root"
+ fi
+
+ cp -pR "$generated_root/." "$destination_root/"
+ set_generated_modes "$generated_root" "$destination_root"
+}
+compare_root() {
+ expected_root="$1"
+ actual_root="$2"
+ language="$3"
+ failed=false
+
+ if ! reject_symlinks "$actual_root" "$language"; then
+ return 1
+ fi
+ if [ "$(mode_for "$expected_root")" != "$(mode_for "$actual_root")" ]; then
+ echo "generated mode differs: $language" >&2
+ failed=true
+ fi
+
+ expected_manifest="$expected_root/$manifest_name"
+ actual_manifest="$actual_root/$manifest_name"
+ if [ -L "$actual_manifest" ]; then
+ echo "generated symlink is not allowed: $language/$manifest_name" >&2
+ return 1
+ fi
+ if [ ! -f "$actual_manifest" ]; then
+ echo "missing generated path: $language/$manifest_name" >&2
+ return 1
+ fi
+ if ! cmp -s "$expected_manifest" "$actual_manifest"; then
+ echo "generated content differs: $language/$manifest_name" >&2
+ failed=true
+ fi
+ if [ "$(mode_for "$expected_manifest")" != "$(mode_for "$actual_manifest")" ]; then
+ echo "generated mode differs: $language/$manifest_name" >&2
+ failed=true
+ fi
+
+ while IFS=' ' read -r type path; do
+ if ! validate_manifest_path "$path"; then
+ echo "invalid generated manifest path: $language/$path" >&2
+ failed=true
+ continue
+ fi
+ expected="$expected_root/$path"
+ actual="$actual_root/$path"
+ if [ -L "$actual" ]; then
+ echo "generated symlink is not allowed: $language/$path" >&2
+ failed=true
+ continue
+ fi
+ case "$type" in
+ d)
+ if [ ! -d "$actual" ]; then
+ echo "generated path type differs: $language/$path" >&2
+ failed=true
+ continue
+ fi
+ ;;
+ f)
+ if [ ! -f "$actual" ]; then
+ echo "generated path type differs: $language/$path" >&2
+ failed=true
+ continue
+ fi
+ if ! cmp -s "$expected" "$actual"; then
+ echo "generated content differs: $language/$path" >&2
+ failed=true
+ fi
+ ;;
+ *)
+ echo "invalid generated manifest entry: $language/$type $path" >&2
+ failed=true
+ continue
+ ;;
+ esac
+ if [ "$(mode_for "$expected")" != "$(mode_for "$actual")" ]; then
+ echo "generated mode differs: $language/$path" >&2
+ failed=true
+ fi
+ done < "$expected_manifest"
+
+ "$failed" && return 1 || return 0
+}
+
+prepare_complete_replacement_root() {
+ if [ -L "$bindings_dir" ] || [ ! -d "$bindings_dir" ]; then
+ echo "error: sdk-bindings root is missing, not a directory, or a symlink" >&2
+ return 1
+ fi
+
+ replacement_root="$(mktemp -d "$workspace_dir/.sdk-bindings.new.XXXXXX")"
+ cp -pR "$bindings_dir/." "$replacement_root/"
+ for language in $languages; do
+ prepare_replacement_root "$language"
+ done
+}
+
+inject_transaction_point() {
+ point="$1"
+ if [ "${CYCLOPS_SDK_BINDINGS_TEST_FAIL_TRANSACTION_POINT:-}" = "$point" ]; then
+ echo "error: injected generated binding transaction failure at $point" >&2
+ return 1
+ fi
+
+ signal_spec="${CYCLOPS_SDK_BINDINGS_TEST_SIGNAL_TRANSACTION_POINT:-}"
+ if [ -n "$signal_spec" ] && [ "$signal_spec" = "$point:${signal_spec#*:}" ]; then
+ signal_name="${signal_spec#*:}"
+ case "$signal_name" in
+ HUP|INT|TERM)
+ echo "error: injected generated binding transaction signal $signal_name at $point" >&2
+ kill -s "$signal_name" "$$"
+ ;;
+ *)
+ echo "error: invalid transaction signal injection: $signal_spec" >&2
+ return 1
+ ;;
+ esac
+ fi
+}
+
+rollback_transaction() {
+ if [ "$transaction_state" = "finalized" ] || [ "$transaction_state" = "rolled_back" ]; then
+ return 0
+ fi
+
+ if [ -n "$backup_root" ] && { [ -e "$backup_root" ] || [ -L "$backup_root" ]; }; then
+ if [ -e "$bindings_dir" ] || [ -L "$bindings_dir" ]; then
+ rm -rf "$bindings_dir" || {
+ echo "error: could not remove interrupted replacement root" >&2
+ return 1
+ }
+ fi
+ mv "$backup_root" "$bindings_dir" || {
+ echo "error: could not restore original sdk-bindings root from $backup_root" >&2
+ return 1
+ }
+ fi
+
+ transaction_state="rolled_back"
+}
+
+cleanup_transaction() {
+ cleanup_failed=false
+ if [ "$transaction_state" != "finalized" ]; then
+ if ! rollback_transaction; then
+ cleanup_failed=true
+ echo "error: original sdk-bindings backup retained at $backup_root" >&2
+ fi
+ fi
+
+ rm -rf "$temporary_output"
+ if [ -n "$replacement_root" ] && { [ -e "$replacement_root" ] || [ -L "$replacement_root" ]; }; then
+ rm -rf "$replacement_root"
+ fi
+ if [ -n "$backup_container" ] && [ ! -e "$backup_root" ] && [ ! -L "$backup_root" ]; then
+ # Removing the temporary backup parent is best-effort exit cleanup.
+ rmdir "$backup_container" 2>/dev/null || true # lint-ignore: error-masking
+ fi
+
+ "$cleanup_failed" && return 1 || return 0
+}
+
+handle_exit() {
+ status="$?"
+ trap - EXIT HUP INT TERM
+ set +e
+ if ! cleanup_transaction; then
+ status=1
+ fi
+ exit "$status"
+}
+
+handle_signal() {
+ signal_name="$1"
+ trap - EXIT HUP INT TERM
+ set +e
+ if ! cleanup_transaction; then
+ echo "error: failed to restore sdk-bindings after $signal_name" >&2
+ fi
+ exit 1
+}
+
+replace_binding_root() {
+ backup_container="$(mktemp -d "$workspace_dir/.sdk-bindings.backup.XXXXXX")"
+ backup_root="$backup_container/original"
+
+ inject_transaction_point before-backup-move
+ mv "$bindings_dir" "$backup_root"
+ transaction_state="backup_moved"
+
+ inject_transaction_point after-backup-move
+ mv "$replacement_root" "$bindings_dir"
+ transaction_state="new_live"
+
+ inject_transaction_point after-new-live
+ transaction_state="finalized"
+
+ # Signals are ignored only after the root swap has fully committed.
+ trap '' HUP INT TERM
+ if ! rm -rf "$backup_container"; then
+ echo "warning: could not remove finalized sdk-bindings backup: $backup_container" >&2
+ fi
+ trap 'handle_signal HUP' HUP
+ trap 'handle_signal INT' INT
+ trap 'handle_signal TERM' TERM
+}
+
+trap 'handle_exit' EXIT
+trap 'handle_signal HUP' HUP
+trap 'handle_signal INT' INT
+trap 'handle_signal TERM' TERM
+cd "$workspace_dir"
+metadata_output="$temporary_output/cargo-metadata.json"
+if ! "$cargo_bin" metadata --locked --format-version 1 --no-deps --manifest-path "$workspace" > "$metadata_output"; then
+ echo "error: cargo metadata failed while resolving the target directory" >&2
+ cat "$metadata_output" >&2
+ exit 1
+fi
+build_messages="$temporary_output/cargo-build-messages.json"
+if ! "$cargo_bin" build --locked --release --manifest-path "$workspace" -p cyclops-sdk \
+ --message-format=json-render-diagnostics > "$build_messages"; then
+ echo "error: cargo failed to build cyclops-sdk" >&2
+ cat "$build_messages" >&2
+ exit 1
+fi
+if ! library="$("$cargo_bin" run --quiet --locked --manifest-path "$workspace" -p cyclops-sdk-bindgen --target "$host_triple" -- \
+ resolve-cdylib --sdk-manifest "$workspace_dir/sdk/Cargo.toml" --metadata "$metadata_output" \
+ --build-messages "$build_messages")"; then
+ echo "error: could not resolve the cyclops-sdk cdylib from Cargo JSON output" >&2
+ exit 1
+fi
+if [ ! -f "$library" ]; then
+ echo "error: resolved cyclops-sdk cdylib does not exist: $library" >&2
+ exit 1
+fi
+
+raw_output="$temporary_output/raw"
+generated_root="$temporary_output/generated"
+mkdir -p "$raw_output" "$generated_root/python/cyclops_sdk" "$generated_root/kotlin" \
+ "$generated_root/swift" "$generated_root/ruby/cyclops_sdk"
+"$cargo_bin" run --locked --manifest-path "$workspace" -p cyclops-sdk-bindgen --target "$host_triple" -- \
+ generate --library "$library" --config "$bindings_dir/uniffi.toml" \
+ --language python --language kotlin --language swift --language ruby \
+ --out-dir "$raw_output" --no-format
+
+mv "$raw_output/cyclops_sdk.py" "$generated_root/python/cyclops_sdk/_sdk.py"
+mv "$raw_output/cyclops_sdk_schema.py" "$generated_root/python/cyclops_sdk/_schema.py"
+write_python_facade \
+ "$generated_root/python/cyclops_sdk/_sdk.py" \
+ "$generated_root/python/cyclops_sdk/_schema.py" \
+ "$generated_root/python/cyclops_sdk/__init__.py"
+
+mv "$raw_output/ai" "$generated_root/kotlin/"
+mv "$raw_output/CyclopsSdk.swift" "$generated_root/swift/"
+mv "$raw_output/CyclopsSdkSchema.swift" "$generated_root/swift/"
+mv "$raw_output/CyclopsSdkFFI.h" "$generated_root/swift/"
+mv "$raw_output/CyclopsSdkFFI.modulemap" "$generated_root/swift/"
+mv "$raw_output/CyclopsSdkSchemaFFI.h" "$generated_root/swift/"
+mv "$raw_output/CyclopsSdkSchemaFFI.modulemap" "$generated_root/swift/"
+cat "$generated_root/swift/CyclopsSdkFFI.modulemap" "$generated_root/swift/CyclopsSdkSchemaFFI.modulemap" > "$generated_root/swift/CyclopsSdk.modulemap"
+
+mv "$raw_output/cyclops_sdk.rb" "$generated_root/ruby/cyclops_sdk/sdk.rb"
+mv "$raw_output/cyclops_sdk_schema.rb" "$generated_root/ruby/cyclops_sdk/schema.rb"
+write_ruby_facade \
+ "$generated_root/ruby/cyclops_sdk/sdk.rb" \
+ "$generated_root/ruby/cyclops_sdk/schema.rb" \
+ "$generated_root/ruby/cyclops_sdk.rb"
+
+normalize_generated_text
+for language in $languages; do
+ find -P "$generated_root/$language" -type d -exec chmod 755 {} \;
+ find -P "$generated_root/$language" -type f -exec chmod 644 {} \;
+ write_manifest "$generated_root/$language" "$temporary_output/$language.manifest"
+ mv "$temporary_output/$language.manifest" "$generated_root/$language/$manifest_name"
+ chmod 644 "$generated_root/$language/$manifest_name"
+done
+
+if "$check_only"; then
+ check_failed=false
+ for language in $languages; do
+ if ! compare_root "$generated_root/$language" "$bindings_dir/$language" "$language"; then
+ check_failed=true
+ fi
+ done
+ "$check_failed" && exit 1
+ echo "SDK bindings are up to date."
+ exit 0
+fi
+
+
+prepare_complete_replacement_root
+replace_binding_root
+
+echo "Generated SDK bindings in $bindings_dir."
diff --git a/libs/fleet/scripts/run-python-sdk-binding.sh b/libs/fleet/scripts/run-python-sdk-binding.sh
new file mode 100755
index 0000000000..6bb65af418
--- /dev/null
+++ b/libs/fleet/scripts/run-python-sdk-binding.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+bindings="$repo_root/cyclops-cs/sdk-bindings/python"
+library="$("$repo_root"/cyclops-cs/scripts/build-sdk-bindings-native.sh)"
+runtime="$(mktemp -d "${TMPDIR:-/tmp}/cyclops-python-sdk.XXXXXX")"
+trap 'rm -rf "$runtime"' EXIT
+cp -R "$bindings/cyclops_sdk" "$runtime/cyclops_sdk"
+cp "$library" "$runtime/cyclops_sdk/$(basename "$library")"
+target="$1"
+case "$target" in /*) ;; *) target="$repo_root/$target" ;; esac
+shift
+PYTHONPATH="$runtime:$bindings${PYTHONPATH:+:$PYTHONPATH}" python3 "$target" "$@"
diff --git a/libs/fleet/scripts/run-ruby-sdk-binding.sh b/libs/fleet/scripts/run-ruby-sdk-binding.sh
new file mode 100755
index 0000000000..30d1272d07
--- /dev/null
+++ b/libs/fleet/scripts/run-ruby-sdk-binding.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+bindings="$repo_root/cyclops-cs/sdk-bindings/ruby"
+library="$("$repo_root"/cyclops-cs/scripts/build-sdk-bindings-native.sh)"
+runtime="$(mktemp -d "${TMPDIR:-/tmp}/cyclops-ruby-sdk.XXXXXX")"
+trap 'rm -rf "$runtime"' EXIT
+cp -R "$bindings/cyclops_sdk" "$runtime/cyclops_sdk"
+cp "$bindings/cyclops_sdk.rb" "$runtime/cyclops_sdk.rb"
+cp "$library" "$runtime/cyclops_sdk/$(basename "$library")"
+library_dir="$runtime/cyclops_sdk"
+target="$1"
+case "$target" in /*) ;; *) target="$repo_root/$target" ;; esac
+shift
+case "$(uname -s)" in
+ Darwin) export DYLD_LIBRARY_PATH="$library_dir${DYLD_LIBRARY_PATH:+:$DYLD_LIBRARY_PATH}" ;;
+ Linux) export LD_LIBRARY_PATH="$library_dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ;;
+ MINGW*|MSYS*|CYGWIN*) export PATH="$library_dir:$PATH" ;;
+ *) echo "Unsupported Ruby SDK host: $(uname -s)" >&2; exit 1 ;;
+esac
+RUBYLIB="$runtime:$bindings${RUBYLIB:+:$RUBYLIB}" ruby "$target" "$@"
diff --git a/libs/fleet/scripts/run-swift-sdk-binding.sh b/libs/fleet/scripts/run-swift-sdk-binding.sh
new file mode 100755
index 0000000000..9867dc607f
--- /dev/null
+++ b/libs/fleet/scripts/run-swift-sdk-binding.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+swift_dir="$repo_root/cyclops-cs/sdk-bindings/swift"
+library="$("$repo_root"/cyclops-cs/scripts/build-sdk-bindings-native.sh)"
+library_dir="$(dirname "$library")"
+output="$(mktemp "${TMPDIR:-/tmp}/cyclops-swift-sdk.XXXXXX")"
+trap 'rm -f "$output"' EXIT
+target="$1"
+case "$target" in /*) ;; *) target="$repo_root/$target" ;; esac
+shift
+for header in CyclopsSdkFFI.h CyclopsSdkSchemaFFI.h; do
+ [ -f "$swift_dir/$header" ] || { echo "Swift FFI header is missing: $swift_dir/$header" >&2; exit 1; }
+done
+
+# Module-map headers resolve relative to their module-map directory.
+swiftc_args=(
+ -module-name CyclopsSdk
+ -I "$swift_dir"
+ -Xcc "-fmodule-map-file=$swift_dir/CyclopsSdkFFI.modulemap"
+ -Xcc "-fmodule-map-file=$swift_dir/CyclopsSdkSchemaFFI.modulemap"
+ -L "$library_dir"
+ -lcyclops_sdk
+ -Xlinker -rpath
+ -Xlinker "$library_dir"
+ "$swift_dir/CyclopsSdk.swift"
+ "$swift_dir/CyclopsSdkSchema.swift"
+ "$target"
+ "$@"
+ -o "$output"
+)
+swiftc "${swiftc_args[@]}"
+"$output"
diff --git a/libs/fleet/scripts/test-cleanup-live-sdk-example.sh b/libs/fleet/scripts/test-cleanup-live-sdk-example.sh
new file mode 100755
index 0000000000..987496a71e
--- /dev/null
+++ b/libs/fleet/scripts/test-cleanup-live-sdk-example.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+temporary="$(mktemp -d "${TMPDIR:-/tmp}/cyclops-live-cleanup-test.XXXXXX")"
+trap 'rm -rf "$temporary"' EXIT
+
+cat > "$temporary/curl" <<'FAKE_CURL'
+#!/usr/bin/env bash
+set -euo pipefail
+log="${CLEANUP_TEST_LOG:?}"
+output_file=""
+method="GET"
+url=""
+while (($#)); do
+ case "$1" in
+ -o|--output) output_file="$2"; shift 2 ;;
+ -X) method="$2"; shift 2 ;;
+ --write-out) shift 2 ;;
+ -H|-d|--data-urlencode) shift 2 ;;
+ --fail-with-body|--silent|--show-error) shift ;;
+ http*) url="$1"; shift ;;
+ *) shift ;;
+ esac
+done
+printf '%s %s\n' "$method" "$url" >> "$log"
+if [[ "$url" == *'/protocol/openid-connect/token' ]]; then
+ printf '{"access_token":"test-token"}\n'
+ exit 0
+fi
+if [[ "$method" == DELETE ]]; then
+ printf '204'
+ exit 0
+fi
+case "$url" in
+ */osgymsandboxclaims)
+ printf '{"items":[{"metadata":{"name":"claim-a"}}]}' > "$output_file"
+ ;;
+ */osgymworkspacepools)
+ printf '{"items":[{"metadata":{"name":"pool-a"}}]}' > "$output_file"
+ ;;
+ *)
+ printf '{"items":[]}' > "$output_file"
+ ;;
+esac
+printf '200'
+FAKE_CURL
+chmod +x "$temporary/curl"
+
+export CLEANUP_TEST_LOG="$temporary/requests.log"
+export CURL_BIN="$temporary/curl"
+export CUA_BASE_URL="https://run.example"
+export CUA_TOKEN_URL="https://auth.example/protocol/openid-connect/token"
+export CUA_CLIENT_ID="client-id"
+export CUA_CLIENT_SECRET="client-secret"
+export CYCLOPS_NAMESPACE="sdk-example-python-1-1"
+
+"$repo_root/cyclops-cs/scripts/cleanup-live-sdk-example.sh"
+
+cat > "$temporary/expected.log" <<'EXPECTED'
+POST https://auth.example/protocol/openid-connect/token
+GET https://run.example/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/sdk-example-python-1-1/osgymsandboxclaims
+DELETE https://run.example/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/sdk-example-python-1-1/osgymsandboxclaims/claim-a
+GET https://run.example/api/k8s/apis/cua.ai/v1/namespaces/sdk-example-python-1-1/osgymworkspacepools
+DELETE https://run.example/api/k8s/apis/cua.ai/v1/namespaces/sdk-example-python-1-1/osgymworkspacepools/pool-a
+DELETE https://run.example/api/namespaces/sdk-example-python-1-1
+EXPECTED
+
+diff -u "$temporary/expected.log" "$CLEANUP_TEST_LOG"
+printf 'live SDK cleanup regression checks passed.\n'
diff --git a/libs/fleet/scripts/test-generate-sdk-bindings.sh b/libs/fleet/scripts/test-generate-sdk-bindings.sh
new file mode 100755
index 0000000000..6eae66d31b
--- /dev/null
+++ b/libs/fleet/scripts/test-generate-sdk-bindings.sh
@@ -0,0 +1,440 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+workspace_dir="$repo_root/cyclops-cs"
+generator="$workspace_dir/scripts/generate-sdk-bindings.sh"
+bindings_dir="$workspace_dir/sdk-bindings"
+temporary_directory="$(mktemp -d "${TMPDIR:-/tmp}/cyclops-sdk-bindings-test.XXXXXX")"
+if cargo_bin="$(command -v cargo)" && [ -n "$cargo_bin" ]; then
+ :
+else
+ echo "error: cargo must be available on PATH" >&2
+ exit 127
+fi
+resolver_manifest="$workspace_dir/bindgen-cli/Cargo.toml"
+resolver_fixtures="$workspace_dir/bindgen-cli/tests/fixtures"
+handwritten_file="$bindings_dir/python/tests/task10-harness-preserved.txt"
+handwritten_directory="$(dirname "$handwritten_file")"
+handwritten_directory_created=false
+runtime_copy=""
+cargo_config_directory="$workspace_dir/.cargo"
+cargo_config_file="$cargo_config_directory/config.toml"
+cargo_config_directory_created=false
+cargo_config_active=false
+
+cleanup() {
+ if [ "$cargo_config_active" = true ] && [ -f "$cargo_config_file" ]; then
+ rm -f "$cargo_config_file"
+ fi
+ if [ "$cargo_config_directory_created" = true ]; then
+ # Trap cleanup must not override the harness result if the directory is nonempty.
+ rmdir "$cargo_config_directory" 2>/dev/null || true # lint-ignore: error-masking
+ fi
+ rm -rf "$temporary_directory"
+}
+trap cleanup EXIT HUP INT TERM
+mode_for() {
+ if stat -f '%Lp' "$1" >/dev/null 2>&1; then
+ stat -f '%Lp' "$1"
+ else
+ stat -c '%a' "$1"
+ fi
+}
+
+fail() {
+ echo "error: $1" >&2
+ exit 1
+}
+
+expect_check_failure() {
+ label="$1"
+ if "$generator" --check > "$temporary_directory/$label.log" 2>&1; then
+ fail "expected --check to reject $label"
+ fi
+}
+
+tree_hash() {
+ root="$1"
+ (
+ cd "$root"
+ find -P . -print | LC_ALL=C sort | while IFS= read -r path; do
+ if [ -L "$path" ]; then
+ printf 'link %s %s\n' "$path" "$(readlink "$path")"
+ elif [ -d "$path" ]; then
+ printf 'directory %s %s\n' "$path" "$(mode_for "$path")"
+ elif [ -f "$path" ]; then
+ printf 'file %s %s ' "$path" "$(mode_for "$path")"
+ cksum "$path"
+ else
+ printf 'other %s\n' "$path"
+ fi
+ done
+ ) | cksum
+}
+
+find_cyclops_sdk_library() {
+ metadata_output="$temporary_directory/cargo-metadata.json"
+ build_messages="$temporary_directory/cargo-build-messages.json"
+ if ! "$cargo_bin" metadata --locked --format-version 1 --no-deps --manifest-path "$workspace_dir/Cargo.toml" > "$metadata_output"; then
+ cat "$metadata_output" >&2
+ return 1
+ fi
+ if ! "$cargo_bin" build --locked --release --manifest-path "$workspace_dir/Cargo.toml" -p cyclops-sdk \
+ --message-format=json-render-diagnostics > "$build_messages"; then
+ cat "$build_messages" >&2
+ return 1
+ fi
+ "$cargo_bin" run --quiet --locked --manifest-path "$resolver_manifest" --target "$host_triple" -- \
+ resolve-cdylib --sdk-manifest "$workspace_dir/sdk/Cargo.toml" --metadata "$metadata_output" \
+ --build-messages "$build_messages"
+}
+assert_no_harness_artifacts() {
+ if [ -e "$handwritten_file" ] || [ -L "$handwritten_file" ]; then
+ fail "harness fixture was not removed"
+ fi
+ if [ "$handwritten_directory_created" = true ]; then
+ if [ -e "$handwritten_directory" ] || [ -L "$handwritten_directory" ]; then
+ fail "harness-created test directory was not removed"
+ fi
+ fi
+ [ -z "$runtime_copy" ] || [ ! -e "$runtime_copy" ] || fail "temporary Python runtime library was not removed"
+}
+
+assert_tree_unchanged() {
+ expected_hash="$1"
+ label="$2"
+ actual_hash="$(tree_hash "$bindings_dir")"
+ [ "$expected_hash" = "$actual_hash" ] || fail "$label changed sdk-bindings"
+ assert_no_harness_artifacts
+}
+
+expect_transaction_failure() {
+ point="$1"
+ baseline_hash="$2"
+ if CYCLOPS_SDK_BINDINGS_TEST_FAIL_TRANSACTION_POINT="$point" "$generator" \
+ > "$temporary_directory/failure-$point.log" 2>&1; then
+ fail "expected injected transaction failure at $point"
+ fi
+ assert_tree_unchanged "$baseline_hash" "transaction failure at $point"
+ "$generator" --check
+}
+
+expect_transaction_signal() {
+ point="$1"
+ signal="$2"
+ baseline_hash="$3"
+ if CYCLOPS_SDK_BINDINGS_TEST_SIGNAL_TRANSACTION_POINT="$point:$signal" "$generator" \
+ > "$temporary_directory/signal-$point-$signal.log" 2>&1; then
+ fail "expected injected $signal at $point"
+ fi
+ assert_tree_unchanged "$baseline_hash" "transaction signal $signal at $point"
+ "$generator" --check
+}
+
+
+expect_resolver_fixture() {
+ fixture="$1"
+ expected_library="$2"
+ actual_library="$("$cargo_bin" run --quiet --locked --manifest-path "$resolver_manifest" \
+ -- resolve-build-messages --package-id 'exact 0.1.0' \
+ --build-messages "$resolver_fixtures/$fixture")" || fail "resolver rejected $fixture"
+ [ "$actual_library" = "$expected_library" ] || fail "resolver selected the wrong library for $fixture"
+}
+
+expect_resolver_fixture_failure() {
+ fixture="$1"
+ expected_error="$2"
+ if "$cargo_bin" run --quiet --locked --manifest-path "$resolver_manifest" -- \
+ resolve-build-messages --package-id 'exact 0.1.0' \
+ --build-messages "$resolver_fixtures/$fixture" > "$temporary_directory/$fixture.log" 2>&1; then
+ fail "resolver unexpectedly accepted $fixture"
+ fi
+ grep -F "$expected_error" "$temporary_directory/$fixture.log" >/dev/null || \
+ fail "resolver error for $fixture did not mention $expected_error"
+}
+
+run_resolver_fixture_regressions() {
+ expect_resolver_fixture 'resolver-valid-reordered.jsonl' '/tmp/exact/libcyclops_sdk.so'
+ expect_resolver_fixture_failure 'resolver-multiple-artifacts.jsonl' 'multiple matching compiler-artifact records'
+ expect_resolver_fixture_failure 'resolver-multiple-libraries.jsonl' 'multiple host library filenames'
+ expect_resolver_fixture_failure 'resolver-no-match.jsonl' 'no matching compiler-artifact record'
+}
+
+
+host_triple="$(rustc -vV | sed -n 's/^host: //p')"
+[ -n "$host_triple" ] || fail "could not determine the Rust host target"
+
+run_resolver_fixture_regressions
+
+run_target_layout_regressions() {
+ build_target_directory="$temporary_directory/build-target-env"
+ CARGO_TARGET_DIR="$build_target_directory" CARGO_BUILD_TARGET="$host_triple" "$generator"
+ CARGO_TARGET_DIR="$build_target_directory" CARGO_BUILD_TARGET="$host_triple" "$generator" --check
+
+ if [ -e "$cargo_config_file" ] || [ -L "$cargo_config_file" ]; then
+ echo "skipping workspace Cargo config target regression: $cargo_config_file already exists" >&2
+ return 0
+ fi
+ if [ ! -d "$cargo_config_directory" ]; then
+ mkdir -p "$cargo_config_directory"
+ cargo_config_directory_created=true
+ fi
+ cat > "$cargo_config_file" <<EOF_CONFIG
+[build]
+target = "$host_triple"
+EOF_CONFIG
+ cargo_config_active=true
+
+ config_target_directory="$temporary_directory/build-target-config"
+ CARGO_TARGET_DIR="$config_target_directory" "$generator"
+ CARGO_TARGET_DIR="$config_target_directory" "$generator" --check
+
+ rm "$cargo_config_file"
+ cargo_config_active=false
+ if [ "$cargo_config_directory_created" = true ]; then
+ rmdir "$cargo_config_directory"
+ cargo_config_directory_created=false
+ fi
+}
+run_target_layout_regressions
+"$generator"
+run_language_linkage_audits() {
+ python3 - "$bindings_dir" <<'LANGUAGE_AUDIT'
+import re
+import sys
+from pathlib import Path
+
+bindings = Path(sys.argv[1])
+ruby_sdk = (bindings / "ruby/cyclops_sdk/sdk.rb").read_text(encoding="utf-8")
+ruby_schema = (bindings / "ruby/cyclops_sdk/schema.rb").read_text(encoding="utf-8")
+ruby_facade = (bindings / "ruby/cyclops_sdk.rb").read_text(encoding="utf-8")
+if "CyclopsSdkSchema.const_get(:RustBufferStream, false)" not in ruby_facade:
+ raise AssertionError("Ruby facade does not reflectively bridge the private schema stream")
+if "CyclopsSdkSchema::RustBufferStream" in ruby_facade:
+ raise AssertionError("Ruby facade directly references a private schema constant")
+for prefix in ("check_lower", "read", "write"):
+ references = set(re.findall(rf"\b{prefix}_Type[A-Za-z0-9_]+", ruby_sdk))
+ sdk_definitions = set(re.findall(rf"^\s*def (?:self\.)?({prefix}_Type[A-Za-z0-9_]+)", ruby_sdk, re.MULTILINE))
+ schema_definitions = set(re.findall(rf"^\s*def (?:self\.)?({prefix}_Type[A-Za-z0-9_]+)", ruby_schema, re.MULTILINE))
+ external = references - sdk_definitions
+ unresolved = sorted(external - schema_definitions)
+ if unresolved:
+ raise AssertionError(f"Ruby SDK has unresolved schema methods: {unresolved}")
+ unbridged = sorted(method for method in external if not re.search(rf"^\s+{re.escape(method)}$", ruby_facade, re.MULTILINE))
+ if unbridged:
+ raise AssertionError(f"Ruby facade does not bridge schema methods: {unbridged}")
+
+kotlin_sdk = (bindings / "kotlin/ai/cua/cyclops/sdk/cyclops_sdk.kt").read_text(encoding="utf-8")
+kotlin_schema = (bindings / "kotlin/ai/cua/cyclops/sdk/schema/cyclops_sdk_schema.kt").read_text(encoding="utf-8")
+if "package ai.cua.cyclops.sdk" not in kotlin_sdk or "package ai.cua.cyclops.sdk.schema" not in kotlin_schema:
+ raise AssertionError("Kotlin components are not generated into distinct configured packages")
+if "var `spec`: PoolSpec" not in kotlin_sdk or "data class PoolSpec" not in kotlin_schema:
+ raise AssertionError("Kotlin PoolSpec external type is not linked through the schema package")
+
+swift_sdk = (bindings / "swift/CyclopsSdk.swift").read_text(encoding="utf-8")
+swift_schema = (bindings / "swift/CyclopsSdkSchema.swift").read_text(encoding="utf-8")
+if "public var spec: PoolSpec" not in swift_sdk or "public struct PoolSpec" not in swift_schema:
+ raise AssertionError("Swift PoolSpec external type is not available for one-module compilation")
+pool_spec = re.search(
+ r"public struct PoolSpec: Equatable, Hashable \{(?P<body>.*?)\n\}\n\n#if compiler",
+ swift_schema,
+ re.DOTALL,
+)
+if pool_spec is None:
+ raise AssertionError("Swift PoolSpec is missing explicit Equatable and Hashable conformances")
+for method in ("public static func ==", "public func hash(into hasher: inout Hasher)"):
+ if method not in pool_spec.group("body"):
+ raise AssertionError(f"Swift PoolSpec is missing Rust-backed conformance method: {method}")
+LANGUAGE_AUDIT
+}
+run_language_linkage_audits
+initial_hash="$(tree_hash "$bindings_dir")"
+if [ ! -d "$handwritten_directory" ]; then
+ mkdir -p "$handwritten_directory"
+ handwritten_directory_created=true
+fi
+printf 'handwritten test fixture\n' > "$handwritten_file"
+"$generator"
+cmp -s "$handwritten_file" <(printf 'handwritten test fixture\n') || fail "normal generation removed handwritten test fixture"
+rm "$handwritten_file"
+if [ "$handwritten_directory_created" = true ]; then
+ rmdir "$handwritten_directory"
+fi
+assert_tree_unchanged "$initial_hash" "handwritten fixture cleanup"
+"$generator" --check
+
+runtime_library="$(find_cyclops_sdk_library)" || fail "could not read a cyclops-sdk cdylib from Cargo compiler-artifact output"
+[ -f "$runtime_library" ] || fail "Cargo reported a missing cyclops-sdk cdylib: $runtime_library"
+runtime_copy="$bindings_dir/python/cyclops_sdk/$(basename "$runtime_library")"
+cp "$runtime_library" "$runtime_copy"
+PYTHONPATH="$bindings_dir/python" python3 - "$bindings_dir/python/cyclops_sdk/_sdk.py" <<'PYTHON_SMOKE'
+import asyncio
+import json
+import re
+import sys
+
+import cyclops_sdk
+
+sdk_source = open(sys.argv[1], encoding="utf-8").read()
+required_private_exports = set(re.findall(r"\bcyclops_sdk\.(_[A-Za-z_][A-Za-z0-9_]*)", sdk_source))
+missing = sorted(required_private_exports.difference(vars(cyclops_sdk)))
+if missing:
+ raise AssertionError(f"missing schema-private SDK dependencies: {missing}")
+public_exports = set(cyclops_sdk.__all__)
+leaked = sorted(required_private_exports.intersection(public_exports))
+if leaked:
+ raise AssertionError(f"schema-private dependencies leaked into __all__: {leaked}")
+
+class CallbackHttpClient(cyclops_sdk.HttpClient):
+ def __init__(self):
+ self.requests = []
+
+ async def execute(self, request):
+ self.requests.append(request)
+ if request.url.endswith("/protocol/openid-connect/token"):
+ body = {"access_token": "offline-token", "expires_in": 3600}
+ elif request.url.endswith("/api/namespaces"):
+ body = {"metadata": {"name": "default"}}
+ elif request.url.endswith("/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools"):
+ body = {
+ "apiVersion": "cua.ai/v1",
+ "kind": "OSGymWorkspacePool",
+ "metadata": {"namespace": "default", "name": "offline-pool"},
+ "spec": {
+ "replicas": 1,
+ "template": {"containerDiskImage": "registry.example/desktop:offline"},
+ },
+ }
+ else:
+ raise AssertionError(f"unexpected callback request: {request.method} {request.url}")
+ return cyclops_sdk.HttpResponse(status=201, headers=[], body=json.dumps(body).encode())
+
+async def smoke_create_pool():
+ transport = CallbackHttpClient()
+ client = cyclops_sdk.CyclopsClient.connect(
+ cyclops_sdk.CyclopsConfiguration(
+ base_url="https://cyclops.invalid",
+ token_url="https://keycloak.invalid/realms/offline/protocol/openid-connect/token",
+ credentials=cyclops_sdk.CyclopsCredentials("client-id", "client-secret"),
+ pool_poll_interval_ms=1,
+ pool_poll_limit=1,
+ claim_poll_interval_ms=1,
+ claim_poll_limit=1,
+ ),
+ transport,
+ )
+ spec = cyclops_sdk.PoolSpec(
+ replicas=1,
+ template=cyclops_sdk.PoolTemplate(
+ runtime=None,
+ runtime_class_name=None,
+ node_selector=None,
+ tolerations=None,
+ command=None,
+ container_disk_image="registry.example/desktop:offline",
+ image_pull_secret=None,
+ cpu_cores=None,
+ memory=None,
+ firmware=None,
+ probes=None,
+ oidc=None,
+ ),
+ autoscaling=None,
+ services=None,
+ )
+ pool = await client.create_pool(cyclops_sdk.CreatePoolRequest(namespace="default", spec=spec))
+ assert pool.metadata.name == "offline-pool"
+ assert any(request.url.endswith("/osgymworkspacepools") for request in transport.requests)
+
+asyncio.run(smoke_create_pool())
+PYTHON_SMOKE
+rm "$runtime_copy"
+runtime_copy=""
+"$generator" --check
+baseline_hash="$(tree_hash "$bindings_dir")"
+assert_no_harness_artifacts
+
+stale_manifest="$bindings_dir/python/.cyclops-sdk-generated-files"
+stale_obsolete_root="$bindings_dir/python/cyclops_sdk/obsolete"
+stale_nested_root="$stale_obsolete_root/nested directory"
+stale_handwritten_root="$bindings_dir/python/cyclops_sdk/handwritten sibling"
+mkdir -p "$stale_nested_root" "$stale_handwritten_root"
+printf 'stale generated file\n' > "$stale_nested_root/stale generated.py"
+printf 'handwritten sibling\n' > "$stale_handwritten_root/keep.txt"
+cat >> "$stale_manifest" <<'EOF_MANIFEST'
+d cyclops_sdk/obsolete
+d cyclops_sdk/obsolete/nested directory
+f cyclops_sdk/obsolete/nested directory/stale generated.py
+EOF_MANIFEST
+expect_check_failure stale-manifest
+"$generator"
+if [ -e "$stale_obsolete_root" ] || [ -L "$stale_obsolete_root" ]; then
+ fail "normal generation retained stale manifest-owned directory"
+fi
+cmp -s "$stale_handwritten_root/keep.txt" <(printf 'handwritten sibling\n') || fail "normal generation removed handwritten sibling"
+"$generator" --check
+rm "$stale_handwritten_root/keep.txt"
+rmdir "$stale_handwritten_root"
+assert_tree_unchanged "$baseline_hash" "stale manifest cleanup"
+
+content_file="$bindings_dir/python/cyclops_sdk/__init__.py"
+content_file_mode="$(mode_for "$content_file")"
+cp "$content_file" "$temporary_directory/content-file"
+printf '\n# task10 content drift\n' >> "$content_file"
+expect_check_failure content
+mv "$temporary_directory/content-file" "$content_file"
+chmod "$content_file_mode" "$content_file"
+"$generator" --check
+
+mode_file="$bindings_dir/ruby/cyclops_sdk.rb"
+mode_file_mode="$(mode_for "$mode_file")"
+chmod 600 "$mode_file"
+expect_check_failure file-mode
+chmod "$mode_file_mode" "$mode_file"
+"$generator" --check
+
+type_file="$bindings_dir/python/cyclops_sdk/_schema.py"
+mv "$type_file" "$temporary_directory/type-file"
+mkdir "$type_file"
+expect_check_failure file-type
+rmdir "$type_file"
+mv "$temporary_directory/type-file" "$type_file"
+"$generator" --check
+
+file_link="$bindings_dir/python/cyclops_sdk/_sdk.py"
+mv "$file_link" "$temporary_directory/file-link-target"
+ln -s "$temporary_directory/file-link-target" "$file_link"
+expect_check_failure file-symlink
+[ -L "$file_link" ] || fail "file symlink disappeared during --check"
+[ -f "$temporary_directory/file-link-target" ] || fail "file symlink target changed during --check"
+rm "$file_link"
+mv "$temporary_directory/file-link-target" "$file_link"
+"$generator" --check
+
+directory_link="$bindings_dir/kotlin/ai"
+mv "$directory_link" "$temporary_directory/ai"
+ln -s "$temporary_directory/ai" "$directory_link"
+expect_check_failure directory-symlink
+[ -L "$directory_link" ] || fail "directory symlink disappeared during --check"
+[ -d "$temporary_directory/ai" ] || fail "directory symlink target changed during --check"
+rm "$directory_link"
+mv "$temporary_directory/ai" "$directory_link"
+"$generator" --check
+
+root_mode="$(mode_for "$bindings_dir/python")"
+chmod 700 "$bindings_dir/python"
+expect_check_failure root-mode
+chmod "$root_mode" "$bindings_dir/python"
+"$generator" --check
+
+expect_transaction_failure before-backup-move "$baseline_hash"
+expect_transaction_failure after-backup-move "$baseline_hash"
+expect_transaction_failure after-new-live "$baseline_hash"
+expect_transaction_signal after-backup-move INT "$baseline_hash"
+expect_transaction_signal after-new-live TERM "$baseline_hash"
+"$generator"
+assert_tree_unchanged "$baseline_hash" "normal root replacement"
+"$generator" --check
+
+printf 'generate-sdk-bindings regression checks passed.\n'
diff --git a/libs/fleet/sdk-bindings/README.md b/libs/fleet/sdk-bindings/README.md
index b6bd988588..c4a190e0a4 100644
--- a/libs/fleet/sdk-bindings/README.md
+++ b/libs/fleet/sdk-bindings/README.md
@@ -1,111 +1,222 @@
-# Cyclops multi-language SDK
+# Cyclops UniFFI SDK bindings
-Rust, TypeScript, Go, and Python expose typed `Pool`, `Claim`, and `Sandbox` resources. `connect` configures the Cyclops base URL and OAuth credentials once. The Rust core owns service routing, tokens, authorization headers, network execution, and one retry after `401`.
+This directory contains the checked-in, generated source for the official
+Cyclops SDK bindings: **Python, Kotlin, Swift, and Ruby**. Rust is the native
+`cyclops-sdk` API and owns the canonical implementation. JavaScript/OpenAPI
+clients, arbitrary community-language wrappers, and native-library packaging
+are outside this binding surface.
-## Porcelain API
+## Source of truth and compatibility
-Pool operations:
+`cyclops-cs/sdk-schema` is the canonical schema source. The raw Kubernetes
+CRD bundle at `clusters/base/osgym/crd.yaml` is derived from that schema with
+`generate-crds`; it is not hand-maintained and must not be post-processed.
+Short-term compatibility breaks in this evolving API are intentional. Update
+the schema and raw CRD together rather than adding compatibility shims,
+rewriters, or binding-specific post-processing.
-```text
-pool = create_pool({ namespace, spec: pool_spec })
-list_pools(namespace)
-get_pool(pool)
-update_pool(pool)
-delete_pool(pool)
-```
+Generated binding source is committed so review and drift checks are
+reproducible. Native libraries, Cargo target output, Gradle caches, and staged
+language runtime directories are not committed.
-Claim operations:
+## Prerequisites
-```text
-claim = create_claim({ pool })
-claim = create_claim({ pool, spec: claim_spec }) # optional advanced override
-list_claims(namespace)
-get_claim(claim)
-update_claim(claim)
-delete_claim(claim)
-sandbox = wait_claim(claim)
-```
+- Rust `1.97.0` with `rustfmt` and `clippy` (`cyclops-cs/rust-toolchain.toml`).
+- Python `3.11` for the Python contract fixture and source checker.
+- A supported Ruby `3.3` runtime for the Ruby fixture.
+- JDK `21` and Gradle `8.10.2` for Kotlin (or an equivalent checked-out
+ wrapper that resolves Gradle `8.10.2`).
+- A host C compiler and linker (`build-essential`/`pkg-config` on Ubuntu).
+- macOS Swift requires Xcode's `swiftc`; the native library is named
+ `libcyclops_sdk.dylib`. Linux uses `libcyclops_sdk.so`.
-`PoolSpec` and `ClaimSpec` come from the checked-in Kubernetes CRDs. `wait_claim` returns sandbox identity and the pool's available service names. It does not expose service endpoint URLs.
+Every command below is cwd-independent. Set `REPO_ROOT` to the absolute path
+of this checkout; CI uses `REPO_ROOT="$GITHUB_WORKSPACE"`.
-## Named service HTTP
+```sh
+REPO_ROOT=/absolute/path/to/cloud
+export REPO_ROOT
+```
-Select a client with a `Sandbox` and a user-defined pool service name. Requests use relative paths only. Unknown services raise a structured error with the requested name and sorted available names.
+## Generate and check
-Python returns an `httpx.Client` backed by an SDK transport:
+Generate the raw kube-derived CRDs after changing the schema:
-```python
-with sdk.service_client(sandbox, "mcp") as mcp:
- response = mcp.post("/mcp", json={"jsonrpc": "2.0", "method": "initialize"})
+```sh
+cargo run --locked --manifest-path "$REPO_ROOT/cyclops-cs/Cargo.toml" \
+ --package cyclops-sdk-schema --bin generate-crds -- \
+ --output "$REPO_ROOT/clusters/base/osgym/crd.yaml"
```
-TypeScript returns a fetch-compatible function:
+Verify the committed CRD bundle without rewriting it:
-```ts
-const mcp = sdk.serviceFetch(sandbox, "mcp")
-const response = await mcp("/mcp", { method: "POST", body: JSON.stringify(payload) })
+```sh
+cargo run --locked --manifest-path "$REPO_ROOT/cyclops-cs/Cargo.toml" \
+ --package cyclops-sdk-schema --bin generate-crds -- --check \
+ --output "$REPO_ROOT/clusters/base/osgym/crd.yaml"
```
-Go provides a `net/http`-style request adapter whose `Do` method executes through the core:
+Generate or check all four UniFFI language roots with the pinned workspace
+wrapper around UniFFI `0.32.0`:
-```go
-mcp, err := sdk.ServiceClient(sandbox, "mcp")
-request, err := mcp.NewRequest("POST", "/mcp", bytes.NewReader(body))
-response, err := mcp.Do(request)
+```sh
+"$REPO_ROOT/cyclops-cs/scripts/generate-sdk-bindings.sh"
+"$REPO_ROOT/cyclops-cs/scripts/generate-sdk-bindings.sh" --check
+"$REPO_ROOT/cyclops-cs/scripts/test-generate-sdk-bindings.sh"
```
-Rust provides an SDK-owned request builder:
+The regression harness verifies transaction rollback, inventory pruning,
+generated-file modes, symlink rejection, and structural cdylib discovery.
+It is intentionally a generator test, not compatibility post-processing.
+
+Check the hand-written contract fixtures, then run the checker self-test that
+proves comments alone do not satisfy source requirements:
-```rust
-let mut mcp = sdk.service_client(&sandbox, "mcp")?;
-let response = mcp.post("/mcp").body(body).send()?;
+```sh
+"$REPO_ROOT/cyclops-cs/scripts/check-sdk-binding-contract-sources.sh"
+"$REPO_ROOT/cyclops-cs/scripts/check-sdk-binding-contract-sources.sh" --self-test
```
-Applications never construct service endpoint URLs or receive OAuth tokens. The SDK does not expose a generic authenticated URL client; service selection plus a relative path is the only application-controlled HTTP route surface.
+## Build once and run bindings
+
+The launchers stage a freshly built host cdylib in a temporary language runtime
+and never copy it into generated source. To share one native build across
+commands, use this target directory:
-## App-controlled sequence
+```sh
+export CYCLOPS_SDK_NATIVE_TARGET_DIR="$REPO_ROOT/cyclops-cs/target/sdk-bindings-native"
+"$REPO_ROOT/cyclops-cs/scripts/build-sdk-bindings-native.sh"
+```
-Each example creates a pool with an `mcp` service, creates and waits for a claim, selects `mcp`, and sends MCP `initialize` to `/mcp`. Because binding resets the guest, examples retry transient `502`, `503`, and `504` responses for up to five minutes. Cleanup deletes the claim before the pool and then closes the SDK host.
+Run the Python contract and deterministic lifecycle example:
-```text
-cyclops-cs/sdk-bindings/examples/python/app_controlled.py
-cyclops-cs/sdk-bindings/examples/typescript/app-controlled.ts
-cyclops-cs/sdk-bindings/go/examples/app_controlled.go
-cyclops-cs/sdk-bindings/rust/examples/app_controlled.rs
+```sh
+"$REPO_ROOT/cyclops-cs/scripts/run-python-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/python/tests/test_async_client.py" -v
+"$REPO_ROOT/cyclops-cs/scripts/run-python-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/python/app_controlled.py"
```
-## Live example validation
+Run the Kotlin contract and example after staging the Linux cdylib:
+
+```sh
+export CYCLOPS_SDK_NATIVE_DIR="$(dirname "$CYCLOPS_SDK_NATIVE_TARGET_DIR/debug/libcyclops_sdk.so")"
+gradle -p "$REPO_ROOT/cyclops-cs/sdk-bindings/kotlin" contract
+gradle -p "$REPO_ROOT/cyclops-cs/sdk-bindings/kotlin" example
+```
-Build the shared Rust core runner and provide credentials through environment variables. Enter the client secret interactively so it does not enter shell history:
+Run the Ruby contract and example:
```sh
-cargo build --locked --manifest-path cyclops-cs/sdk-core/Cargo.toml --bin cyclops-core-runner
-export CYCLOPS_CORE_RUNNER="$(pwd)/cyclops-cs/sdk-core/target/debug/cyclops-core-runner"
-export CUA_CLIENT_ID="<client-id>"
-read -rsp "CUA client secret: " CUA_CLIENT_SECRET && export CUA_CLIENT_SECRET && printf '\n'
-export CUA_IMAGE="296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace@sha256:b9e74dbff4cc727c33ff4b8483bffa0860bb99213041c88f11260ac31db7628f"
-export CUA_IMAGE_PULL_SECRET="ecr-credentials"
+"$REPO_ROOT/cyclops-cs/scripts/run-ruby-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/ruby/tests/test_async_client.rb"
+"$REPO_ROOT/cyclops-cs/scripts/run-ruby-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/ruby/app_controlled.rb"
```
-`CUA_BASE_URL` defaults to `https://run.cua.ai`. `CUA_TOKEN_URL` defaults to the production Cyclops OAuth endpoint. Run examples independently so each receives a generated namespace:
+On macOS, run the Swift contract and full example. The documented runner
+compiles `CyclopsSdk.swift` and `CyclopsSdkSchema.swift` together into one
+`CyclopsSdk` module, includes both checked-in FFI module maps, and links with
+an rpath to the host `libcyclops_sdk.dylib`.
```sh
-uv run --project cyclops-cs/sdk-bindings/python python cyclops-cs/sdk-bindings/examples/python/app_controlled.py
-(cd cyclops-cs/sdk-bindings/typescript && npm run build && node dist-examples/app-controlled.js)
-(cd cyclops-cs/sdk-bindings/go && go run ./examples)
-cargo run --locked --manifest-path cyclops-cs/sdk-bindings/rust/Cargo.toml --example app_controlled
+"$REPO_ROOT/cyclops-cs/scripts/run-swift-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/swift/tests/TestAsyncClient.swift"
+"$REPO_ROOT/cyclops-cs/scripts/run-swift-sdk-binding.sh" \
+ "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/swift/AppControlled.swift"
```
-## Validation
+## Typed lifecycle shape
+
+Use the generated constructors and schema records rather than ad-hoc JSON.
+The exact optional fields and language naming are generated, so consult the
+checked-in language source for the complete constructor signatures. The Python
+shape is representative:
+
+```python
+credentials = CyclopsCredentials("client-id", "client-secret")
+client = CyclopsClient.connect(
+ CyclopsConfiguration(
+ base_url="https://api.example.test",
+ token_url="https://issuer.example.test/oauth/token",
+ credentials=credentials,
+ pool_poll_interval_ms=1_000,
+ pool_poll_limit=60,
+ claim_poll_interval_ms=1_000,
+ claim_poll_limit=60,
+ ),
+ transport,
+)
+
+pool_spec = PoolSpec(replicas=1, template=template, autoscaling=None, services=[])
+pool = await client.create_pool(CreatePoolRequest(namespace="default", spec=pool_spec))
+
+claim_spec = ClaimSpec(
+ sandbox_template_ref=SandboxTemplateRef(name=pool.metadata.name),
+ warmpool=None,
+ bind_deadline=None,
+ lifecycle=None,
+)
+claim = await client.create_claim(CreateClaimRequest(pool=pool, spec=claim_spec))
+sandbox = await client.wait_claim(claim)
+response = await client.service_request(sandbox, "mcp", "/health", request)
+await client.delete_claim(claim)
+await client.delete_pool(pool)
+```
+
+The Kotlin package is `ai.cua.cyclops.sdk`; Swift compiles as `CyclopsSdk`;
+Python and Ruby expose records through their public `cyclops_sdk` facade. The
+checked-in contract tests and examples above are the executable, per-language
+forms of this lifecycle.
+
+### Foreign HTTP client boundary
+
+`HttpClient` is asynchronous and foreign-language implemented. It is a
+security boundary: the callback sees OAuth client credentials in token-form
+requests, bearer tokens on authenticated requests, and resolved control-plane and
+service URLs. Treat it as trusted transport code: do not log or export
+those values, validate destination policy there, and preserve request/response
+body semantics. The SDK strips caller-supplied service `Authorization` and
+hop-by-hop headers before applying its own authentication.
+
+## CI mapping
+
+`.github/workflows/ci-cyclops-cs.yml` runs Linux Rust formatting, locked
+clippy/tests, raw CRD drift, binding drift, the generator harness, source
+checker/self-test, and Python/Kotlin/Ruby contracts plus examples. It pins
+Rust `1.97.0`, Python `3.11`, Ruby `3.3`, JDK `21`, and Gradle `8.10.2`.
+
+`.github/workflows/cyclops-sdk-swift.yml` runs on macOS, verifies generated
+bindings and the portable source checker, builds the host cdylib, checks the
+Mach-O architecture and library name, then runs both Swift fixtures through
+the one-module/rpath runner.
+
+## Troubleshooting
+
+- `cargo must be available on PATH`: install Rust `1.97.0` and retry with the
+ workspace toolchain active.
+- CRD or binding drift: run the matching generation command above and commit
+ only the raw generated source; do not patch it afterward.
+- `libcyclops_sdk` cannot load: run `build-sdk-bindings-native.sh`, export the
+ documented native target variables, and use the host-appropriate `.so` or
+ `.dylib` filename.
+- Kotlin cannot find JNA or the cdylib: use JDK 21/Gradle 8.10.2 and set
+ `CYCLOPS_SDK_NATIVE_DIR` to the staged library directory.
+- Swift cannot import FFI modules: run on macOS with Xcode Swift, keep both
+ FFI module maps beside the generated Swift files, and use the supplied
+ runner rather than compiling either generated file in isolation.
+
+## Live examples
+
+The `live_app_controlled` examples use the generated typed SDK records against a real Cyclops deployment. They create billable live resources. The regular `app_controlled` examples remain deterministic and offline.
+
+Set these variables before running a live example: `CUA_BASE_URL`, `CUA_TOKEN_URL`, `CUA_CLIENT_ID`, `CUA_CLIENT_SECRET`, `CYCLOPS_NAMESPACE`, `CUA_IMAGE`, and `CUA_IMAGE_PULL_SECRET`.
```sh
-(cd cyclops-cs/sdk-schema-generator && go run . -root ../.. -check)
-cargo fmt --manifest-path cyclops-cs/sdk-core/Cargo.toml -- --check
-cargo clippy --locked --manifest-path cyclops-cs/sdk-core/Cargo.toml --all-targets -- -D warnings
-cargo test --locked --manifest-path cyclops-cs/sdk-core/Cargo.toml
-cargo clippy --locked --manifest-path cyclops-cs/sdk-bindings/rust/Cargo.toml --all-targets -- -D warnings
-cargo test --locked --manifest-path cyclops-cs/sdk-bindings/rust/Cargo.toml --all-targets
-(cd cyclops-cs/sdk-bindings/typescript && npm ci && npm run typecheck && npm test)
-(cd cyclops-cs/sdk-bindings/go && test -z "$(gofmt -l .)" && go vet ./... && go test ./...)
-(cd cyclops-cs/sdk-bindings/python && uv run --with ruff==0.9.10 ruff check cyclops_sdk tests ../examples && uv run python -m unittest discover -s tests && uv build)
+cyclops-cs/scripts/run-python-sdk-binding.sh cyclops-cs/sdk-bindings/examples/python/live_app_controlled.py
+CYCLOPS_SDK_NATIVE_DIR="$CYCLOPS_SDK_NATIVE_TARGET_DIR/debug" gradle -p cyclops-cs/sdk-bindings/kotlin liveExample
+cyclops-cs/scripts/run-ruby-sdk-binding.sh cyclops-cs/sdk-bindings/examples/ruby/live_app_controlled.rb
+cyclops-cs/scripts/run-swift-sdk-binding.sh cyclops-cs/sdk-bindings/examples/swift/LiveAppControlled.swift
```
+
+The pull-request workflow obtains `CUA_CLIENT_ID`, `CUA_CLIENT_SECRET`, and `CUA_TOKEN_URL` from AWS Secrets Manager through GitHub OIDC. Forked pull requests are guarded from requesting those credentials, and every live job runs the language-independent fallback cleanup script under `if: always()`.
diff --git a/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
new file mode 100644
index 0000000000..4fba57f5dc
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
@@ -0,0 +1,47 @@
+import ai.cua.cyclops.sdk.*
+import ai.cua.cyclops.sdk.schema.*
+import kotlinx.coroutines.runBlocking
+import java.util.Collections
+
+private data class Expected(val method: String, val url: String, val headers: List<Pair<String, String>>, val body: ByteArray?, val status: UShort, val response: String)
+private class ScriptedHttpClient : HttpClient {
+ private val lock = Any()
+ private val expected = ArrayDeque(listOf(
+ Expected("POST", "https://keycloak.invalid/token", listOf("accept" to "application/json", "content-type" to "application/x-www-form-urlencoded"), "grant_type=client_credentials&client_id=client-id&client_secret=client-secret".encodeToByteArray(), 200u, "{\"access_token\":\"offline-token\",\"expires_in\":3600}"),
+ Expected("POST", "https://cyclops.invalid/api/namespaces", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), "{\"name\":\"default\"}".encodeToByteArray(), 201u, "{}"),
+ Expected("POST", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}".encodeToByteArray(), 201u, "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}"),
+ Expected("POST", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"claim-1\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":null}".encodeToByteArray(), 201u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
+ Expected("GET", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 200u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
+ Expected("GET", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 200u, "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}"),
+ Expected("POST", "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp", listOf("authorization" to "Bearer offline-token"), "{\"offline\":true}".encodeToByteArray(), 202u, "offline service accepted"),
+ Expected("DELETE", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, ""),
+ Expected("DELETE", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, ""),
+ Expected("DELETE", "https://cyclops.invalid/api/namespaces/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, "")
+ ))
+ override suspend fun execute(request: HttpRequest): HttpResponse = synchronized(lock) {
+ val item = expected.removeFirst()
+ check(request.method == item.method && request.url == item.url)
+ check(request.headers.map { it.name to it.value } == item.headers)
+ check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ HttpResponse(item.status, emptyList(), item.response.encodeToByteArray())
+ }
+ fun assertExhausted() = check(expected.isEmpty())
+}
+
+fun main() = runBlocking {
+ val vmTemplate = VmTemplate("registry.example/desktop:offline", null, null, null, null, null, null, null, null, null, null, null, null, null)
+ val spec = PoolSpec(1u, PoolTemplate(null, null, null, null, null, vmTemplate.containerDiskImage, null, null, null, null, null, null), null, listOf(SandboxService("mcp", 8080u, null)))
+ val transport = ScriptedHttpClient()
+ val credentials = CyclopsCredentials("client-id", "client-secret")
+ val client = CyclopsClient.connect(CyclopsConfiguration("https://cyclops.invalid", "https://keycloak.invalid/token", credentials, 1uL, 1u, 1uL, 2u), transport)
+ val pool = client.createPool(CreatePoolRequest("default", spec))
+ val claim = client.createClaim(CreateClaimRequest(pool, ClaimSpec(SandboxTemplateRef(pool.metadata.name), null, null, null)))
+ val sandbox = client.waitClaim(claim)
+ val service = client.serviceRequest(sandbox, "mcp", "/mcp", HttpRequest("POST", "https://ignored.invalid/mcp", emptyList(), "{\"offline\":true}".encodeToByteArray()))
+ client.deleteClaim(claim)
+ client.deletePool(pool)
+ check(pool.metadata.name == "default" && claim.metadata.name == "default" && sandbox.name == "offline-sandbox")
+ check(service.status == 202.toUShort())
+ transport.assertExhausted()
+ println("pool=${pool.metadata.name} claim=${claim.metadata.name} sandbox=${sandbox.name} service_status=${service.status}")
+}
diff --git a/libs/fleet/sdk-bindings/examples/kotlin/LiveAppControlled.kt b/libs/fleet/sdk-bindings/examples/kotlin/LiveAppControlled.kt
new file mode 100644
index 0000000000..427e426d94
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/kotlin/LiveAppControlled.kt
@@ -0,0 +1,97 @@
+import ai.cua.cyclops.sdk.*
+import ai.cua.cyclops.sdk.schema.*
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import java.net.URI
+import java.net.http.HttpClient as JdkHttpClient
+import java.net.http.HttpRequest as JdkHttpRequest
+import java.net.http.HttpResponse as JdkHttpResponse
+import java.time.Duration
+
+private fun required(name: String) = System.getenv(name)?.takeIf { it.isNotBlank() }
+ ?: error("$name is required")
+
+private class JavaHttpClient : HttpClient {
+ private val client = JdkHttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build()
+
+ override suspend fun execute(request: HttpRequest): HttpResponse {
+ val builder = JdkHttpRequest.newBuilder(URI.create(request.url)).timeout(Duration.ofSeconds(60))
+ request.headers.forEach { builder.header(it.name, it.value) }
+ val publisher = request.body?.let(JdkHttpRequest.BodyPublishers::ofByteArray)
+ ?: JdkHttpRequest.BodyPublishers.noBody()
+ builder.method(request.method, publisher)
+ val response = client.send(builder.build(), JdkHttpResponse.BodyHandlers.ofByteArray())
+ return HttpResponse(
+ response.statusCode().toUShort(),
+ response.headers().map().flatMap { (name, values) -> values.map { HttpHeader(name, it) } },
+ response.body(),
+ )
+ }
+}
+
+private fun poolSpec() = PoolSpec(
+ 1u,
+ PoolTemplate(
+ null, null, null, null, null,
+ required("CUA_IMAGE"),
+ required("CUA_IMAGE_PULL_SECRET"),
+ 4u,
+ "4Gi",
+ null, null, null,
+ ),
+ null,
+ listOf(SandboxService("mcp", 3000u, null)),
+)
+
+private suspend fun initializeMcp(client: CyclopsClient, sandbox: Sandbox): UShort {
+ val body = """{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"cyclops-uniffi-kotlin","version":"0.1.0"}}}""".encodeToByteArray()
+ val deadline = System.nanoTime() + Duration.ofMinutes(5).toNanos()
+ while (true) {
+ val response = client.serviceRequest(
+ sandbox,
+ "mcp",
+ "/mcp",
+ HttpRequest(
+ "POST",
+ "https://ignored.invalid/mcp",
+ listOf(
+ HttpHeader("accept", "application/json, text/event-stream"),
+ HttpHeader("content-type", "application/json"),
+ ),
+ body,
+ ),
+ )
+ if (response.status.toInt() in 200..299) return response.status
+ if (response.status.toInt() in setOf(502, 503, 504) && System.nanoTime() < deadline) {
+ delay(5_000)
+ continue
+ }
+ error("MCP initialize failed with HTTP ${response.status}: ${response.body.decodeToString()}")
+ }
+}
+
+fun main() = runBlocking {
+ val namespace = required("CYCLOPS_NAMESPACE")
+ val client = CyclopsClient.connect(
+ CyclopsConfiguration(
+ required("CUA_BASE_URL"),
+ required("CUA_TOKEN_URL"),
+ CyclopsCredentials(required("CUA_CLIENT_ID"), required("CUA_CLIENT_SECRET")),
+ 5_000uL, 120u, 5_000uL, 120u,
+ ),
+ JavaHttpClient(),
+ )
+ var pool: Pool? = null
+ var claim: Claim? = null
+ try {
+ pool = client.createPool(CreatePoolRequest(namespace, poolSpec()))
+ claim = client.createClaim(CreateClaimRequest(pool, null))
+ val sandbox = client.waitClaim(claim)
+ val status = initializeMcp(client, sandbox)
+ println("namespace=$namespace pool=${pool.metadata.name} claim=${claim.metadata.name} sandbox=${sandbox.name} mcp_status=$status")
+ } finally {
+ claim?.let { client.deleteClaim(it) }
+ pool?.let { client.deletePool(it) }
+ client.close()
+ }
+}
diff --git a/libs/fleet/sdk-bindings/examples/python/app_controlled.py b/libs/fleet/sdk-bindings/examples/python/app_controlled.py
index 34afd58472..6a8ccf9b5d 100644
--- a/libs/fleet/sdk-bindings/examples/python/app_controlled.py
+++ b/libs/fleet/sdk-bindings/examples/python/app_controlled.py
@@ -1,82 +1,6 @@
-#!/usr/bin/env python3
-"""Application-controlled pool, claim, and sandbox operation flow."""
-import json
-import os
-import time
-import uuid
-
-from cyclops_sdk import Claim, Pool, Sandbox, SDK, connect
-
-
-def run_agent(sdk: SDK, sandbox: Sandbox):
- deadline = time.monotonic() + 300
- with sdk.service_client(sandbox, "mcp") as mcp:
- while True:
- response = mcp.post(
- "/mcp",
- headers={
- "accept": "application/json, text/event-stream",
- "content-type": "application/json",
- },
- json={
- "jsonrpc": "2.0",
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": "2025-03-26",
- "capabilities": {},
- "clientInfo": {"name": "cyclops-sdk-python-example", "version": "0.1.0"},
- },
- },
- )
- if 200 <= response.status_code < 300:
- return {"namespace": sandbox["namespace"], "claim": sandbox["claim"], "sandbox": sandbox["sandbox"], "mcp_status": response.status_code}
- if response.status_code not in (502, 503, 504) or time.monotonic() >= deadline:
- raise RuntimeError(f"MCP initialize failed with HTTP {response.status_code}: {response.text}")
- time.sleep(5)
-
-
-def main():
- namespace = os.getenv("CYCLOPS_NAMESPACE", f"sdk-example-{uuid.uuid4().hex[:8]}")
- sdk = connect({
- "base_url": os.getenv("CUA_BASE_URL", "https://run.cua.ai"),
- "oauth": {
- "token_url": os.getenv("CUA_TOKEN_URL", "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"),
- "client_id": os.environ["CUA_CLIENT_ID"],
- "client_secret": os.environ["CUA_CLIENT_SECRET"],
- },
- })
- pool: Pool | None = None
- claim: Claim | None = None
- try:
- pool = sdk.create_pool({
- "namespace": namespace,
- "spec": {
- "replicas": 1,
- "services": [{"name": "mcp", "targetPort": 3000, "protocol": "TCP"}],
- "template": {
- "containerDiskImage": os.environ["CUA_IMAGE"],
- "imagePullSecret": os.environ["CUA_IMAGE_PULL_SECRET"],
- "cpuCores": 4,
- "memory": "4Gi",
- },
- },
- })
- claim = sdk.create_claim({"pool": pool})
- sandbox = sdk.wait_claim(claim)
- result = run_agent(sdk, sandbox)
- print(json.dumps(result, sort_keys=True))
- finally:
- try:
- if claim is not None:
- sdk.delete_claim(claim)
- finally:
- try:
- if pool is not None:
- sdk.delete_pool(pool)
- finally:
- sdk.close()
-
-
-if __name__ == "__main__":
- main()
+import asyncio
+from contract_fixture import ScriptedHttpClient, expected_lifecycle, run_lifecycle
+async def main():
+ pool, claim, sandbox, service = await run_lifecycle(ScriptedHttpClient(expected_lifecycle()))
+ print(f'pool={pool.metadata.name} claim={claim.metadata.name} sandbox={sandbox.name} service_status={service.status}')
+asyncio.run(main())
diff --git a/libs/fleet/sdk-bindings/examples/python/live_app_controlled.py b/libs/fleet/sdk-bindings/examples/python/live_app_controlled.py
new file mode 100755
index 0000000000..c31b54f2d1
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/python/live_app_controlled.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+import asyncio
+import json
+import os
+import time
+import urllib.error
+import urllib.request
+
+from cyclops_sdk import (
+ CreateClaimRequest,
+ CreatePoolRequest,
+ CyclopsClient,
+ CyclopsConfiguration,
+ CyclopsCredentials,
+ HttpClient,
+ HttpHeader,
+ HttpRequest,
+ HttpResponse,
+ PoolSpec,
+ PoolTemplate,
+ SandboxService,
+)
+
+
+class UrlLibHttpClient(HttpClient):
+ async def execute(self, request: HttpRequest) -> HttpResponse:
+ return await asyncio.to_thread(self._execute, request)
+
+ def _execute(self, request: HttpRequest) -> HttpResponse:
+ native = urllib.request.Request(
+ request.url,
+ data=request.body,
+ method=request.method,
+ headers={header.name: header.value for header in request.headers},
+ )
+ try:
+ with urllib.request.urlopen(native, timeout=60) as response:
+ return HttpResponse(
+ status=response.status,
+ headers=[HttpHeader(name=name, value=value) for name, value in response.headers.items()],
+ body=response.read(),
+ )
+ except urllib.error.HTTPError as error: # lint-ignore: swallowed-exception
+ return HttpResponse(
+ status=error.code,
+ headers=[HttpHeader(name=name, value=value) for name, value in error.headers.items()],
+ body=error.read(),
+ )
+
+
+def pool_spec(image: str, image_pull_secret: str) -> PoolSpec:
+ return PoolSpec(
+ replicas=1,
+ template=PoolTemplate(
+ runtime=None,
+ runtime_class_name=None,
+ node_selector=None,
+ tolerations=None,
+ command=None,
+ container_disk_image=image,
+ image_pull_secret=image_pull_secret,
+ cpu_cores=4,
+ memory="4Gi",
+ firmware=None,
+ probes=None,
+ oidc=None,
+ ),
+ autoscaling=None,
+ services=[SandboxService(name="mcp", target_port=3000, protocol=None)],
+ )
+
+
+async def initialize_mcp(client: CyclopsClient, sandbox) -> int:
+ body = json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "cyclops-uniffi-python", "version": "0.1.0"},
+ },
+ },
+ separators=(",", ":"),
+ ).encode()
+ deadline = time.monotonic() + 300
+ while True:
+ response = await client.service_request(
+ sandbox,
+ "mcp",
+ "/mcp",
+ HttpRequest(
+ method="POST",
+ url="https://ignored.invalid/mcp",
+ headers=[
+ HttpHeader(name="accept", value="application/json, text/event-stream"),
+ HttpHeader(name="content-type", value="application/json"),
+ ],
+ body=body,
+ ),
+ )
+ if 200 <= response.status < 300:
+ return response.status
+ if response.status in (502, 503, 504) and time.monotonic() < deadline:
+ await asyncio.sleep(5)
+ continue
+ raise RuntimeError(f"MCP initialize failed with HTTP {response.status}: {response.body!r}")
+
+
+async def main() -> None:
+ client_id = os.environ["CUA_CLIENT_ID"]
+ client_secret = os.environ["CUA_CLIENT_SECRET"]
+ base_url = os.environ["CUA_BASE_URL"]
+ token_url = os.environ["CUA_TOKEN_URL"]
+ namespace = os.environ["CYCLOPS_NAMESPACE"]
+ image_pull_secret = os.environ["CUA_IMAGE_PULL_SECRET"]
+ image = os.environ["CUA_IMAGE"]
+
+ client = CyclopsClient.connect(
+ CyclopsConfiguration(
+ base_url=base_url,
+ token_url=token_url,
+ credentials=CyclopsCredentials(client_id, client_secret),
+ pool_poll_interval_ms=5000,
+ pool_poll_limit=120,
+ claim_poll_interval_ms=5000,
+ claim_poll_limit=120,
+ ),
+ UrlLibHttpClient(),
+ )
+ pool = None
+ claim = None
+ try:
+ pool = await client.create_pool(
+ CreatePoolRequest(namespace=namespace, spec=pool_spec(image, image_pull_secret))
+ )
+ claim = await client.create_claim(CreateClaimRequest(pool=pool, spec=None))
+ sandbox = await client.wait_claim(claim)
+ status = await initialize_mcp(client, sandbox)
+ print(
+ json.dumps(
+ {
+ "namespace": namespace,
+ "pool": pool.metadata.name,
+ "claim": claim.metadata.name,
+ "sandbox": sandbox.name,
+ "mcp_status": status,
+ },
+ sort_keys=True,
+ )
+ )
+ finally:
+ if claim is not None:
+ await client.delete_claim(claim)
+ if pool is not None:
+ await client.delete_pool(pool)
+
+
+asyncio.run(main())
diff --git a/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
new file mode 100644
index 0000000000..d94bcddd70
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
@@ -0,0 +1,42 @@
+require 'json'
+require 'cyclops_sdk'
+
+require 'json'
+require 'thread'
+Expected = Struct.new(:method, :url, :headers, :body, :status, :response)
+BASE = 'https://cyclops.invalid'; TOKEN = 'https://keycloak.invalid/token'; JSON_HEADERS = [['accept','application/json'],['content-type','application/json'],['authorization','Bearer offline-token']]
+def pool_json; { apiVersion:'cua.ai/v1',kind:'OSGymWorkspacePool',metadata:{namespace:'default',name:'default',labels:nil},spec:{replicas:1,template:{containerDiskImage:'registry.example/desktop:offline'},services:[{name:'mcp',targetPort:8080}]},status:nil }; end
+def claim_json(bound=false); value={apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxClaim',metadata:{namespace:'default',name:'default',labels:nil},spec:{sandboxTemplateRef:{name:'default'}},status:nil}; value[:status]={phase:'Bound',sandbox:{name:'offline-sandbox'}} if bound; value; end
+def queue
+ pool_url="#{BASE}/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default"; claim_url="#{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default"; pool_body=JSON.generate(pool_json).b; claim_body='{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"claim-1","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":null}'.b
+ [Expected.new('POST',TOKEN,[['accept','application/json'],['content-type','application/x-www-form-urlencoded']], 'grant_type=client_credentials&client_id=client-id&client_secret=client-secret'.b,200,{access_token:'offline-token',expires_in:3600}),Expected.new('POST',"#{BASE}/api/namespaces",JSON_HEADERS,'{"name":"default"}'.b,201,{}),Expected.new('POST',pool_url.sub(%r{/default\z}, ''),JSON_HEADERS,pool_body,201,pool_json),Expected.new('POST',claim_url.sub(%r{/default\z}, ''),JSON_HEADERS,claim_body,201,claim_json),Expected.new('GET',claim_url,JSON_HEADERS,nil,200,claim_json(true)),Expected.new('GET',pool_url,JSON_HEADERS,nil,200,pool_json),Expected.new('POST',"#{BASE}/api/svc/default/offline-sandbox-mcp/mcp",[['authorization','Bearer offline-token']],'{"offline":true}'.b,202,'offline service accepted'),Expected.new('DELETE',claim_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',pool_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',"#{BASE}/api/namespaces/default",JSON_HEADERS,nil,204,'')]
+end
+
+class ScriptedHttpClient < CyclopsSdk::HttpClient
+ def initialize; @expected=queue; @mutex=Mutex.new; end
+ def execute(request)
+ @mutex.synchronize do
+ [email protected] or raise 'unexpected request'
+ actual=[request.method,request.url,request.headers.map{|h|[h.name,h.value]},request.body]
+ raise "request mismatch: #{actual.inspect}" unless actual == [item.method,item.url,item.headers,item.body]
+ body=item.response.is_a?(String) ? item.response.b : JSON.generate(item.response).b
+ CyclopsSdk::HttpResponse.new(status:item.status,headers:[],body:body)
+ end
+ end
+ def assert_exhausted!; raise @expected.inspect unless @expected.empty?; end
+end
+
+vm_template = CyclopsSdk::VmTemplate.new(container_disk_image: 'registry.example/desktop:offline', command: nil, runtime: nil, runtime_class_name: nil, node_selector: nil, tolerations: nil, image_pull_policy: nil, image_pull_secret: nil, cpu_cores: nil, memory: nil, firmware: nil, probes: nil, services: nil, oidc: nil)
+spec = CyclopsSdk::PoolSpec.new(replicas: 1, template: CyclopsSdk::PoolTemplate.new(runtime: nil, runtime_class_name: nil, node_selector: nil, tolerations: nil, command: nil, container_disk_image: vm_template.container_disk_image, image_pull_secret: nil, cpu_cores: nil, memory: nil, firmware: nil, probes: nil, oidc: nil), autoscaling: nil, services: [CyclopsSdk::SandboxService.new(name: 'mcp', target_port: 8080, protocol: nil)])
+transport = ScriptedHttpClient.new
+credentials = CyclopsSdk::CyclopsCredentials.new('client-id', 'client-secret')
+client = CyclopsSdk::CyclopsClient.connect(CyclopsSdk::CyclopsConfiguration.new(base_url: 'https://cyclops.invalid', token_url: 'https://keycloak.invalid/token', credentials: credentials, pool_poll_interval_ms: 1, pool_poll_limit: 1, claim_poll_interval_ms: 1, claim_poll_limit: 2), transport)
+pool = client.create_pool(CyclopsSdk::CreatePoolRequest.new(namespace: 'default', spec: spec))
+claim = client.create_claim(CyclopsSdk::CreateClaimRequest.new(pool: pool, spec: CyclopsSdk::ClaimSpec.new(sandbox_template_ref: CyclopsSdk::SandboxTemplateRef.new(name: pool.metadata.name), warmpool: nil, bind_deadline: nil, lifecycle: nil)))
+sandbox = client.wait_claim(claim)
+service = client.service_request(sandbox, 'mcp', '/mcp', CyclopsSdk::HttpRequest.new(method: 'POST', url: 'https://ignored.invalid/mcp', headers: [], body: '{"offline":true}'.b))
+client.delete_claim(claim)
+client.delete_pool(pool)
+transport.assert_exhausted!
+raise 'unexpected service response' unless service.status == 202
+puts "pool=#{pool.metadata.name} claim=#{claim.metadata.name} sandbox=#{sandbox.name} service_status=#{service.status}"
diff --git a/libs/fleet/sdk-bindings/examples/ruby/live_app_controlled.rb b/libs/fleet/sdk-bindings/examples/ruby/live_app_controlled.rb
new file mode 100755
index 0000000000..8d7e950ef0
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/ruby/live_app_controlled.rb
@@ -0,0 +1,59 @@
+#!/usr/bin/env ruby
+require 'json'
+require 'net/http'
+require 'uri'
+require 'cyclops_sdk'
+
+class NetHttpClient < CyclopsSdk::HttpClient
+ def execute(request)
+ uri = URI(request.url)
+ native = Net::HTTPGenericRequest.new(request.method, !request.body.nil?, request.method != 'HEAD', uri.request_uri, request.headers.to_h { |header| [header.name, header.value] })
+ native.body = request.body unless request.body.nil?
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 30, read_timeout: 60) { |http| http.request(native) }
+ CyclopsSdk::HttpResponse.new(status: response.code.to_i, headers: response.each_header.map { |name, value| CyclopsSdk::HttpHeader.new(name: name, value: value) }, body: response.body.to_s.b)
+ rescue StandardError => error
+ raise CyclopsSdk::HttpError::Transport.new(reason: error.message)
+ end
+end
+
+def required(name)
+ ENV.fetch(name).tap { |value| raise "#{name} is required" if value.empty? }
+end
+
+def pool_spec
+ CyclopsSdk::PoolSpec.new(replicas: 1, template: CyclopsSdk::PoolTemplate.new(runtime: nil, runtime_class_name: nil, node_selector: nil, tolerations: nil, command: nil, container_disk_image: required('CUA_IMAGE'), image_pull_secret: required('CUA_IMAGE_PULL_SECRET'), cpu_cores: 4, memory: '4Gi', firmware: nil, probes: nil, oidc: nil), autoscaling: nil, services: [CyclopsSdk::SandboxService.new(name: 'mcp', target_port: 3000, protocol: nil)])
+end
+
+def initialize_mcp(client, sandbox)
+ body = JSON.generate(jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'cyclops-uniffi-ruby', version: '0.1.0' } }).b
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 300
+ loop do
+ response = client.service_request(sandbox, 'mcp', '/mcp', CyclopsSdk::HttpRequest.new(method: 'POST', url: 'https://ignored.invalid/mcp', headers: [CyclopsSdk::HttpHeader.new(name: 'accept', value: 'application/json, text/event-stream'), CyclopsSdk::HttpHeader.new(name: 'content-type', value: 'application/json')], body: body))
+ return response.status if response.status.between?(200, 299)
+ if [502, 503, 504].include?(response.status) && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
+ sleep 5
+ next
+ end
+ raise "MCP initialize failed with HTTP #{response.status}: #{response.body.inspect}"
+ end
+end
+
+namespace = required('CYCLOPS_NAMESPACE')
+credentials = CyclopsSdk::CyclopsCredentials.new(required('CUA_CLIENT_ID'), required('CUA_CLIENT_SECRET'))
+configuration = CyclopsSdk::CyclopsConfiguration.new(base_url: required('CUA_BASE_URL'), token_url: required('CUA_TOKEN_URL'), credentials: credentials, pool_poll_interval_ms: 5000, pool_poll_limit: 120, claim_poll_interval_ms: 5000, claim_poll_limit: 120)
+client = CyclopsSdk::CyclopsClient.connect(configuration, NetHttpClient.new)
+pool = nil
+claim = nil
+begin
+ pool = client.create_pool(CyclopsSdk::CreatePoolRequest.new(namespace: namespace, spec: pool_spec))
+ claim = client.create_claim(CyclopsSdk::CreateClaimRequest.new(pool: pool, spec: nil))
+ sandbox = client.wait_claim(claim)
+ status = initialize_mcp(client, sandbox)
+ puts JSON.generate(namespace: namespace, pool: pool.metadata.name, claim: claim.metadata.name, sandbox: sandbox.name, mcp_status: status)
+ensure
+ begin
+ client.delete_claim(claim) unless claim.nil?
+ ensure
+ client.delete_pool(pool) unless pool.nil?
+ end
+end
diff --git a/libs/fleet/sdk-bindings/examples/swift/AppControlled.swift b/libs/fleet/sdk-bindings/examples/swift/AppControlled.swift
new file mode 100644
index 0000000000..7712e45890
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/swift/AppControlled.swift
@@ -0,0 +1,39 @@
+import Foundation
+
+actor ScriptedHttpClient: HttpClient {
+ private var expected: [(String, String, UInt16, String)] = [
+ ("POST", "https://keycloak.invalid/token", 200, #"{"access_token":"offline-token","expires_in":3600}"#),
+ ("POST", "https://cyclops.invalid/api/namespaces", 201, "{}"),
+ ("POST", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools", 201, #"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"replicas":1,"template":{"containerDiskImage":"registry.example/desktop:offline"},"services":[{"name":"mcp","targetPort":8080}]},"status":null}"#),
+ ("POST", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims", 201, #"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":{"phase":"Bound","sandbox":{"name":"offline-sandbox"}}}"#),
+ ("GET", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", 200, #"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":{"phase":"Bound","sandbox":{"name":"offline-sandbox"}}}"#),
+ ("GET", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", 200, #"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"replicas":1,"template":{"containerDiskImage":"registry.example/desktop:offline"},"services":[{"name":"mcp","targetPort":8080}]},"status":null}"#),
+ ("POST", "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp", 202, "offline service accepted"),
+ ("DELETE", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", 204, ""),
+ ("DELETE", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", 204, ""),
+ ("DELETE", "https://cyclops.invalid/api/namespaces/default", 204, "")]
+ private var requests = [HttpRequest]()
+ func execute(request: HttpRequest) async throws -> HttpResponse { let item = expected.removeFirst(); precondition(request.method == item.0 && request.url == item.1); requests.append(request); return HttpResponse(status: item.2, headers: [], body: Data(item.3.utf8)) }
+ func assertExhausted() { precondition(expected.isEmpty) }
+ func methods() -> [String] { requests.map(\.method) }
+}
+
+@main struct AppControlled {
+ static func main() async throws {
+ let vmTemplate = VmTemplate(containerDiskImage: "registry.example/desktop:offline", command: nil, runtime: nil, runtimeClassName: nil, nodeSelector: nil, tolerations: nil, imagePullPolicy: nil, imagePullSecret: nil, cpuCores: nil, memory: nil, firmware: nil, probes: nil, services: nil, oidc: nil)
+ let spec = PoolSpec(replicas: 1, template: PoolTemplate(runtime: nil, runtimeClassName: nil, nodeSelector: nil, tolerations: nil, command: nil, containerDiskImage: vmTemplate.containerDiskImage, imagePullSecret: nil, cpuCores: nil, memory: nil, firmware: nil, probes: nil, oidc: nil), autoscaling: nil, services: [SandboxService(name: "mcp", targetPort: 8080, protocol: nil)])
+ let transport = ScriptedHttpClient()
+ let credentials = CyclopsCredentials(clientId: "client-id", clientSecret: "client-secret")
+ let client = try CyclopsClient.connect(configuration: CyclopsConfiguration(baseUrl: "https://cyclops.invalid", tokenUrl: "https://keycloak.invalid/token", credentials: credentials, poolPollIntervalMs: 1, poolPollLimit: 1, claimPollIntervalMs: 1, claimPollLimit: 2), httpClient: transport)
+ let pool = try await client.createPool(request: CreatePoolRequest(namespace: "default", spec: spec))
+ let claim = try await client.createClaim(request: CreateClaimRequest(pool: pool, spec: ClaimSpec(sandboxTemplateRef: SandboxTemplateRef(name: pool.metadata.name), warmpool: nil, bindDeadline: nil, lifecycle: nil)))
+ let sandbox = try await client.waitClaim(claim: claim)
+ let service = try await client.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: HttpRequest(method: "POST", url: "https://ignored.invalid/mcp", headers: [], body: Data("{\"offline\":true}".utf8)))
+ try await client.deleteClaim(claim: claim)
+ try await client.deletePool(pool: pool)
+ await transport.assertExhausted()
+ let methods = await transport.methods()
+ precondition(methods == ["POST", "POST", "POST", "POST", "GET", "GET", "POST", "DELETE", "DELETE", "DELETE"])
+ print("pool=\(pool.metadata.name) claim=\(claim.metadata.name) sandbox=\(sandbox.name) service_status=\(service.status)")
+ }
+}
diff --git a/libs/fleet/sdk-bindings/examples/swift/LiveAppControlled.swift b/libs/fleet/sdk-bindings/examples/swift/LiveAppControlled.swift
new file mode 100644
index 0000000000..1fb2891c2a
--- /dev/null
+++ b/libs/fleet/sdk-bindings/examples/swift/LiveAppControlled.swift
@@ -0,0 +1,118 @@
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+
+final class UrlSessionHttpClient: HttpClient, @unchecked Sendable {
+ func execute(request: HttpRequest) async throws -> HttpResponse {
+ guard let url = URL(string: request.url) else {
+ throw HttpError.Transport(reason: "invalid URL: \(request.url)")
+ }
+ var native = URLRequest(url: url, timeoutInterval: 60)
+ native.httpMethod = request.method
+ request.headers.forEach { native.setValue($0.value, forHTTPHeaderField: $0.name) }
+ native.httpBody = request.body
+ do {
+ let (body, response) = try await URLSession.shared.data(for: native)
+ guard let http = response as? HTTPURLResponse else {
+ throw HttpError.Transport(reason: "non-HTTP response")
+ }
+ let headers = http.allHeaderFields.compactMap { key, value -> HttpHeader? in
+ guard let name = key as? String else { return nil }
+ return HttpHeader(name: name, value: String(describing: value))
+ }
+ return HttpResponse(status: UInt16(http.statusCode), headers: headers, body: body)
+ } catch let error as HttpError {
+ throw error
+ } catch {
+ throw HttpError.Transport(reason: error.localizedDescription)
+ }
+ }
+}
+
+private func required(_ name: String) -> String {
+ guard let value = ProcessInfo.processInfo.environment[name], !value.isEmpty else {
+ fatalError("\(name) is required")
+ }
+ return value
+}
+
+private func poolSpec() -> PoolSpec {
+ PoolSpec(
+ replicas: 1,
+ template: PoolTemplate(
+ runtime: nil, runtimeClassName: nil, nodeSelector: nil, tolerations: nil, command: nil,
+ containerDiskImage: required("CUA_IMAGE"), imagePullSecret: required("CUA_IMAGE_PULL_SECRET"),
+ cpuCores: 4, memory: "4Gi", firmware: nil, probes: nil, oidc: nil
+ ),
+ autoscaling: nil,
+ services: [SandboxService(name: "mcp", targetPort: 3000, protocol: nil)]
+ )
+}
+
+private func initializeMcp(client: CyclopsClient, sandbox: Sandbox) async throws -> UInt16 {
+ let body = Data(#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"cyclops-uniffi-swift","version":"0.1.0"}}}"#.utf8)
+ let clock = ContinuousClock()
+ let deadline = clock.now.advanced(by: .seconds(300))
+ while true {
+ let response = try await client.serviceRequest(
+ sandbox: sandbox,
+ service: "mcp",
+ path: "/mcp",
+ request: HttpRequest(
+ method: "POST",
+ url: "https://ignored.invalid/mcp",
+ headers: [
+ HttpHeader(name: "accept", value: "application/json, text/event-stream"),
+ HttpHeader(name: "content-type", value: "application/json"),
+ ],
+ body: body
+ )
+ )
+ if (200...299).contains(Int(response.status)) { return response.status }
+ if [502, 503, 504].contains(Int(response.status)) && clock.now < deadline {
+ try await Task.sleep(for: .seconds(5))
+ continue
+ }
+ throw HttpError.Transport(reason: "MCP initialize failed with HTTP \(response.status)")
+ }
+}
+
+private func cleanup(client: CyclopsClient, claim: Claim?, pool: Pool?) async {
+ do {
+ if let claim { try await client.deleteClaim(claim: claim) }
+ } catch {
+ FileHandle.standardError.write(Data("claim cleanup failed: \(error)\n".utf8))
+ }
+ do {
+ if let pool { try await client.deletePool(pool: pool) }
+ } catch {
+ FileHandle.standardError.write(Data("pool cleanup failed: \(error)\n".utf8))
+ }
+}
+
+@main struct LiveAppControlled {
+ static func main() async throws {
+ let namespace = required("CYCLOPS_NAMESPACE")
+ let credentials = CyclopsCredentials(clientId: required("CUA_CLIENT_ID"), clientSecret: required("CUA_CLIENT_SECRET"))
+ let client = try CyclopsClient.connect(
+ configuration: CyclopsConfiguration(baseUrl: required("CUA_BASE_URL"), tokenUrl: required("CUA_TOKEN_URL"), credentials: credentials, poolPollIntervalMs: 5_000, poolPollLimit: 120, claimPollIntervalMs: 5_000, claimPollLimit: 120),
+ httpClient: UrlSessionHttpClient()
+ )
+ var createdPool: Pool?
+ var createdClaim: Claim?
+ do {
+ let pool = try await client.createPool(request: CreatePoolRequest(namespace: namespace, spec: poolSpec()))
+ createdPool = pool
+ let claim = try await client.createClaim(request: CreateClaimRequest(pool: pool, spec: nil))
+ createdClaim = claim
+ let sandbox = try await client.waitClaim(claim: claim)
+ let status = try await initializeMcp(client: client, sandbox: sandbox)
+ print(#"{"namespace":"\#(namespace)","pool":"\#(pool.metadata.name)","claim":"\#(claim.metadata.name)","sandbox":"\#(sandbox.name)","mcp_status":\#(status)}"#)
+ } catch {
+ await cleanup(client: client, claim: createdClaim, pool: createdPool)
+ throw error
+ }
+ await cleanup(client: client, claim: createdClaim, pool: createdPool)
+ }
+}
diff --git a/libs/fleet/sdk-bindings/examples/typescript/app-controlled.ts b/libs/fleet/sdk-bindings/examples/typescript/app-controlled.ts
deleted file mode 100644
index 98ff071171..0000000000
--- a/libs/fleet/sdk-bindings/examples/typescript/app-controlled.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env -S node --enable-source-maps
-import { randomUUID } from "node:crypto"
-import { connect, type Claim, type Pool, type Sandbox, type SDK } from "../../typescript/dist/index.js"
-
-async function runAgent(sdk: SDK, sandbox: Sandbox): Promise<unknown> {
- const deadline = Date.now() + 300_000
- const mcp = sdk.serviceFetch(sandbox, "mcp")
- while (true) {
- const response = await mcp("/mcp", {
- method: "POST",
- headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },
- body: JSON.stringify({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "cyclops-sdk-typescript-example", version: "0.1.0" } },
- }),
- })
- if (response.status >= 200 && response.status < 300) {
- return { namespace: sandbox.namespace, claim: sandbox.claim, sandbox: sandbox.sandbox, mcp_status: response.status }
- }
- const body = await response.text()
- if (![502, 503, 504].includes(response.status) || Date.now() >= deadline) {
- throw new Error(`MCP initialize failed with HTTP ${response.status}: ${body}`)
- }
- await new Promise((resolve) => setTimeout(resolve, 5_000))
- }
-}
-
-
-const namespace = process.env.CYCLOPS_NAMESPACE ?? `sdk-example-${randomUUID().replaceAll("-", "").slice(0, 8)}`
-const sdk = await connect({
- baseUrl: process.env.CUA_BASE_URL ?? "https://run.cua.ai",
- oauth: {
- tokenUrl: process.env.CUA_TOKEN_URL ?? "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",
- clientId: required("CUA_CLIENT_ID"),
- clientSecret: required("CUA_CLIENT_SECRET"),
- },
-})
-let pool: Pool | undefined
-let claim: Claim | undefined
-try {
- pool = await sdk.createPool({
- namespace,
- spec: {
- replicas: 1,
- services: [{ name: "mcp", targetPort: 3000, protocol: "TCP" }],
- template: {
- containerDiskImage: required("CUA_IMAGE"),
- imagePullSecret: required("CUA_IMAGE_PULL_SECRET"),
- cpuCores: 4,
- memory: "4Gi",
- },
- },
- })
- claim = await sdk.createClaim({ pool })
- const sandbox = await sdk.waitClaim(claim)
- const result = await runAgent(sdk, sandbox)
- console.log(JSON.stringify(result))
-} finally {
- try {
- if (claim) await sdk.deleteClaim(claim)
- } finally {
- try {
- if (pool) await sdk.deletePool(pool)
- } finally {
- sdk.close()
- }
- }
-}
-
-function required(name: string): string {
- const value = process.env[name]
- if (!value) throw new Error(`${name} is required`)
- return value
-}
diff --git a/libs/fleet/sdk-bindings/go/.gitignore b/libs/fleet/sdk-bindings/go/.gitignore
deleted file mode 100644
index fc522ce6b9..0000000000
--- a/libs/fleet/sdk-bindings/go/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/go
-/cyclops-sdk-go
-/cyclops-sdk-raw
diff --git a/libs/fleet/sdk-bindings/go/examples/app_controlled.go b/libs/fleet/sdk-bindings/go/examples/app_controlled.go
deleted file mode 100644
index f661d85f36..0000000000
--- a/libs/fleet/sdk-bindings/go/examples/app_controlled.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package main
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "os"
- "time"
-
- cyclopssdk "github.com/trycua/cloud/cyclops-cs/sdk-bindings/go"
-)
-
-func runAgent(sdk *cyclopssdk.SDK, sandbox cyclopssdk.Sandbox) (any, error) {
- mcp, err := sdk.ServiceClient(sandbox, "mcp")
- if err != nil {
- return nil, err
- }
- body := []byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"cyclops-sdk-go-example","version":"0.1.0"}}}`)
- deadline := time.Now().Add(5 * time.Minute)
- for {
- request, err := mcp.NewRequest("POST", "/mcp", bytes.NewReader(body))
- if err != nil {
- return nil, err
- }
- request.Header.Set("accept", "application/json, text/event-stream")
- request.Header.Set("content-type", "application/json")
- response, err := mcp.Do(request)
- if err != nil {
- return nil, err
- }
- responseBody, readErr := io.ReadAll(response.Body)
- response.Body.Close()
- if readErr != nil {
- return nil, readErr
- }
- if response.StatusCode >= 200 && response.StatusCode < 300 {
- return map[string]any{"namespace": sandbox.Namespace, "claim": sandbox.Claim, "sandbox": sandbox.Sandbox, "mcp_status": response.StatusCode}, nil
- }
- transient := response.StatusCode == 502 || response.StatusCode == 503 || response.StatusCode == 504
- if !transient || time.Now().After(deadline) {
- return nil, fmt.Errorf("MCP initialize failed with HTTP %d: %s", response.StatusCode, responseBody)
- }
- time.Sleep(5 * time.Second)
- }
-}
-
-func main() {
- namespace := env("CYCLOPS_NAMESPACE", fmt.Sprintf("sdk-example-%08x", uint32(time.Now().UnixNano())))
- sdk, err := cyclopssdk.Connect(cyclopssdk.Configuration{
- BaseURL: env("CUA_BASE_URL", "https://run.cua.ai"),
- OAuth: cyclopssdk.OAuthConfiguration{
- TokenURL: env("CUA_TOKEN_URL", "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"),
- ClientID: required("CUA_CLIENT_ID"), ClientSecret: required("CUA_CLIENT_SECRET"),
- },
- })
- must(err)
- defer func() { must(sdk.Close()) }()
- cpuCores := uint32(4)
- memory := "4Gi"
- imagePullSecret := required("CUA_IMAGE_PULL_SECRET")
- protocol := cyclopssdk.PoolSpecServiceProtocolTCP
- pool, err := sdk.CreatePool(cyclopssdk.CreatePoolRequest{
- Namespace: namespace,
- Spec: cyclopssdk.PoolSpec{
- Replicas: 1,
- Services: []cyclopssdk.PoolSpecService{{
- Name: "mcp", TargetPort: 3000, Protocol: &protocol,
- }},
- Template: cyclopssdk.PoolTemplate{
- ContainerDiskImage: required("CUA_IMAGE"), ImagePullSecret: &imagePullSecret, CpuCores: &cpuCores, Memory: &memory,
- },
- },
- })
- must(err)
- defer func() { must(sdk.DeletePool(pool)) }()
- claim, err := sdk.CreateClaim(cyclopssdk.CreateClaimRequest{Pool: pool})
- must(err)
- defer func() { must(sdk.DeleteClaim(claim)) }()
- sandbox, err := sdk.WaitClaim(claim)
- must(err)
- result, err := runAgent(sdk, sandbox)
- must(err)
- output, err := json.Marshal(result)
- must(err)
- fmt.Println(string(output))
-}
-
-func env(name, fallback string) string {
- if value := os.Getenv(name); value != "" {
- return value
- }
- return fallback
-}
-func required(name string) string {
- if value := os.Getenv(name); value != "" {
- return value
- }
- panic(name + " is required")
-}
-func must(err error) {
- if err != nil && !errors.Is(err, os.ErrProcessDone) {
- panic(err)
- }
-}
diff --git a/libs/fleet/sdk-bindings/go/generated_crd.go b/libs/fleet/sdk-bindings/go/generated_crd.go
deleted file mode 100644
index 2e3ec1bec1..0000000000
--- a/libs/fleet/sdk-bindings/go/generated_crd.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-package cyclopssdk
-
-type ClaimSpec struct {
- BindDeadline *uint32 `json:"bindDeadline,omitempty"`
- Lifecycle *ClaimSpecLifecycle `json:"lifecycle,omitempty"`
- SandboxTemplateRef SandboxTemplateRef `json:"sandboxTemplateRef"`
- Warmpool *string `json:"warmpool,omitempty"`
-}
-
-type ClaimSpecLifecycle struct {
- AutoRenew *bool `json:"autoRenew,omitempty"`
- ShutdownPolicy *string `json:"shutdownPolicy,omitempty"`
- ShutdownTime *string `json:"shutdownTime,omitempty"`
-}
-
-type PoolSpec struct {
- Autoscaling *PoolSpecAutoscaling `json:"autoscaling,omitempty"`
- Replicas uint32 `json:"replicas"`
- Services []PoolSpecService `json:"services,omitempty"`
- Template PoolTemplate `json:"template"`
-}
-
-type PoolSpecAutoscaling struct {
- InitialPoolSize *uint32 `json:"initialPoolSize,omitempty"`
- MaxPoolSize *uint32 `json:"maxPoolSize,omitempty"`
- MinPoolSize *uint32 `json:"minPoolSize,omitempty"`
-}
-
-type PoolSpecService struct {
- Name string `json:"name"`
- Protocol *PoolSpecServiceProtocol `json:"protocol,omitempty"`
- TargetPort uint32 `json:"targetPort"`
-}
-
-type PoolSpecServiceProtocol string
-
-const (
- PoolSpecServiceProtocolTCP PoolSpecServiceProtocol = "TCP"
- PoolSpecServiceProtocolUDP PoolSpecServiceProtocol = "UDP"
-)
-
-type PoolTemplate struct {
- Command []string `json:"command,omitempty"`
- ContainerDiskImage string `json:"containerDiskImage"`
- CpuCores *uint32 `json:"cpuCores,omitempty"`
- Firmware *PoolTemplateFirmware `json:"firmware,omitempty"`
- ImagePullSecret *string `json:"imagePullSecret,omitempty"`
- Memory *string `json:"memory,omitempty"`
- NodeSelector map[string]string `json:"nodeSelector,omitempty"`
- Oidc *PoolTemplateOidc `json:"oidc,omitempty"`
- Probes any `json:"probes,omitempty"`
- Runtime *PoolTemplateRuntime `json:"runtime,omitempty"`
- RuntimeClassName *string `json:"runtimeClassName,omitempty"`
- Tolerations []any `json:"tolerations,omitempty"`
-}
-
-type PoolTemplateFirmware string
-
-const (
- PoolTemplateFirmwareBios PoolTemplateFirmware = "bios"
- PoolTemplateFirmwareEfi PoolTemplateFirmware = "efi"
-)
-
-type PoolTemplateOidc struct {
- AwsRegion *string `json:"awsRegion,omitempty"`
- AwsRoleArn *string `json:"awsRoleArn,omitempty"`
- CredentialsSecret string `json:"credentialsSecret"`
- RefreshIntervalSeconds *uint32 `json:"refreshIntervalSeconds,omitempty"`
- TokenUrl string `json:"tokenUrl"`
-}
-
-type PoolTemplateRuntime string
-
-const (
- PoolTemplateRuntimeKubevirt PoolTemplateRuntime = "kubevirt"
- PoolTemplateRuntimeMacos PoolTemplateRuntime = "macos"
- PoolTemplateRuntimeGvisor PoolTemplateRuntime = "gvisor"
-)
-
-type SandboxTemplateRef struct {
- Name string `json:"name"`
-}
diff --git a/libs/fleet/sdk-bindings/go/go.mod b/libs/fleet/sdk-bindings/go/go.mod
deleted file mode 100644
index 54d0750622..0000000000
--- a/libs/fleet/sdk-bindings/go/go.mod
+++ /dev/null
@@ -1,3 +0,0 @@
-module github.com/trycua/cloud/cyclops-cs/sdk-bindings/go
-
-go 1.23.6
diff --git a/libs/fleet/sdk-bindings/go/public_api_test.go b/libs/fleet/sdk-bindings/go/public_api_test.go
deleted file mode 100644
index 6e729748d8..0000000000
--- a/libs/fleet/sdk-bindings/go/public_api_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package cyclopssdk
-
-import (
- "net/http"
- "testing"
-)
-
-func TestTypedResourceAPIOnly(t *testing.T) {
- var _ func(Configuration) (*SDK, error) = Connect
- var _ func(*SDK, CreatePoolRequest) (Pool, error) = (*SDK).CreatePool
- var _ func(*SDK, string) ([]Pool, error) = (*SDK).ListPools
- var _ func(*SDK, Pool) (Pool, error) = (*SDK).GetPool
- var _ func(*SDK, Pool) (Pool, error) = (*SDK).UpdatePool
- var _ func(*SDK, Pool) error = (*SDK).DeletePool
- var _ func(*SDK, CreateClaimRequest) (Claim, error) = (*SDK).CreateClaim
- var _ func(*SDK, string) ([]Claim, error) = (*SDK).ListClaims
- var _ func(*SDK, Claim) (Claim, error) = (*SDK).GetClaim
- var _ func(*SDK, Claim) (Claim, error) = (*SDK).UpdateClaim
- var _ func(*SDK, Claim) error = (*SDK).DeleteClaim
- var _ func(*SDK, Claim) (Sandbox, error) = (*SDK).WaitClaim
- var _ func(*SDK, Sandbox, string) (*ServiceClient, error) = (*SDK).ServiceClient
- var _ func(*ServiceClient, *http.Request) (*http.Response, error) = (*ServiceClient).Do
- var _ func(*SDK) error = (*SDK).Close
-}
-
-func TestUnknownServiceErrorListsAvailableNames(t *testing.T) {
- _, err := (&SDK{}).ServiceClient(Sandbox{Services: []string{"novnc", "mcp", "mcp"}}, "metrics")
- serviceErr, ok := err.(*UnknownServiceError)
- if !ok {
- t.Fatalf("error = %T, want *UnknownServiceError", err)
- }
- if serviceErr.Requested != "metrics" {
- t.Fatalf("requested = %q", serviceErr.Requested)
- }
- if got := serviceErr.Available; len(got) != 2 || got[0] != "mcp" || got[1] != "novnc" {
- t.Fatalf("available = %v", got)
- }
-}
-
-func TestServiceClientBuildsRelativeRequests(t *testing.T) {
- client := &ServiceClient{}
- request, err := client.NewRequest("POST", "/mcp?session=one", nil)
- if err != nil {
- t.Fatal(err)
- }
- if request.URL.IsAbs() || request.URL.Host != "" {
- t.Fatalf("URL = %s, want relative", request.URL)
- }
- if path, err := relativeRequestPath(request.URL); err != nil || path != "/mcp?session=one" {
- t.Fatalf("path = %q, err = %v", path, err)
- }
-}
diff --git a/libs/fleet/sdk-bindings/go/sdk.go b/libs/fleet/sdk-bindings/go/sdk.go
deleted file mode 100644
index 14b1f951d3..0000000000
--- a/libs/fleet/sdk-bindings/go/sdk.go
+++ /dev/null
@@ -1,361 +0,0 @@
-package cyclopssdk
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
- "os/exec"
- "sort"
- "strings"
- "time"
-)
-
-type OAuthConfiguration struct {
- TokenURL string `json:"token_url"`
- ClientID string `json:"client_id"`
- ClientSecret string `json:"client_secret"`
-}
-type Configuration struct {
- BaseURL string `json:"base_url"`
- OAuth OAuthConfiguration `json:"oauth"`
-}
-type ResourceMetadata struct {
- Namespace string `json:"namespace"`
- Name string `json:"name"`
- Labels map[string]string `json:"labels,omitempty"`
-}
-type Pool struct {
- APIVersion string `json:"apiVersion"`
- Kind string `json:"kind"`
- Metadata ResourceMetadata `json:"metadata"`
- Spec map[string]any `json:"spec"`
- Status map[string]any `json:"status,omitempty"`
-}
-type Claim struct {
- APIVersion string `json:"apiVersion"`
- Kind string `json:"kind"`
- Metadata ResourceMetadata `json:"metadata"`
- Spec map[string]any `json:"spec"`
- Status map[string]any `json:"status,omitempty"`
-}
-type Sandbox struct {
- Namespace string `json:"namespace"`
- Claim string `json:"claim"`
- Sandbox string `json:"sandbox"`
- Services []string `json:"services"`
-}
-type CreatePoolRequest struct {
- Namespace string `json:"namespace"`
- Spec PoolSpec `json:"spec"`
-}
-type CreateClaimRequest struct {
- Pool Pool `json:"pool"`
- Spec *ClaimSpec `json:"spec,omitempty"`
-}
-type serviceRequest struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Headers [][2]string `json:"headers"`
- Body *string `json:"body,omitempty"`
-}
-type serviceResponse struct {
- Status int `json:"status"`
- Body string `json:"body"`
-}
-type UnknownServiceError struct {
- Requested string
- Available []string
-}
-
-func (error *UnknownServiceError) Error() string {
- return fmt.Sprintf("unknown sandbox service %q; available services: %v", error.Requested, error.Available)
-}
-
-type SDK struct {
- configuration Configuration
- command *exec.Cmd
- input io.WriteCloser
- output *bufio.Reader
- token map[string]any
-}
-type ServiceClient struct {
- sdk *SDK
- sandbox Sandbox
- service string
-}
-
-type hostCall struct {
- Kind string `json:"kind"`
- Request *struct {
- Method string `json:"method"`
- URL string `json:"url"`
- Headers [][2]string `json:"headers"`
- Body *string `json:"body"`
- } `json:"request,omitempty"`
- Milliseconds int64 `json:"milliseconds,omitempty"`
- Token map[string]any `json:"token,omitempty"`
-}
-type reply struct {
- OK bool `json:"ok"`
- Value json.RawMessage `json:"value"`
- Error string `json:"error,omitempty"`
-}
-
-func Connect(configuration Configuration) (*SDK, error) {
- command := exec.Command(env("CYCLOPS_CORE_RUNNER", "cyclops-core-runner"))
- input, err := command.StdinPipe()
- if err != nil {
- return nil, err
- }
- output, err := command.StdoutPipe()
- if err != nil {
- return nil, err
- }
- command.Stderr = os.Stderr
- if err := command.Start(); err != nil {
- return nil, err
- }
- sdk := &SDK{configuration: configuration, command: command, input: input, output: bufio.NewReader(output)}
- if err := sdk.call(map[string]any{"op": "configure", "configuration": map[string]any{"protocol_version": 7, "base_url": configuration.BaseURL}}, nil); err != nil {
- _ = sdk.Close()
- return nil, err
- }
- return sdk, nil
-}
-func (sdk *SDK) CreatePool(request CreatePoolRequest) (Pool, error) {
- var value Pool
- return value, sdk.call(map[string]any{"op": "create_pool", "request": request}, &value)
-}
-func (sdk *SDK) ListPools(namespace string) ([]Pool, error) {
- var value []Pool
- return value, sdk.call(map[string]any{"op": "list_pools", "namespace": namespace}, &value)
-}
-func (sdk *SDK) GetPool(pool Pool) (Pool, error) {
- var value Pool
- return value, sdk.call(map[string]any{"op": "get_pool", "pool": pool}, &value)
-}
-func (sdk *SDK) UpdatePool(pool Pool) (Pool, error) {
- var value Pool
- return value, sdk.call(map[string]any{"op": "update_pool", "pool": pool}, &value)
-}
-func (sdk *SDK) DeletePool(pool Pool) error {
- return sdk.call(map[string]any{"op": "delete_pool", "pool": pool}, nil)
-}
-func (sdk *SDK) CreateClaim(request CreateClaimRequest) (Claim, error) {
- var value Claim
- return value, sdk.call(map[string]any{"op": "create_claim", "request": request}, &value)
-}
-func (sdk *SDK) ListClaims(namespace string) ([]Claim, error) {
- var value []Claim
- return value, sdk.call(map[string]any{"op": "list_claims", "namespace": namespace}, &value)
-}
-func (sdk *SDK) GetClaim(claim Claim) (Claim, error) {
- var value Claim
- return value, sdk.call(map[string]any{"op": "get_claim", "claim": claim}, &value)
-}
-func (sdk *SDK) UpdateClaim(claim Claim) (Claim, error) {
- var value Claim
- return value, sdk.call(map[string]any{"op": "update_claim", "claim": claim}, &value)
-}
-func (sdk *SDK) DeleteClaim(claim Claim) error {
- return sdk.call(map[string]any{"op": "delete_claim", "claim": claim}, nil)
-}
-func (sdk *SDK) WaitClaim(claim Claim) (Sandbox, error) {
- var value Sandbox
- return value, sdk.call(map[string]any{"op": "wait_claim", "claim": claim}, &value)
-}
-func (sdk *SDK) ServiceClient(sandbox Sandbox, service string) (*ServiceClient, error) {
- available := append([]string(nil), sandbox.Services...)
- sort.Strings(available)
- available = compactStrings(available)
- for _, candidate := range available {
- if candidate == service {
- return &ServiceClient{sdk: sdk, sandbox: sandbox, service: service}, nil
- }
- }
- return nil, &UnknownServiceError{Requested: service, Available: available}
-}
-func (client *ServiceClient) NewRequest(method, path string, body io.Reader) (*http.Request, error) {
- if err := validateServicePath(path); err != nil {
- return nil, err
- }
- request, err := http.NewRequest(method, "https://cyclops.invalid"+path, body)
- if err != nil {
- return nil, err
- }
- request.URL.Scheme = ""
- request.URL.Host = ""
- request.Host = ""
- return request, nil
-}
-func (client *ServiceClient) Do(request *http.Request) (*http.Response, error) {
- path, err := relativeRequestPath(request.URL)
- if err != nil {
- return nil, err
- }
- var body *string
- if request.Body != nil {
- data, readErr := io.ReadAll(request.Body)
- if readErr != nil {
- return nil, readErr
- }
- value := string(data)
- body = &value
- }
- headers := make([][2]string, 0, len(request.Header))
- for name, values := range request.Header {
- for _, value := range values {
- headers = append(headers, [2]string{name, value})
- }
- }
- var response serviceResponse
- err = client.sdk.call(map[string]any{
- "op": "service_request",
- "sandbox": client.sandbox,
- "service": client.service,
- "request": serviceRequest{Method: request.Method, Path: path, Headers: headers, Body: body},
- }, &response)
- if err != nil {
- return nil, err
- }
- return &http.Response{
- StatusCode: response.Status,
- Status: fmt.Sprintf("%d %s", response.Status, http.StatusText(response.Status)),
- Header: make(http.Header),
- Body: io.NopCloser(strings.NewReader(response.Body)),
- Request: request,
- }, nil
-}
-func (sdk *SDK) Close() error {
- if sdk.input != nil {
- _ = sdk.input.Close()
- }
- if sdk.command != nil {
- return sdk.command.Wait()
- }
- return nil
-}
-
-func (sdk *SDK) call(request any, result any) error {
- if err := json.NewEncoder(sdk.input).Encode(request); err != nil {
- return err
- }
- for {
- line, err := sdk.output.ReadBytes('\n')
- if err != nil {
- return err
- }
- var message map[string]json.RawMessage
- if err := json.Unmarshal(line, &message); err != nil {
- return err
- }
- if kindRaw, ok := message["kind"]; ok {
- var call hostCall
- if err := json.Unmarshal(line, &call); err != nil {
- return err
- }
- value, dispatchErr := sdk.dispatch(call)
- response := map[string]any{"ok": dispatchErr == nil, "value": value}
- if dispatchErr != nil {
- response["error"] = map[string]string{"transport": dispatchErr.Error()}
- }
- if err := json.NewEncoder(sdk.input).Encode(response); err != nil {
- return err
- }
- _ = kindRaw
- continue
- }
- var response reply
- if err := json.Unmarshal(line, &response); err != nil {
- return err
- }
- if !response.OK {
- return fmt.Errorf("%s", response.Error)
- }
- if result != nil && len(response.Value) > 0 && string(response.Value) != "null" {
- return json.Unmarshal(response.Value, result)
- }
- return nil
- }
-}
-func (sdk *SDK) dispatch(call hostCall) (any, error) {
- switch call.Kind {
- case "http":
- body := io.Reader(nil)
- if call.Request.Body != nil {
- body = bytes.NewBufferString(*call.Request.Body)
- }
- request, err := http.NewRequest(call.Request.Method, call.Request.URL, body)
- if err != nil {
- return nil, err
- }
- for _, header := range call.Request.Headers {
- request.Header.Add(header[0], header[1])
- }
- client := &http.Client{CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
- response, err := client.Do(request)
- if err != nil {
- return nil, err
- }
- defer response.Body.Close()
- data, err := io.ReadAll(response.Body)
- return map[string]any{"status": response.StatusCode, "body": string(data)}, err
- case "sleep":
- time.Sleep(time.Duration(call.Milliseconds) * time.Millisecond)
- return nil, nil
- case "now_ms":
- return time.Now().UnixMilli(), nil
- case "acquire_oauth_credentials":
- return map[string]string{"token_url": sdk.configuration.OAuth.TokenURL, "client_id": sdk.configuration.OAuth.ClientID, "client_secret": sdk.configuration.OAuth.ClientSecret}, nil
- case "load_access_token":
- return sdk.token, nil
- case "store_access_token":
- sdk.token = call.Token
- return nil, nil
- default:
- return nil, fmt.Errorf("unknown host call %s", call.Kind)
- }
-}
-func validateServicePath(path string) error {
- if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") || strings.Contains(path, "#") {
- return fmt.Errorf("service request path must be relative and start with '/': %s", path)
- }
- return nil
-}
-func relativeRequestPath(value *url.URL) (string, error) {
- if value == nil || value.IsAbs() || value.Host != "" {
- return "", fmt.Errorf("service requests must use relative URLs")
- }
- path := value.EscapedPath()
- if path == "" {
- path = "/"
- }
- if value.RawQuery != "" {
- path += "?" + value.RawQuery
- }
- return path, validateServicePath(path)
-}
-func compactStrings(values []string) []string {
- if len(values) == 0 {
- return values
- }
- result := values[:1]
- for _, value := range values[1:] {
- if value != result[len(result)-1] {
- result = append(result, value)
- }
- }
- return result
-}
-
-func env(name, fallback string) string {
- if value := os.Getenv(name); value != "" {
- return value
- }
- return fallback
-}
diff --git a/libs/fleet/sdk-bindings/kotlin/.cyclops-sdk-generated-files b/libs/fleet/sdk-bindings/kotlin/.cyclops-sdk-generated-files
new file mode 100644
index 0000000000..ae0d9dbeeb
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/.cyclops-sdk-generated-files
@@ -0,0 +1,7 @@
+d ai
+d ai/cua
+d ai/cua/cyclops
+d ai/cua/cyclops/sdk
+d ai/cua/cyclops/sdk/schema
+f ai/cua/cyclops/sdk/cyclops_sdk.kt
+f ai/cua/cyclops/sdk/schema/cyclops_sdk_schema.kt
diff --git a/libs/fleet/sdk-bindings/kotlin/README.md b/libs/fleet/sdk-bindings/kotlin/README.md
new file mode 100644
index 0000000000..d2d7d245c6
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/README.md
@@ -0,0 +1,12 @@
+# Kotlin Contract Binding
+
+Requires JDK 21 and Gradle 8.10.2; Task 12 must install that exact Gradle release. All Kotlin/JNA/coroutines dependency versions are pinned in `build.gradle.kts`.
+
+```bash
+REPO_ROOT=/path/to/clone
+export CYCLOPS_SDK_NATIVE_DIR="$(dirname "$($REPO_ROOT/cyclops-cs/scripts/build-sdk-bindings-native.sh)")"
+gradle -p "$REPO_ROOT/cyclops-cs/sdk-bindings/kotlin" contract
+# The example target is `gradle -p "$REPO_ROOT/cyclops-cs/sdk-bindings/kotlin" example`.
+```
+
+The project compiles generated schema and SDK sources together under the authoritative `ai.cua.cyclops.sdk` package and supplies JNA plus Kotlin coroutines required by UniFFI 0.32 output.
diff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/cyclops_sdk.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/cyclops_sdk.kt
new file mode 100644
index 0000000000..b7b5d42b51
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/cyclops_sdk.kt
@@ -0,0 +1,3676 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+@file:Suppress("NAME_SHADOWING")
+
+package ai.cua.cyclops.sdk
+
+// Common helper code.
+//
+// Ideally this would live in a separate .kt file where it can be unittested etc
+// in isolation, and perhaps even published as a re-useable package.
+//
+// However, it's important that the details of how this helper code works (e.g. the
+// way that different builtin types are passed across the FFI) exactly match what's
+// expected by the Rust code on the other side of the interface. In practice right
+// now that means coming from the exact some version of `uniffi` that was used to
+// compile the Rust component. The easiest way to ensure this is to bundle the Kotlin
+// helpers directly inline like we're doing here.
+
+import com.sun.jna.Library
+import com.sun.jna.IntegerType
+import com.sun.jna.Native
+import com.sun.jna.Pointer
+import com.sun.jna.Structure
+import com.sun.jna.Callback
+import com.sun.jna.ptr.*
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.nio.CharBuffer
+import java.nio.charset.CodingErrorAction
+import java.util.concurrent.atomic.AtomicLong
+import java.util.concurrent.ConcurrentHashMap
+import ai.cua.cyclops.sdk.schema.ClaimSpec
+import ai.cua.cyclops.sdk.schema.FfiConverterTypeClaimSpec
+import ai.cua.cyclops.sdk.schema.FfiConverterTypeOSGymSandboxClaimStatus
+import ai.cua.cyclops.sdk.schema.FfiConverterTypeOSGymWorkspacePoolStatus
+import ai.cua.cyclops.sdk.schema.FfiConverterTypePoolSpec
+import ai.cua.cyclops.sdk.schema.OsGymSandboxClaimStatus
+import ai.cua.cyclops.sdk.schema.OsGymWorkspacePoolStatus
+import ai.cua.cyclops.sdk.schema.PoolSpec
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlin.coroutines.resume
+import kotlinx.coroutines.CancellableContinuation
+import kotlinx.coroutines.DelicateCoroutinesApi
+import kotlinx.coroutines.GlobalScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.suspendCancellableCoroutine
+import ai.cua.cyclops.sdk.schema.RustBuffer as RustBufferClaimSpec
+import ai.cua.cyclops.sdk.schema.RustBuffer as RustBufferOSGymSandboxClaimStatus
+import ai.cua.cyclops.sdk.schema.RustBuffer as RustBufferOSGymWorkspacePoolStatus
+import ai.cua.cyclops.sdk.schema.RustBuffer as RustBufferPoolSpec
+
+// This is a helper for safely working with byte buffers returned from the Rust code.
+// A rust-owned buffer is represented by its capacity, its current length, and a
+// pointer to the underlying data.
+
+/**
+ * @suppress
+ */
[email protected]("capacity", "len", "data")
+open class RustBuffer : Structure() {
+ // Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values.
+ // When dealing with these fields, make sure to call `toULong()`.
+ @JvmField var capacity: Long = 0
+ @JvmField var len: Long = 0
+ @JvmField var data: Pointer? = null
+
+ class ByValue: RustBuffer(), Structure.ByValue
+ class ByReference: RustBuffer(), Structure.ByReference
+
+ internal fun setValue(other: RustBuffer) {
+ capacity = other.capacity
+ len = other.len
+ data = other.data
+ }
+
+ companion object {
+ internal fun alloc(size: ULong = 0UL) = uniffiRustCall() { status ->
+ // Note: need to convert the size to a `Long` value to make this work with JVM.
+ UniffiLib.ffi_cyclops_sdk_rustbuffer_alloc(size.toLong(), status)
+ }.also {
+ if(it.data == null) {
+ throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})")
+ }
+ }
+
+ internal fun create(capacity: ULong, len: ULong, data: Pointer?): RustBuffer.ByValue {
+ var buf = RustBuffer.ByValue()
+ buf.capacity = capacity.toLong()
+ buf.len = len.toLong()
+ buf.data = data
+ return buf
+ }
+
+ internal fun free(buf: RustBuffer.ByValue) = uniffiRustCall() { status ->
+ UniffiLib.ffi_cyclops_sdk_rustbuffer_free(buf, status)
+ }
+ }
+
+ @Suppress("TooGenericExceptionThrown")
+ fun asByteBuffer() =
+ this.data?.getByteBuffer(0, this.len)?.also {
+ it.order(ByteOrder.BIG_ENDIAN)
+ }
+}
+
+// This is a helper for safely passing byte references into the rust code.
+// It's not actually used at the moment, because there aren't many things that you
+// can take a direct pointer to in the JVM, and if we're going to copy something
+// then we might as well copy it into a `RustBuffer`. But it's here for API
+// completeness.
+
[email protected]("len", "data")
+internal open class ForeignBytes : Structure() {
+ @JvmField var len: Int = 0
+ @JvmField var data: Pointer? = null
+
+ class ByValue : ForeignBytes(), Structure.ByValue
+}
+
+// Converter for `&[u8]` / `[ByRef] bytes` arguments.
+//
+// Only `lower` is valid — zero-copy byte buffers only flow foreign -> Rust,
+// and only in argument position. `lift`, `read`, `write`, and
+// `allocationSize` have no sound implementation here and all panic at
+// runtime. The `FfiConverter` interface is implemented so that the
+// compiler enforces the full method set (rather than relying on eyeball).
+//
+// The provided `ByteBuffer` MUST be direct — only direct buffers have a
+// stable native address that JNA can expose via `getDirectBufferPointer`.
+// The returned `ForeignBytes.ByValue` is only valid for the duration of
+// the FFI call; the Rust side treats it as a borrow.
+internal object FfiConverterByRefBytes : FfiConverter<java.nio.ByteBuffer, ForeignBytes.ByValue> {
+ override fun lower(value: java.nio.ByteBuffer): ForeignBytes.ByValue {
+ require(value.isDirect) { "UniFFI zero-copy &[u8] requires a direct ByteBuffer. Use ByteBuffer.allocateDirect()." }
+ val remaining = value.remaining()
+ val fb = ForeignBytes.ByValue()
+ fb.len = remaining
+ // Zero-length direct buffers: skip getDirectBufferPointer (platform-variable behavior)
+ // and pass null. The Rust side treats (null, 0) as &[].
+ fb.data = if (remaining == 0) null else com.sun.jna.Native.getDirectBufferPointer(value)
+ return fb
+ }
+
+ override fun lift(value: ForeignBytes.ByValue): java.nio.ByteBuffer =
+ error("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+
+ override fun read(buf: java.nio.ByteBuffer): java.nio.ByteBuffer =
+ error("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ override fun write(value: java.nio.ByteBuffer, buf: java.nio.ByteBuffer): Unit =
+ error("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ override fun allocationSize(value: java.nio.ByteBuffer): ULong =
+ error("ByRef bytes have no RustBuffer allocation size: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+}
+/**
+ * The FfiConverter interface handles converter types to and from the FFI
+ *
+ * All implementing objects should be public to support external types. When a
+ * type is external we need to import it's FfiConverter.
+ *
+ * @suppress
+ */
+public interface FfiConverter<KotlinType, FfiType> {
+ // Convert an FFI type to a Kotlin type
+ fun lift(value: FfiType): KotlinType
+
+ // Convert an Kotlin type to an FFI type
+ fun lower(value: KotlinType): FfiType
+
+ // Read a Kotlin type from a `ByteBuffer`
+ fun read(buf: ByteBuffer): KotlinType
+
+ // Calculate bytes to allocate when creating a `RustBuffer`
+ //
+ // This must return at least as many bytes as the write() function will
+ // write. It can return more bytes than needed, for example when writing
+ // Strings we can't know the exact bytes needed until we the UTF-8
+ // encoding, so we pessimistically allocate the largest size possible (3
+ // bytes per codepoint). Allocating extra bytes is not really a big deal
+ // because the `RustBuffer` is short-lived.
+ fun allocationSize(value: KotlinType): ULong
+
+ // Write a Kotlin type to a `ByteBuffer`
+ fun write(value: KotlinType, buf: ByteBuffer)
+
+ // Lower a value into a `RustBuffer`
+ //
+ // This method lowers a value into a `RustBuffer` rather than the normal
+ // FfiType. It's used by the callback interface code. Callback interface
+ // returns are always serialized into a `RustBuffer` regardless of their
+ // normal FFI type.
+ fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue {
+ val rbuf = RustBuffer.alloc(allocationSize(value))
+ try {
+ val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity).also {
+ it.order(ByteOrder.BIG_ENDIAN)
+ }
+ write(value, bbuf)
+ rbuf.writeField("len", bbuf.position().toLong())
+ return rbuf
+ } catch (e: Throwable) {
+ RustBuffer.free(rbuf)
+ throw e
+ }
+ }
+
+ // Lift a value from a `RustBuffer`.
+ //
+ // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.
+ // It's currently only used by the `FfiConverterRustBuffer` class below.
+ fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType {
+ val byteBuf = rbuf.asByteBuffer()!!
+ try {
+ val item = read(byteBuf)
+ if (byteBuf.hasRemaining()) {
+ throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!")
+ }
+ return item
+ } finally {
+ RustBuffer.free(rbuf)
+ }
+ }
+}
+
+/**
+ * FfiConverter that uses `RustBuffer` as the FfiType
+ *
+ * @suppress
+ */
+public interface FfiConverterRustBuffer<KotlinType>: FfiConverter<KotlinType, RustBuffer.ByValue> {
+ override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value)
+ override fun lower(value: KotlinType) = lowerIntoRustBuffer(value)
+}
+// A handful of classes and functions to support the generated data structures.
+// This would be a good candidate for isolating in its own ffi-support lib.
+
+internal const val UNIFFI_CALL_SUCCESS = 0.toByte()
+internal const val UNIFFI_CALL_ERROR = 1.toByte()
+internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte()
+
[email protected]("code", "error_buf")
+internal open class UniffiRustCallStatus : Structure() {
+ @JvmField var code: Byte = 0
+ @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue()
+
+ class ByValue: UniffiRustCallStatus(), Structure.ByValue
+
+ fun isSuccess(): Boolean {
+ return code == UNIFFI_CALL_SUCCESS
+ }
+
+ fun isError(): Boolean {
+ return code == UNIFFI_CALL_ERROR
+ }
+
+ fun isPanic(): Boolean {
+ return code == UNIFFI_CALL_UNEXPECTED_ERROR
+ }
+
+ companion object {
+ fun create(code: Byte, errorBuf: RustBuffer.ByValue): UniffiRustCallStatus.ByValue {
+ val callStatus = UniffiRustCallStatus.ByValue()
+ callStatus.code = code
+ callStatus.error_buf = errorBuf
+ return callStatus
+ }
+ }
+}
+
+class InternalException(message: String) : kotlin.Exception(message)
+
+/**
+ * Each top-level error class has a companion object that can lift the error from the call status's rust buffer
+ *
+ * @suppress
+ */
+interface UniffiRustCallStatusErrorHandler<E> {
+ fun lift(error_buf: RustBuffer.ByValue): E;
+}
+
+// Helpers for calling Rust
+// In practice we usually need to be synchronized to call this safely, so it doesn't
+// synchronize itself
+
+// Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err
+private inline fun <U, E: kotlin.Exception> uniffiRustCallWithError(errorHandler: UniffiRustCallStatusErrorHandler<E>, callback: (UniffiRustCallStatus) -> U): U {
+ var status = UniffiRustCallStatus()
+ val return_value = callback(status)
+ uniffiCheckCallStatus(errorHandler, status)
+ return return_value
+}
+
+// Check UniffiRustCallStatus and throw an error if the call wasn't successful
+private fun<E: kotlin.Exception> uniffiCheckCallStatus(errorHandler: UniffiRustCallStatusErrorHandler<E>, status: UniffiRustCallStatus) {
+ if (status.isSuccess()) {
+ return
+ } else if (status.isError()) {
+ throw errorHandler.lift(status.error_buf)
+ } else if (status.isPanic()) {
+ // when the rust code sees a panic, it tries to construct a rustbuffer
+ // with the message. but if that code panics, then it just sends back
+ // an empty buffer.
+ if (status.error_buf.len > 0) {
+ throw InternalException(FfiConverterString.lift(status.error_buf))
+ } else {
+ throw InternalException("Rust panic")
+ }
+ } else {
+ throw InternalException("Unknown rust call status: $status.code")
+ }
+}
+
+/**
+ * UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR
+ *
+ * @suppress
+ */
+object UniffiNullRustCallStatusErrorHandler: UniffiRustCallStatusErrorHandler<InternalException> {
+ override fun lift(error_buf: RustBuffer.ByValue): InternalException {
+ RustBuffer.free(error_buf)
+ return InternalException("Unexpected CALL_ERROR")
+ }
+}
+
+// Call a rust function that returns a plain value
+private inline fun <U> uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U {
+ return uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback)
+}
+
+internal inline fun<T> uniffiTraitInterfaceCall(
+ callStatus: UniffiRustCallStatus,
+ makeCall: () -> T,
+ writeReturn: (T) -> Unit,
+) {
+ try {
+ writeReturn(makeCall())
+ } catch(e: kotlin.Exception) {
+ val err = try { e.stackTraceToString() } catch(_: Throwable) { "" }
+ callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
+ callStatus.error_buf = FfiConverterString.lower(err)
+ }
+}
+
+internal inline fun<T, reified E: Throwable> uniffiTraitInterfaceCallWithError(
+ callStatus: UniffiRustCallStatus,
+ makeCall: () -> T,
+ writeReturn: (T) -> Unit,
+ lowerError: (E) -> RustBuffer.ByValue
+) {
+ try {
+ writeReturn(makeCall())
+ } catch(e: kotlin.Exception) {
+ if (e is E) {
+ callStatus.code = UNIFFI_CALL_ERROR
+ callStatus.error_buf = lowerError(e)
+ } else {
+ val err = try { e.stackTraceToString() } catch(_: Throwable) { "" }
+ callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
+ callStatus.error_buf = FfiConverterString.lower(err)
+ }
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that Kotlin-generated handles always have the lowest bit set
+private const val UNIFFI_HANDLEMAP_INITIAL = 1.toLong()
+private const val UNIFFI_HANDLEMAP_DELTA = 2.toLong()
+
+// Map handles to objects
+//
+// This is used pass an opaque 64-bit handle representing a foreign object to the Rust code.
+internal class UniffiHandleMap<T: Any> {
+ private val map = ConcurrentHashMap<Long, T>()
+ // Start
+ private val counter = java.util.concurrent.atomic.AtomicLong(UNIFFI_HANDLEMAP_INITIAL)
+
+ val size: Int
+ get() = map.size
+
+ // Insert a new object into the handle map and get a handle for it
+ fun insert(obj: T): Long {
+ val handle = counter.getAndAdd(UNIFFI_HANDLEMAP_DELTA)
+ map.put(handle, obj)
+ return handle
+ }
+
+ // Clone a handle, creating a new one
+ fun clone(handle: Long): Long {
+ val obj = map.get(handle) ?: throw InternalException("UniffiHandleMap.clone: Invalid handle")
+ return insert(obj)
+ }
+
+ // Get an object from the handle map
+ fun get(handle: Long): T {
+ return map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle")
+ }
+
+ // Remove an entry from the handlemap and get the Kotlin object back
+ fun remove(handle: Long): T {
+ return map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle")
+ }
+}
+
+// Contains loading, initialization code,
+// and the FFI Function declarations in a com.sun.jna.Library.
+@Synchronized
+private fun findLibraryName(componentName: String): String {
+ val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride")
+ if (libOverride != null) {
+ return libOverride
+ }
+ return "cyclops_sdk"
+}
+
+// Define FFI callback types
+internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback {
+ fun callback(`data`: Long,`pollResult`: Byte,)
+}
+internal interface UniffiForeignFutureDroppedCallback : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+}
+internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+}
+internal interface UniffiCallbackInterfaceClone : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+ : Long
+}
[email protected]("handle", "free")
+internal open class UniffiForeignFutureDroppedCallbackStruct(
+ @JvmField internal var `handle`: Long = 0.toLong(),
+ @JvmField internal var `free`: UniffiForeignFutureDroppedCallback? = null,
+) : Structure() {
+ class UniffiByValue(
+ `handle`: Long = 0.toLong(),
+ `free`: UniffiForeignFutureDroppedCallback? = null,
+ ): UniffiForeignFutureDroppedCallbackStruct(`handle`,`free`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureDroppedCallbackStruct) {
+ `handle` = other.`handle`
+ `free` = other.`free`
+ }
+
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU8(
+ @JvmField internal var `returnValue`: Byte = 0.toByte(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Byte = 0.toByte(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU8(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU8) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU8.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI8(
+ @JvmField internal var `returnValue`: Byte = 0.toByte(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Byte = 0.toByte(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI8(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI8) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI8.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU16(
+ @JvmField internal var `returnValue`: Short = 0.toShort(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Short = 0.toShort(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU16(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU16) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU16.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI16(
+ @JvmField internal var `returnValue`: Short = 0.toShort(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Short = 0.toShort(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI16(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI16) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI16.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU32(
+ @JvmField internal var `returnValue`: Int = 0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Int = 0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI32(
+ @JvmField internal var `returnValue`: Int = 0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Int = 0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU64(
+ @JvmField internal var `returnValue`: Long = 0.toLong(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Long = 0.toLong(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI64(
+ @JvmField internal var `returnValue`: Long = 0.toLong(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Long = 0.toLong(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultF32(
+ @JvmField internal var `returnValue`: Float = 0.0f,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Float = 0.0f,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultF32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultF32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultF32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultF64(
+ @JvmField internal var `returnValue`: Double = 0.0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Double = 0.0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultF64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultF64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultF64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultRustBuffer(
+ @JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultRustBuffer(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultRustBuffer) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultRustBuffer.UniffiByValue,)
+}
[email protected]("callStatus")
+internal open class UniffiForeignFutureResultVoid(
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultVoid(`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultVoid) {
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultVoid.UniffiByValue,)
+}
+internal interface UniffiCallbackInterfaceHttpClientMethod0 : com.sun.jna.Callback {
+ fun callback(`uniffiHandle`: Long,`request`: RustBuffer.ByValue,`uniffiFutureCallback`: UniffiForeignFutureCompleteRustBuffer,`uniffiCallbackData`: Long,`uniffiOutDroppedCallback`: UniffiForeignFutureDroppedCallbackStruct,)
+}
[email protected]("uniffiFree", "uniffiClone", "execute")
+internal open class UniffiVTableCallbackInterfaceHttpClient(
+ @JvmField internal var `uniffiFree`: UniffiCallbackInterfaceFree? = null,
+ @JvmField internal var `uniffiClone`: UniffiCallbackInterfaceClone? = null,
+ @JvmField internal var `execute`: UniffiCallbackInterfaceHttpClientMethod0? = null,
+) : Structure() {
+ class UniffiByValue(
+ `uniffiFree`: UniffiCallbackInterfaceFree? = null,
+ `uniffiClone`: UniffiCallbackInterfaceClone? = null,
+ `execute`: UniffiCallbackInterfaceHttpClientMethod0? = null,
+ ): UniffiVTableCallbackInterfaceHttpClient(`uniffiFree`,`uniffiClone`,`execute`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiVTableCallbackInterfaceHttpClient) {
+ `uniffiFree` = other.`uniffiFree`
+ `uniffiClone` = other.`uniffiClone`
+ `execute` = other.`execute`
+ }
+
+}
+
+// A JNA Library to expose the extern-C FFI definitions.
+// This is an implementation detail which will be called internally by the public API.
+
+// For large crates we prevent `MethodTooLargeException` (see #2340)
+// N.B. the name of the extension is very misleading, since it is
+// rather `InterfaceTooLargeException`, caused by too many methods
+// in the interface for large crates.
+//
+// By splitting the otherwise huge interface into two parts
+// * UniffiLib (this)
+// * IntegrityCheckingUniffiLib
+// And all checksum methods are put into `IntegrityCheckingUniffiLib`
+// we allow for ~2x as many methods in the UniffiLib interface.
+//
+// Note: above all written when we used JNA's `loadIndirect` etc.
+// We now use JNA's "direct mapping" - unclear if same considerations apply exactly.
+internal object IntegrityCheckingUniffiLib {
+ init {
+ Native.register(IntegrityCheckingUniffiLib::class.java, findLibraryName(componentName = "cyclops_sdk"))
+ uniffiCheckContractApiVersion(this)
+ uniffiCheckApiChecksums(this)
+ }
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_method_httpclient_execute(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect(
+ ): Int
+ external fun uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new(
+ ): Int
+ external fun ffi_cyclops_sdk_uniffi_contract_version(
+ ): Int
+
+
+}
+
+internal object UniffiLib {
+
+ // The Cleaner for the whole library
+ internal val CLEANER: UniffiCleaner by lazy {
+ UniffiCleaner.create()
+ }
+
+
+ init {
+ Native.register(UniffiLib::class.java, findLibraryName(componentName = "cyclops_sdk"))
+ uniffiCallbackInterfaceHttpClient.register(this)
+ ai.cua.cyclops.sdk.schema.uniffiEnsureInitialized()
+
+ }
+ external fun uniffi_cyclops_sdk_fn_clone_cyclopsclient(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_free_cyclopsclient(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect(`configuration`: RustBuffer.ByValue,`httpClient`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(`ptr`: Long,`request`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(`ptr`: Long,`namespace`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(`ptr`: Long,`request`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(`ptr`: Long,`pool`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(`ptr`: Long,`pool`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(`ptr`: Long,`namespace`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(`ptr`: Long,`pool`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(`ptr`: Long,`sandbox`: RustBuffer.ByValue,`service`: RustBuffer.ByValue,`path`: RustBuffer.ByValue,`request`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_clone_httpclient(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_free_httpclient(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(`vtable`: UniffiVTableCallbackInterfaceHttpClient,
+ ): Unit
+ external fun uniffi_cyclops_sdk_fn_method_httpclient_execute(`ptr`: Long,`request`: RustBuffer.ByValue,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_clone_cyclopscredentials(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_fn_free_cyclopscredentials(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new(`clientId`: RustBuffer.ByValue,`clientSecret`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_rustbuffer_free(`buf`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun ffi_cyclops_sdk_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_rust_future_poll_u8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_u8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_u8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_u8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_rust_future_poll_i8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_i8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_i8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_i8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Byte
+ external fun ffi_cyclops_sdk_rust_future_poll_u16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_u16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_u16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_u16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_rust_future_poll_i16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_i16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_i16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_i16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Short
+ external fun ffi_cyclops_sdk_rust_future_poll_u32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_u32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_u32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_u32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_rust_future_poll_i32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_i32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_i32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_i32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_rust_future_poll_u64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_u64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_u64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_u64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_rust_future_poll_i64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_i64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_i64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_i64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_rust_future_poll_f32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_f32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_f32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_f32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Float
+ external fun ffi_cyclops_sdk_rust_future_poll_f64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_f64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_f64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_f64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Double
+ external fun ffi_cyclops_sdk_rust_future_poll_rust_buffer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_rust_buffer(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_rust_buffer(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_rust_buffer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_rust_future_poll_void(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_cancel_void(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_free_void(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_rust_future_complete_void(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+
+
+}
+
+private fun uniffiCheckContractApiVersion(lib: IntegrityCheckingUniffiLib) {
+ // Get the bindings contract version from our ComponentInterface
+ val bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ val scaffolding_contract_version = lib.ffi_cyclops_sdk_uniffi_contract_version()
+ if (bindings_contract_version != scaffolding_contract_version) {
+ throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ }
+}
+@Suppress("UNUSED_PARAMETER")
+private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim() != 51021) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() != 50650) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() != 55182) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 26952) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 53385) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool() != 31472) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool() != 9252) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool() != 44001) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() != 25465) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool() != 39705) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() != 4680) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 11556) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect() != 48439) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() != 56420) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+/**
+ * @suppress
+ */
+public fun uniffiEnsureInitialized() {
+ IntegrityCheckingUniffiLib
+ // UniffiLib() initialized as objects are used, but we still need to explicitly
+ // reference it so initialization across crates works as expected.
+ UniffiLib
+}
+
+// Async support
+// Async return type handlers
+
+internal const val UNIFFI_RUST_FUTURE_POLL_READY = 0.toByte()
+internal const val UNIFFI_RUST_FUTURE_POLL_WAKE = 1.toByte()
+
+internal val uniffiContinuationHandleMap = UniffiHandleMap<CancellableContinuation<Byte>>()
+
+// FFI type for Rust future continuations
+internal object uniffiRustFutureContinuationCallbackImpl: UniffiRustFutureContinuationCallback {
+ override fun callback(data: Long, pollResult: Byte) {
+ uniffiContinuationHandleMap.remove(data).resume(pollResult)
+ }
+}
+
+internal suspend fun<T, F, E: kotlin.Exception> uniffiRustCallAsync(
+ rustFuture: Long,
+ pollFunc: (Long, UniffiRustFutureContinuationCallback, Long) -> Unit,
+ completeFunc: (Long, UniffiRustCallStatus) -> F,
+ freeFunc: (Long) -> Unit,
+ liftFunc: (F) -> T,
+ errorHandler: UniffiRustCallStatusErrorHandler<E>
+): T {
+ try {
+ do {
+ val pollResult = suspendCancellableCoroutine<Byte> { continuation ->
+ pollFunc(
+ rustFuture,
+ uniffiRustFutureContinuationCallbackImpl,
+ uniffiContinuationHandleMap.insert(continuation)
+ )
+ }
+ } while (pollResult != UNIFFI_RUST_FUTURE_POLL_READY);
+
+ return liftFunc(
+ uniffiRustCallWithError(errorHandler, { status -> completeFunc(rustFuture, status) })
+ )
+ } finally {
+ freeFunc(rustFuture)
+ }
+}
+internal inline fun<T> uniffiTraitInterfaceCallAsync(
+ crossinline makeCall: suspend () -> T,
+ crossinline handleSuccess: (T) -> Unit,
+ crossinline handleError: (UniffiRustCallStatus.ByValue) -> Unit,
+ uniffiOutDroppedCallback: UniffiForeignFutureDroppedCallbackStruct,
+) {
+ // Using `GlobalScope` is labeled as a "delicate API" and generally discouraged in Kotlin programs, since it breaks structured concurrency.
+ // However, our parent task is a Rust future, so we're going to need to break structure concurrency in any case.
+ //
+ // Uniffi does its best to support structured concurrency across the FFI.
+ // If the Rust future is dropped, `uniffiForeignFutureDroppedCallbackImpl` is called, which will cancel the Kotlin coroutine if it's still running.
+ @OptIn(DelicateCoroutinesApi::class)
+ val job = GlobalScope.launch coroutineBlock@ {
+ // Note: it's important we call either `handleSuccess` or `handleError` exactly once. Each
+ // call consumes an Arc reference, which means there should be no possibility of a double
+ // call. The following code is structured so that will will never call both `handleSuccess`
+ // and `handleError`, even in the face of weird exceptions.
+ //
+ // In extreme circumstances we may not call either, for example if we fail to make the JNA
+ // call to `handleSuccess`. This means we will leak the Arc reference, which is better than
+ // double-freeing it.
+ val callResult = try {
+ makeCall()
+ } catch(e: kotlin.Exception) {
+ handleError(
+ UniffiRustCallStatus.create(
+ UNIFFI_CALL_UNEXPECTED_ERROR,
+ FfiConverterString.lower(e.toString()),
+ )
+ )
+ return@coroutineBlock
+ }
+ handleSuccess(callResult)
+ }
+ val handle = uniffiForeignFutureHandleMap.insert(job)
+ uniffiOutDroppedCallback.uniffiSetValue(UniffiForeignFutureDroppedCallbackStruct(handle, uniffiForeignFutureDroppedCallbackImpl))
+}
+
+internal inline fun<T, reified E: Throwable> uniffiTraitInterfaceCallAsyncWithError(
+ crossinline makeCall: suspend () -> T,
+ crossinline handleSuccess: (T) -> Unit,
+ crossinline handleError: (UniffiRustCallStatus.ByValue) -> Unit,
+ crossinline lowerError: (E) -> RustBuffer.ByValue,
+ uniffiOutDroppedCallback: UniffiForeignFutureDroppedCallbackStruct,
+) {
+ // See uniffiTraitInterfaceCallAsync for details on `DelicateCoroutinesApi`
+ @OptIn(DelicateCoroutinesApi::class)
+ val job = GlobalScope.launch coroutineBlock@ {
+ // See the note in uniffiTraitInterfaceCallAsync for details on `handleSuccess` and
+ // `handleError`.
+ val callResult = try {
+ makeCall()
+ } catch(e: kotlin.Exception) {
+ if (e is E) {
+ handleError(
+ UniffiRustCallStatus.create(
+ UNIFFI_CALL_ERROR,
+ lowerError(e),
+ )
+ )
+ } else {
+ handleError(
+ UniffiRustCallStatus.create(
+ UNIFFI_CALL_UNEXPECTED_ERROR,
+ FfiConverterString.lower(e.toString()),
+ )
+ )
+ }
+ return@coroutineBlock
+ }
+ handleSuccess(callResult)
+ }
+ val handle = uniffiForeignFutureHandleMap.insert(job)
+ uniffiOutDroppedCallback.uniffiSetValue(UniffiForeignFutureDroppedCallbackStruct(handle, uniffiForeignFutureDroppedCallbackImpl))
+}
+
+internal val uniffiForeignFutureHandleMap = UniffiHandleMap<Job>()
+
+internal object uniffiForeignFutureDroppedCallbackImpl: UniffiForeignFutureDroppedCallback {
+ override fun callback(handle: Long) {
+ val job = uniffiForeignFutureHandleMap.remove(handle)
+ if (!job.isCompleted) {
+ job.cancel()
+ }
+ }
+}
+
+// For testing
+public fun uniffiForeignFutureHandleCount() = uniffiForeignFutureHandleMap.size
+
+// Public interface members begin here.
+
+
+// Interface implemented by anything that can contain an object reference.
+//
+// Such types expose a `destroy()` method that must be called to cleanly
+// dispose of the contained objects. Failure to call this method may result
+// in memory leaks.
+//
+// The easiest way to ensure this method is called is to use the `.use`
+// helper method to execute a block and destroy the object at the end.
+interface Disposable {
+ fun destroy()
+ companion object {
+ fun destroy(vararg args: Any?) {
+ for (arg in args) {
+ when (arg) {
+ is Disposable -> arg.destroy()
+ is ArrayList<*> -> {
+ for (idx in arg.indices) {
+ val element = arg[idx]
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ is Map<*, *> -> {
+ for (element in arg.values) {
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ is Iterable<*> -> {
+ for (element in arg) {
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @suppress
+ */
+inline fun <T : Disposable?, R> T.use(block: (T) -> R) =
+ try {
+ block(this)
+ } finally {
+ try {
+ // N.B. our implementation is on the nullable type `Disposable?`.
+ this?.destroy()
+ } catch (e: Throwable) {
+ // swallow
+ }
+ }
+
+/**
+ * Placeholder object used to signal that we're constructing an interface with a FFI handle.
+ *
+ * This is the first argument for interface constructors that input a raw handle. It exists is that
+ * so we can avoid signature conflicts when an interface has a regular constructor than inputs a
+ * Long.
+ *
+ * @suppress
+ * */
+object UniffiWithHandle
+
+/**
+ * Used to instantiate an interface without an actual pointer, for fakes in tests, mostly.
+ *
+ * @suppress
+ * */
+object NoHandle// Magic number for the Rust proxy to call using the same mechanism as every other method,
+// to free the callback once it's dropped by Rust.
+internal const val IDX_CALLBACK_FREE = 0
+// Callback return codes
+internal const val UNIFFI_CALLBACK_SUCCESS = 0
+internal const val UNIFFI_CALLBACK_ERROR = 1
+internal const val UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2
+
+/**
+ * @suppress
+ */
+public abstract class FfiConverterCallbackInterface<CallbackInterface: Any>: FfiConverter<CallbackInterface, Long> {
+ internal val handleMap = UniffiHandleMap<CallbackInterface>()
+
+ internal fun drop(handle: Long) {
+ handleMap.remove(handle)
+ }
+
+ override fun lift(value: Long): CallbackInterface {
+ return handleMap.get(value)
+ }
+
+ override fun read(buf: ByteBuffer) = lift(buf.getLong())
+
+ override fun lower(value: CallbackInterface) = handleMap.insert(value)
+
+ override fun allocationSize(value: CallbackInterface) = 8UL
+
+ override fun write(value: CallbackInterface, buf: ByteBuffer) {
+ buf.putLong(lower(value))
+ }
+}
+/**
+ * The cleaner interface for Object finalization code to run.
+ * This is the entry point to any implementation that we're using.
+ *
+ * The cleaner registers objects and returns cleanables, so now we are
+ * defining a `UniffiCleaner` with a `UniffiClenaer.Cleanable` to abstract the
+ * different implmentations available at compile time.
+ *
+ * @suppress
+ */
+interface UniffiCleaner {
+ interface Cleanable {
+ fun clean()
+ }
+
+ fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable
+
+ companion object
+}
+
+// The fallback Jna cleaner, which is available for both Android, and the JVM.
+private class UniffiJnaCleaner : UniffiCleaner {
+ private val cleaner = com.sun.jna.internal.Cleaner.getCleaner()
+
+ override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable =
+ UniffiJnaCleanable(cleaner.register(value, cleanUpTask))
+}
+
+private class UniffiJnaCleanable(
+ private val cleanable: com.sun.jna.internal.Cleaner.Cleanable,
+) : UniffiCleaner.Cleanable {
+ override fun clean() = cleanable.clean()
+}
+
+
+// We decide at uniffi binding generation time whether we were
+// using Android or not.
+// There are further runtime checks to chose the correct implementation
+// of the cleaner.
+private fun UniffiCleaner.Companion.create(): UniffiCleaner =
+ try {
+ // For safety's sake: if the library hasn't been run in android_cleaner = true
+ // mode, but is being run on Android, then we still need to think about
+ // Android API versions.
+ // So we check if java.lang.ref.Cleaner is there, and use that…
+ java.lang.Class.forName("java.lang.ref.Cleaner")
+ JavaLangRefCleaner()
+ } catch (e: ClassNotFoundException) {
+ // … otherwise, fallback to the JNA cleaner.
+ UniffiJnaCleaner()
+ }
+
+private class JavaLangRefCleaner : UniffiCleaner {
+ val cleaner = java.lang.ref.Cleaner.create()
+
+ override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable =
+ JavaLangRefCleanable(cleaner.register(value, cleanUpTask))
+}
+
+private class JavaLangRefCleanable(
+ val cleanable: java.lang.ref.Cleaner.Cleanable
+) : UniffiCleaner.Cleanable {
+ override fun clean() = cleanable.clean()
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterUShort: FfiConverter<UShort, Short> {
+ override fun lift(value: Short): UShort {
+ return value.toUShort()
+ }
+
+ fun lift(value: Int): UShort {
+ return value.toUShort()
+ }
+
+ override fun read(buf: ByteBuffer): UShort {
+ return lift(buf.getShort())
+ }
+
+ override fun lower(value: UShort): Short {
+ return value.toShort()
+ }
+
+ override fun allocationSize(value: UShort) = 2UL
+
+ override fun write(value: UShort, buf: ByteBuffer) {
+ buf.putShort(value.toShort())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterUInt: FfiConverter<UInt, Int> {
+ override fun lift(value: Int): UInt {
+ return value.toUInt()
+ }
+
+ override fun read(buf: ByteBuffer): UInt {
+ return lift(buf.getInt())
+ }
+
+ override fun lower(value: UInt): Int {
+ return value.toInt()
+ }
+
+ override fun allocationSize(value: UInt) = 4UL
+
+ override fun write(value: UInt, buf: ByteBuffer) {
+ buf.putInt(value.toInt())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterULong: FfiConverter<ULong, Long> {
+ override fun lift(value: Long): ULong {
+ return value.toULong()
+ }
+
+ override fun read(buf: ByteBuffer): ULong {
+ return lift(buf.getLong())
+ }
+
+ override fun lower(value: ULong): Long {
+ return value.toLong()
+ }
+
+ override fun allocationSize(value: ULong) = 8UL
+
+ override fun write(value: ULong, buf: ByteBuffer) {
+ buf.putLong(value.toLong())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> {
+ // Note: we don't inherit from FfiConverterRustBuffer, because we use a
+ // special encoding when lowering/lifting. We can use `RustBuffer.len` to
+ // store our length and avoid writing it out to the buffer.
+ override fun lift(value: RustBuffer.ByValue): String {
+ try {
+ val byteArr = ByteArray(value.len.toInt())
+ value.asByteBuffer()!!.get(byteArr)
+ return byteArr.toString(Charsets.UTF_8)
+ } finally {
+ RustBuffer.free(value)
+ }
+ }
+
+ override fun read(buf: ByteBuffer): String {
+ val len = buf.getInt()
+ val byteArr = ByteArray(len)
+ buf.get(byteArr)
+ return byteArr.toString(Charsets.UTF_8)
+ }
+
+ fun toUtf8(value: String): ByteBuffer {
+ // Make sure we don't have invalid UTF-16, check for lone surrogates.
+ return Charsets.UTF_8.newEncoder().run {
+ onMalformedInput(CodingErrorAction.REPORT)
+ encode(CharBuffer.wrap(value))
+ }
+ }
+
+ override fun lower(value: String): RustBuffer.ByValue {
+ val byteBuf = toUtf8(value)
+ // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us
+ // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`.
+ val rbuf = RustBuffer.alloc(byteBuf.limit().toULong())
+ rbuf.asByteBuffer()!!.put(byteBuf)
+ return rbuf
+ }
+
+ // We aren't sure exactly how many bytes our string will be once it's UTF-8
+ // encoded. Allocate 3 bytes per UTF-16 code unit which will always be
+ // enough.
+ override fun allocationSize(value: String): ULong {
+ val sizeForLength = 4UL
+ val sizeForString = value.length.toULong() * 3UL
+ return sizeForLength + sizeForString
+ }
+
+ override fun write(value: String, buf: ByteBuffer) {
+ val byteBuf = toUtf8(value)
+ buf.putInt(byteBuf.limit())
+ buf.put(byteBuf)
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterByteArray: FfiConverterRustBuffer<ByteArray> {
+ override fun read(buf: ByteBuffer): ByteArray {
+ val len = buf.getInt()
+ val byteArr = ByteArray(len)
+ buf.get(byteArr)
+ return byteArr
+ }
+ override fun allocationSize(value: ByteArray): ULong {
+ return 4UL + value.size.toULong()
+ }
+ override fun write(value: ByteArray, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ buf.put(value)
+ }
+}
+
+
+// This template implements a class for working with a Rust struct via a handle
+// to the live Rust struct on the other side of the FFI.
+//
+// There's some subtlety here, because we have to be careful not to operate on a Rust
+// struct after it has been dropped, and because we must expose a public API for freeing
+// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are:
+//
+// * Each instance holds an opaque handle to the underlying Rust struct.
+// Method calls need to read this handle from the object's state and pass it in to
+// the Rust FFI.
+//
+// * When an instance is no longer needed, its handle should be passed to a
+// special destructor function provided by the Rust FFI, which will drop the
+// underlying Rust struct.
+//
+// * Given an instance, calling code is expected to call the special
+// `destroy` method in order to free it after use, either by calling it explicitly
+// or by using a higher-level helper like the `use` method. Failing to do so risks
+// leaking the underlying Rust struct.
+//
+// * We can't assume that calling code will do the right thing, and must be prepared
+// to handle Kotlin method calls executing concurrently with or even after a call to
+// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`.
+//
+// * We must never allow Rust code to operate on the underlying Rust struct after
+// the destructor has been called, and must never call the destructor more than once.
+// Doing so may trigger memory unsafety.
+//
+// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner`
+// is implemented to call the destructor when the Kotlin object becomes unreachable.
+// This is done in a background thread. This is not a panacea, and client code should be aware that
+// 1. the thread may starve if some there are objects that have poorly performing
+// `drop` methods or do significant work in their `drop` methods.
+// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`,
+// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html).
+//
+// If we try to implement this with mutual exclusion on access to the handle, there is the
+// possibility of a race between a method call and a concurrent call to `destroy`:
+//
+// * Thread A starts a method call, reads the value of the handle, but is interrupted
+// before it can pass the handle over the FFI to Rust.
+// * Thread B calls `destroy` and frees the underlying Rust struct.
+// * Thread A resumes, passing the already-read handle value to Rust and triggering
+// a use-after-free.
+//
+// One possible solution would be to use a `ReadWriteLock`, with each method call taking
+// a read lock (and thus allowed to run concurrently) and the special `destroy` method
+// taking a write lock (and thus blocking on live method calls). However, we aim not to
+// generate methods with any hidden blocking semantics, and a `destroy` method that might
+// block if called incorrectly seems to meet that bar.
+//
+// So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track
+// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy`
+// has been called. These are updated according to the following rules:
+//
+// * The initial value of the counter is 1, indicating a live object with no in-flight calls.
+// The initial value for the flag is false.
+//
+// * At the start of each method call, we atomically check the counter.
+// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted.
+// If it is nonzero them we atomically increment it by 1 and proceed with the method call.
+//
+// * At the end of each method call, we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// * When `destroy` is called, we atomically flip the flag from false to true.
+// If the flag was already true we silently fail.
+// Otherwise we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works,
+// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`.
+//
+// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been
+// called *and* all in-flight method calls have completed, avoiding violating any of the expectations
+// of the underlying Rust code.
+//
+// This makes a cleaner a better alternative to _not_ calling `destroy()` as
+// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop`
+// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner
+// thread may be starved, and the app will leak memory.
+//
+// In this case, `destroy`ing manually may be a better solution.
+//
+// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects
+// with Rust peers are reclaimed:
+//
+// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen:
+// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then:
+// 3. The memory is reclaimed when the process terminates.
+//
+// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219
+//
+
+
+public interface CyclopsClientInterface {
+
+ suspend fun `createClaim`(`request`: CreateClaimRequest): Claim
+
+ suspend fun `deleteClaim`(`claim`: Claim)
+
+ suspend fun `getClaim`(`claim`: Claim): Claim
+
+ suspend fun `listClaims`(`namespace`: kotlin.String): List<Claim>
+
+ suspend fun `waitClaim`(`claim`: Claim): Sandbox
+
+ suspend fun `createPool`(`request`: CreatePoolRequest): Pool
+
+ suspend fun `deletePool`(`pool`: Pool)
+
+ suspend fun `getPool`(`pool`: Pool): Pool
+
+ suspend fun `listPools`(`namespace`: kotlin.String): List<Pool>
+
+ suspend fun `updatePool`(`pool`: Pool): Pool
+
+ suspend fun `serviceRequest`(`sandbox`: Sandbox, `service`: kotlin.String, `path`: kotlin.String, `request`: HttpRequest): HttpResponse
+
+ companion object
+}
+
+open class CyclopsClient: Disposable, AutoCloseable, CyclopsClientInterface
+{
+
+ @Suppress("UNUSED_PARAMETER")
+ /**
+ * @suppress
+ */
+ constructor(withHandle: UniffiWithHandle, handle: Long) {
+ this.handle = handle
+ this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(handle))
+ }
+
+ /**
+ * @suppress
+ *
+ * This constructor can be used to instantiate a fake object. Only used for tests. Any
+ * attempt to actually use an object constructed this way will fail as there is no
+ * connected Rust object.
+ */
+ @Suppress("UNUSED_PARAMETER")
+ constructor(noHandle: NoHandle) {
+ this.handle = 0
+ this.cleanable = null
+ }
+
+ protected val handle: Long
+ protected val cleanable: UniffiCleaner.Cleanable?
+
+ private val wasDestroyed = AtomicBoolean(false)
+ private val callCounter = AtomicLong(1)
+
+ /**
+ * Whether the current object has been destroyed and its reference is gone in the Rust side.
+ */
+ val uniffiIsDestroyed: Boolean get() = wasDestroyed.get()
+
+ override fun destroy() {
+ // Only allow a single call to this method.
+ // TODO: maybe we should log a warning if called more than once?
+ if (this.wasDestroyed.compareAndSet(false, true)) {
+ // This decrement always matches the initial count of 1 given at creation time.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ @Synchronized
+ override fun close() {
+ this.destroy()
+ }
+
+ internal inline fun <R> callWithHandle(block: (handle: Long) -> R): R {
+ // Check and increment the call counter, to keep the object alive.
+ // This needs a compare-and-set retry loop in case of concurrent updates.
+ do {
+ val c = this.callCounter.get()
+ if (c == 0L) {
+ throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed")
+ }
+ if (c == Long.MAX_VALUE) {
+ throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow")
+ }
+ } while (! this.callCounter.compareAndSet(c, c + 1L))
+ // Now we can safely do the method call without the handle being freed concurrently.
+ try {
+ return block(this.uniffiCloneHandle())
+ } finally {
+ // This decrement always matches the increment we performed above.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ // Use a static inner class instead of a closure so as not to accidentally
+ // capture `this` as part of the cleanable's action.
+ private class UniffiCleanAction(private val handle: Long) : Runnable {
+ override fun run() {
+ if (handle == 0.toLong()) {
+ // Fake object created with `NoHandle`, don't try to free.
+ return;
+ }
+ uniffiRustCall { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopsclient(handle, status)
+ }
+ }
+ }
+
+ /**
+ * @suppress
+ */
+ fun uniffiCloneHandle(): Long {
+ if (handle == 0.toLong()) {
+ throw InternalException("uniffiCloneHandle() called on NoHandle object");
+ }
+ return uniffiRustCall() { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopsclient(handle, status)
+ }
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `createClaim`(`request`: CreateClaimRequest) : Claim {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(
+ uniffiHandle,
+
+ FfiConverterTypeCreateClaimRequest.lower(`request`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeClaim.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deleteClaim`(`claim`: Claim) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(
+ uniffiHandle,
+
+ FfiConverterTypeClaim.lower(`claim`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `getClaim`(`claim`: Claim) : Claim {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(
+ uniffiHandle,
+
+ FfiConverterTypeClaim.lower(`claim`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeClaim.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `listClaims`(`namespace`: kotlin.String) : List<Claim> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(
+ uniffiHandle,
+
+ FfiConverterString.lower(`namespace`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeClaim.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `waitClaim`(`claim`: Claim) : Sandbox {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(
+ uniffiHandle,
+
+ FfiConverterTypeClaim.lower(`claim`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSandbox.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `createPool`(`request`: CreatePoolRequest) : Pool {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(
+ uniffiHandle,
+
+ FfiConverterTypeCreatePoolRequest.lower(`request`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypePool.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deletePool`(`pool`: Pool) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(
+ uniffiHandle,
+
+ FfiConverterTypePool.lower(`pool`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `getPool`(`pool`: Pool) : Pool {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(
+ uniffiHandle,
+
+ FfiConverterTypePool.lower(`pool`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypePool.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `listPools`(`namespace`: kotlin.String) : List<Pool> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(
+ uniffiHandle,
+
+ FfiConverterString.lower(`namespace`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypePool.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `updatePool`(`pool`: Pool) : Pool {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(
+ uniffiHandle,
+
+ FfiConverterTypePool.lower(`pool`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypePool.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `serviceRequest`(`sandbox`: Sandbox, `service`: kotlin.String, `path`: kotlin.String, `request`: HttpRequest) : HttpResponse {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(
+ uniffiHandle,
+
+ FfiConverterTypeSandbox.lower(`sandbox`),
+ FfiConverterString.lower(`service`),
+ FfiConverterString.lower(`path`),
+ FfiConverterTypeHttpRequest.lower(`request`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeHttpResponse.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+
+
+
+
+
+ companion object {
+
+ @Throws(SdkException::class) fun `connect`(`configuration`: CyclopsConfiguration, `httpClient`: HttpClient): CyclopsClient {
+ return FfiConverterTypeCyclopsClient.lift(
+ uniffiRustCallWithError(SdkException) { _status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect(
+
+
+ FfiConverterTypeCyclopsConfiguration.lower(`configuration`),
+ FfiConverterTypeHttpClient.lower(`httpClient`),_status)
+}
+ )
+ }
+
+
+
+ }
+
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCyclopsClient: FfiConverter<CyclopsClient, Long> {
+ override fun lower(value: CyclopsClient): Long {
+ return value.uniffiCloneHandle()
+ }
+
+ override fun lift(value: Long): CyclopsClient {
+ return CyclopsClient(UniffiWithHandle, value)
+ }
+
+ override fun read(buf: ByteBuffer): CyclopsClient {
+ return lift(buf.getLong())
+ }
+
+ override fun allocationSize(value: CyclopsClient) = 8UL
+
+ override fun write(value: CyclopsClient, buf: ByteBuffer) {
+ buf.putLong(lower(value))
+ }
+}
+
+
+// This template implements a class for working with a Rust struct via a handle
+// to the live Rust struct on the other side of the FFI.
+//
+// There's some subtlety here, because we have to be careful not to operate on a Rust
+// struct after it has been dropped, and because we must expose a public API for freeing
+// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are:
+//
+// * Each instance holds an opaque handle to the underlying Rust struct.
+// Method calls need to read this handle from the object's state and pass it in to
+// the Rust FFI.
+//
+// * When an instance is no longer needed, its handle should be passed to a
+// special destructor function provided by the Rust FFI, which will drop the
+// underlying Rust struct.
+//
+// * Given an instance, calling code is expected to call the special
+// `destroy` method in order to free it after use, either by calling it explicitly
+// or by using a higher-level helper like the `use` method. Failing to do so risks
+// leaking the underlying Rust struct.
+//
+// * We can't assume that calling code will do the right thing, and must be prepared
+// to handle Kotlin method calls executing concurrently with or even after a call to
+// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`.
+//
+// * We must never allow Rust code to operate on the underlying Rust struct after
+// the destructor has been called, and must never call the destructor more than once.
+// Doing so may trigger memory unsafety.
+//
+// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner`
+// is implemented to call the destructor when the Kotlin object becomes unreachable.
+// This is done in a background thread. This is not a panacea, and client code should be aware that
+// 1. the thread may starve if some there are objects that have poorly performing
+// `drop` methods or do significant work in their `drop` methods.
+// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`,
+// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html).
+//
+// If we try to implement this with mutual exclusion on access to the handle, there is the
+// possibility of a race between a method call and a concurrent call to `destroy`:
+//
+// * Thread A starts a method call, reads the value of the handle, but is interrupted
+// before it can pass the handle over the FFI to Rust.
+// * Thread B calls `destroy` and frees the underlying Rust struct.
+// * Thread A resumes, passing the already-read handle value to Rust and triggering
+// a use-after-free.
+//
+// One possible solution would be to use a `ReadWriteLock`, with each method call taking
+// a read lock (and thus allowed to run concurrently) and the special `destroy` method
+// taking a write lock (and thus blocking on live method calls). However, we aim not to
+// generate methods with any hidden blocking semantics, and a `destroy` method that might
+// block if called incorrectly seems to meet that bar.
+//
+// So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track
+// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy`
+// has been called. These are updated according to the following rules:
+//
+// * The initial value of the counter is 1, indicating a live object with no in-flight calls.
+// The initial value for the flag is false.
+//
+// * At the start of each method call, we atomically check the counter.
+// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted.
+// If it is nonzero them we atomically increment it by 1 and proceed with the method call.
+//
+// * At the end of each method call, we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// * When `destroy` is called, we atomically flip the flag from false to true.
+// If the flag was already true we silently fail.
+// Otherwise we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works,
+// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`.
+//
+// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been
+// called *and* all in-flight method calls have completed, avoiding violating any of the expectations
+// of the underlying Rust code.
+//
+// This makes a cleaner a better alternative to _not_ calling `destroy()` as
+// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop`
+// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner
+// thread may be starved, and the app will leak memory.
+//
+// In this case, `destroy`ing manually may be a better solution.
+//
+// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects
+// with Rust peers are reclaimed:
+//
+// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen:
+// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then:
+// 3. The memory is reclaimed when the process terminates.
+//
+// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219
+//
+
+
+public interface CyclopsCredentialsInterface {
+
+ companion object
+}
+
+open class CyclopsCredentials: Disposable, AutoCloseable, CyclopsCredentialsInterface
+{
+
+ @Suppress("UNUSED_PARAMETER")
+ /**
+ * @suppress
+ */
+ constructor(withHandle: UniffiWithHandle, handle: Long) {
+ this.handle = handle
+ this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(handle))
+ }
+
+ /**
+ * @suppress
+ *
+ * This constructor can be used to instantiate a fake object. Only used for tests. Any
+ * attempt to actually use an object constructed this way will fail as there is no
+ * connected Rust object.
+ */
+ @Suppress("UNUSED_PARAMETER")
+ constructor(noHandle: NoHandle) {
+ this.handle = 0
+ this.cleanable = null
+ }
+ constructor(`clientId`: kotlin.String, `clientSecret`: kotlin.String) :
+ this(UniffiWithHandle,
+ uniffiRustCall() { _status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new(
+
+
+ FfiConverterString.lower(`clientId`),
+ FfiConverterString.lower(`clientSecret`),_status)
+}
+ )
+
+ protected val handle: Long
+ protected val cleanable: UniffiCleaner.Cleanable?
+
+ private val wasDestroyed = AtomicBoolean(false)
+ private val callCounter = AtomicLong(1)
+
+ /**
+ * Whether the current object has been destroyed and its reference is gone in the Rust side.
+ */
+ val uniffiIsDestroyed: Boolean get() = wasDestroyed.get()
+
+ override fun destroy() {
+ // Only allow a single call to this method.
+ // TODO: maybe we should log a warning if called more than once?
+ if (this.wasDestroyed.compareAndSet(false, true)) {
+ // This decrement always matches the initial count of 1 given at creation time.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ @Synchronized
+ override fun close() {
+ this.destroy()
+ }
+
+ internal inline fun <R> callWithHandle(block: (handle: Long) -> R): R {
+ // Check and increment the call counter, to keep the object alive.
+ // This needs a compare-and-set retry loop in case of concurrent updates.
+ do {
+ val c = this.callCounter.get()
+ if (c == 0L) {
+ throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed")
+ }
+ if (c == Long.MAX_VALUE) {
+ throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow")
+ }
+ } while (! this.callCounter.compareAndSet(c, c + 1L))
+ // Now we can safely do the method call without the handle being freed concurrently.
+ try {
+ return block(this.uniffiCloneHandle())
+ } finally {
+ // This decrement always matches the increment we performed above.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ // Use a static inner class instead of a closure so as not to accidentally
+ // capture `this` as part of the cleanable's action.
+ private class UniffiCleanAction(private val handle: Long) : Runnable {
+ override fun run() {
+ if (handle == 0.toLong()) {
+ // Fake object created with `NoHandle`, don't try to free.
+ return;
+ }
+ uniffiRustCall { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopscredentials(handle, status)
+ }
+ }
+ }
+
+ /**
+ * @suppress
+ */
+ fun uniffiCloneHandle(): Long {
+ if (handle == 0.toLong()) {
+ throw InternalException("uniffiCloneHandle() called on NoHandle object");
+ }
+ return uniffiRustCall() { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopscredentials(handle, status)
+ }
+ }
+
+
+
+
+
+
+
+
+ /**
+ * @suppress
+ */
+ companion object
+
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCyclopsCredentials: FfiConverter<CyclopsCredentials, Long> {
+ override fun lower(value: CyclopsCredentials): Long {
+ return value.uniffiCloneHandle()
+ }
+
+ override fun lift(value: Long): CyclopsCredentials {
+ return CyclopsCredentials(UniffiWithHandle, value)
+ }
+
+ override fun read(buf: ByteBuffer): CyclopsCredentials {
+ return lift(buf.getLong())
+ }
+
+ override fun allocationSize(value: CyclopsCredentials) = 8UL
+
+ override fun write(value: CyclopsCredentials, buf: ByteBuffer) {
+ buf.putLong(lower(value))
+ }
+}
+
+
+// This template implements a class for working with a Rust struct via a handle
+// to the live Rust struct on the other side of the FFI.
+//
+// There's some subtlety here, because we have to be careful not to operate on a Rust
+// struct after it has been dropped, and because we must expose a public API for freeing
+// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are:
+//
+// * Each instance holds an opaque handle to the underlying Rust struct.
+// Method calls need to read this handle from the object's state and pass it in to
+// the Rust FFI.
+//
+// * When an instance is no longer needed, its handle should be passed to a
+// special destructor function provided by the Rust FFI, which will drop the
+// underlying Rust struct.
+//
+// * Given an instance, calling code is expected to call the special
+// `destroy` method in order to free it after use, either by calling it explicitly
+// or by using a higher-level helper like the `use` method. Failing to do so risks
+// leaking the underlying Rust struct.
+//
+// * We can't assume that calling code will do the right thing, and must be prepared
+// to handle Kotlin method calls executing concurrently with or even after a call to
+// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`.
+//
+// * We must never allow Rust code to operate on the underlying Rust struct after
+// the destructor has been called, and must never call the destructor more than once.
+// Doing so may trigger memory unsafety.
+//
+// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner`
+// is implemented to call the destructor when the Kotlin object becomes unreachable.
+// This is done in a background thread. This is not a panacea, and client code should be aware that
+// 1. the thread may starve if some there are objects that have poorly performing
+// `drop` methods or do significant work in their `drop` methods.
+// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`,
+// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html).
+//
+// If we try to implement this with mutual exclusion on access to the handle, there is the
+// possibility of a race between a method call and a concurrent call to `destroy`:
+//
+// * Thread A starts a method call, reads the value of the handle, but is interrupted
+// before it can pass the handle over the FFI to Rust.
+// * Thread B calls `destroy` and frees the underlying Rust struct.
+// * Thread A resumes, passing the already-read handle value to Rust and triggering
+// a use-after-free.
+//
+// One possible solution would be to use a `ReadWriteLock`, with each method call taking
+// a read lock (and thus allowed to run concurrently) and the special `destroy` method
+// taking a write lock (and thus blocking on live method calls). However, we aim not to
+// generate methods with any hidden blocking semantics, and a `destroy` method that might
+// block if called incorrectly seems to meet that bar.
+//
+// So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track
+// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy`
+// has been called. These are updated according to the following rules:
+//
+// * The initial value of the counter is 1, indicating a live object with no in-flight calls.
+// The initial value for the flag is false.
+//
+// * At the start of each method call, we atomically check the counter.
+// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted.
+// If it is nonzero them we atomically increment it by 1 and proceed with the method call.
+//
+// * At the end of each method call, we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// * When `destroy` is called, we atomically flip the flag from false to true.
+// If the flag was already true we silently fail.
+// Otherwise we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works,
+// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`.
+//
+// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been
+// called *and* all in-flight method calls have completed, avoiding violating any of the expectations
+// of the underlying Rust code.
+//
+// This makes a cleaner a better alternative to _not_ calling `destroy()` as
+// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop`
+// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner
+// thread may be starved, and the app will leak memory.
+//
+// In this case, `destroy`ing manually may be a better solution.
+//
+// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects
+// with Rust peers are reclaimed:
+//
+// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen:
+// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then:
+// 3. The memory is reclaimed when the process terminates.
+//
+// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219
+//
+
+
+public interface HttpClient {
+
+ suspend fun `execute`(`request`: HttpRequest): HttpResponse
+
+ companion object
+}
+
+open class HttpClientImpl: Disposable, AutoCloseable, HttpClient
+{
+
+ @Suppress("UNUSED_PARAMETER")
+ /**
+ * @suppress
+ */
+ constructor(withHandle: UniffiWithHandle, handle: Long) {
+ this.handle = handle
+ this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(handle))
+ }
+
+ /**
+ * @suppress
+ *
+ * This constructor can be used to instantiate a fake object. Only used for tests. Any
+ * attempt to actually use an object constructed this way will fail as there is no
+ * connected Rust object.
+ */
+ @Suppress("UNUSED_PARAMETER")
+ constructor(noHandle: NoHandle) {
+ this.handle = 0
+ this.cleanable = null
+ }
+
+ protected val handle: Long
+ protected val cleanable: UniffiCleaner.Cleanable?
+
+ private val wasDestroyed = AtomicBoolean(false)
+ private val callCounter = AtomicLong(1)
+
+ /**
+ * Whether the current object has been destroyed and its reference is gone in the Rust side.
+ */
+ val uniffiIsDestroyed: Boolean get() = wasDestroyed.get()
+
+ override fun destroy() {
+ // Only allow a single call to this method.
+ // TODO: maybe we should log a warning if called more than once?
+ if (this.wasDestroyed.compareAndSet(false, true)) {
+ // This decrement always matches the initial count of 1 given at creation time.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ @Synchronized
+ override fun close() {
+ this.destroy()
+ }
+
+ internal inline fun <R> callWithHandle(block: (handle: Long) -> R): R {
+ // Check and increment the call counter, to keep the object alive.
+ // This needs a compare-and-set retry loop in case of concurrent updates.
+ do {
+ val c = this.callCounter.get()
+ if (c == 0L) {
+ throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed")
+ }
+ if (c == Long.MAX_VALUE) {
+ throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow")
+ }
+ } while (! this.callCounter.compareAndSet(c, c + 1L))
+ // Now we can safely do the method call without the handle being freed concurrently.
+ try {
+ return block(this.uniffiCloneHandle())
+ } finally {
+ // This decrement always matches the increment we performed above.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ // Use a static inner class instead of a closure so as not to accidentally
+ // capture `this` as part of the cleanable's action.
+ private class UniffiCleanAction(private val handle: Long) : Runnable {
+ override fun run() {
+ if (handle == 0.toLong()) {
+ // Fake object created with `NoHandle`, don't try to free.
+ return;
+ }
+ uniffiRustCall { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_free_httpclient(handle, status)
+ }
+ }
+ }
+
+ /**
+ * @suppress
+ */
+ fun uniffiCloneHandle(): Long {
+ if (handle == 0.toLong()) {
+ throw InternalException("uniffiCloneHandle() called on NoHandle object");
+ }
+ return uniffiRustCall() { status ->
+ UniffiLib.uniffi_cyclops_sdk_fn_clone_httpclient(handle, status)
+ }
+ }
+
+
+ @Throws(HttpException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `execute`(`request`: HttpRequest) : HttpResponse {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_httpclient_execute(
+ uniffiHandle,
+
+ FfiConverterTypeHttpRequest.lower(`request`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeHttpResponse.lift(it) },
+ // Error FFI converter
+ HttpException.ErrorHandler,
+ )
+ }
+
+
+
+
+
+
+
+
+ /**
+ * @suppress
+ */
+ companion object
+
+}
+
+
+
+// Put the implementation in an object so we don't pollute the top-level namespace
+internal object uniffiCallbackInterfaceHttpClient {
+ internal object `execute`: UniffiCallbackInterfaceHttpClientMethod0 {
+ override fun callback(`uniffiHandle`: Long,`request`: RustBuffer.ByValue,`uniffiFutureCallback`: UniffiForeignFutureCompleteRustBuffer,`uniffiCallbackData`: Long,`uniffiOutDroppedCallback`: UniffiForeignFutureDroppedCallbackStruct,) {
+ val uniffiObj = FfiConverterTypeHttpClient.handleMap.get(uniffiHandle)
+ val makeCall = suspend { ->
+ uniffiObj.`execute`(
+ FfiConverterTypeHttpRequest.lift(`request`),
+ )
+ }
+ val uniffiHandleSuccess = { returnValue: HttpResponse ->
+ val uniffiResult = UniffiForeignFutureResultRustBuffer.UniffiByValue(
+ FfiConverterTypeHttpResponse.lower(returnValue),
+ UniffiRustCallStatus.ByValue()
+ )
+ uniffiResult.write()
+ uniffiFutureCallback.callback(uniffiCallbackData, uniffiResult)
+ }
+ val uniffiHandleError = { callStatus: UniffiRustCallStatus.ByValue ->
+ uniffiFutureCallback.callback(
+ uniffiCallbackData,
+ UniffiForeignFutureResultRustBuffer.UniffiByValue(
+ RustBuffer.ByValue(),
+ callStatus,
+ ),
+ )
+ }
+ uniffiTraitInterfaceCallAsyncWithError(
+ makeCall,
+ uniffiHandleSuccess,
+ uniffiHandleError,
+ { e: HttpException -> FfiConverterTypeHttpError.lower(e) },
+ uniffiOutDroppedCallback
+ )
+ }
+ }
+
+ internal object uniffiFree: UniffiCallbackInterfaceFree {
+ override fun callback(handle: Long) {
+ FfiConverterTypeHttpClient.handleMap.remove(handle)
+ }
+ }
+
+ internal object uniffiClone: UniffiCallbackInterfaceClone {
+ override fun callback(handle: Long): Long {
+ return FfiConverterTypeHttpClient.handleMap.clone(handle)
+ }
+ }
+
+ internal var vtable = UniffiVTableCallbackInterfaceHttpClient.UniffiByValue(
+ uniffiFree,
+ uniffiClone,
+ `execute`,
+ )
+
+ // Registers the foreign callback with the Rust side.
+ // This method is generated for each callback interface.
+ internal fun register(lib: UniffiLib) {
+ lib.uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(vtable)
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeHttpClient: FfiConverter<HttpClient, Long> {
+ internal val handleMap = UniffiHandleMap<HttpClient>()
+
+ override fun lower(value: HttpClient): Long {
+ if (value is HttpClientImpl) {
+ // Rust-implemented object. Clone the handle and return it
+ return value.uniffiCloneHandle()
+ } else {
+ // Kotlin object, generate a new vtable handle and return that.
+ return handleMap.insert(value)
+ }
+ }
+
+ override fun lift(value: Long): HttpClient {
+ if ((value and 1.toLong()) == 0.toLong()) {
+ // Rust-generated handle, construct a new class that uses the handle to implement the
+ // interface
+ return HttpClientImpl(UniffiWithHandle, value)
+ } else {
+ // Kotlin-generated handle, get the object from the handle map
+ return handleMap.remove(value)
+ }
+ }
+
+ override fun read(buf: ByteBuffer): HttpClient {
+ return lift(buf.getLong())
+ }
+
+ override fun allocationSize(value: HttpClient) = 8UL
+
+ override fun write(value: HttpClient, buf: ByteBuffer) {
+ buf.putLong(lower(value))
+ }
+}
+
+
+
+data class Claim (
+ var `apiVersion`: kotlin.String
+ ,
+ var `kind`: kotlin.String
+ ,
+ var `metadata`: ResourceMetadata
+ ,
+ var `spec`: ClaimSpec
+ ,
+ var `status`: OsGymSandboxClaimStatus?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeClaim: FfiConverterRustBuffer<Claim> {
+ override fun read(buf: ByteBuffer): Claim {
+ return Claim(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterTypeResourceMetadata.read(buf),
+ FfiConverterTypeClaimSpec.read(buf),
+ FfiConverterOptionalTypeOSGymSandboxClaimStatus.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: Claim) = (
+ FfiConverterString.allocationSize(value.`apiVersion`) +
+ FfiConverterString.allocationSize(value.`kind`) +
+ FfiConverterTypeResourceMetadata.allocationSize(value.`metadata`) +
+ FfiConverterTypeClaimSpec.allocationSize(value.`spec`) +
+ FfiConverterOptionalTypeOSGymSandboxClaimStatus.allocationSize(value.`status`)
+ )
+
+ override fun write(value: Claim, buf: ByteBuffer) {
+ FfiConverterString.write(value.`apiVersion`, buf)
+ FfiConverterString.write(value.`kind`, buf)
+ FfiConverterTypeResourceMetadata.write(value.`metadata`, buf)
+ FfiConverterTypeClaimSpec.write(value.`spec`, buf)
+ FfiConverterOptionalTypeOSGymSandboxClaimStatus.write(value.`status`, buf)
+ }
+}
+
+
+
+data class CreateClaimRequest (
+ var `pool`: Pool
+ ,
+ var `spec`: ClaimSpec?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCreateClaimRequest: FfiConverterRustBuffer<CreateClaimRequest> {
+ override fun read(buf: ByteBuffer): CreateClaimRequest {
+ return CreateClaimRequest(
+ FfiConverterTypePool.read(buf),
+ FfiConverterOptionalTypeClaimSpec.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: CreateClaimRequest) = (
+ FfiConverterTypePool.allocationSize(value.`pool`) +
+ FfiConverterOptionalTypeClaimSpec.allocationSize(value.`spec`)
+ )
+
+ override fun write(value: CreateClaimRequest, buf: ByteBuffer) {
+ FfiConverterTypePool.write(value.`pool`, buf)
+ FfiConverterOptionalTypeClaimSpec.write(value.`spec`, buf)
+ }
+}
+
+
+
+data class CreatePoolRequest (
+ var `namespace`: kotlin.String
+ ,
+ var `spec`: PoolSpec
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCreatePoolRequest: FfiConverterRustBuffer<CreatePoolRequest> {
+ override fun read(buf: ByteBuffer): CreatePoolRequest {
+ return CreatePoolRequest(
+ FfiConverterString.read(buf),
+ FfiConverterTypePoolSpec.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: CreatePoolRequest) = (
+ FfiConverterString.allocationSize(value.`namespace`) +
+ FfiConverterTypePoolSpec.allocationSize(value.`spec`)
+ )
+
+ override fun write(value: CreatePoolRequest, buf: ByteBuffer) {
+ FfiConverterString.write(value.`namespace`, buf)
+ FfiConverterTypePoolSpec.write(value.`spec`, buf)
+ }
+}
+
+
+
+data class CyclopsConfiguration (
+ var `baseUrl`: kotlin.String
+ ,
+ var `tokenUrl`: kotlin.String
+ ,
+ var `credentials`: CyclopsCredentials
+ ,
+ var `poolPollIntervalMs`: kotlin.ULong
+ ,
+ var `poolPollLimit`: kotlin.UInt
+ ,
+ var `claimPollIntervalMs`: kotlin.ULong
+ ,
+ var `claimPollLimit`: kotlin.UInt
+
+): Disposable{
+
+
+
+
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`baseUrl`,
+ this.`tokenUrl`,
+ this.`credentials`,
+ this.`poolPollIntervalMs`,
+ this.`poolPollLimit`,
+ this.`claimPollIntervalMs`,
+ this.`claimPollLimit`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCyclopsConfiguration: FfiConverterRustBuffer<CyclopsConfiguration> {
+ override fun read(buf: ByteBuffer): CyclopsConfiguration {
+ return CyclopsConfiguration(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterTypeCyclopsCredentials.read(buf),
+ FfiConverterULong.read(buf),
+ FfiConverterUInt.read(buf),
+ FfiConverterULong.read(buf),
+ FfiConverterUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: CyclopsConfiguration) = (
+ FfiConverterString.allocationSize(value.`baseUrl`) +
+ FfiConverterString.allocationSize(value.`tokenUrl`) +
+ FfiConverterTypeCyclopsCredentials.allocationSize(value.`credentials`) +
+ FfiConverterULong.allocationSize(value.`poolPollIntervalMs`) +
+ FfiConverterUInt.allocationSize(value.`poolPollLimit`) +
+ FfiConverterULong.allocationSize(value.`claimPollIntervalMs`) +
+ FfiConverterUInt.allocationSize(value.`claimPollLimit`)
+ )
+
+ override fun write(value: CyclopsConfiguration, buf: ByteBuffer) {
+ FfiConverterString.write(value.`baseUrl`, buf)
+ FfiConverterString.write(value.`tokenUrl`, buf)
+ FfiConverterTypeCyclopsCredentials.write(value.`credentials`, buf)
+ FfiConverterULong.write(value.`poolPollIntervalMs`, buf)
+ FfiConverterUInt.write(value.`poolPollLimit`, buf)
+ FfiConverterULong.write(value.`claimPollIntervalMs`, buf)
+ FfiConverterUInt.write(value.`claimPollLimit`, buf)
+ }
+}
+
+
+
+data class HttpHeader (
+ var `name`: kotlin.String
+ ,
+ var `value`: kotlin.String
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeHttpHeader: FfiConverterRustBuffer<HttpHeader> {
+ override fun read(buf: ByteBuffer): HttpHeader {
+ return HttpHeader(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: HttpHeader) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterString.allocationSize(value.`value`)
+ )
+
+ override fun write(value: HttpHeader, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterString.write(value.`value`, buf)
+ }
+}
+
+
+
+data class HttpRequest (
+ var `method`: kotlin.String
+ ,
+ var `url`: kotlin.String
+ ,
+ var `headers`: List<HttpHeader>
+ ,
+ var `body`: kotlin.ByteArray?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeHttpRequest: FfiConverterRustBuffer<HttpRequest> {
+ override fun read(buf: ByteBuffer): HttpRequest {
+ return HttpRequest(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterSequenceTypeHttpHeader.read(buf),
+ FfiConverterOptionalByteArray.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: HttpRequest) = (
+ FfiConverterString.allocationSize(value.`method`) +
+ FfiConverterString.allocationSize(value.`url`) +
+ FfiConverterSequenceTypeHttpHeader.allocationSize(value.`headers`) +
+ FfiConverterOptionalByteArray.allocationSize(value.`body`)
+ )
+
+ override fun write(value: HttpRequest, buf: ByteBuffer) {
+ FfiConverterString.write(value.`method`, buf)
+ FfiConverterString.write(value.`url`, buf)
+ FfiConverterSequenceTypeHttpHeader.write(value.`headers`, buf)
+ FfiConverterOptionalByteArray.write(value.`body`, buf)
+ }
+}
+
+
+
+data class HttpResponse (
+ var `status`: kotlin.UShort
+ ,
+ var `headers`: List<HttpHeader>
+ ,
+ var `body`: kotlin.ByteArray
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeHttpResponse: FfiConverterRustBuffer<HttpResponse> {
+ override fun read(buf: ByteBuffer): HttpResponse {
+ return HttpResponse(
+ FfiConverterUShort.read(buf),
+ FfiConverterSequenceTypeHttpHeader.read(buf),
+ FfiConverterByteArray.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: HttpResponse) = (
+ FfiConverterUShort.allocationSize(value.`status`) +
+ FfiConverterSequenceTypeHttpHeader.allocationSize(value.`headers`) +
+ FfiConverterByteArray.allocationSize(value.`body`)
+ )
+
+ override fun write(value: HttpResponse, buf: ByteBuffer) {
+ FfiConverterUShort.write(value.`status`, buf)
+ FfiConverterSequenceTypeHttpHeader.write(value.`headers`, buf)
+ FfiConverterByteArray.write(value.`body`, buf)
+ }
+}
+
+
+
+/**
+ * UniFFI cannot emit aliases for external record types. Generated bindings use
+ * `OSGymWorkspacePoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
+ */
+data class Pool (
+ var `apiVersion`: kotlin.String
+ ,
+ var `kind`: kotlin.String
+ ,
+ var `metadata`: ResourceMetadata
+ ,
+ var `spec`: PoolSpec
+ ,
+ var `status`: OsGymWorkspacePoolStatus?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypePool: FfiConverterRustBuffer<Pool> {
+ override fun read(buf: ByteBuffer): Pool {
+ return Pool(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterTypeResourceMetadata.read(buf),
+ FfiConverterTypePoolSpec.read(buf),
+ FfiConverterOptionalTypeOSGymWorkspacePoolStatus.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: Pool) = (
+ FfiConverterString.allocationSize(value.`apiVersion`) +
+ FfiConverterString.allocationSize(value.`kind`) +
+ FfiConverterTypeResourceMetadata.allocationSize(value.`metadata`) +
+ FfiConverterTypePoolSpec.allocationSize(value.`spec`) +
+ FfiConverterOptionalTypeOSGymWorkspacePoolStatus.allocationSize(value.`status`)
+ )
+
+ override fun write(value: Pool, buf: ByteBuffer) {
+ FfiConverterString.write(value.`apiVersion`, buf)
+ FfiConverterString.write(value.`kind`, buf)
+ FfiConverterTypeResourceMetadata.write(value.`metadata`, buf)
+ FfiConverterTypePoolSpec.write(value.`spec`, buf)
+ FfiConverterOptionalTypeOSGymWorkspacePoolStatus.write(value.`status`, buf)
+ }
+}
+
+
+
+data class ResourceMetadata (
+ var `namespace`: kotlin.String
+ ,
+ var `name`: kotlin.String
+ ,
+ var `labels`: Map<kotlin.String, kotlin.String>?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeResourceMetadata: FfiConverterRustBuffer<ResourceMetadata> {
+ override fun read(buf: ByteBuffer): ResourceMetadata {
+ return ResourceMetadata(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalMapStringString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: ResourceMetadata) = (
+ FfiConverterString.allocationSize(value.`namespace`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterOptionalMapStringString.allocationSize(value.`labels`)
+ )
+
+ override fun write(value: ResourceMetadata, buf: ByteBuffer) {
+ FfiConverterString.write(value.`namespace`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterOptionalMapStringString.write(value.`labels`, buf)
+ }
+}
+
+
+
+data class Sandbox (
+ var `namespace`: kotlin.String
+ ,
+ var `claim`: kotlin.String
+ ,
+ var `name`: kotlin.String
+ ,
+ var `services`: List<kotlin.String>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSandbox: FfiConverterRustBuffer<Sandbox> {
+ override fun read(buf: ByteBuffer): Sandbox {
+ return Sandbox(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: Sandbox) = (
+ FfiConverterString.allocationSize(value.`namespace`) +
+ FfiConverterString.allocationSize(value.`claim`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterSequenceString.allocationSize(value.`services`)
+ )
+
+ override fun write(value: Sandbox, buf: ByteBuffer) {
+ FfiConverterString.write(value.`namespace`, buf)
+ FfiConverterString.write(value.`claim`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterSequenceString.write(value.`services`, buf)
+ }
+}
+
+
+
+
+
+sealed class HttpException: kotlin.Exception() {
+
+ class Transport(
+
+ val `reason`: kotlin.String
+ ) : HttpException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+
+
+
+
+ companion object ErrorHandler : UniffiRustCallStatusErrorHandler<HttpException> {
+ override fun lift(error_buf: RustBuffer.ByValue): HttpException = FfiConverterTypeHttpError.lift(error_buf)
+ }
+
+
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeHttpError : FfiConverterRustBuffer<HttpException> {
+ override fun read(buf: ByteBuffer): HttpException {
+
+
+ return when(buf.getInt()) {
+ 1 -> HttpException.Transport(
+ FfiConverterString.read(buf),
+ )
+ else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
+ }
+ }
+
+ override fun allocationSize(value: HttpException): ULong {
+ return when(value) {
+ is HttpException.Transport -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ }
+ }
+
+ override fun write(value: HttpException, buf: ByteBuffer) {
+ when(value) {
+ is HttpException.Transport -> {
+ buf.putInt(1)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
+ }
+
+}
+
+
+
+
+
+sealed class SdkException: kotlin.Exception() {
+
+ class Configuration(
+
+ val `reason`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+ class InvalidResourceName(
+
+ val `field`: kotlin.String,
+
+ val `value`: kotlin.String,
+
+ val `reason`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "field=${ `field` }, value=${ `value` }, reason=${ `reason` }"
+ }
+
+ class Transport(
+
+ val `reason`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+ class Token(
+
+ val `reason`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+ class Body(
+
+ val `reason`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+ class Status(
+
+ val `operation`: kotlin.String,
+
+ val `status`: kotlin.UShort,
+
+ val `body`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "operation=${ `operation` }, status=${ `status` }, body=${ `body` }"
+ }
+
+ class UnknownService(
+
+ val `requested`: kotlin.String,
+
+ val `available`: List<kotlin.String>
+ ) : SdkException() {
+ override val message
+ get() = "requested=${ `requested` }, available=${ `available` }"
+ }
+
+ class InvalidServicePath(
+
+ val `path`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "path=${ `path` }"
+ }
+
+ class ClaimFailed(
+
+ val `phase`: kotlin.String,
+
+ val `status`: kotlin.String
+ ) : SdkException() {
+ override val message
+ get() = "phase=${ `phase` }, status=${ `status` }"
+ }
+
+ class ClaimTimeout(
+ ) : SdkException() {
+ override val message
+ get() = ""
+ }
+
+
+
+
+
+ companion object ErrorHandler : UniffiRustCallStatusErrorHandler<SdkException> {
+ override fun lift(error_buf: RustBuffer.ByValue): SdkException = FfiConverterTypeSdkError.lift(error_buf)
+ }
+
+
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSdkError : FfiConverterRustBuffer<SdkException> {
+ override fun read(buf: ByteBuffer): SdkException {
+
+
+ return when(buf.getInt()) {
+ 1 -> SdkException.Configuration(
+ FfiConverterString.read(buf),
+ )
+ 2 -> SdkException.InvalidResourceName(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ )
+ 3 -> SdkException.Transport(
+ FfiConverterString.read(buf),
+ )
+ 4 -> SdkException.Token(
+ FfiConverterString.read(buf),
+ )
+ 5 -> SdkException.Body(
+ FfiConverterString.read(buf),
+ )
+ 6 -> SdkException.Status(
+ FfiConverterString.read(buf),
+ FfiConverterUShort.read(buf),
+ FfiConverterString.read(buf),
+ )
+ 7 -> SdkException.UnknownService(
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ 8 -> SdkException.InvalidServicePath(
+ FfiConverterString.read(buf),
+ )
+ 9 -> SdkException.ClaimFailed(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ )
+ 10 -> SdkException.ClaimTimeout()
+ else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
+ }
+ }
+
+ override fun allocationSize(value: SdkException): ULong {
+ return when(value) {
+ is SdkException.Configuration -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ is SdkException.InvalidResourceName -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`field`)
+ + FfiConverterString.allocationSize(value.`value`)
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ is SdkException.Transport -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ is SdkException.Token -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ is SdkException.Body -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ is SdkException.Status -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`operation`)
+ + FfiConverterUShort.allocationSize(value.`status`)
+ + FfiConverterString.allocationSize(value.`body`)
+ )
+ is SdkException.UnknownService -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`requested`)
+ + FfiConverterSequenceString.allocationSize(value.`available`)
+ )
+ is SdkException.InvalidServicePath -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`path`)
+ )
+ is SdkException.ClaimFailed -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`phase`)
+ + FfiConverterString.allocationSize(value.`status`)
+ )
+ is SdkException.ClaimTimeout -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ )
+ }
+ }
+
+ override fun write(value: SdkException, buf: ByteBuffer) {
+ when(value) {
+ is SdkException.Configuration -> {
+ buf.putInt(1)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ is SdkException.InvalidResourceName -> {
+ buf.putInt(2)
+ FfiConverterString.write(value.`field`, buf)
+ FfiConverterString.write(value.`value`, buf)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ is SdkException.Transport -> {
+ buf.putInt(3)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ is SdkException.Token -> {
+ buf.putInt(4)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ is SdkException.Body -> {
+ buf.putInt(5)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ is SdkException.Status -> {
+ buf.putInt(6)
+ FfiConverterString.write(value.`operation`, buf)
+ FfiConverterUShort.write(value.`status`, buf)
+ FfiConverterString.write(value.`body`, buf)
+ Unit
+ }
+ is SdkException.UnknownService -> {
+ buf.putInt(7)
+ FfiConverterString.write(value.`requested`, buf)
+ FfiConverterSequenceString.write(value.`available`, buf)
+ Unit
+ }
+ is SdkException.InvalidServicePath -> {
+ buf.putInt(8)
+ FfiConverterString.write(value.`path`, buf)
+ Unit
+ }
+ is SdkException.ClaimFailed -> {
+ buf.putInt(9)
+ FfiConverterString.write(value.`phase`, buf)
+ FfiConverterString.write(value.`status`, buf)
+ Unit
+ }
+ is SdkException.ClaimTimeout -> {
+ buf.putInt(10)
+ Unit
+ }
+ }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
+ }
+
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalByteArray: FfiConverterRustBuffer<kotlin.ByteArray?> {
+ override fun read(buf: ByteBuffer): kotlin.ByteArray? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterByteArray.read(buf)
+ }
+
+ override fun allocationSize(value: kotlin.ByteArray?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterByteArray.allocationSize(value)
+ }
+ }
+
+ override fun write(value: kotlin.ByteArray?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterByteArray.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeClaimSpec: FfiConverterRustBuffer<ClaimSpec?> {
+ override fun read(buf: ByteBuffer): ClaimSpec? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeClaimSpec.read(buf)
+ }
+
+ override fun allocationSize(value: ClaimSpec?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeClaimSpec.allocationSize(value)
+ }
+ }
+
+ override fun write(value: ClaimSpec?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeClaimSpec.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeOSGymSandboxClaimStatus: FfiConverterRustBuffer<OsGymSandboxClaimStatus?> {
+ override fun read(buf: ByteBuffer): OsGymSandboxClaimStatus? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeOSGymSandboxClaimStatus.read(buf)
+ }
+
+ override fun allocationSize(value: OsGymSandboxClaimStatus?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeOSGymSandboxClaimStatus.allocationSize(value)
+ }
+ }
+
+ override fun write(value: OsGymSandboxClaimStatus?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeOSGymSandboxClaimStatus.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeOSGymWorkspacePoolStatus: FfiConverterRustBuffer<OsGymWorkspacePoolStatus?> {
+ override fun read(buf: ByteBuffer): OsGymWorkspacePoolStatus? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeOSGymWorkspacePoolStatus.read(buf)
+ }
+
+ override fun allocationSize(value: OsGymWorkspacePoolStatus?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeOSGymWorkspacePoolStatus.allocationSize(value)
+ }
+ }
+
+ override fun write(value: OsGymWorkspacePoolStatus?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeOSGymWorkspacePoolStatus.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>?> {
+ override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterMapStringString.read(buf)
+ }
+
+ override fun allocationSize(value: Map<kotlin.String, kotlin.String>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterMapStringString.allocationSize(value)
+ }
+ }
+
+ override fun write(value: Map<kotlin.String, kotlin.String>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterMapStringString.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceString: FfiConverterRustBuffer<List<kotlin.String>> {
+ override fun read(buf: ByteBuffer): List<kotlin.String> {
+ val len = buf.getInt()
+ return List<kotlin.String>(len) {
+ FfiConverterString.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<kotlin.String>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterString.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<kotlin.String>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterString.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeClaim: FfiConverterRustBuffer<List<Claim>> {
+ override fun read(buf: ByteBuffer): List<Claim> {
+ val len = buf.getInt()
+ return List<Claim>(len) {
+ FfiConverterTypeClaim.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<Claim>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeClaim.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<Claim>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeClaim.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeHttpHeader: FfiConverterRustBuffer<List<HttpHeader>> {
+ override fun read(buf: ByteBuffer): List<HttpHeader> {
+ val len = buf.getInt()
+ return List<HttpHeader>(len) {
+ FfiConverterTypeHttpHeader.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<HttpHeader>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeHttpHeader.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<HttpHeader>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeHttpHeader.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypePool: FfiConverterRustBuffer<List<Pool>> {
+ override fun read(buf: ByteBuffer): List<Pool> {
+ val len = buf.getInt()
+ return List<Pool>(len) {
+ FfiConverterTypePool.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<Pool>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypePool.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<Pool>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypePool.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>> {
+ override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String> {
+ val len = buf.getInt()
+ return buildMap<kotlin.String, kotlin.String>(len) {
+ repeat(len) {
+ val k = FfiConverterString.read(buf)
+ val v = FfiConverterString.read(buf)
+ this[k] = v
+ }
+ }
+ }
+
+ override fun allocationSize(value: Map<kotlin.String, kotlin.String>): ULong {
+ val spaceForMapSize = 4UL
+ val spaceForChildren = value.map { (k, v) ->
+ FfiConverterString.allocationSize(k) +
+ FfiConverterString.allocationSize(v)
+ }.sum()
+ return spaceForMapSize + spaceForChildren
+ }
+
+ override fun write(value: Map<kotlin.String, kotlin.String>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ // The parens on `(k, v)` here ensure we're calling the right method,
+ // which is important for compatibility with older android devices.
+ // Ref https://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/
+ value.forEach { (k, v) ->
+ FfiConverterString.write(k, buf)
+ FfiConverterString.write(v, buf)
+ }
+ }
+}
diff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/schema/cyclops_sdk_schema.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/schema/cyclops_sdk_schema.kt
new file mode 100644
index 0000000000..73a4a8787c
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/schema/cyclops_sdk_schema.kt
@@ -0,0 +1,3292 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+@file:Suppress("NAME_SHADOWING")
+
+package ai.cua.cyclops.sdk.schema
+
+// Common helper code.
+//
+// Ideally this would live in a separate .kt file where it can be unittested etc
+// in isolation, and perhaps even published as a re-useable package.
+//
+// However, it's important that the details of how this helper code works (e.g. the
+// way that different builtin types are passed across the FFI) exactly match what's
+// expected by the Rust code on the other side of the interface. In practice right
+// now that means coming from the exact some version of `uniffi` that was used to
+// compile the Rust component. The easiest way to ensure this is to bundle the Kotlin
+// helpers directly inline like we're doing here.
+
+import com.sun.jna.Library
+import com.sun.jna.IntegerType
+import com.sun.jna.Native
+import com.sun.jna.Pointer
+import com.sun.jna.Structure
+import com.sun.jna.Callback
+import com.sun.jna.ptr.*
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.nio.CharBuffer
+import java.nio.charset.CodingErrorAction
+import java.util.concurrent.atomic.AtomicLong
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicBoolean
+
+// This is a helper for safely working with byte buffers returned from the Rust code.
+// A rust-owned buffer is represented by its capacity, its current length, and a
+// pointer to the underlying data.
+
+/**
+ * @suppress
+ */
[email protected]("capacity", "len", "data")
+open class RustBuffer : Structure() {
+ // Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values.
+ // When dealing with these fields, make sure to call `toULong()`.
+ @JvmField var capacity: Long = 0
+ @JvmField var len: Long = 0
+ @JvmField var data: Pointer? = null
+
+ class ByValue: RustBuffer(), Structure.ByValue
+ class ByReference: RustBuffer(), Structure.ByReference
+
+ internal fun setValue(other: RustBuffer) {
+ capacity = other.capacity
+ len = other.len
+ data = other.data
+ }
+
+ companion object {
+ internal fun alloc(size: ULong = 0UL) = uniffiRustCall() { status ->
+ // Note: need to convert the size to a `Long` value to make this work with JVM.
+ UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_alloc(size.toLong(), status)
+ }.also {
+ if(it.data == null) {
+ throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})")
+ }
+ }
+
+ internal fun create(capacity: ULong, len: ULong, data: Pointer?): RustBuffer.ByValue {
+ var buf = RustBuffer.ByValue()
+ buf.capacity = capacity.toLong()
+ buf.len = len.toLong()
+ buf.data = data
+ return buf
+ }
+
+ internal fun free(buf: RustBuffer.ByValue) = uniffiRustCall() { status ->
+ UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_free(buf, status)
+ }
+ }
+
+ @Suppress("TooGenericExceptionThrown")
+ fun asByteBuffer() =
+ this.data?.getByteBuffer(0, this.len)?.also {
+ it.order(ByteOrder.BIG_ENDIAN)
+ }
+}
+
+// This is a helper for safely passing byte references into the rust code.
+// It's not actually used at the moment, because there aren't many things that you
+// can take a direct pointer to in the JVM, and if we're going to copy something
+// then we might as well copy it into a `RustBuffer`. But it's here for API
+// completeness.
+
[email protected]("len", "data")
+internal open class ForeignBytes : Structure() {
+ @JvmField var len: Int = 0
+ @JvmField var data: Pointer? = null
+
+ class ByValue : ForeignBytes(), Structure.ByValue
+}
+
+// Converter for `&[u8]` / `[ByRef] bytes` arguments.
+//
+// Only `lower` is valid — zero-copy byte buffers only flow foreign -> Rust,
+// and only in argument position. `lift`, `read`, `write`, and
+// `allocationSize` have no sound implementation here and all panic at
+// runtime. The `FfiConverter` interface is implemented so that the
+// compiler enforces the full method set (rather than relying on eyeball).
+//
+// The provided `ByteBuffer` MUST be direct — only direct buffers have a
+// stable native address that JNA can expose via `getDirectBufferPointer`.
+// The returned `ForeignBytes.ByValue` is only valid for the duration of
+// the FFI call; the Rust side treats it as a borrow.
+internal object FfiConverterByRefBytes : FfiConverter<java.nio.ByteBuffer, ForeignBytes.ByValue> {
+ override fun lower(value: java.nio.ByteBuffer): ForeignBytes.ByValue {
+ require(value.isDirect) { "UniFFI zero-copy &[u8] requires a direct ByteBuffer. Use ByteBuffer.allocateDirect()." }
+ val remaining = value.remaining()
+ val fb = ForeignBytes.ByValue()
+ fb.len = remaining
+ // Zero-length direct buffers: skip getDirectBufferPointer (platform-variable behavior)
+ // and pass null. The Rust side treats (null, 0) as &[].
+ fb.data = if (remaining == 0) null else com.sun.jna.Native.getDirectBufferPointer(value)
+ return fb
+ }
+
+ override fun lift(value: ForeignBytes.ByValue): java.nio.ByteBuffer =
+ error("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+
+ override fun read(buf: java.nio.ByteBuffer): java.nio.ByteBuffer =
+ error("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ override fun write(value: java.nio.ByteBuffer, buf: java.nio.ByteBuffer): Unit =
+ error("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ override fun allocationSize(value: java.nio.ByteBuffer): ULong =
+ error("ByRef bytes have no RustBuffer allocation size: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+}
+/**
+ * The FfiConverter interface handles converter types to and from the FFI
+ *
+ * All implementing objects should be public to support external types. When a
+ * type is external we need to import it's FfiConverter.
+ *
+ * @suppress
+ */
+public interface FfiConverter<KotlinType, FfiType> {
+ // Convert an FFI type to a Kotlin type
+ fun lift(value: FfiType): KotlinType
+
+ // Convert an Kotlin type to an FFI type
+ fun lower(value: KotlinType): FfiType
+
+ // Read a Kotlin type from a `ByteBuffer`
+ fun read(buf: ByteBuffer): KotlinType
+
+ // Calculate bytes to allocate when creating a `RustBuffer`
+ //
+ // This must return at least as many bytes as the write() function will
+ // write. It can return more bytes than needed, for example when writing
+ // Strings we can't know the exact bytes needed until we the UTF-8
+ // encoding, so we pessimistically allocate the largest size possible (3
+ // bytes per codepoint). Allocating extra bytes is not really a big deal
+ // because the `RustBuffer` is short-lived.
+ fun allocationSize(value: KotlinType): ULong
+
+ // Write a Kotlin type to a `ByteBuffer`
+ fun write(value: KotlinType, buf: ByteBuffer)
+
+ // Lower a value into a `RustBuffer`
+ //
+ // This method lowers a value into a `RustBuffer` rather than the normal
+ // FfiType. It's used by the callback interface code. Callback interface
+ // returns are always serialized into a `RustBuffer` regardless of their
+ // normal FFI type.
+ fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue {
+ val rbuf = RustBuffer.alloc(allocationSize(value))
+ try {
+ val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity).also {
+ it.order(ByteOrder.BIG_ENDIAN)
+ }
+ write(value, bbuf)
+ rbuf.writeField("len", bbuf.position().toLong())
+ return rbuf
+ } catch (e: Throwable) {
+ RustBuffer.free(rbuf)
+ throw e
+ }
+ }
+
+ // Lift a value from a `RustBuffer`.
+ //
+ // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.
+ // It's currently only used by the `FfiConverterRustBuffer` class below.
+ fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType {
+ val byteBuf = rbuf.asByteBuffer()!!
+ try {
+ val item = read(byteBuf)
+ if (byteBuf.hasRemaining()) {
+ throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!")
+ }
+ return item
+ } finally {
+ RustBuffer.free(rbuf)
+ }
+ }
+}
+
+/**
+ * FfiConverter that uses `RustBuffer` as the FfiType
+ *
+ * @suppress
+ */
+public interface FfiConverterRustBuffer<KotlinType>: FfiConverter<KotlinType, RustBuffer.ByValue> {
+ override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value)
+ override fun lower(value: KotlinType) = lowerIntoRustBuffer(value)
+}
+// A handful of classes and functions to support the generated data structures.
+// This would be a good candidate for isolating in its own ffi-support lib.
+
+internal const val UNIFFI_CALL_SUCCESS = 0.toByte()
+internal const val UNIFFI_CALL_ERROR = 1.toByte()
+internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte()
+
[email protected]("code", "error_buf")
+internal open class UniffiRustCallStatus : Structure() {
+ @JvmField var code: Byte = 0
+ @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue()
+
+ class ByValue: UniffiRustCallStatus(), Structure.ByValue
+
+ fun isSuccess(): Boolean {
+ return code == UNIFFI_CALL_SUCCESS
+ }
+
+ fun isError(): Boolean {
+ return code == UNIFFI_CALL_ERROR
+ }
+
+ fun isPanic(): Boolean {
+ return code == UNIFFI_CALL_UNEXPECTED_ERROR
+ }
+
+ companion object {
+ fun create(code: Byte, errorBuf: RustBuffer.ByValue): UniffiRustCallStatus.ByValue {
+ val callStatus = UniffiRustCallStatus.ByValue()
+ callStatus.code = code
+ callStatus.error_buf = errorBuf
+ return callStatus
+ }
+ }
+}
+
+class InternalException(message: String) : kotlin.Exception(message)
+
+/**
+ * Each top-level error class has a companion object that can lift the error from the call status's rust buffer
+ *
+ * @suppress
+ */
+interface UniffiRustCallStatusErrorHandler<E> {
+ fun lift(error_buf: RustBuffer.ByValue): E;
+}
+
+// Helpers for calling Rust
+// In practice we usually need to be synchronized to call this safely, so it doesn't
+// synchronize itself
+
+// Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err
+private inline fun <U, E: kotlin.Exception> uniffiRustCallWithError(errorHandler: UniffiRustCallStatusErrorHandler<E>, callback: (UniffiRustCallStatus) -> U): U {
+ var status = UniffiRustCallStatus()
+ val return_value = callback(status)
+ uniffiCheckCallStatus(errorHandler, status)
+ return return_value
+}
+
+// Check UniffiRustCallStatus and throw an error if the call wasn't successful
+private fun<E: kotlin.Exception> uniffiCheckCallStatus(errorHandler: UniffiRustCallStatusErrorHandler<E>, status: UniffiRustCallStatus) {
+ if (status.isSuccess()) {
+ return
+ } else if (status.isError()) {
+ throw errorHandler.lift(status.error_buf)
+ } else if (status.isPanic()) {
+ // when the rust code sees a panic, it tries to construct a rustbuffer
+ // with the message. but if that code panics, then it just sends back
+ // an empty buffer.
+ if (status.error_buf.len > 0) {
+ throw InternalException(FfiConverterString.lift(status.error_buf))
+ } else {
+ throw InternalException("Rust panic")
+ }
+ } else {
+ throw InternalException("Unknown rust call status: $status.code")
+ }
+}
+
+/**
+ * UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR
+ *
+ * @suppress
+ */
+object UniffiNullRustCallStatusErrorHandler: UniffiRustCallStatusErrorHandler<InternalException> {
+ override fun lift(error_buf: RustBuffer.ByValue): InternalException {
+ RustBuffer.free(error_buf)
+ return InternalException("Unexpected CALL_ERROR")
+ }
+}
+
+// Call a rust function that returns a plain value
+private inline fun <U> uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U {
+ return uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback)
+}
+
+internal inline fun<T> uniffiTraitInterfaceCall(
+ callStatus: UniffiRustCallStatus,
+ makeCall: () -> T,
+ writeReturn: (T) -> Unit,
+) {
+ try {
+ writeReturn(makeCall())
+ } catch(e: kotlin.Exception) {
+ val err = try { e.stackTraceToString() } catch(_: Throwable) { "" }
+ callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
+ callStatus.error_buf = FfiConverterString.lower(err)
+ }
+}
+
+internal inline fun<T, reified E: Throwable> uniffiTraitInterfaceCallWithError(
+ callStatus: UniffiRustCallStatus,
+ makeCall: () -> T,
+ writeReturn: (T) -> Unit,
+ lowerError: (E) -> RustBuffer.ByValue
+) {
+ try {
+ writeReturn(makeCall())
+ } catch(e: kotlin.Exception) {
+ if (e is E) {
+ callStatus.code = UNIFFI_CALL_ERROR
+ callStatus.error_buf = lowerError(e)
+ } else {
+ val err = try { e.stackTraceToString() } catch(_: Throwable) { "" }
+ callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
+ callStatus.error_buf = FfiConverterString.lower(err)
+ }
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that Kotlin-generated handles always have the lowest bit set
+private const val UNIFFI_HANDLEMAP_INITIAL = 1.toLong()
+private const val UNIFFI_HANDLEMAP_DELTA = 2.toLong()
+
+// Map handles to objects
+//
+// This is used pass an opaque 64-bit handle representing a foreign object to the Rust code.
+internal class UniffiHandleMap<T: Any> {
+ private val map = ConcurrentHashMap<Long, T>()
+ // Start
+ private val counter = java.util.concurrent.atomic.AtomicLong(UNIFFI_HANDLEMAP_INITIAL)
+
+ val size: Int
+ get() = map.size
+
+ // Insert a new object into the handle map and get a handle for it
+ fun insert(obj: T): Long {
+ val handle = counter.getAndAdd(UNIFFI_HANDLEMAP_DELTA)
+ map.put(handle, obj)
+ return handle
+ }
+
+ // Clone a handle, creating a new one
+ fun clone(handle: Long): Long {
+ val obj = map.get(handle) ?: throw InternalException("UniffiHandleMap.clone: Invalid handle")
+ return insert(obj)
+ }
+
+ // Get an object from the handle map
+ fun get(handle: Long): T {
+ return map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle")
+ }
+
+ // Remove an entry from the handlemap and get the Kotlin object back
+ fun remove(handle: Long): T {
+ return map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle")
+ }
+}
+
+// Contains loading, initialization code,
+// and the FFI Function declarations in a com.sun.jna.Library.
+@Synchronized
+private fun findLibraryName(componentName: String): String {
+ val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride")
+ if (libOverride != null) {
+ return libOverride
+ }
+ return "cyclops_sdk"
+}
+
+// Define FFI callback types
+internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback {
+ fun callback(`data`: Long,`pollResult`: Byte,)
+}
+internal interface UniffiForeignFutureDroppedCallback : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+}
+internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+}
+internal interface UniffiCallbackInterfaceClone : com.sun.jna.Callback {
+ fun callback(`handle`: Long,)
+ : Long
+}
[email protected]("handle", "free")
+internal open class UniffiForeignFutureDroppedCallbackStruct(
+ @JvmField internal var `handle`: Long = 0.toLong(),
+ @JvmField internal var `free`: UniffiForeignFutureDroppedCallback? = null,
+) : Structure() {
+ class UniffiByValue(
+ `handle`: Long = 0.toLong(),
+ `free`: UniffiForeignFutureDroppedCallback? = null,
+ ): UniffiForeignFutureDroppedCallbackStruct(`handle`,`free`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureDroppedCallbackStruct) {
+ `handle` = other.`handle`
+ `free` = other.`free`
+ }
+
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU8(
+ @JvmField internal var `returnValue`: Byte = 0.toByte(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Byte = 0.toByte(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU8(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU8) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU8.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI8(
+ @JvmField internal var `returnValue`: Byte = 0.toByte(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Byte = 0.toByte(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI8(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI8) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI8.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU16(
+ @JvmField internal var `returnValue`: Short = 0.toShort(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Short = 0.toShort(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU16(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU16) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU16.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI16(
+ @JvmField internal var `returnValue`: Short = 0.toShort(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Short = 0.toShort(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI16(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI16) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI16.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU32(
+ @JvmField internal var `returnValue`: Int = 0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Int = 0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI32(
+ @JvmField internal var `returnValue`: Int = 0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Int = 0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultU64(
+ @JvmField internal var `returnValue`: Long = 0.toLong(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Long = 0.toLong(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultU64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultU64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultU64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultI64(
+ @JvmField internal var `returnValue`: Long = 0.toLong(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Long = 0.toLong(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultI64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultI64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultI64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultF32(
+ @JvmField internal var `returnValue`: Float = 0.0f,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Float = 0.0f,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultF32(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultF32) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultF32.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultF64(
+ @JvmField internal var `returnValue`: Double = 0.0,
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: Double = 0.0,
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultF64(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultF64) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultF64.UniffiByValue,)
+}
[email protected]("returnValue", "callStatus")
+internal open class UniffiForeignFutureResultRustBuffer(
+ @JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultRustBuffer(`returnValue`,`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultRustBuffer) {
+ `returnValue` = other.`returnValue`
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultRustBuffer.UniffiByValue,)
+}
[email protected]("callStatus")
+internal open class UniffiForeignFutureResultVoid(
+ @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+) : Structure() {
+ class UniffiByValue(
+ `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
+ ): UniffiForeignFutureResultVoid(`callStatus`,), Structure.ByValue
+
+ internal fun uniffiSetValue(other: UniffiForeignFutureResultVoid) {
+ `callStatus` = other.`callStatus`
+ }
+
+}
+internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback {
+ fun callback(`callbackData`: Long,`result`: UniffiForeignFutureResultVoid.UniffiByValue,)
+}
+
+// A JNA Library to expose the extern-C FFI definitions.
+// This is an implementation detail which will be called internally by the public API.
+
+// For large crates we prevent `MethodTooLargeException` (see #2340)
+// N.B. the name of the extension is very misleading, since it is
+// rather `InterfaceTooLargeException`, caused by too many methods
+// in the interface for large crates.
+//
+// By splitting the otherwise huge interface into two parts
+// * UniffiLib (this)
+// * IntegrityCheckingUniffiLib
+// And all checksum methods are put into `IntegrityCheckingUniffiLib`
+// we allow for ~2x as many methods in the UniffiLib interface.
+//
+// Note: above all written when we used JNA's `loadIndirect` etc.
+// We now use JNA's "direct mapping" - unclear if same considerations apply exactly.
+internal object IntegrityCheckingUniffiLib {
+ init {
+ Native.register(IntegrityCheckingUniffiLib::class.java, findLibraryName(componentName = "cyclops_sdk_schema"))
+ uniffiCheckContractApiVersion(this)
+ uniffiCheckApiChecksums(this)
+ }
+ external fun uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json(
+ ): Int
+ external fun uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json(
+ ): Int
+ external fun ffi_cyclops_sdk_schema_uniffi_contract_version(
+ ): Int
+
+
+}
+
+internal object UniffiLib {
+
+ // The Cleaner for the whole library
+ internal val CLEANER: UniffiCleaner by lazy {
+ UniffiCleaner.create()
+ }
+
+
+ init {
+ Native.register(UniffiLib::class.java, findLibraryName(componentName = "cyclops_sdk_schema"))
+
+ }
+ external fun uniffi_cyclops_sdk_schema_fn_clone_preservedjson(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_schema_fn_free_preservedjson(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json(`value`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq(`ptr`: RustBuffer.ByValue,`other`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Byte
+ external fun uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne(`ptr`: RustBuffer.ByValue,`other`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Byte
+ external fun uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash(`ptr`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_schema_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_schema_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_schema_rustbuffer_free(`buf`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_u8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_u8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_u8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_u8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_i8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_i8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_i8(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_i8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Byte
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_u16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_u16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_u16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_u16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_i16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_i16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_i16(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_i16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Short
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_u32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_u32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_u32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_u32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_i32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_i32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_i32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_i32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Int
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_u64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_u64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_u64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_u64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_i64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_i64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_i64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_i64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Long
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_f32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_f32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_f32(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_f32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Float
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_f64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_f64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_f64(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_f64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Double
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_rust_buffer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_rust_buffer(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_rust_buffer(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_rust_buffer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): RustBuffer.ByValue
+ external fun ffi_cyclops_sdk_schema_rust_future_poll_void(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_cancel_void(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_free_void(`handle`: Long,
+ ): Unit
+ external fun ffi_cyclops_sdk_schema_rust_future_complete_void(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
+ ): Unit
+
+
+}
+
+private fun uniffiCheckContractApiVersion(lib: IntegrityCheckingUniffiLib) {
+ // Get the bindings contract version from our ComponentInterface
+ val bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ val scaffolding_contract_version = lib.ffi_cyclops_sdk_schema_uniffi_contract_version()
+ if (bindings_contract_version != scaffolding_contract_version) {
+ throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ }
+}
+@Suppress("UNUSED_PARAMETER")
+private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
+ if (lib.uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json() != 675) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json() != 56364) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+/**
+ * @suppress
+ */
+public fun uniffiEnsureInitialized() {
+ IntegrityCheckingUniffiLib
+ // UniffiLib() initialized as objects are used, but we still need to explicitly
+ // reference it so initialization across crates works as expected.
+ UniffiLib
+}
+
+// Async support
+
+// Public interface members begin here.
+
+
+// Interface implemented by anything that can contain an object reference.
+//
+// Such types expose a `destroy()` method that must be called to cleanly
+// dispose of the contained objects. Failure to call this method may result
+// in memory leaks.
+//
+// The easiest way to ensure this method is called is to use the `.use`
+// helper method to execute a block and destroy the object at the end.
+interface Disposable {
+ fun destroy()
+ companion object {
+ fun destroy(vararg args: Any?) {
+ for (arg in args) {
+ when (arg) {
+ is Disposable -> arg.destroy()
+ is ArrayList<*> -> {
+ for (idx in arg.indices) {
+ val element = arg[idx]
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ is Map<*, *> -> {
+ for (element in arg.values) {
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ is Iterable<*> -> {
+ for (element in arg) {
+ if (element is Disposable) {
+ element.destroy()
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @suppress
+ */
+inline fun <T : Disposable?, R> T.use(block: (T) -> R) =
+ try {
+ block(this)
+ } finally {
+ try {
+ // N.B. our implementation is on the nullable type `Disposable?`.
+ this?.destroy()
+ } catch (e: Throwable) {
+ // swallow
+ }
+ }
+
+/**
+ * Placeholder object used to signal that we're constructing an interface with a FFI handle.
+ *
+ * This is the first argument for interface constructors that input a raw handle. It exists is that
+ * so we can avoid signature conflicts when an interface has a regular constructor than inputs a
+ * Long.
+ *
+ * @suppress
+ * */
+object UniffiWithHandle
+
+/**
+ * Used to instantiate an interface without an actual pointer, for fakes in tests, mostly.
+ *
+ * @suppress
+ * */
+object NoHandle
+/**
+ * The cleaner interface for Object finalization code to run.
+ * This is the entry point to any implementation that we're using.
+ *
+ * The cleaner registers objects and returns cleanables, so now we are
+ * defining a `UniffiCleaner` with a `UniffiClenaer.Cleanable` to abstract the
+ * different implmentations available at compile time.
+ *
+ * @suppress
+ */
+interface UniffiCleaner {
+ interface Cleanable {
+ fun clean()
+ }
+
+ fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable
+
+ companion object
+}
+
+// The fallback Jna cleaner, which is available for both Android, and the JVM.
+private class UniffiJnaCleaner : UniffiCleaner {
+ private val cleaner = com.sun.jna.internal.Cleaner.getCleaner()
+
+ override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable =
+ UniffiJnaCleanable(cleaner.register(value, cleanUpTask))
+}
+
+private class UniffiJnaCleanable(
+ private val cleanable: com.sun.jna.internal.Cleaner.Cleanable,
+) : UniffiCleaner.Cleanable {
+ override fun clean() = cleanable.clean()
+}
+
+
+// We decide at uniffi binding generation time whether we were
+// using Android or not.
+// There are further runtime checks to chose the correct implementation
+// of the cleaner.
+private fun UniffiCleaner.Companion.create(): UniffiCleaner =
+ try {
+ // For safety's sake: if the library hasn't been run in android_cleaner = true
+ // mode, but is being run on Android, then we still need to think about
+ // Android API versions.
+ // So we check if java.lang.ref.Cleaner is there, and use that…
+ java.lang.Class.forName("java.lang.ref.Cleaner")
+ JavaLangRefCleaner()
+ } catch (e: ClassNotFoundException) {
+ // … otherwise, fallback to the JNA cleaner.
+ UniffiJnaCleaner()
+ }
+
+private class JavaLangRefCleaner : UniffiCleaner {
+ val cleaner = java.lang.ref.Cleaner.create()
+
+ override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable =
+ JavaLangRefCleanable(cleaner.register(value, cleanUpTask))
+}
+
+private class JavaLangRefCleanable(
+ val cleanable: java.lang.ref.Cleaner.Cleanable
+) : UniffiCleaner.Cleanable {
+ override fun clean() = cleanable.clean()
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterUShort: FfiConverter<UShort, Short> {
+ override fun lift(value: Short): UShort {
+ return value.toUShort()
+ }
+
+ fun lift(value: Int): UShort {
+ return value.toUShort()
+ }
+
+ override fun read(buf: ByteBuffer): UShort {
+ return lift(buf.getShort())
+ }
+
+ override fun lower(value: UShort): Short {
+ return value.toShort()
+ }
+
+ override fun allocationSize(value: UShort) = 2UL
+
+ override fun write(value: UShort, buf: ByteBuffer) {
+ buf.putShort(value.toShort())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterUInt: FfiConverter<UInt, Int> {
+ override fun lift(value: Int): UInt {
+ return value.toUInt()
+ }
+
+ override fun read(buf: ByteBuffer): UInt {
+ return lift(buf.getInt())
+ }
+
+ override fun lower(value: UInt): Int {
+ return value.toInt()
+ }
+
+ override fun allocationSize(value: UInt) = 4UL
+
+ override fun write(value: UInt, buf: ByteBuffer) {
+ buf.putInt(value.toInt())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterULong: FfiConverter<ULong, Long> {
+ override fun lift(value: Long): ULong {
+ return value.toULong()
+ }
+
+ override fun read(buf: ByteBuffer): ULong {
+ return lift(buf.getLong())
+ }
+
+ override fun lower(value: ULong): Long {
+ return value.toLong()
+ }
+
+ override fun allocationSize(value: ULong) = 8UL
+
+ override fun write(value: ULong, buf: ByteBuffer) {
+ buf.putLong(value.toLong())
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterBoolean: FfiConverter<Boolean, Byte> {
+ override fun lift(value: Byte): Boolean {
+ return value.toInt() != 0
+ }
+
+ override fun read(buf: ByteBuffer): Boolean {
+ return lift(buf.get())
+ }
+
+ override fun lower(value: Boolean): Byte {
+ return if (value) 1.toByte() else 0.toByte()
+ }
+
+ override fun allocationSize(value: Boolean) = 1UL
+
+ override fun write(value: Boolean, buf: ByteBuffer) {
+ buf.put(lower(value))
+ }
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> {
+ // Note: we don't inherit from FfiConverterRustBuffer, because we use a
+ // special encoding when lowering/lifting. We can use `RustBuffer.len` to
+ // store our length and avoid writing it out to the buffer.
+ override fun lift(value: RustBuffer.ByValue): String {
+ try {
+ val byteArr = ByteArray(value.len.toInt())
+ value.asByteBuffer()!!.get(byteArr)
+ return byteArr.toString(Charsets.UTF_8)
+ } finally {
+ RustBuffer.free(value)
+ }
+ }
+
+ override fun read(buf: ByteBuffer): String {
+ val len = buf.getInt()
+ val byteArr = ByteArray(len)
+ buf.get(byteArr)
+ return byteArr.toString(Charsets.UTF_8)
+ }
+
+ fun toUtf8(value: String): ByteBuffer {
+ // Make sure we don't have invalid UTF-16, check for lone surrogates.
+ return Charsets.UTF_8.newEncoder().run {
+ onMalformedInput(CodingErrorAction.REPORT)
+ encode(CharBuffer.wrap(value))
+ }
+ }
+
+ override fun lower(value: String): RustBuffer.ByValue {
+ val byteBuf = toUtf8(value)
+ // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us
+ // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`.
+ val rbuf = RustBuffer.alloc(byteBuf.limit().toULong())
+ rbuf.asByteBuffer()!!.put(byteBuf)
+ return rbuf
+ }
+
+ // We aren't sure exactly how many bytes our string will be once it's UTF-8
+ // encoded. Allocate 3 bytes per UTF-16 code unit which will always be
+ // enough.
+ override fun allocationSize(value: String): ULong {
+ val sizeForLength = 4UL
+ val sizeForString = value.length.toULong() * 3UL
+ return sizeForLength + sizeForString
+ }
+
+ override fun write(value: String, buf: ByteBuffer) {
+ val byteBuf = toUtf8(value)
+ buf.putInt(byteBuf.limit())
+ buf.put(byteBuf)
+ }
+}
+
+
+// This template implements a class for working with a Rust struct via a handle
+// to the live Rust struct on the other side of the FFI.
+//
+// There's some subtlety here, because we have to be careful not to operate on a Rust
+// struct after it has been dropped, and because we must expose a public API for freeing
+// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are:
+//
+// * Each instance holds an opaque handle to the underlying Rust struct.
+// Method calls need to read this handle from the object's state and pass it in to
+// the Rust FFI.
+//
+// * When an instance is no longer needed, its handle should be passed to a
+// special destructor function provided by the Rust FFI, which will drop the
+// underlying Rust struct.
+//
+// * Given an instance, calling code is expected to call the special
+// `destroy` method in order to free it after use, either by calling it explicitly
+// or by using a higher-level helper like the `use` method. Failing to do so risks
+// leaking the underlying Rust struct.
+//
+// * We can't assume that calling code will do the right thing, and must be prepared
+// to handle Kotlin method calls executing concurrently with or even after a call to
+// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`.
+//
+// * We must never allow Rust code to operate on the underlying Rust struct after
+// the destructor has been called, and must never call the destructor more than once.
+// Doing so may trigger memory unsafety.
+//
+// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner`
+// is implemented to call the destructor when the Kotlin object becomes unreachable.
+// This is done in a background thread. This is not a panacea, and client code should be aware that
+// 1. the thread may starve if some there are objects that have poorly performing
+// `drop` methods or do significant work in their `drop` methods.
+// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`,
+// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html).
+//
+// If we try to implement this with mutual exclusion on access to the handle, there is the
+// possibility of a race between a method call and a concurrent call to `destroy`:
+//
+// * Thread A starts a method call, reads the value of the handle, but is interrupted
+// before it can pass the handle over the FFI to Rust.
+// * Thread B calls `destroy` and frees the underlying Rust struct.
+// * Thread A resumes, passing the already-read handle value to Rust and triggering
+// a use-after-free.
+//
+// One possible solution would be to use a `ReadWriteLock`, with each method call taking
+// a read lock (and thus allowed to run concurrently) and the special `destroy` method
+// taking a write lock (and thus blocking on live method calls). However, we aim not to
+// generate methods with any hidden blocking semantics, and a `destroy` method that might
+// block if called incorrectly seems to meet that bar.
+//
+// So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track
+// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy`
+// has been called. These are updated according to the following rules:
+//
+// * The initial value of the counter is 1, indicating a live object with no in-flight calls.
+// The initial value for the flag is false.
+//
+// * At the start of each method call, we atomically check the counter.
+// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted.
+// If it is nonzero them we atomically increment it by 1 and proceed with the method call.
+//
+// * At the end of each method call, we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// * When `destroy` is called, we atomically flip the flag from false to true.
+// If the flag was already true we silently fail.
+// Otherwise we atomically decrement and check the counter.
+// If it has reached zero then we destroy the underlying Rust struct.
+//
+// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works,
+// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`.
+//
+// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been
+// called *and* all in-flight method calls have completed, avoiding violating any of the expectations
+// of the underlying Rust code.
+//
+// This makes a cleaner a better alternative to _not_ calling `destroy()` as
+// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop`
+// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner
+// thread may be starved, and the app will leak memory.
+//
+// In this case, `destroy`ing manually may be a better solution.
+//
+// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects
+// with Rust peers are reclaimed:
+//
+// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen:
+// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then:
+// 3. The memory is reclaimed when the process terminates.
+//
+// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219
+//
+
+
+public interface PreservedJsonInterface {
+
+ fun `toJson`(): kotlin.String
+
+ companion object
+}
+
+open class PreservedJson: Disposable, AutoCloseable, PreservedJsonInterface
+{
+
+ @Suppress("UNUSED_PARAMETER")
+ /**
+ * @suppress
+ */
+ constructor(withHandle: UniffiWithHandle, handle: Long) {
+ this.handle = handle
+ this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(handle))
+ }
+
+ /**
+ * @suppress
+ *
+ * This constructor can be used to instantiate a fake object. Only used for tests. Any
+ * attempt to actually use an object constructed this way will fail as there is no
+ * connected Rust object.
+ */
+ @Suppress("UNUSED_PARAMETER")
+ constructor(noHandle: NoHandle) {
+ this.handle = 0
+ this.cleanable = null
+ }
+
+ protected val handle: Long
+ protected val cleanable: UniffiCleaner.Cleanable?
+
+ private val wasDestroyed = AtomicBoolean(false)
+ private val callCounter = AtomicLong(1)
+
+ /**
+ * Whether the current object has been destroyed and its reference is gone in the Rust side.
+ */
+ val uniffiIsDestroyed: Boolean get() = wasDestroyed.get()
+
+ override fun destroy() {
+ // Only allow a single call to this method.
+ // TODO: maybe we should log a warning if called more than once?
+ if (this.wasDestroyed.compareAndSet(false, true)) {
+ // This decrement always matches the initial count of 1 given at creation time.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ @Synchronized
+ override fun close() {
+ this.destroy()
+ }
+
+ internal inline fun <R> callWithHandle(block: (handle: Long) -> R): R {
+ // Check and increment the call counter, to keep the object alive.
+ // This needs a compare-and-set retry loop in case of concurrent updates.
+ do {
+ val c = this.callCounter.get()
+ if (c == 0L) {
+ throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed")
+ }
+ if (c == Long.MAX_VALUE) {
+ throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow")
+ }
+ } while (! this.callCounter.compareAndSet(c, c + 1L))
+ // Now we can safely do the method call without the handle being freed concurrently.
+ try {
+ return block(this.uniffiCloneHandle())
+ } finally {
+ // This decrement always matches the increment we performed above.
+ if (this.callCounter.decrementAndGet() == 0L) {
+ cleanable?.clean()
+ }
+ }
+ }
+
+ // Use a static inner class instead of a closure so as not to accidentally
+ // capture `this` as part of the cleanable's action.
+ private class UniffiCleanAction(private val handle: Long) : Runnable {
+ override fun run() {
+ if (handle == 0.toLong()) {
+ // Fake object created with `NoHandle`, don't try to free.
+ return;
+ }
+ uniffiRustCall { status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_free_preservedjson(handle, status)
+ }
+ }
+ }
+
+ /**
+ * @suppress
+ */
+ fun uniffiCloneHandle(): Long {
+ if (handle == 0.toLong()) {
+ throw InternalException("uniffiCloneHandle() called on NoHandle object");
+ }
+ return uniffiRustCall() { status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_clone_preservedjson(handle, status)
+ }
+ }
+
+ override fun `toJson`(): kotlin.String {
+ return FfiConverterString.lift(
+ callWithHandle {
+ uniffiRustCall() { _status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json(
+ it,
+ _status)
+}
+ }
+ )
+ }
+
+
+
+
+
+
+
+
+ companion object {
+
+ @Throws(JsonValueException::class) fun `fromJson`(`value`: kotlin.String): PreservedJson {
+ return FfiConverterTypePreservedJson.lift(
+ uniffiRustCallWithError(JsonValueException) { _status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json(
+
+
+ FfiConverterString.lower(`value`),_status)
+}
+ )
+ }
+
+
+
+ }
+
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypePreservedJson: FfiConverter<PreservedJson, Long> {
+ override fun lower(value: PreservedJson): Long {
+ return value.uniffiCloneHandle()
+ }
+
+ override fun lift(value: Long): PreservedJson {
+ return PreservedJson(UniffiWithHandle, value)
+ }
+
+ override fun read(buf: ByteBuffer): PreservedJson {
+ return lift(buf.getLong())
+ }
+
+ override fun allocationSize(value: PreservedJson) = 8UL
+
+ override fun write(value: PreservedJson, buf: ByteBuffer) {
+ buf.putLong(lower(value))
+ }
+}
+
+
+
+data class ClaimLifecycle (
+ var `shutdownTime`: kotlin.String?
+ ,
+ var `shutdownPolicy`: kotlin.String?
+ ,
+ var `autoRenew`: kotlin.Boolean?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeClaimLifecycle: FfiConverterRustBuffer<ClaimLifecycle> {
+ override fun read(buf: ByteBuffer): ClaimLifecycle {
+ return ClaimLifecycle(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: ClaimLifecycle) = (
+ FfiConverterOptionalString.allocationSize(value.`shutdownTime`) +
+ FfiConverterOptionalString.allocationSize(value.`shutdownPolicy`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`autoRenew`)
+ )
+
+ override fun write(value: ClaimLifecycle, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`shutdownTime`, buf)
+ FfiConverterOptionalString.write(value.`shutdownPolicy`, buf)
+ FfiConverterOptionalBoolean.write(value.`autoRenew`, buf)
+ }
+}
+
+
+
+data class ClaimSpec (
+ var `sandboxTemplateRef`: SandboxTemplateRef
+ ,
+ var `warmpool`: kotlin.String?
+ ,
+ var `bindDeadline`: kotlin.UInt?
+ ,
+ var `lifecycle`: ClaimLifecycle?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeClaimSpec: FfiConverterRustBuffer<ClaimSpec> {
+ override fun read(buf: ByteBuffer): ClaimSpec {
+ return ClaimSpec(
+ FfiConverterTypeSandboxTemplateRef.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalTypeClaimLifecycle.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: ClaimSpec) = (
+ FfiConverterTypeSandboxTemplateRef.allocationSize(value.`sandboxTemplateRef`) +
+ FfiConverterOptionalString.allocationSize(value.`warmpool`) +
+ FfiConverterOptionalUInt.allocationSize(value.`bindDeadline`) +
+ FfiConverterOptionalTypeClaimLifecycle.allocationSize(value.`lifecycle`)
+ )
+
+ override fun write(value: ClaimSpec, buf: ByteBuffer) {
+ FfiConverterTypeSandboxTemplateRef.write(value.`sandboxTemplateRef`, buf)
+ FfiConverterOptionalString.write(value.`warmpool`, buf)
+ FfiConverterOptionalUInt.write(value.`bindDeadline`, buf)
+ FfiConverterOptionalTypeClaimLifecycle.write(value.`lifecycle`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxClaimCondition (
+ var `type`: kotlin.String?
+ ,
+ var `status`: kotlin.String?
+ ,
+ var `reason`: kotlin.String?
+ ,
+ var `message`: kotlin.String?
+ ,
+ var `lastTransitionTime`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer<OsGymSandboxClaimCondition> {
+ override fun read(buf: ByteBuffer): OsGymSandboxClaimCondition {
+ return OsGymSandboxClaimCondition(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxClaimCondition) = (
+ FfiConverterOptionalString.allocationSize(value.`type`) +
+ FfiConverterOptionalString.allocationSize(value.`status`) +
+ FfiConverterOptionalString.allocationSize(value.`reason`) +
+ FfiConverterOptionalString.allocationSize(value.`message`) +
+ FfiConverterOptionalString.allocationSize(value.`lastTransitionTime`)
+ )
+
+ override fun write(value: OsGymSandboxClaimCondition, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`type`, buf)
+ FfiConverterOptionalString.write(value.`status`, buf)
+ FfiConverterOptionalString.write(value.`reason`, buf)
+ FfiConverterOptionalString.write(value.`message`, buf)
+ FfiConverterOptionalString.write(value.`lastTransitionTime`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxClaimSandbox (
+ var `name`: kotlin.String?
+ ,
+ var `service`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxClaimSandbox: FfiConverterRustBuffer<OsGymSandboxClaimSandbox> {
+ override fun read(buf: ByteBuffer): OsGymSandboxClaimSandbox {
+ return OsGymSandboxClaimSandbox(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxClaimSandbox) = (
+ FfiConverterOptionalString.allocationSize(value.`name`) +
+ FfiConverterOptionalString.allocationSize(value.`service`)
+ )
+
+ override fun write(value: OsGymSandboxClaimSandbox, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`name`, buf)
+ FfiConverterOptionalString.write(value.`service`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxClaimStatus (
+ var `phase`: kotlin.String?
+ ,
+ var `conditions`: List<OsGymSandboxClaimCondition>?
+ ,
+ var `sandbox`: OsGymSandboxClaimSandbox?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxClaimStatus: FfiConverterRustBuffer<OsGymSandboxClaimStatus> {
+ override fun read(buf: ByteBuffer): OsGymSandboxClaimStatus {
+ return OsGymSandboxClaimStatus(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.read(buf),
+ FfiConverterOptionalTypeOSGymSandboxClaimSandbox.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxClaimStatus) = (
+ FfiConverterOptionalString.allocationSize(value.`phase`) +
+ FfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.allocationSize(value.`conditions`) +
+ FfiConverterOptionalTypeOSGymSandboxClaimSandbox.allocationSize(value.`sandbox`)
+ )
+
+ override fun write(value: OsGymSandboxClaimStatus, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`phase`, buf)
+ FfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.write(value.`conditions`, buf)
+ FfiConverterOptionalTypeOSGymSandboxClaimSandbox.write(value.`sandbox`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxSpec (
+ var `vmTemplate`: VmTemplate
+
+): Disposable{
+
+
+
+
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`vmTemplate`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxSpec: FfiConverterRustBuffer<OsGymSandboxSpec> {
+ override fun read(buf: ByteBuffer): OsGymSandboxSpec {
+ return OsGymSandboxSpec(
+ FfiConverterTypeVmTemplate.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxSpec) = (
+ FfiConverterTypeVmTemplate.allocationSize(value.`vmTemplate`)
+ )
+
+ override fun write(value: OsGymSandboxSpec, buf: ByteBuffer) {
+ FfiConverterTypeVmTemplate.write(value.`vmTemplate`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxStatus (
+ var `phase`: kotlin.String?
+ ,
+ var `runtime`: kotlin.String?
+ ,
+ var `ready`: kotlin.Boolean?
+ ,
+ var `vmName`: kotlin.String?
+ ,
+ var `service`: kotlin.String?
+ ,
+ var `message`: kotlin.String?
+ ,
+ var `resetIssuedAt`: kotlin.String?
+ ,
+ var `resetVmiUid`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxStatus: FfiConverterRustBuffer<OsGymSandboxStatus> {
+ override fun read(buf: ByteBuffer): OsGymSandboxStatus {
+ return OsGymSandboxStatus(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxStatus) = (
+ FfiConverterOptionalString.allocationSize(value.`phase`) +
+ FfiConverterOptionalString.allocationSize(value.`runtime`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`ready`) +
+ FfiConverterOptionalString.allocationSize(value.`vmName`) +
+ FfiConverterOptionalString.allocationSize(value.`service`) +
+ FfiConverterOptionalString.allocationSize(value.`message`) +
+ FfiConverterOptionalString.allocationSize(value.`resetIssuedAt`) +
+ FfiConverterOptionalString.allocationSize(value.`resetVmiUid`)
+ )
+
+ override fun write(value: OsGymSandboxStatus, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`phase`, buf)
+ FfiConverterOptionalString.write(value.`runtime`, buf)
+ FfiConverterOptionalBoolean.write(value.`ready`, buf)
+ FfiConverterOptionalString.write(value.`vmName`, buf)
+ FfiConverterOptionalString.write(value.`service`, buf)
+ FfiConverterOptionalString.write(value.`message`, buf)
+ FfiConverterOptionalString.write(value.`resetIssuedAt`, buf)
+ FfiConverterOptionalString.write(value.`resetVmiUid`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxTemplateSpec (
+ var `vmTemplate`: VmTemplate
+
+): Disposable{
+
+
+
+
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`vmTemplate`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxTemplateSpec: FfiConverterRustBuffer<OsGymSandboxTemplateSpec> {
+ override fun read(buf: ByteBuffer): OsGymSandboxTemplateSpec {
+ return OsGymSandboxTemplateSpec(
+ FfiConverterTypeVmTemplate.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxTemplateSpec) = (
+ FfiConverterTypeVmTemplate.allocationSize(value.`vmTemplate`)
+ )
+
+ override fun write(value: OsGymSandboxTemplateSpec, buf: ByteBuffer) {
+ FfiConverterTypeVmTemplate.write(value.`vmTemplate`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxWarmPoolSpec (
+ var `replicas`: kotlin.UInt
+ ,
+ var `sandboxTemplateRef`: SandboxTemplateRef
+ ,
+ var `autoscaling`: WarmPoolAutoscaling?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxWarmPoolSpec: FfiConverterRustBuffer<OsGymSandboxWarmPoolSpec> {
+ override fun read(buf: ByteBuffer): OsGymSandboxWarmPoolSpec {
+ return OsGymSandboxWarmPoolSpec(
+ FfiConverterUInt.read(buf),
+ FfiConverterTypeSandboxTemplateRef.read(buf),
+ FfiConverterOptionalTypeWarmPoolAutoscaling.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxWarmPoolSpec) = (
+ FfiConverterUInt.allocationSize(value.`replicas`) +
+ FfiConverterTypeSandboxTemplateRef.allocationSize(value.`sandboxTemplateRef`) +
+ FfiConverterOptionalTypeWarmPoolAutoscaling.allocationSize(value.`autoscaling`)
+ )
+
+ override fun write(value: OsGymSandboxWarmPoolSpec, buf: ByteBuffer) {
+ FfiConverterUInt.write(value.`replicas`, buf)
+ FfiConverterTypeSandboxTemplateRef.write(value.`sandboxTemplateRef`, buf)
+ FfiConverterOptionalTypeWarmPoolAutoscaling.write(value.`autoscaling`, buf)
+ }
+}
+
+
+
+data class OsGymSandboxWarmPoolStatus (
+ var `replicas`: kotlin.UInt?
+ ,
+ var `readyReplicas`: kotlin.UInt?
+ ,
+ var `selector`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymSandboxWarmPoolStatus: FfiConverterRustBuffer<OsGymSandboxWarmPoolStatus> {
+ override fun read(buf: ByteBuffer): OsGymSandboxWarmPoolStatus {
+ return OsGymSandboxWarmPoolStatus(
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymSandboxWarmPoolStatus) = (
+ FfiConverterOptionalUInt.allocationSize(value.`replicas`) +
+ FfiConverterOptionalUInt.allocationSize(value.`readyReplicas`) +
+ FfiConverterOptionalString.allocationSize(value.`selector`)
+ )
+
+ override fun write(value: OsGymSandboxWarmPoolStatus, buf: ByteBuffer) {
+ FfiConverterOptionalUInt.write(value.`replicas`, buf)
+ FfiConverterOptionalUInt.write(value.`readyReplicas`, buf)
+ FfiConverterOptionalString.write(value.`selector`, buf)
+ }
+}
+
+
+
+data class OsGymWorkspacePoolStatus (
+ var `phase`: kotlin.String?
+ ,
+ var `totalCount`: kotlin.UInt?
+ ,
+ var `availableCount`: kotlin.UInt?
+ ,
+ var `claimedCount`: kotlin.UInt?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOSGymWorkspacePoolStatus: FfiConverterRustBuffer<OsGymWorkspacePoolStatus> {
+ override fun read(buf: ByteBuffer): OsGymWorkspacePoolStatus {
+ return OsGymWorkspacePoolStatus(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OsGymWorkspacePoolStatus) = (
+ FfiConverterOptionalString.allocationSize(value.`phase`) +
+ FfiConverterOptionalUInt.allocationSize(value.`totalCount`) +
+ FfiConverterOptionalUInt.allocationSize(value.`availableCount`) +
+ FfiConverterOptionalUInt.allocationSize(value.`claimedCount`)
+ )
+
+ override fun write(value: OsGymWorkspacePoolStatus, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`phase`, buf)
+ FfiConverterOptionalUInt.write(value.`totalCount`, buf)
+ FfiConverterOptionalUInt.write(value.`availableCount`, buf)
+ FfiConverterOptionalUInt.write(value.`claimedCount`, buf)
+ }
+}
+
+
+
+data class OidcConfig (
+ var `credentialsSecret`: kotlin.String
+ ,
+ var `tokenUrl`: kotlin.String
+ ,
+ var `awsRoleArn`: kotlin.String?
+ ,
+ var `awsRegion`: kotlin.String?
+ ,
+ var `refreshIntervalSeconds`: kotlin.UInt?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeOidcConfig: FfiConverterRustBuffer<OidcConfig> {
+ override fun read(buf: ByteBuffer): OidcConfig {
+ return OidcConfig(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: OidcConfig) = (
+ FfiConverterString.allocationSize(value.`credentialsSecret`) +
+ FfiConverterString.allocationSize(value.`tokenUrl`) +
+ FfiConverterOptionalString.allocationSize(value.`awsRoleArn`) +
+ FfiConverterOptionalString.allocationSize(value.`awsRegion`) +
+ FfiConverterOptionalUInt.allocationSize(value.`refreshIntervalSeconds`)
+ )
+
+ override fun write(value: OidcConfig, buf: ByteBuffer) {
+ FfiConverterString.write(value.`credentialsSecret`, buf)
+ FfiConverterString.write(value.`tokenUrl`, buf)
+ FfiConverterOptionalString.write(value.`awsRoleArn`, buf)
+ FfiConverterOptionalString.write(value.`awsRegion`, buf)
+ FfiConverterOptionalUInt.write(value.`refreshIntervalSeconds`, buf)
+ }
+}
+
+
+
+data class PoolSpec (
+ var `replicas`: kotlin.UInt
+ ,
+ var `template`: PoolTemplate
+ ,
+ var `autoscaling`: WarmPoolAutoscaling?
+ ,
+ var `services`: List<SandboxService>?
+
+): Disposable{
+
+
+
+
+ // The local Rust `Eq` implementation - only `eq` is used.
+ override fun equals(other: Any?): Boolean {
+ if (other !is PoolSpec) return false
+ return FfiConverterBoolean.lift(
+ uniffiRustCall() { _status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq(FfiConverterTypePoolSpec.lower(this),
+
+ FfiConverterTypePoolSpec.lower(`other`),_status)
+}
+ )
+ }
+ // The local Rust `Hash` implementation
+ override fun hashCode(): Int {
+ return FfiConverterULong.lift(
+ uniffiRustCall() { _status ->
+ UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash(FfiConverterTypePoolSpec.lower(this),
+ _status)
+}
+ ).toInt()
+ }
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`replicas`,
+ this.`template`,
+ this.`autoscaling`,
+ this.`services`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypePoolSpec: FfiConverterRustBuffer<PoolSpec> {
+ override fun read(buf: ByteBuffer): PoolSpec {
+ return PoolSpec(
+ FfiConverterUInt.read(buf),
+ FfiConverterTypePoolTemplate.read(buf),
+ FfiConverterOptionalTypeWarmPoolAutoscaling.read(buf),
+ FfiConverterOptionalSequenceTypeSandboxService.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: PoolSpec) = (
+ FfiConverterUInt.allocationSize(value.`replicas`) +
+ FfiConverterTypePoolTemplate.allocationSize(value.`template`) +
+ FfiConverterOptionalTypeWarmPoolAutoscaling.allocationSize(value.`autoscaling`) +
+ FfiConverterOptionalSequenceTypeSandboxService.allocationSize(value.`services`)
+ )
+
+ override fun write(value: PoolSpec, buf: ByteBuffer) {
+ FfiConverterUInt.write(value.`replicas`, buf)
+ FfiConverterTypePoolTemplate.write(value.`template`, buf)
+ FfiConverterOptionalTypeWarmPoolAutoscaling.write(value.`autoscaling`, buf)
+ FfiConverterOptionalSequenceTypeSandboxService.write(value.`services`, buf)
+ }
+}
+
+
+
+data class PoolTemplate (
+ var `runtime`: RuntimeKind?
+ ,
+ var `runtimeClassName`: kotlin.String?
+ ,
+ var `nodeSelector`: Map<kotlin.String, kotlin.String>?
+ ,
+ var `tolerations`: List<PreservedJson>?
+ ,
+ var `command`: List<kotlin.String>?
+ ,
+ var `containerDiskImage`: kotlin.String
+ ,
+ var `imagePullSecret`: kotlin.String?
+ ,
+ var `cpuCores`: kotlin.UInt?
+ ,
+ var `memory`: kotlin.String?
+ ,
+ var `firmware`: Firmware?
+ ,
+ var `probes`: PreservedJson?
+ ,
+ var `oidc`: OidcConfig?
+
+): Disposable{
+
+
+
+
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`runtime`,
+ this.`runtimeClassName`,
+ this.`nodeSelector`,
+ this.`tolerations`,
+ this.`command`,
+ this.`containerDiskImage`,
+ this.`imagePullSecret`,
+ this.`cpuCores`,
+ this.`memory`,
+ this.`firmware`,
+ this.`probes`,
+ this.`oidc`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypePoolTemplate: FfiConverterRustBuffer<PoolTemplate> {
+ override fun read(buf: ByteBuffer): PoolTemplate {
+ return PoolTemplate(
+ FfiConverterOptionalTypeRuntimeKind.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalMapStringString.read(buf),
+ FfiConverterOptionalSequenceTypePreservedJson.read(buf),
+ FfiConverterOptionalSequenceString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalTypeFirmware.read(buf),
+ FfiConverterOptionalTypePreservedJson.read(buf),
+ FfiConverterOptionalTypeOidcConfig.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: PoolTemplate) = (
+ FfiConverterOptionalTypeRuntimeKind.allocationSize(value.`runtime`) +
+ FfiConverterOptionalString.allocationSize(value.`runtimeClassName`) +
+ FfiConverterOptionalMapStringString.allocationSize(value.`nodeSelector`) +
+ FfiConverterOptionalSequenceTypePreservedJson.allocationSize(value.`tolerations`) +
+ FfiConverterOptionalSequenceString.allocationSize(value.`command`) +
+ FfiConverterString.allocationSize(value.`containerDiskImage`) +
+ FfiConverterOptionalString.allocationSize(value.`imagePullSecret`) +
+ FfiConverterOptionalUInt.allocationSize(value.`cpuCores`) +
+ FfiConverterOptionalString.allocationSize(value.`memory`) +
+ FfiConverterOptionalTypeFirmware.allocationSize(value.`firmware`) +
+ FfiConverterOptionalTypePreservedJson.allocationSize(value.`probes`) +
+ FfiConverterOptionalTypeOidcConfig.allocationSize(value.`oidc`)
+ )
+
+ override fun write(value: PoolTemplate, buf: ByteBuffer) {
+ FfiConverterOptionalTypeRuntimeKind.write(value.`runtime`, buf)
+ FfiConverterOptionalString.write(value.`runtimeClassName`, buf)
+ FfiConverterOptionalMapStringString.write(value.`nodeSelector`, buf)
+ FfiConverterOptionalSequenceTypePreservedJson.write(value.`tolerations`, buf)
+ FfiConverterOptionalSequenceString.write(value.`command`, buf)
+ FfiConverterString.write(value.`containerDiskImage`, buf)
+ FfiConverterOptionalString.write(value.`imagePullSecret`, buf)
+ FfiConverterOptionalUInt.write(value.`cpuCores`, buf)
+ FfiConverterOptionalString.write(value.`memory`, buf)
+ FfiConverterOptionalTypeFirmware.write(value.`firmware`, buf)
+ FfiConverterOptionalTypePreservedJson.write(value.`probes`, buf)
+ FfiConverterOptionalTypeOidcConfig.write(value.`oidc`, buf)
+ }
+}
+
+
+
+data class SandboxService (
+ var `name`: kotlin.String
+ ,
+ var `targetPort`: kotlin.UShort
+ ,
+ var `protocol`: ServiceProtocol?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSandboxService: FfiConverterRustBuffer<SandboxService> {
+ override fun read(buf: ByteBuffer): SandboxService {
+ return SandboxService(
+ FfiConverterString.read(buf),
+ FfiConverterUShort.read(buf),
+ FfiConverterOptionalTypeServiceProtocol.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SandboxService) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterUShort.allocationSize(value.`targetPort`) +
+ FfiConverterOptionalTypeServiceProtocol.allocationSize(value.`protocol`)
+ )
+
+ override fun write(value: SandboxService, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterUShort.write(value.`targetPort`, buf)
+ FfiConverterOptionalTypeServiceProtocol.write(value.`protocol`, buf)
+ }
+}
+
+
+
+data class SandboxTemplateRef (
+ var `name`: kotlin.String
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSandboxTemplateRef: FfiConverterRustBuffer<SandboxTemplateRef> {
+ override fun read(buf: ByteBuffer): SandboxTemplateRef {
+ return SandboxTemplateRef(
+ FfiConverterString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SandboxTemplateRef) = (
+ FfiConverterString.allocationSize(value.`name`)
+ )
+
+ override fun write(value: SandboxTemplateRef, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ }
+}
+
+
+
+data class VmTemplate (
+ var `containerDiskImage`: kotlin.String
+ ,
+ var `command`: List<kotlin.String>?
+ ,
+ var `runtime`: RuntimeKind?
+ ,
+ var `runtimeClassName`: kotlin.String?
+ ,
+ var `nodeSelector`: Map<kotlin.String, kotlin.String>?
+ ,
+ var `tolerations`: List<PreservedJson>?
+ ,
+ var `imagePullPolicy`: ImagePullPolicy?
+ ,
+ var `imagePullSecret`: kotlin.String?
+ ,
+ var `cpuCores`: kotlin.UInt?
+ ,
+ var `memory`: kotlin.String?
+ ,
+ var `firmware`: Firmware?
+ ,
+ var `probes`: PreservedJson?
+ ,
+ var `services`: List<SandboxService>?
+ ,
+ var `oidc`: OidcConfig?
+
+): Disposable{
+
+
+
+
+
+ @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here
+ override fun destroy() {
+
+ Disposable.destroy(
+ this.`containerDiskImage`,
+ this.`command`,
+ this.`runtime`,
+ this.`runtimeClassName`,
+ this.`nodeSelector`,
+ this.`tolerations`,
+ this.`imagePullPolicy`,
+ this.`imagePullSecret`,
+ this.`cpuCores`,
+ this.`memory`,
+ this.`firmware`,
+ this.`probes`,
+ this.`services`,
+ this.`oidc`
+ )
+ }
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeVmTemplate: FfiConverterRustBuffer<VmTemplate> {
+ override fun read(buf: ByteBuffer): VmTemplate {
+ return VmTemplate(
+ FfiConverterString.read(buf),
+ FfiConverterOptionalSequenceString.read(buf),
+ FfiConverterOptionalTypeRuntimeKind.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalMapStringString.read(buf),
+ FfiConverterOptionalSequenceTypePreservedJson.read(buf),
+ FfiConverterOptionalTypeImagePullPolicy.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalTypeFirmware.read(buf),
+ FfiConverterOptionalTypePreservedJson.read(buf),
+ FfiConverterOptionalSequenceTypeSandboxService.read(buf),
+ FfiConverterOptionalTypeOidcConfig.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: VmTemplate) = (
+ FfiConverterString.allocationSize(value.`containerDiskImage`) +
+ FfiConverterOptionalSequenceString.allocationSize(value.`command`) +
+ FfiConverterOptionalTypeRuntimeKind.allocationSize(value.`runtime`) +
+ FfiConverterOptionalString.allocationSize(value.`runtimeClassName`) +
+ FfiConverterOptionalMapStringString.allocationSize(value.`nodeSelector`) +
+ FfiConverterOptionalSequenceTypePreservedJson.allocationSize(value.`tolerations`) +
+ FfiConverterOptionalTypeImagePullPolicy.allocationSize(value.`imagePullPolicy`) +
+ FfiConverterOptionalString.allocationSize(value.`imagePullSecret`) +
+ FfiConverterOptionalUInt.allocationSize(value.`cpuCores`) +
+ FfiConverterOptionalString.allocationSize(value.`memory`) +
+ FfiConverterOptionalTypeFirmware.allocationSize(value.`firmware`) +
+ FfiConverterOptionalTypePreservedJson.allocationSize(value.`probes`) +
+ FfiConverterOptionalSequenceTypeSandboxService.allocationSize(value.`services`) +
+ FfiConverterOptionalTypeOidcConfig.allocationSize(value.`oidc`)
+ )
+
+ override fun write(value: VmTemplate, buf: ByteBuffer) {
+ FfiConverterString.write(value.`containerDiskImage`, buf)
+ FfiConverterOptionalSequenceString.write(value.`command`, buf)
+ FfiConverterOptionalTypeRuntimeKind.write(value.`runtime`, buf)
+ FfiConverterOptionalString.write(value.`runtimeClassName`, buf)
+ FfiConverterOptionalMapStringString.write(value.`nodeSelector`, buf)
+ FfiConverterOptionalSequenceTypePreservedJson.write(value.`tolerations`, buf)
+ FfiConverterOptionalTypeImagePullPolicy.write(value.`imagePullPolicy`, buf)
+ FfiConverterOptionalString.write(value.`imagePullSecret`, buf)
+ FfiConverterOptionalUInt.write(value.`cpuCores`, buf)
+ FfiConverterOptionalString.write(value.`memory`, buf)
+ FfiConverterOptionalTypeFirmware.write(value.`firmware`, buf)
+ FfiConverterOptionalTypePreservedJson.write(value.`probes`, buf)
+ FfiConverterOptionalSequenceTypeSandboxService.write(value.`services`, buf)
+ FfiConverterOptionalTypeOidcConfig.write(value.`oidc`, buf)
+ }
+}
+
+
+
+data class WarmPoolAutoscaling (
+ var `minPoolSize`: kotlin.UInt?
+ ,
+ var `initialPoolSize`: kotlin.UInt?
+ ,
+ var `maxPoolSize`: kotlin.UInt?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeWarmPoolAutoscaling: FfiConverterRustBuffer<WarmPoolAutoscaling> {
+ override fun read(buf: ByteBuffer): WarmPoolAutoscaling {
+ return WarmPoolAutoscaling(
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ FfiConverterOptionalUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: WarmPoolAutoscaling) = (
+ FfiConverterOptionalUInt.allocationSize(value.`minPoolSize`) +
+ FfiConverterOptionalUInt.allocationSize(value.`initialPoolSize`) +
+ FfiConverterOptionalUInt.allocationSize(value.`maxPoolSize`)
+ )
+
+ override fun write(value: WarmPoolAutoscaling, buf: ByteBuffer) {
+ FfiConverterOptionalUInt.write(value.`minPoolSize`, buf)
+ FfiConverterOptionalUInt.write(value.`initialPoolSize`, buf)
+ FfiConverterOptionalUInt.write(value.`maxPoolSize`, buf)
+ }
+}
+
+
+
+
+enum class Firmware {
+
+ BIOS,
+ EFI;
+
+
+
+
+ companion object
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeFirmware: FfiConverterRustBuffer<Firmware> {
+ override fun read(buf: ByteBuffer) = try {
+ Firmware.values()[buf.getInt() - 1]
+ } catch (e: IndexOutOfBoundsException) {
+ throw RuntimeException("invalid enum value, something is very wrong!!", e)
+ }
+
+ override fun allocationSize(value: Firmware) = 4UL
+
+ override fun write(value: Firmware, buf: ByteBuffer) {
+ buf.putInt(value.ordinal + 1)
+ }
+}
+
+
+
+
+
+
+enum class ImagePullPolicy {
+
+ ALWAYS,
+ IF_NOT_PRESENT,
+ NEVER;
+
+
+
+
+ companion object
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeImagePullPolicy: FfiConverterRustBuffer<ImagePullPolicy> {
+ override fun read(buf: ByteBuffer) = try {
+ ImagePullPolicy.values()[buf.getInt() - 1]
+ } catch (e: IndexOutOfBoundsException) {
+ throw RuntimeException("invalid enum value, something is very wrong!!", e)
+ }
+
+ override fun allocationSize(value: ImagePullPolicy) = 4UL
+
+ override fun write(value: ImagePullPolicy, buf: ByteBuffer) {
+ buf.putInt(value.ordinal + 1)
+ }
+}
+
+
+
+
+
+
+
+sealed class JsonValueException: kotlin.Exception() {
+
+ class Invalid(
+
+ val `reason`: kotlin.String
+ ) : JsonValueException() {
+ override val message
+ get() = "reason=${ `reason` }"
+ }
+
+
+
+
+
+ companion object ErrorHandler : UniffiRustCallStatusErrorHandler<JsonValueException> {
+ override fun lift(error_buf: RustBuffer.ByValue): JsonValueException = FfiConverterTypeJsonValueError.lift(error_buf)
+ }
+
+
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeJsonValueError : FfiConverterRustBuffer<JsonValueException> {
+ override fun read(buf: ByteBuffer): JsonValueException {
+
+
+ return when(buf.getInt()) {
+ 1 -> JsonValueException.Invalid(
+ FfiConverterString.read(buf),
+ )
+ else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
+ }
+ }
+
+ override fun allocationSize(value: JsonValueException): ULong {
+ return when(value) {
+ is JsonValueException.Invalid -> (
+ // Add the size for the Int that specifies the variant plus the size needed for all fields
+ 4UL
+ + FfiConverterString.allocationSize(value.`reason`)
+ )
+ }
+ }
+
+ override fun write(value: JsonValueException, buf: ByteBuffer) {
+ when(value) {
+ is JsonValueException.Invalid -> {
+ buf.putInt(1)
+ FfiConverterString.write(value.`reason`, buf)
+ Unit
+ }
+ }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
+ }
+
+}
+
+
+
+
+enum class RuntimeKind {
+
+ KUBEVIRT,
+ MACOS,
+ GVISOR;
+
+
+
+
+ companion object
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeRuntimeKind: FfiConverterRustBuffer<RuntimeKind> {
+ override fun read(buf: ByteBuffer) = try {
+ RuntimeKind.values()[buf.getInt() - 1]
+ } catch (e: IndexOutOfBoundsException) {
+ throw RuntimeException("invalid enum value, something is very wrong!!", e)
+ }
+
+ override fun allocationSize(value: RuntimeKind) = 4UL
+
+ override fun write(value: RuntimeKind, buf: ByteBuffer) {
+ buf.putInt(value.ordinal + 1)
+ }
+}
+
+
+
+
+
+
+enum class ServiceProtocol {
+
+ TCP,
+ UDP;
+
+
+
+
+ companion object
+}
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeServiceProtocol: FfiConverterRustBuffer<ServiceProtocol> {
+ override fun read(buf: ByteBuffer) = try {
+ ServiceProtocol.values()[buf.getInt() - 1]
+ } catch (e: IndexOutOfBoundsException) {
+ throw RuntimeException("invalid enum value, something is very wrong!!", e)
+ }
+
+ override fun allocationSize(value: ServiceProtocol) = 4UL
+
+ override fun write(value: ServiceProtocol, buf: ByteBuffer) {
+ buf.putInt(value.ordinal + 1)
+ }
+}
+
+
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalUInt: FfiConverterRustBuffer<kotlin.UInt?> {
+ override fun read(buf: ByteBuffer): kotlin.UInt? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterUInt.read(buf)
+ }
+
+ override fun allocationSize(value: kotlin.UInt?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterUInt.allocationSize(value)
+ }
+ }
+
+ override fun write(value: kotlin.UInt?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterUInt.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalBoolean: FfiConverterRustBuffer<kotlin.Boolean?> {
+ override fun read(buf: ByteBuffer): kotlin.Boolean? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterBoolean.read(buf)
+ }
+
+ override fun allocationSize(value: kotlin.Boolean?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterBoolean.allocationSize(value)
+ }
+ }
+
+ override fun write(value: kotlin.Boolean?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterBoolean.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalString: FfiConverterRustBuffer<kotlin.String?> {
+ override fun read(buf: ByteBuffer): kotlin.String? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterString.read(buf)
+ }
+
+ override fun allocationSize(value: kotlin.String?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterString.allocationSize(value)
+ }
+ }
+
+ override fun write(value: kotlin.String?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterString.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypePreservedJson: FfiConverterRustBuffer<PreservedJson?> {
+ override fun read(buf: ByteBuffer): PreservedJson? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypePreservedJson.read(buf)
+ }
+
+ override fun allocationSize(value: PreservedJson?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypePreservedJson.allocationSize(value)
+ }
+ }
+
+ override fun write(value: PreservedJson?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypePreservedJson.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeClaimLifecycle: FfiConverterRustBuffer<ClaimLifecycle?> {
+ override fun read(buf: ByteBuffer): ClaimLifecycle? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeClaimLifecycle.read(buf)
+ }
+
+ override fun allocationSize(value: ClaimLifecycle?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeClaimLifecycle.allocationSize(value)
+ }
+ }
+
+ override fun write(value: ClaimLifecycle?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeClaimLifecycle.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeOSGymSandboxClaimSandbox: FfiConverterRustBuffer<OsGymSandboxClaimSandbox?> {
+ override fun read(buf: ByteBuffer): OsGymSandboxClaimSandbox? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeOSGymSandboxClaimSandbox.read(buf)
+ }
+
+ override fun allocationSize(value: OsGymSandboxClaimSandbox?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeOSGymSandboxClaimSandbox.allocationSize(value)
+ }
+ }
+
+ override fun write(value: OsGymSandboxClaimSandbox?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeOSGymSandboxClaimSandbox.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeOidcConfig: FfiConverterRustBuffer<OidcConfig?> {
+ override fun read(buf: ByteBuffer): OidcConfig? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeOidcConfig.read(buf)
+ }
+
+ override fun allocationSize(value: OidcConfig?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeOidcConfig.allocationSize(value)
+ }
+ }
+
+ override fun write(value: OidcConfig?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeOidcConfig.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeWarmPoolAutoscaling: FfiConverterRustBuffer<WarmPoolAutoscaling?> {
+ override fun read(buf: ByteBuffer): WarmPoolAutoscaling? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeWarmPoolAutoscaling.read(buf)
+ }
+
+ override fun allocationSize(value: WarmPoolAutoscaling?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeWarmPoolAutoscaling.allocationSize(value)
+ }
+ }
+
+ override fun write(value: WarmPoolAutoscaling?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeWarmPoolAutoscaling.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeFirmware: FfiConverterRustBuffer<Firmware?> {
+ override fun read(buf: ByteBuffer): Firmware? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeFirmware.read(buf)
+ }
+
+ override fun allocationSize(value: Firmware?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeFirmware.allocationSize(value)
+ }
+ }
+
+ override fun write(value: Firmware?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeFirmware.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeImagePullPolicy: FfiConverterRustBuffer<ImagePullPolicy?> {
+ override fun read(buf: ByteBuffer): ImagePullPolicy? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeImagePullPolicy.read(buf)
+ }
+
+ override fun allocationSize(value: ImagePullPolicy?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeImagePullPolicy.allocationSize(value)
+ }
+ }
+
+ override fun write(value: ImagePullPolicy?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeImagePullPolicy.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeRuntimeKind: FfiConverterRustBuffer<RuntimeKind?> {
+ override fun read(buf: ByteBuffer): RuntimeKind? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeRuntimeKind.read(buf)
+ }
+
+ override fun allocationSize(value: RuntimeKind?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeRuntimeKind.allocationSize(value)
+ }
+ }
+
+ override fun write(value: RuntimeKind?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeRuntimeKind.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeServiceProtocol: FfiConverterRustBuffer<ServiceProtocol?> {
+ override fun read(buf: ByteBuffer): ServiceProtocol? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeServiceProtocol.read(buf)
+ }
+
+ override fun allocationSize(value: ServiceProtocol?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeServiceProtocol.allocationSize(value)
+ }
+ }
+
+ override fun write(value: ServiceProtocol?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeServiceProtocol.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalSequenceString: FfiConverterRustBuffer<List<kotlin.String>?> {
+ override fun read(buf: ByteBuffer): List<kotlin.String>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterSequenceString.read(buf)
+ }
+
+ override fun allocationSize(value: List<kotlin.String>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterSequenceString.allocationSize(value)
+ }
+ }
+
+ override fun write(value: List<kotlin.String>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterSequenceString.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalSequenceTypePreservedJson: FfiConverterRustBuffer<List<PreservedJson>?> {
+ override fun read(buf: ByteBuffer): List<PreservedJson>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterSequenceTypePreservedJson.read(buf)
+ }
+
+ override fun allocationSize(value: List<PreservedJson>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterSequenceTypePreservedJson.allocationSize(value)
+ }
+ }
+
+ override fun write(value: List<PreservedJson>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterSequenceTypePreservedJson.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer<List<OsGymSandboxClaimCondition>?> {
+ override fun read(buf: ByteBuffer): List<OsGymSandboxClaimCondition>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterSequenceTypeOSGymSandboxClaimCondition.read(buf)
+ }
+
+ override fun allocationSize(value: List<OsGymSandboxClaimCondition>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterSequenceTypeOSGymSandboxClaimCondition.allocationSize(value)
+ }
+ }
+
+ override fun write(value: List<OsGymSandboxClaimCondition>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterSequenceTypeOSGymSandboxClaimCondition.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalSequenceTypeSandboxService: FfiConverterRustBuffer<List<SandboxService>?> {
+ override fun read(buf: ByteBuffer): List<SandboxService>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterSequenceTypeSandboxService.read(buf)
+ }
+
+ override fun allocationSize(value: List<SandboxService>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterSequenceTypeSandboxService.allocationSize(value)
+ }
+ }
+
+ override fun write(value: List<SandboxService>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterSequenceTypeSandboxService.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>?> {
+ override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String>? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterMapStringString.read(buf)
+ }
+
+ override fun allocationSize(value: Map<kotlin.String, kotlin.String>?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterMapStringString.allocationSize(value)
+ }
+ }
+
+ override fun write(value: Map<kotlin.String, kotlin.String>?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterMapStringString.write(value, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceString: FfiConverterRustBuffer<List<kotlin.String>> {
+ override fun read(buf: ByteBuffer): List<kotlin.String> {
+ val len = buf.getInt()
+ return List<kotlin.String>(len) {
+ FfiConverterString.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<kotlin.String>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterString.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<kotlin.String>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterString.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypePreservedJson: FfiConverterRustBuffer<List<PreservedJson>> {
+ override fun read(buf: ByteBuffer): List<PreservedJson> {
+ val len = buf.getInt()
+ return List<PreservedJson>(len) {
+ FfiConverterTypePreservedJson.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<PreservedJson>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypePreservedJson.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<PreservedJson>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypePreservedJson.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer<List<OsGymSandboxClaimCondition>> {
+ override fun read(buf: ByteBuffer): List<OsGymSandboxClaimCondition> {
+ val len = buf.getInt()
+ return List<OsGymSandboxClaimCondition>(len) {
+ FfiConverterTypeOSGymSandboxClaimCondition.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<OsGymSandboxClaimCondition>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeOSGymSandboxClaimCondition.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<OsGymSandboxClaimCondition>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeOSGymSandboxClaimCondition.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeSandboxService: FfiConverterRustBuffer<List<SandboxService>> {
+ override fun read(buf: ByteBuffer): List<SandboxService> {
+ val len = buf.getInt()
+ return List<SandboxService>(len) {
+ FfiConverterTypeSandboxService.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<SandboxService>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeSandboxService.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<SandboxService>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeSandboxService.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>> {
+ override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String> {
+ val len = buf.getInt()
+ return buildMap<kotlin.String, kotlin.String>(len) {
+ repeat(len) {
+ val k = FfiConverterString.read(buf)
+ val v = FfiConverterString.read(buf)
+ this[k] = v
+ }
+ }
+ }
+
+ override fun allocationSize(value: Map<kotlin.String, kotlin.String>): ULong {
+ val spaceForMapSize = 4UL
+ val spaceForChildren = value.map { (k, v) ->
+ FfiConverterString.allocationSize(k) +
+ FfiConverterString.allocationSize(v)
+ }.sum()
+ return spaceForMapSize + spaceForChildren
+ }
+
+ override fun write(value: Map<kotlin.String, kotlin.String>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ // The parens on `(k, v)` here ensure we're calling the right method,
+ // which is important for compatibility with older android devices.
+ // Ref https://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/
+ value.forEach { (k, v) ->
+ FfiConverterString.write(k, buf)
+ FfiConverterString.write(v, buf)
+ }
+ }
+}
diff --git a/libs/fleet/sdk-bindings/kotlin/build.gradle.kts b/libs/fleet/sdk-bindings/kotlin/build.gradle.kts
new file mode 100644
index 0000000000..c36f8a98cd
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/build.gradle.kts
@@ -0,0 +1,36 @@
+plugins { kotlin("jvm") version "2.1.0" }
+dependencies {
+ implementation("net.java.dev.jna:jna:5.16.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
+}
+kotlin { jvmToolchain(21) }
+sourceSets.main { kotlin.srcDirs("ai") }
+sourceSets.test { kotlin.srcDirs("tests") }
+val example by sourceSets.creating {
+ kotlin.srcDir("../examples/kotlin")
+ compileClasspath += sourceSets.main.get().output
+ runtimeClasspath += sourceSets.main.get().output
+}
+configurations[example.implementationConfigurationName].extendsFrom(
+ configurations[sourceSets.main.get().implementationConfigurationName],
+)
+configurations[example.runtimeOnlyConfigurationName].extendsFrom(
+ configurations[sourceSets.main.get().runtimeOnlyConfigurationName],
+)
+tasks.register<JavaExec>("contract") {
+ classpath = sourceSets.test.get().runtimeClasspath
+ mainClass.set("TestAsyncClientKt")
+ jvmArgs("-Djna.library.path=" + System.getenv("CYCLOPS_SDK_NATIVE_DIR"))
+}
+tasks.register<JavaExec>("example") {
+ dependsOn(example.classesTaskName)
+ classpath = example.runtimeClasspath
+ mainClass.set("AppControlledKt")
+ jvmArgs("-Djna.library.path=" + System.getenv("CYCLOPS_SDK_NATIVE_DIR"))
+}
+tasks.register<JavaExec>("liveExample") {
+ dependsOn(example.classesTaskName)
+ classpath = example.runtimeClasspath
+ mainClass.set("LiveAppControlledKt")
+ jvmArgs("-Djna.library.path=" + System.getenv("CYCLOPS_SDK_NATIVE_DIR"))
+}
diff --git a/libs/fleet/sdk-bindings/kotlin/gradle.properties b/libs/fleet/sdk-bindings/kotlin/gradle.properties
new file mode 100644
index 0000000000..985d4b57da
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/gradle.properties
@@ -0,0 +1,2 @@
+org.gradle.configuration-cache=true
+org.gradle.dependency.verification=lenient
diff --git a/libs/fleet/sdk-bindings/kotlin/settings.gradle.kts b/libs/fleet/sdk-bindings/kotlin/settings.gradle.kts
new file mode 100644
index 0000000000..57822ed5d7
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/settings.gradle.kts
@@ -0,0 +1,3 @@
+pluginManagement { repositories { gradlePluginPortal(); mavenCentral() } }
+dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { mavenCentral() } }
+rootProject.name = "cyclops-sdk-kotlin-contract"
diff --git a/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
new file mode 100644
index 0000000000..f01605537b
--- /dev/null
+++ b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
@@ -0,0 +1,147 @@
+import ai.cua.cyclops.sdk.*
+import ai.cua.cyclops.sdk.schema.*
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.runBlocking
+
+private data class Expected(
+ val method: String,
+ val url: String,
+ val headers: List<Pair<String, String>>,
+ val body: ByteArray?,
+ val status: UShort,
+ val response: ByteArray,
+)
+
+private val jsonHeaders = listOf(
+ "accept" to "application/json",
+ "content-type" to "application/json",
+ "authorization" to "Bearer offline-token",
+)
+
+private fun textExpected(
+ method: String,
+ url: String,
+ headers: List<Pair<String, String>>,
+ body: ByteArray?,
+ status: UShort,
+ response: String,
+) = Expected(method, url, headers, body, status, response.encodeToByteArray())
+
+private fun tokenExpected() = textExpected(
+ "POST",
+ "https://keycloak.invalid/token",
+ listOf("accept" to "application/json", "content-type" to "application/x-www-form-urlencoded"),
+ "grant_type=client_credentials&client_id=client-id&client_secret=client-secret".encodeToByteArray(),
+ 200u,
+ "{\"access_token\":\"offline-token\",\"expires_in\":3600}",
+)
+
+private fun serviceExpected(body: ByteArray?, response: ByteArray) = Expected(
+ "POST",
+ "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp",
+ listOf("authorization" to "Bearer offline-token"),
+ body,
+ 202u,
+ response,
+)
+
+private fun lifecycleQueue() = listOf(
+ tokenExpected(),
+ textExpected("POST", "https://cyclops.invalid/api/namespaces", jsonHeaders, "{\"name\":\"default\"}".encodeToByteArray(), 201u, "{}"),
+ textExpected("POST", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools", jsonHeaders, "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}".encodeToByteArray(), 201u, "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}"),
+ textExpected("POST", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims", jsonHeaders, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"claim-1\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":null}".encodeToByteArray(), 201u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
+ textExpected("GET", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", jsonHeaders, null, 200u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
+ textExpected("GET", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", jsonHeaders, null, 200u, "{\"apiVersion\":\"cua.ai/v1\",\"kind\":\"OSGymWorkspacePool\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"replicas\":1,\"template\":{\"containerDiskImage\":\"registry.example/desktop:offline\"},\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]},\"status\":null}"),
+ serviceExpected("{\"offline\":true}".encodeToByteArray(), "offline service accepted".encodeToByteArray()),
+ textExpected("DELETE", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", jsonHeaders, null, 204u, ""),
+ textExpected("DELETE", "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", jsonHeaders, null, 204u, ""),
+ textExpected("DELETE", "https://cyclops.invalid/api/namespaces/default", jsonHeaders, null, 204u, ""),
+)
+
+private class ScriptedHttpClient(expected: List<Expected>) : HttpClient {
+ private val lock = Any()
+ private val expected = ArrayDeque(expected)
+
+ override suspend fun execute(request: HttpRequest): HttpResponse = synchronized(lock) {
+ val item = expected.removeFirstOrNull() ?: error("unexpected request")
+ check(request.method == item.method && request.url == item.url)
+ check(request.headers.map { it.name to it.value } == item.headers)
+ check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ HttpResponse(item.status, emptyList(), item.response)
+ }
+
+ fun assertExhausted() = synchronized(lock) { check(expected.isEmpty()) }
+}
+
+private class FailingHttpClient : HttpClient {
+ override suspend fun execute(request: HttpRequest): HttpResponse {
+ throw HttpException.Transport(reason = "scripted callback failure")
+ }
+}
+
+private fun configuration() = CyclopsConfiguration(
+ "https://cyclops.invalid",
+ "https://keycloak.invalid/token",
+ CyclopsCredentials("client-id", "client-secret"),
+ 1uL,
+ 1u,
+ 1uL,
+ 2u,
+)
+
+private fun serviceRequest(body: ByteArray?) = HttpRequest("POST", "https://ignored.invalid/mcp", emptyList(), body)
+private val sandbox = Sandbox("default", "default", "offline-sandbox", listOf("mcp"))
+
+fun main() = runBlocking {
+ val vmTemplate = VmTemplate("registry.example/desktop:offline", null, null, null, null, null, null, null, null, null, null, null, null, null)
+ val spec = PoolSpec(1u, PoolTemplate(null, null, null, null, null, vmTemplate.containerDiskImage, null, null, null, null, null, null), null, listOf(SandboxService("mcp", 8080u, null)))
+ val transport = ScriptedHttpClient(lifecycleQueue())
+ val client = CyclopsClient.connect(configuration(), transport)
+ val pool = client.createPool(CreatePoolRequest("default", spec))
+ val claim = client.createClaim(CreateClaimRequest(pool, ClaimSpec(SandboxTemplateRef(pool.metadata.name), null, null, null)))
+ val createdSandbox = client.waitClaim(claim)
+ val service = client.serviceRequest(createdSandbox, "mcp", "/mcp", serviceRequest("{\"offline\":true}".encodeToByteArray()))
+ client.deleteClaim(claim)
+ client.deletePool(pool)
+ check(pool.metadata.name == "default" && claim.metadata.name == "default" && createdSandbox.name == "offline-sandbox")
+ check(service.status == 202.toUShort())
+ transport.assertExhausted()
+
+ val failingClient = CyclopsClient.connect(configuration(), FailingHttpClient())
+ try {
+ failingClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest(null))
+ error("expected generated SdkException.Transport")
+ } catch (error: SdkException.Transport) {
+ check(error.reason == "scripted callback failure")
+ }
+
+ val bodyTransport = ScriptedHttpClient(listOf(
+ tokenExpected(),
+ serviceExpected(null, byteArrayOf()),
+ serviceExpected(ByteArray(0), byteArrayOf(0, 0x7f, 0xff.toByte())),
+ ))
+ val bodyClient = CyclopsClient.connect(configuration(), bodyTransport)
+ check(bodyClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest(null)).body.isEmpty())
+ check(bodyClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest(ByteArray(0))).body.contentEquals(byteArrayOf(0, 0x7f, 0xff.toByte())))
+ bodyTransport.assertExhausted()
+
+ val concurrentTransport = ScriptedHttpClient(listOf(
+ tokenExpected(),
+ serviceExpected(null, "warm".encodeToByteArray()),
+ serviceExpected("parallel".encodeToByteArray(), "first".encodeToByteArray()),
+ serviceExpected("parallel".encodeToByteArray(), "second".encodeToByteArray()),
+ ))
+ val concurrentClient = CyclopsClient.connect(configuration(), concurrentTransport)
+ concurrentClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest(null))
+ val responses = coroutineScope {
+ listOf(
+ async { concurrentClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest("parallel".encodeToByteArray())) },
+ async { concurrentClient.serviceRequest(sandbox, "mcp", "/mcp", serviceRequest("parallel".encodeToByteArray())) },
+ ).awaitAll()
+ }
+ check(responses.map { it.body.decodeToString() }.toSet() == setOf("first", "second"))
+ concurrentTransport.assertExhausted()
+ println("pool=${pool.metadata.name} claim=${claim.metadata.name} sandbox=${createdSandbox.name} service_status=${service.status}")
+}
diff --git a/libs/fleet/sdk-bindings/python/.cyclops-sdk-generated-files b/libs/fleet/sdk-bindings/python/.cyclops-sdk-generated-files
new file mode 100644
index 0000000000..edbe9c6995
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/.cyclops-sdk-generated-files
@@ -0,0 +1,4 @@
+d cyclops_sdk
+f cyclops_sdk/__init__.py
+f cyclops_sdk/_schema.py
+f cyclops_sdk/_sdk.py
diff --git a/libs/fleet/sdk-bindings/python/README.md b/libs/fleet/sdk-bindings/python/README.md
new file mode 100644
index 0000000000..f1ed9c0f30
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/README.md
@@ -0,0 +1,12 @@
+# Python Contract Binding
+
+Run from any working directory after setting `REPO_ROOT` to the absolute path of
+this clone (for example, `REPO_ROOT=/path/to/clone`):
+
+```bash
+REPO_ROOT=/path/to/clone
+$REPO_ROOT/cyclops-cs/scripts/run-python-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/python/tests/test_async_client.py" -v
+$REPO_ROOT/cyclops-cs/scripts/run-python-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/python/app_controlled.py"
+```
+
+The launcher builds the cdylib once in `cyclops-cs/target/sdk-bindings-native`, stages a temporary Python package, and deletes it on exit. It never copies a native library into generated source.
diff --git a/libs/fleet/sdk-bindings/python/contract_fixture.py b/libs/fleet/sdk-bindings/python/contract_fixture.py
new file mode 100644
index 0000000000..474a376a01
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/contract_fixture.py
@@ -0,0 +1,102 @@
+import asyncio
+import json
+from dataclasses import dataclass
+
+from cyclops_sdk import (ClaimSpec, CreateClaimRequest, CreatePoolRequest, CyclopsClient,
+ CyclopsConfiguration, CyclopsCredentials, HttpClient, HttpRequest, HttpResponse, PoolSpec,
+ PoolTemplate, Sandbox, SandboxService, SandboxTemplateRef, VmTemplate)
+
+BASE = 'https://cyclops.invalid'
+TOKEN = 'https://keycloak.invalid/realms/offline/protocol/openid-connect/token'
+JSON_HEADERS = [('accept', 'application/json'), ('content-type', 'application/json'), ('authorization', 'Bearer offline-token')]
+SERVICE_HEADERS = [('authorization', 'Bearer offline-token')]
+SERVICE_URL = f'{BASE}/api/svc/default/offline-sandbox-mcp/mcp'
+
+@dataclass(frozen=True)
+class Expected:
+ method: str
+ url: str
+ headers: list
+ body: bytes | None
+ status: int
+ response: object
+
+class ScriptedHttpClient(HttpClient):
+ def __init__(self, expected):
+ self.expected = list(expected)
+ self.requests = []
+ self.lock = asyncio.Lock()
+
+ async def execute(self, request):
+ async with self.lock:
+ assert self.expected, f'unexpected request: {request.method} {request.url}'
+ item = self.expected.pop(0)
+ actual_headers = [(header.name, header.value) for header in request.headers]
+ assert (request.method, request.url, actual_headers, request.body) == (item.method, item.url, item.headers, item.body)
+ self.requests.append(request)
+ body = item.response if isinstance(item.response, bytes) else json.dumps(item.response, separators=(',', ':')).encode()
+ return HttpResponse(status=item.status, headers=[], body=body)
+
+ def assert_exhausted(self):
+ assert not self.expected, self.expected
+
+def token_expected():
+ return Expected('POST', TOKEN, [('accept', 'application/json'), ('content-type', 'application/x-www-form-urlencoded')], b'grant_type=client_credentials&client_id=client-id&client_secret=client-secret', 200, {'access_token': 'offline-token', 'expires_in': 3600})
+
+def service_expected(body, response):
+ return Expected('POST', SERVICE_URL, SERVICE_HEADERS, body, 202, response)
+
+def expected_service_calls(*calls):
+ return [token_expected(), *(service_expected(body, response) for body, response in calls)]
+
+def offline_sandbox():
+ return Sandbox(namespace='default', claim='default', name='offline-sandbox', services=['mcp'])
+
+def service_request(body):
+ return HttpRequest(method='POST', url='https://ignored.invalid/mcp', headers=[], body=body)
+
+def pool_spec():
+ return PoolSpec(replicas=1, template=PoolTemplate(runtime=None, runtime_class_name=None, node_selector=None, tolerations=None, command=None, container_disk_image='registry.example/desktop:offline', image_pull_secret=None, cpu_cores=None, memory=None, firmware=None, probes=None, oidc=None), autoscaling=None, services=[SandboxService(name='mcp', target_port=8080, protocol=None)])
+
+def pool_response():
+ return {'apiVersion': 'cua.ai/v1', 'kind': 'OSGymWorkspacePool', 'metadata': {'namespace': 'default', 'name': 'default', 'labels': None}, 'spec': {'replicas': 1, 'template': {'containerDiskImage': 'registry.example/desktop:offline'}, 'services': [{'name': 'mcp', 'targetPort': 8080}]}, 'status': None}
+
+def claim_response(bound=False):
+ result = {'apiVersion': 'osgym.cua.ai/v1alpha1', 'kind': 'OSGymSandboxClaim', 'metadata': {'namespace': 'default', 'name': 'default', 'labels': None}, 'spec': {'sandboxTemplateRef': {'name': 'default'}}, 'status': None}
+ if bound:
+ result['status'] = {'phase': 'Bound', 'sandbox': {'name': 'offline-sandbox'}}
+ return result
+
+def expected_lifecycle():
+ pool_body = json.dumps(pool_response(), separators=(',', ':')).encode()
+ claim_body = b'{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"claim-1","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":null}'
+ claim_url = f'{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default'
+ pool_url = f'{BASE}/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default'
+ return [
+ token_expected(),
+ Expected('POST', f'{BASE}/api/namespaces', JSON_HEADERS, b'{"name":"default"}', 201, {}),
+ Expected('POST', pool_url.removesuffix('/default'), JSON_HEADERS, pool_body, 201, pool_response()),
+ Expected('POST', claim_url.removesuffix('/default'), JSON_HEADERS, claim_body, 201, claim_response()),
+ Expected('GET', claim_url, JSON_HEADERS, None, 200, claim_response(True)),
+ Expected('GET', pool_url, JSON_HEADERS, None, 200, pool_response()),
+ service_expected(b'{"offline":true}', b'offline service accepted'),
+ Expected('DELETE', claim_url, JSON_HEADERS, None, 204, b''),
+ Expected('DELETE', pool_url, JSON_HEADERS, None, 204, b''),
+ Expected('DELETE', f'{BASE}/api/namespaces/default', JSON_HEADERS, None, 204, b''),
+ ]
+
+def client(transport):
+ return CyclopsClient.connect(CyclopsConfiguration(base_url=BASE, token_url=TOKEN, credentials=CyclopsCredentials('client-id', 'client-secret'), pool_poll_interval_ms=1, pool_poll_limit=1, claim_poll_interval_ms=1, claim_poll_limit=2), transport)
+
+async def run_lifecycle(transport):
+ vm = VmTemplate(container_disk_image='registry.example/desktop:offline', command=None, runtime=None, runtime_class_name=None, node_selector=None, tolerations=None, image_pull_policy=None, image_pull_secret=None, cpu_cores=None, memory=None, firmware=None, probes=None, services=None, oidc=None)
+ assert vm.container_disk_image
+ sdk = client(transport)
+ pool = await sdk.create_pool(CreatePoolRequest(namespace='default', spec=pool_spec()))
+ claim = await sdk.create_claim(CreateClaimRequest(pool=pool, spec=ClaimSpec(sandbox_template_ref=SandboxTemplateRef(name=pool.metadata.name), warmpool=None, bind_deadline=None, lifecycle=None)))
+ sandbox = await sdk.wait_claim(claim)
+ service = await sdk.service_request(sandbox, 'mcp', '/mcp', service_request(b'{"offline":true}'))
+ await sdk.delete_claim(claim)
+ await sdk.delete_pool(pool)
+ transport.assert_exhausted()
+ return pool, claim, sandbox, service
diff --git a/libs/fleet/sdk-bindings/python/cyclops_sdk/__init__.py b/libs/fleet/sdk-bindings/python/cyclops_sdk/__init__.py
index 3e538570f0..fb39d42c0e 100644
--- a/libs/fleet/sdk-bindings/python/cyclops_sdk/__init__.py
+++ b/libs/fleet/sdk-bindings/python/cyclops_sdk/__init__.py
@@ -1,226 +1,14 @@
-import json
-import logging
-import os
-import subprocess
-import time
-import urllib.error
-import urllib.request
-from typing import Any, NotRequired, TypedDict
+from . import _schema as _schema_component
+from ._schema import *
+_UniffiFfiConverterTypeClaimSpec = _schema_component._UniffiFfiConverterTypeClaimSpec
+_UniffiFfiConverterTypeOSGymSandboxClaimStatus = _schema_component._UniffiFfiConverterTypeOSGymSandboxClaimStatus
+_UniffiFfiConverterTypeOSGymWorkspacePoolStatus = _schema_component._UniffiFfiConverterTypeOSGymWorkspacePoolStatus
+_UniffiFfiConverterTypePoolSpec = _schema_component._UniffiFfiConverterTypePoolSpec
-import httpx
+from . import _sdk as _sdk_component
+from ._sdk import *
-from .generated_crd import (
- ClaimSpec as ClaimSpec,
- ClaimSpecLifecycle as ClaimSpecLifecycle,
- PoolSpec as PoolSpec,
- PoolSpecAutoscaling as PoolSpecAutoscaling,
- PoolSpecService as PoolSpecService,
- PoolSpecServiceProtocol as PoolSpecServiceProtocol,
- PoolTemplate as PoolTemplate,
- PoolTemplateFirmware as PoolTemplateFirmware,
- PoolTemplateOidc as PoolTemplateOidc,
- PoolTemplateRuntime as PoolTemplateRuntime,
- SandboxTemplateRef as SandboxTemplateRef,
-)
+__all__ = [*_schema_component.__all__, *_sdk_component.__all__]
-logger = logging.getLogger(__name__)
-
-
-class ResourceMetadata(TypedDict):
- namespace: str
- name: str
- labels: NotRequired[dict[str, str]]
-
-
-class Pool(TypedDict):
- apiVersion: str
- kind: str
- metadata: ResourceMetadata
- spec: dict[str, Any]
- status: NotRequired[dict[str, Any]]
-
-
-class Claim(TypedDict):
- apiVersion: str
- kind: str
- metadata: ResourceMetadata
- spec: dict[str, Any]
- status: NotRequired[dict[str, Any]]
-
-
-class Sandbox(TypedDict):
- namespace: str
- claim: str
- sandbox: str
- services: list[str]
-
-
-class CreatePoolRequest(TypedDict):
- namespace: str
- spec: PoolSpec
-
-
-class CreateClaimRequest(TypedDict):
- pool: Pool
- spec: NotRequired[ClaimSpec]
-
-
-class _NoRedirect(urllib.request.HTTPRedirectHandler):
- def redirect_request(self, *_args):
- return None
-
-
-class UnknownServiceError(ValueError):
- def __init__(self, requested: str, available: list[str]):
- self.requested = requested
- self.available = available
- super().__init__(
- f"unknown sandbox service {requested!r}; available services: {available!r}"
- )
-
-
-class _ServiceTransport(httpx.BaseTransport):
- def __init__(self, sdk, sandbox: Sandbox, service: str):
- self._sdk = sdk
- self._sandbox = sandbox
- self._service = service
-
- def handle_request(self, request: httpx.Request) -> httpx.Response:
- path = request.url.raw_path.decode("ascii")
- if not path.startswith("/") or path.startswith("//") or "#" in path:
- raise ValueError(
- f"service request path must be relative and start with '/': {path}"
- )
- body = request.read()
- response = self._sdk._call({
- "op": "service_request",
- "sandbox": self._sandbox,
- "service": self._service,
- "request": {
- "method": request.method,
- "path": path,
- "headers": list(request.headers.multi_items()),
- "body": body.decode("utf-8") if body else None,
- },
- })
- return httpx.Response(
- response["status"],
- content=response["body"].encode(),
- request=request,
- )
-
-
-class SDK:
- def __init__(self, configuration):
- self._configuration = configuration
- self._token = None
- self._process = subprocess.Popen(
- [os.environ.get("CYCLOPS_CORE_RUNNER", "cyclops-core-runner")],
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- text=True,
- )
- try:
- self._call({"op": "configure", "configuration": {"protocol_version": 7, "base_url": configuration["base_url"]}})
- except BaseException:
- self.close()
- raise
-
- def create_pool(self, request: CreatePoolRequest) -> Pool:
- return self._call({"op": "create_pool", "request": request})
-
- def list_pools(self, namespace: str) -> list[Pool]:
- return self._call({"op": "list_pools", "namespace": namespace})
-
- def get_pool(self, pool: Pool) -> Pool:
- return self._call({"op": "get_pool", "pool": pool})
-
- def update_pool(self, pool: Pool) -> Pool:
- return self._call({"op": "update_pool", "pool": pool})
-
- def delete_pool(self, pool: Pool) -> None:
- self._call({"op": "delete_pool", "pool": pool})
-
- def create_claim(self, request: CreateClaimRequest) -> Claim:
- return self._call({"op": "create_claim", "request": request})
-
- def list_claims(self, namespace: str) -> list[Claim]:
- return self._call({"op": "list_claims", "namespace": namespace})
-
- def get_claim(self, claim: Claim) -> Claim:
- return self._call({"op": "get_claim", "claim": claim})
-
- def update_claim(self, claim: Claim) -> Claim:
- return self._call({"op": "update_claim", "claim": claim})
-
- def delete_claim(self, claim: Claim) -> None:
- self._call({"op": "delete_claim", "claim": claim})
-
- def wait_claim(self, claim: Claim) -> Sandbox:
- return self._call({"op": "wait_claim", "claim": claim})
-
- def service_client(self, sandbox: Sandbox, service: str) -> httpx.Client:
- available = sorted(set(sandbox["services"]))
- if service not in available:
- raise UnknownServiceError(service, available)
- return httpx.Client(
- base_url="https://cyclops.invalid",
- transport=_ServiceTransport(self, sandbox, service),
- )
-
- def close(self):
- if self._process.poll() is None:
- self._process.stdin.close()
- self._process.terminate()
- self._process.wait()
-
- def _call(self, request):
- self._process.stdin.write(json.dumps(request) + "\n")
- self._process.stdin.flush()
- for line in self._process.stdout:
- message = json.loads(line)
- if "kind" not in message:
- if not message["ok"]:
- raise RuntimeError(message.get("error", "core operation failed"))
- return message.get("value")
- try:
- value = self._dispatch(message)
- reply = {"ok": True, "value": value}
- except BaseException as error:
- logger.warning("Cyclops host call failed: %s", error)
- reply = {"ok": False, "error": {"transport": str(error)}}
- self._process.stdin.write(json.dumps(reply) + "\n")
- self._process.stdin.flush()
- raise RuntimeError("core runner exited")
-
- def _dispatch(self, message):
- kind = message["kind"]
- if kind == "http":
- request = message["request"]
- body = request.get("body")
- http_request = urllib.request.Request(request["url"], data=body.encode() if body is not None else None, headers=dict(request["headers"]), method=request["method"])
- opener = urllib.request.build_opener(_NoRedirect())
- try:
- with opener.open(http_request, timeout=30) as response:
- return {"status": response.status, "body": response.read().decode()}
- except urllib.error.HTTPError as error:
- logger.debug("HTTP request returned status %s", error.code)
- return {"status": error.code, "body": error.read().decode()}
- if kind == "sleep":
- time.sleep(message["milliseconds"] / 1000)
- return None
- if kind == "now_ms":
- return int(time.time() * 1000)
- if kind == "acquire_oauth_credentials":
- oauth = self._configuration["oauth"]
- return {"token_url": oauth["token_url"], "client_id": oauth["client_id"], "client_secret": oauth["client_secret"]}
- if kind == "load_access_token":
- return self._token
- if kind == "store_access_token":
- self._token = message["token"]
- return None
- raise RuntimeError(f"unknown host call {kind}")
-
-
-def connect(configuration):
- return SDK(configuration)
+del _schema_component
+del _sdk_component
diff --git a/libs/fleet/sdk-bindings/python/cyclops_sdk/_schema.py b/libs/fleet/sdk-bindings/python/cyclops_sdk/_schema.py
new file mode 100644
index 0000000000..5121529208
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/cyclops_sdk/_schema.py
@@ -0,0 +1,2541 @@
+# This file was autogenerated by some hot garbage in the `uniffi` crate.
+# Trust me, you don't want to mess with it!
+
+# Common helper code.
+#
+# Ideally this would live in a separate .py file where it can be unittested etc
+# in isolation, and perhaps even published as a re-useable package.
+#
+# However, it's important that the details of how this helper code works (e.g. the
+# way that different builtin types are passed across the FFI) exactly match what's
+# expected by the rust code on the other side of the interface. In practice right
+# now that means coming from the exact some version of `uniffi` that was used to
+# compile the rust component. The easiest way to ensure this is to bundle the Python
+# helpers directly inline like we're doing here.
+
+from __future__ import annotations
+import os
+import sys
+import ctypes
+from dataclasses import dataclass
+import enum
+import struct
+import contextlib
+import datetime
+import threading
+import itertools
+import traceback
+import typing
+import platform
+
+
+# Used for default argument values
+_DEFAULT = object() # type: typing.Any
+
+import ctypes
+import struct
+
+class _UniffiRustBuffer(ctypes.Structure):
+ _fields_ = [
+ ("capacity", ctypes.c_uint64),
+ ("len", ctypes.c_uint64),
+ ("data", ctypes.POINTER(ctypes.c_char)),
+ ]
+
+ @staticmethod
+ def default():
+ return _UniffiRustBuffer(0, 0, None)
+
+ @staticmethod
+ def alloc(size):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_alloc, size)
+
+ @staticmethod
+ def reserve(rbuf, additional):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_reserve, rbuf, additional)
+
+ def free(self):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_free, self)
+
+ def __str__(self):
+ return "_UniffiRustBuffer(capacity={}, len={}, data={})".format(
+ self.capacity,
+ self.len,
+ self.data[0:self.len]
+ )
+
+ @contextlib.contextmanager
+ def alloc_with_builder(*args):
+ """Context-manger to allocate a buffer using a _UniffiRustBufferBuilder.
+
+ The allocated buffer will be automatically freed if an error occurs, ensuring that
+ we don't accidentally leak it.
+ """
+ builder = _UniffiRustBufferBuilder()
+ try:
+ yield builder
+ except:
+ builder.discard()
+ raise
+
+ @contextlib.contextmanager
+ def consume_with_stream(self):
+ """Context-manager to consume a buffer using a _UniffiRustBufferStream.
+
+ The _UniffiRustBuffer will be freed once the context-manager exits, ensuring that we don't
+ leak it even if an error occurs.
+ """
+ try:
+ s = _UniffiRustBufferStream.from_rust_buffer(self)
+ yield s
+ if s.remaining() != 0:
+ raise RuntimeError(f"junk data left in buffer at end of consume_with_stream {s.remaining()}")
+ finally:
+ self.free()
+
+ @contextlib.contextmanager
+ def read_with_stream(self):
+ """Context-manager to read a buffer using a _UniffiRustBufferStream.
+
+ This is like consume_with_stream, but doesn't free the buffer afterwards.
+ It should only be used with borrowed `_UniffiRustBuffer` data.
+ """
+ s = _UniffiRustBufferStream.from_rust_buffer(self)
+ yield s
+ if s.remaining() != 0:
+ raise RuntimeError(f"junk data left in buffer at end of read_with_stream {s.remaining()}")
+
+class _UniffiForeignBytes(ctypes.Structure):
+ _fields_ = [
+ ("len", ctypes.c_int32),
+ ("data", ctypes.POINTER(ctypes.c_char)),
+ ]
+
+ def __str__(self):
+ return "_UniffiForeignBytes(len={}, data={})".format(self.len, self.data[0:self.len])
+
+
+class _UniffiFfiConverterByRefBytes:
+ """Zero-copy converter for `&[u8]` / `[ByRef] bytes` arguments.
+
+ Only `lower` and `check_lower` are valid — zero-copy byte buffers only
+ flow foreign -> Rust, and only in argument position. `lift`, `read`, and
+ `write` have no sound implementation here.
+
+ CPython `bytes` objects are immutable and their internal buffer doesn't
+ move for the lifetime of the object; the caller must keep the source
+ `bytes` alive for the duration of the FFI call.
+ """
+
+ @staticmethod
+ def check_lower(value):
+ # Tighter than `bytes-like`: `lower` uses `ctypes.c_char_p` which only
+ # accepts `bytes`/`None`, so fail fast with a matching check.
+ if not isinstance(value, bytes):
+ raise TypeError("a bytes object is required, not {!r}".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value):
+ fb = _UniffiForeignBytes()
+ if len(value) == 0:
+ fb.len = 0
+ fb.data = None
+ else:
+ fb.len = len(value)
+ fb.data = ctypes.cast(ctypes.c_char_p(value), ctypes.POINTER(ctypes.c_char))
+ return fb
+
+ @staticmethod
+ def lift(value):
+ raise NotImplementedError("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+
+ @staticmethod
+ def read(buf):
+ raise NotImplementedError("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ @staticmethod
+ def write(value, buf):
+ raise NotImplementedError("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+
+class _UniffiRustBufferStream:
+ """
+ Helper for structured reading of bytes from a _UniffiRustBuffer
+ """
+
+ def __init__(self, data, len):
+ self.data = data
+ self.len = len
+ self.offset = 0
+
+ @classmethod
+ def from_rust_buffer(cls, buf):
+ return cls(buf.data, buf.len)
+
+ def remaining(self):
+ return self.len - self.offset
+
+ def _unpack_from(self, size, format):
+ if self.offset + size > self.len:
+ raise InternalError("read past end of rust buffer")
+ value = struct.unpack(format, self.data[self.offset:self.offset+size])[0]
+ self.offset += size
+ return value
+
+ def read(self, size):
+ if self.offset + size > self.len:
+ raise InternalError("read past end of rust buffer")
+ data = self.data[self.offset:self.offset+size]
+ self.offset += size
+ return data
+
+ def read_i8(self):
+ return self._unpack_from(1, ">b")
+
+ def read_u8(self):
+ return self._unpack_from(1, ">B")
+
+ def read_i16(self):
+ return self._unpack_from(2, ">h")
+
+ def read_u16(self):
+ return self._unpack_from(2, ">H")
+
+ def read_i32(self):
+ return self._unpack_from(4, ">i")
+
+ def read_u32(self):
+ return self._unpack_from(4, ">I")
+
+ def read_i64(self):
+ return self._unpack_from(8, ">q")
+
+ def read_u64(self):
+ return self._unpack_from(8, ">Q")
+
+ def read_float(self):
+ v = self._unpack_from(4, ">f")
+ return v
+
+ def read_double(self):
+ return self._unpack_from(8, ">d")
+
+class _UniffiRustBufferBuilder:
+ """
+ Helper for structured writing of bytes into a _UniffiRustBuffer.
+ """
+
+ def __init__(self):
+ self.rbuf = _UniffiRustBuffer.alloc(16)
+ self.rbuf.len = 0
+
+ def finalize(self):
+ rbuf = self.rbuf
+ self.rbuf = None
+ return rbuf
+
+ def discard(self):
+ if self.rbuf is not None:
+ rbuf = self.finalize()
+ rbuf.free()
+
+ @contextlib.contextmanager
+ def _reserve(self, num_bytes):
+ if self.rbuf.len + num_bytes > self.rbuf.capacity:
+ self.rbuf = _UniffiRustBuffer.reserve(self.rbuf, num_bytes)
+ yield None
+ self.rbuf.len += num_bytes
+
+ def _pack_into(self, size, format, value):
+ with self._reserve(size):
+ packed = struct.pack(format, value)
+ if size > 0:
+ ctypes.memmove(ctypes.addressof(self.rbuf.data.contents) + self.rbuf.len, packed, size)
+
+ def write(self, value):
+ length = len(value)
+ with self._reserve(length):
+ if length > 0:
+ ctypes.memmove(ctypes.addressof(self.rbuf.data.contents) + self.rbuf.len, value, length)
+
+ def write_i8(self, v):
+ self._pack_into(1, ">b", v)
+
+ def write_u8(self, v):
+ self._pack_into(1, ">B", v)
+
+ def write_i16(self, v):
+ self._pack_into(2, ">h", v)
+
+ def write_u16(self, v):
+ self._pack_into(2, ">H", v)
+
+ def write_i32(self, v):
+ self._pack_into(4, ">i", v)
+
+ def write_u32(self, v):
+ self._pack_into(4, ">I", v)
+
+ def write_i64(self, v):
+ self._pack_into(8, ">q", v)
+
+ def write_u64(self, v):
+ self._pack_into(8, ">Q", v)
+
+ def write_float(self, v):
+ self._pack_into(4, ">f", v)
+
+ def write_double(self, v):
+ self._pack_into(8, ">d", v)
+
+ def write_c_size_t(self, v):
+ self._pack_into(ctypes.sizeof(ctypes.c_size_t) , "@N", v)
+# A handful of classes and functions to support the generated data structures.
+# This would be a good candidate for isolating in its own ffi-support lib.
+
+class InternalError(Exception):
+ pass
+
+class _UniffiRustCallStatus(ctypes.Structure):
+ """
+ Error runtime.
+ """
+ _fields_ = [
+ ("code", ctypes.c_int8),
+ ("error_buf", _UniffiRustBuffer),
+ ]
+
+ # These match the values from the uniffi::rustcalls module
+ CALL_SUCCESS = 0
+ CALL_ERROR = 1
+ CALL_UNEXPECTED_ERROR = 2
+
+ @staticmethod
+ def default():
+ return _UniffiRustCallStatus(code=_UniffiRustCallStatus.CALL_SUCCESS, error_buf=_UniffiRustBuffer.default())
+
+ def __str__(self):
+ if self.code == _UniffiRustCallStatus.CALL_SUCCESS:
+ return "_UniffiRustCallStatus(CALL_SUCCESS)"
+ elif self.code == _UniffiRustCallStatus.CALL_ERROR:
+ return "_UniffiRustCallStatus(CALL_ERROR)"
+ elif self.code == _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR:
+ return "_UniffiRustCallStatus(CALL_UNEXPECTED_ERROR)"
+ else:
+ return "_UniffiRustCallStatus(<invalid code>)"
+
+def _uniffi_rust_call(fn, *args):
+ # Call a rust function
+ return _uniffi_rust_call_with_error(None, fn, *args)
+
+def _uniffi_rust_call_with_error(error_ffi_converter, fn, *args):
+ # Call a rust function and handle any errors
+ #
+ # This function is used for rust calls that return Result<> and therefore can set the CALL_ERROR status code.
+ # error_ffi_converter must be set to the _UniffiConverter for the error class that corresponds to the result.
+ call_status = _UniffiRustCallStatus.default()
+
+ args_with_error = args + (ctypes.byref(call_status),)
+ result = fn(*args_with_error)
+ _uniffi_check_call_status(error_ffi_converter, call_status)
+ return result
+
+def _uniffi_check_call_status(error_ffi_converter, call_status):
+ if call_status.code == _UniffiRustCallStatus.CALL_SUCCESS:
+ pass
+ elif call_status.code == _UniffiRustCallStatus.CALL_ERROR:
+ if error_ffi_converter is None:
+ call_status.error_buf.free()
+ raise InternalError("_uniffi_rust_call_with_error: CALL_ERROR, but error_ffi_converter is None")
+ else:
+ raise error_ffi_converter.lift(call_status.error_buf)
+ elif call_status.code == _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR:
+ # When the rust code sees a panic, it tries to construct a _UniffiRustBuffer
+ # with the message. But if that code panics, then it just sends back
+ # an empty buffer.
+ if call_status.error_buf.len > 0:
+ msg = _UniffiFfiConverterString.lift(call_status.error_buf)
+ else:
+ msg = "Unknown rust panic"
+ raise InternalError(msg)
+ else:
+ raise InternalError("Invalid _UniffiRustCallStatus code: {}".format(
+ call_status.code))
+
+def _uniffi_trait_interface_call(call_status, make_call, write_return_value):
+ try:
+ return write_return_value(make_call())
+ except Exception as e:
+ call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR
+ call_status.error_buf = _UniffiFfiConverterString.lower(repr(e))
+
+def _uniffi_trait_interface_call_with_error(call_status, make_call, write_return_value, error_type, lower_error):
+ try:
+ try:
+ return write_return_value(make_call())
+ except error_type as e:
+ call_status.code = _UniffiRustCallStatus.CALL_ERROR
+ call_status.error_buf = lower_error(e)
+ except Exception as e:
+ call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR
+ call_status.error_buf = _UniffiFfiConverterString.lower(repr(e))
+# Initial value and increment amount for handles.
+# These ensure that Python-generated handles always have the lowest bit set
+_UNIFFI_HANDLEMAP_INITIAL = 1
+_UNIFFI_HANDLEMAP_DELTA = 2
+
+class _UniffiHandleMap:
+ """
+ A map where inserting, getting and removing data is synchronized with a lock.
+ """
+
+ def __init__(self):
+ # type Handle = int
+ self._map = {} # type: Dict[Handle, Any]
+ self._lock = threading.Lock()
+ self._counter = _UNIFFI_HANDLEMAP_INITIAL
+
+ def insert(self, obj):
+ with self._lock:
+ return self._insert(obj)
+
+ """Low-level insert, this assumes `self._lock` is held."""
+ def _insert(self, obj):
+ handle = self._counter
+ self._counter += _UNIFFI_HANDLEMAP_DELTA
+ self._map[handle] = obj
+ return handle
+
+ def get(self, handle):
+ try:
+ with self._lock:
+ return self._map[handle]
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.get: Invalid handle {handle}")
+
+ def clone(self, handle):
+ try:
+ with self._lock:
+ obj = self._map[handle]
+ return self._insert(obj)
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.clone: Invalid handle {handle}")
+
+ def remove(self, handle):
+ try:
+ with self._lock:
+ return self._map.pop(handle)
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.remove: Invalid handle: {handle}")
+
+ def __len__(self):
+ return len(self._map)
+# Types conforming to `_UniffiConverterPrimitive` pass themselves directly over the FFI.
+class _UniffiConverterPrimitive:
+ @classmethod
+ def lift(cls, value):
+ return value
+
+ @classmethod
+ def lower(cls, value):
+ return value
+
+class _UniffiConverterPrimitiveInt(_UniffiConverterPrimitive):
+ @classmethod
+ def check_lower(cls, value):
+ try:
+ value = value.__index__()
+ except Exception:
+ raise TypeError("'{}' object cannot be interpreted as an integer".format(type(value).__name__))
+ if not isinstance(value, int):
+ raise TypeError("__index__ returned non-int (type {})".format(type(value).__name__))
+ if not cls.VALUE_MIN <= value < cls.VALUE_MAX:
+ raise ValueError("{} requires {} <= value < {}".format(cls.CLASS_NAME, cls.VALUE_MIN, cls.VALUE_MAX))
+
+class _UniffiConverterPrimitiveFloat(_UniffiConverterPrimitive):
+ @classmethod
+ def check_lower(cls, value):
+ try:
+ value = value.__float__()
+ except Exception:
+ raise TypeError("must be real number, not {}".format(type(value).__name__))
+ if not isinstance(value, float):
+ raise TypeError("__float__ returned non-float (type {})".format(type(value).__name__))
+
+# Helper class for wrapper types that will always go through a _UniffiRustBuffer.
+# Classes should inherit from this and implement the `read` and `write` static methods.
+class _UniffiConverterRustBuffer:
+ @classmethod
+ def lift(cls, rbuf):
+ with rbuf.consume_with_stream() as stream:
+ return cls.read(stream)
+
+ @classmethod
+ def lower(cls, value):
+ with _UniffiRustBuffer.alloc_with_builder() as builder:
+ cls.write(value, builder)
+ return builder.finalize()
+
+# Contains loading, initialization code, and the FFI Function declarations.
+# Define some ctypes FFI types that we use in the library
+
+"""
+Function pointer for a Rust task, which a callback function that takes a opaque pointer
+"""
+_UNIFFI_RUST_TASK = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int8)
+
+def _uniffi_future_callback_t(return_type):
+ """
+ Factory function to create callback function types for async functions
+ """
+ return ctypes.CFUNCTYPE(None, ctypes.c_uint64, return_type, _UniffiRustCallStatus)
+
+def _uniffi_load_indirect():
+ """
+ This is how we find and load the dynamic library provided by the component.
+ For now we just look it up by name.
+ """
+ if sys.platform == "darwin":
+ libname = "lib{}.dylib"
+ elif sys.platform.startswith("win"):
+ # As of python3.8, ctypes does not seem to search $PATH when loading DLLs.
+ # We could use `os.add_dll_directory` to configure the search path, but
+ # it doesn't feel right to mess with application-wide settings. Let's
+ # assume that the `.dll` is next to the `.py` file and load by full path.
+ libname = os.path.join(
+ os.path.dirname(__file__),
+ "{}.dll",
+ )
+ else:
+ # Anything else must be an ELF platform - Linux, *BSD, Solaris/illumos
+ libname = "lib{}.so"
+
+ libname = libname.format("cyclops_sdk")
+ path = os.path.join(os.path.dirname(__file__), libname)
+ lib = ctypes.cdll.LoadLibrary(path)
+ return lib
+
+def _uniffi_check_contract_api_version(lib):
+ # Get the bindings contract version from our ComponentInterface
+ bindings_contract_version = 30
+ # Get the scaffolding contract version by calling the into the dylib
+ scaffolding_contract_version = lib.ffi_cyclops_sdk_schema_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version:
+ raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+
+def _uniffi_check_api_checksums(lib):
+ if lib.uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json() != 675:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json() != 56364:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+
+# A ctypes library to expose the extern-C FFI definitions.
+# This is an implementation detail which will be called internally by the public API.
+
+_UniffiLib = _uniffi_load_indirect()
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_alloc.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_alloc.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_from_bytes.argtypes = (
+ _UniffiForeignBytes,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_from_bytes.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_free.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_free.restype = None
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_reserve.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_schema_rustbuffer_reserve.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_schema_uniffi_contract_version.argtypes = (
+)
+_UniffiLib.ffi_cyclops_sdk_schema_uniffi_contract_version.restype = ctypes.c_uint32
+_UniffiLib.uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq.restype = ctypes.c_int8
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne.restype = ctypes.c_int8
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_clone_preservedjson.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_clone_preservedjson.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_free_preservedjson.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_schema_fn_free_preservedjson.restype = None
+
+_uniffi_check_contract_api_version(_UniffiLib)
+# _uniffi_check_api_checksums(_UniffiLib)
+
+
+
+# Public interface members begin here.
+
+
+class _UniffiFfiConverterString:
+ @staticmethod
+ def check_lower(value):
+ if not isinstance(value, str):
+ raise TypeError("argument must be str, not {}".format(type(value).__name__))
+ return value
+
+ @staticmethod
+ def read(buf):
+ size = buf.read_i32()
+ if size < 0:
+ raise InternalError("Unexpected negative string length")
+ utf8_bytes = buf.read(size)
+ return utf8_bytes.decode("utf-8")
+
+ @staticmethod
+ def write(value, buf):
+ utf8_bytes = value.encode("utf-8")
+ buf.write_i32(len(utf8_bytes))
+ buf.write(utf8_bytes)
+
+ @staticmethod
+ def lift(buf):
+ with buf.consume_with_stream() as stream:
+ return stream.read(stream.remaining()).decode("utf-8")
+
+ @staticmethod
+ def lower(value):
+ with _UniffiRustBuffer.alloc_with_builder() as builder:
+ builder.write(value.encode("utf-8"))
+ return builder.finalize()
+
+class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterString.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterString.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterBoolean:
+ @classmethod
+ def check_lower(cls, value):
+ return not not value
+
+ @classmethod
+ def lower(cls, value):
+ return 1 if value else 0
+
+ @staticmethod
+ def lift(value):
+ return value != 0
+
+ @classmethod
+ def read(cls, buf):
+ return cls.lift(buf.read_u8())
+
+ @classmethod
+ def write(cls, value, buf):
+ buf.write_u8(value)
+
+class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterBoolean.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterBoolean.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterBoolean.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class ClaimLifecycle:
+ def __init__(self, *, shutdown_time:typing.Optional[str], shutdown_policy:typing.Optional[str], auto_renew:typing.Optional[bool]):
+ self.shutdown_time = shutdown_time
+ self.shutdown_policy = shutdown_policy
+ self.auto_renew = auto_renew
+
+
+
+
+ def __str__(self):
+ return "ClaimLifecycle(shutdown_time={}, shutdown_policy={}, auto_renew={})".format(self.shutdown_time, self.shutdown_policy, self.auto_renew)
+ def __eq__(self, other):
+ if self.shutdown_time != other.shutdown_time:
+ return False
+ if self.shutdown_policy != other.shutdown_policy:
+ return False
+ if self.auto_renew != other.auto_renew:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeClaimLifecycle(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ClaimLifecycle(
+ shutdown_time=_UniffiFfiConverterOptionalString.read(buf),
+ shutdown_policy=_UniffiFfiConverterOptionalString.read(buf),
+ auto_renew=_UniffiFfiConverterOptionalBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.shutdown_time)
+ _UniffiFfiConverterOptionalString.check_lower(value.shutdown_policy)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.auto_renew)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.shutdown_time, buf)
+ _UniffiFfiConverterOptionalString.write(value.shutdown_policy, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.auto_renew, buf)
+
+@dataclass
+class SandboxTemplateRef:
+ def __init__(self, *, name:str):
+ self.name = name
+
+
+
+
+ def __str__(self):
+ return "SandboxTemplateRef(name={})".format(self.name)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSandboxTemplateRef(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SandboxTemplateRef(
+ name=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+
+class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u32"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**32
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u32()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u32(value)
+
+class _UniffiFfiConverterOptionalUInt32(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterUInt32.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterUInt32.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterUInt32.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterOptionalTypeClaimLifecycle(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeClaimLifecycle.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeClaimLifecycle.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeClaimLifecycle.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class ClaimSpec:
+ def __init__(self, *, sandbox_template_ref:SandboxTemplateRef, warmpool:typing.Optional[str], bind_deadline:typing.Optional[int], lifecycle:typing.Optional[ClaimLifecycle]):
+ self.sandbox_template_ref = sandbox_template_ref
+ self.warmpool = warmpool
+ self.bind_deadline = bind_deadline
+ self.lifecycle = lifecycle
+
+
+
+
+ def __str__(self):
+ return "ClaimSpec(sandbox_template_ref={}, warmpool={}, bind_deadline={}, lifecycle={})".format(self.sandbox_template_ref, self.warmpool, self.bind_deadline, self.lifecycle)
+ def __eq__(self, other):
+ if self.sandbox_template_ref != other.sandbox_template_ref:
+ return False
+ if self.warmpool != other.warmpool:
+ return False
+ if self.bind_deadline != other.bind_deadline:
+ return False
+ if self.lifecycle != other.lifecycle:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeClaimSpec(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ClaimSpec(
+ sandbox_template_ref=_UniffiFfiConverterTypeSandboxTemplateRef.read(buf),
+ warmpool=_UniffiFfiConverterOptionalString.read(buf),
+ bind_deadline=_UniffiFfiConverterOptionalUInt32.read(buf),
+ lifecycle=_UniffiFfiConverterOptionalTypeClaimLifecycle.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeSandboxTemplateRef.check_lower(value.sandbox_template_ref)
+ _UniffiFfiConverterOptionalString.check_lower(value.warmpool)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.bind_deadline)
+ _UniffiFfiConverterOptionalTypeClaimLifecycle.check_lower(value.lifecycle)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeSandboxTemplateRef.write(value.sandbox_template_ref, buf)
+ _UniffiFfiConverterOptionalString.write(value.warmpool, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.bind_deadline, buf)
+ _UniffiFfiConverterOptionalTypeClaimLifecycle.write(value.lifecycle, buf)
+
+@dataclass
+class OsGymSandboxClaimCondition:
+ def __init__(self, *, type:typing.Optional[str], status:typing.Optional[str], reason:typing.Optional[str], message:typing.Optional[str], last_transition_time:typing.Optional[str]):
+ self.type = type
+ self.status = status
+ self.reason = reason
+ self.message = message
+ self.last_transition_time = last_transition_time
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxClaimCondition(type={}, status={}, reason={}, message={}, last_transition_time={})".format(self.type, self.status, self.reason, self.message, self.last_transition_time)
+ def __eq__(self, other):
+ if self.type != other.type:
+ return False
+ if self.status != other.status:
+ return False
+ if self.reason != other.reason:
+ return False
+ if self.message != other.message:
+ return False
+ if self.last_transition_time != other.last_transition_time:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxClaimCondition(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxClaimCondition(
+ type=_UniffiFfiConverterOptionalString.read(buf),
+ status=_UniffiFfiConverterOptionalString.read(buf),
+ reason=_UniffiFfiConverterOptionalString.read(buf),
+ message=_UniffiFfiConverterOptionalString.read(buf),
+ last_transition_time=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.type)
+ _UniffiFfiConverterOptionalString.check_lower(value.status)
+ _UniffiFfiConverterOptionalString.check_lower(value.reason)
+ _UniffiFfiConverterOptionalString.check_lower(value.message)
+ _UniffiFfiConverterOptionalString.check_lower(value.last_transition_time)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.type, buf)
+ _UniffiFfiConverterOptionalString.write(value.status, buf)
+ _UniffiFfiConverterOptionalString.write(value.reason, buf)
+ _UniffiFfiConverterOptionalString.write(value.message, buf)
+ _UniffiFfiConverterOptionalString.write(value.last_transition_time, buf)
+
+@dataclass
+class OsGymSandboxClaimSandbox:
+ def __init__(self, *, name:typing.Optional[str], service:typing.Optional[str]):
+ self.name = name
+ self.service = service
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxClaimSandbox(name={}, service={})".format(self.name, self.service)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.service != other.service:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxClaimSandbox(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxClaimSandbox(
+ name=_UniffiFfiConverterOptionalString.read(buf),
+ service=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.name)
+ _UniffiFfiConverterOptionalString.check_lower(value.service)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.name, buf)
+ _UniffiFfiConverterOptionalString.write(value.service, buf)
+
+class _UniffiFfiConverterSequenceTypeOSGymSandboxClaimCondition(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeOSGymSandboxClaimCondition.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeOSGymSandboxClaimCondition.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeOSGymSandboxClaimCondition.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterSequenceTypeOSGymSandboxClaimCondition.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterSequenceTypeOSGymSandboxClaimCondition.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterSequenceTypeOSGymSandboxClaimCondition.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterOptionalTypeOSGymSandboxClaimSandbox(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeOSGymSandboxClaimSandbox.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeOSGymSandboxClaimSandbox.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeOSGymSandboxClaimSandbox.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class OsGymSandboxClaimStatus:
+ def __init__(self, *, phase:typing.Optional[str], conditions:typing.Optional[typing.List[OsGymSandboxClaimCondition]], sandbox:typing.Optional[OsGymSandboxClaimSandbox]):
+ self.phase = phase
+ self.conditions = conditions
+ self.sandbox = sandbox
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxClaimStatus(phase={}, conditions={}, sandbox={})".format(self.phase, self.conditions, self.sandbox)
+ def __eq__(self, other):
+ if self.phase != other.phase:
+ return False
+ if self.conditions != other.conditions:
+ return False
+ if self.sandbox != other.sandbox:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxClaimStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxClaimStatus(
+ phase=_UniffiFfiConverterOptionalString.read(buf),
+ conditions=_UniffiFfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.read(buf),
+ sandbox=_UniffiFfiConverterOptionalTypeOSGymSandboxClaimSandbox.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.phase)
+ _UniffiFfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.check_lower(value.conditions)
+ _UniffiFfiConverterOptionalTypeOSGymSandboxClaimSandbox.check_lower(value.sandbox)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.phase, buf)
+ _UniffiFfiConverterOptionalSequenceTypeOSGymSandboxClaimCondition.write(value.conditions, buf)
+ _UniffiFfiConverterOptionalTypeOSGymSandboxClaimSandbox.write(value.sandbox, buf)
+
+class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterString.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterString.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterString.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterOptionalSequenceString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterSequenceString.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterSequenceString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterSequenceString.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+
+
+
+
+class RuntimeKind(enum.Enum):
+
+ KUBEVIRT = 0
+
+ MACOS = 1
+
+ GVISOR = 2
+
+
+
+class _UniffiFfiConverterTypeRuntimeKind(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return RuntimeKind.KUBEVIRT
+ if variant == 2:
+ return RuntimeKind.MACOS
+ if variant == 3:
+ return RuntimeKind.GVISOR
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == RuntimeKind.KUBEVIRT:
+ return
+ if value == RuntimeKind.MACOS:
+ return
+ if value == RuntimeKind.GVISOR:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == RuntimeKind.KUBEVIRT:
+ buf.write_i32(1)
+ if value == RuntimeKind.MACOS:
+ buf.write_i32(2)
+ if value == RuntimeKind.GVISOR:
+ buf.write_i32(3)
+
+
+
+class _UniffiFfiConverterOptionalTypeRuntimeKind(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeRuntimeKind.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeRuntimeKind.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeRuntimeKind.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterMapStringString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, items):
+ for (key, value) in items.items():
+ _UniffiFfiConverterString.check_lower(key)
+ _UniffiFfiConverterString.check_lower(value)
+
+ @classmethod
+ def write(cls, items, buf):
+ buf.write_i32(len(items))
+ for (key, value) in items.items():
+ _UniffiFfiConverterString.write(key, buf)
+ _UniffiFfiConverterString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative map size")
+
+ # It would be nice to use a dict comprehension,
+ # but in Python 3.7 and before the evaluation order is not according to spec,
+ # so we we're reading the value before the key.
+ # This loop makes the order explicit: first reading the key, then the value.
+ d = {}
+ for i in range(count):
+ key = _UniffiFfiConverterString.read(buf)
+ val = _UniffiFfiConverterString.read(buf)
+ d[key] = val
+ return d
+
+class _UniffiFfiConverterOptionalMapStringString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterMapStringString.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterMapStringString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterMapStringString.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+class PreservedJsonProtocol(typing.Protocol):
+
+ def to_json(self, ) -> str:
+ raise NotImplementedError
+
+class PreservedJson(PreservedJsonProtocol):
+
+ _handle: ctypes.c_uint64
+ @classmethod
+ def from_json(cls, value: str) -> PreservedJson:
+
+ _UniffiFfiConverterString.check_lower(value)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterString.lower(value),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypePreservedJson.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeJsonValueError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_schema_fn_free_preservedjson, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_schema_fn_clone_preservedjson, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ def to_json(self, ) -> str:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+
+
+
+
+
+class _UniffiFfiConverterTypePreservedJson:
+ @staticmethod
+ def lift(value: int) -> PreservedJson:
+ return PreservedJson._uniffi_make_instance(value)
+
+ @staticmethod
+ def check_lower(value: PreservedJson):
+ if not isinstance(value, PreservedJson):
+ raise TypeError("Expected PreservedJson instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: PreservedJson) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> PreservedJson:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: PreservedJson, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+class _UniffiFfiConverterSequenceTypePreservedJson(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypePreservedJson.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypePreservedJson.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypePreservedJson.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterOptionalSequenceTypePreservedJson(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterSequenceTypePreservedJson.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterSequenceTypePreservedJson.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterSequenceTypePreservedJson.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+
+
+
+
+class ImagePullPolicy(enum.Enum):
+
+ ALWAYS = 0
+
+ IF_NOT_PRESENT = 1
+
+ NEVER = 2
+
+
+
+class _UniffiFfiConverterTypeImagePullPolicy(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return ImagePullPolicy.ALWAYS
+ if variant == 2:
+ return ImagePullPolicy.IF_NOT_PRESENT
+ if variant == 3:
+ return ImagePullPolicy.NEVER
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == ImagePullPolicy.ALWAYS:
+ return
+ if value == ImagePullPolicy.IF_NOT_PRESENT:
+ return
+ if value == ImagePullPolicy.NEVER:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == ImagePullPolicy.ALWAYS:
+ buf.write_i32(1)
+ if value == ImagePullPolicy.IF_NOT_PRESENT:
+ buf.write_i32(2)
+ if value == ImagePullPolicy.NEVER:
+ buf.write_i32(3)
+
+
+
+class _UniffiFfiConverterOptionalTypeImagePullPolicy(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeImagePullPolicy.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeImagePullPolicy.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeImagePullPolicy.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+
+
+
+
+class Firmware(enum.Enum):
+
+ BIOS = 0
+
+ EFI = 1
+
+
+
+class _UniffiFfiConverterTypeFirmware(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return Firmware.BIOS
+ if variant == 2:
+ return Firmware.EFI
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == Firmware.BIOS:
+ return
+ if value == Firmware.EFI:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == Firmware.BIOS:
+ buf.write_i32(1)
+ if value == Firmware.EFI:
+ buf.write_i32(2)
+
+
+
+class _UniffiFfiConverterOptionalTypeFirmware(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeFirmware.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeFirmware.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeFirmware.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterOptionalTypePreservedJson(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypePreservedJson.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypePreservedJson.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypePreservedJson.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u16"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**16
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u16()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u16(value)
+
+
+
+
+
+
+class ServiceProtocol(enum.Enum):
+
+ TCP = 0
+
+ UDP = 1
+
+
+
+class _UniffiFfiConverterTypeServiceProtocol(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return ServiceProtocol.TCP
+ if variant == 2:
+ return ServiceProtocol.UDP
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == ServiceProtocol.TCP:
+ return
+ if value == ServiceProtocol.UDP:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == ServiceProtocol.TCP:
+ buf.write_i32(1)
+ if value == ServiceProtocol.UDP:
+ buf.write_i32(2)
+
+
+
+class _UniffiFfiConverterOptionalTypeServiceProtocol(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeServiceProtocol.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeServiceProtocol.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeServiceProtocol.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class SandboxService:
+ def __init__(self, *, name:str, target_port:int, protocol:typing.Optional[ServiceProtocol]):
+ self.name = name
+ self.target_port = target_port
+ self.protocol = protocol
+
+
+
+
+ def __str__(self):
+ return "SandboxService(name={}, target_port={}, protocol={})".format(self.name, self.target_port, self.protocol)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.target_port != other.target_port:
+ return False
+ if self.protocol != other.protocol:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSandboxService(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SandboxService(
+ name=_UniffiFfiConverterString.read(buf),
+ target_port=_UniffiFfiConverterUInt16.read(buf),
+ protocol=_UniffiFfiConverterOptionalTypeServiceProtocol.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterUInt16.check_lower(value.target_port)
+ _UniffiFfiConverterOptionalTypeServiceProtocol.check_lower(value.protocol)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterUInt16.write(value.target_port, buf)
+ _UniffiFfiConverterOptionalTypeServiceProtocol.write(value.protocol, buf)
+
+class _UniffiFfiConverterSequenceTypeSandboxService(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeSandboxService.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeSandboxService.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeSandboxService.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterOptionalSequenceTypeSandboxService(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterSequenceTypeSandboxService.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterSequenceTypeSandboxService.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterSequenceTypeSandboxService.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class OidcConfig:
+ def __init__(self, *, credentials_secret:str, token_url:str, aws_role_arn:typing.Optional[str], aws_region:typing.Optional[str], refresh_interval_seconds:typing.Optional[int]):
+ self.credentials_secret = credentials_secret
+ self.token_url = token_url
+ self.aws_role_arn = aws_role_arn
+ self.aws_region = aws_region
+ self.refresh_interval_seconds = refresh_interval_seconds
+
+
+
+
+ def __str__(self):
+ return "OidcConfig(credentials_secret={}, token_url={}, aws_role_arn={}, aws_region={}, refresh_interval_seconds={})".format(self.credentials_secret, self.token_url, self.aws_role_arn, self.aws_region, self.refresh_interval_seconds)
+ def __eq__(self, other):
+ if self.credentials_secret != other.credentials_secret:
+ return False
+ if self.token_url != other.token_url:
+ return False
+ if self.aws_role_arn != other.aws_role_arn:
+ return False
+ if self.aws_region != other.aws_region:
+ return False
+ if self.refresh_interval_seconds != other.refresh_interval_seconds:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOidcConfig(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OidcConfig(
+ credentials_secret=_UniffiFfiConverterString.read(buf),
+ token_url=_UniffiFfiConverterString.read(buf),
+ aws_role_arn=_UniffiFfiConverterOptionalString.read(buf),
+ aws_region=_UniffiFfiConverterOptionalString.read(buf),
+ refresh_interval_seconds=_UniffiFfiConverterOptionalUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.credentials_secret)
+ _UniffiFfiConverterString.check_lower(value.token_url)
+ _UniffiFfiConverterOptionalString.check_lower(value.aws_role_arn)
+ _UniffiFfiConverterOptionalString.check_lower(value.aws_region)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.refresh_interval_seconds)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.credentials_secret, buf)
+ _UniffiFfiConverterString.write(value.token_url, buf)
+ _UniffiFfiConverterOptionalString.write(value.aws_role_arn, buf)
+ _UniffiFfiConverterOptionalString.write(value.aws_region, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.refresh_interval_seconds, buf)
+
+class _UniffiFfiConverterOptionalTypeOidcConfig(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeOidcConfig.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeOidcConfig.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeOidcConfig.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class VmTemplate:
+ def __init__(self, *, container_disk_image:str, command:typing.Optional[typing.List[str]], runtime:typing.Optional[RuntimeKind], runtime_class_name:typing.Optional[str], node_selector:typing.Optional[dict[str, str]], tolerations:typing.Optional[typing.List[PreservedJson]], image_pull_policy:typing.Optional[ImagePullPolicy], image_pull_secret:typing.Optional[str], cpu_cores:typing.Optional[int], memory:typing.Optional[str], firmware:typing.Optional[Firmware], probes:typing.Optional[PreservedJson], services:typing.Optional[typing.List[SandboxService]], oidc:typing.Optional[OidcConfig]):
+ self.container_disk_image = container_disk_image
+ self.command = command
+ self.runtime = runtime
+ self.runtime_class_name = runtime_class_name
+ self.node_selector = node_selector
+ self.tolerations = tolerations
+ self.image_pull_policy = image_pull_policy
+ self.image_pull_secret = image_pull_secret
+ self.cpu_cores = cpu_cores
+ self.memory = memory
+ self.firmware = firmware
+ self.probes = probes
+ self.services = services
+ self.oidc = oidc
+
+
+
+
+ def __str__(self):
+ return "VmTemplate(container_disk_image={}, command={}, runtime={}, runtime_class_name={}, node_selector={}, tolerations={}, image_pull_policy={}, image_pull_secret={}, cpu_cores={}, memory={}, firmware={}, probes={}, services={}, oidc={})".format(self.container_disk_image, self.command, self.runtime, self.runtime_class_name, self.node_selector, self.tolerations, self.image_pull_policy, self.image_pull_secret, self.cpu_cores, self.memory, self.firmware, self.probes, self.services, self.oidc)
+ def __eq__(self, other):
+ if self.container_disk_image != other.container_disk_image:
+ return False
+ if self.command != other.command:
+ return False
+ if self.runtime != other.runtime:
+ return False
+ if self.runtime_class_name != other.runtime_class_name:
+ return False
+ if self.node_selector != other.node_selector:
+ return False
+ if self.tolerations != other.tolerations:
+ return False
+ if self.image_pull_policy != other.image_pull_policy:
+ return False
+ if self.image_pull_secret != other.image_pull_secret:
+ return False
+ if self.cpu_cores != other.cpu_cores:
+ return False
+ if self.memory != other.memory:
+ return False
+ if self.firmware != other.firmware:
+ return False
+ if self.probes != other.probes:
+ return False
+ if self.services != other.services:
+ return False
+ if self.oidc != other.oidc:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeVmTemplate(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return VmTemplate(
+ container_disk_image=_UniffiFfiConverterString.read(buf),
+ command=_UniffiFfiConverterOptionalSequenceString.read(buf),
+ runtime=_UniffiFfiConverterOptionalTypeRuntimeKind.read(buf),
+ runtime_class_name=_UniffiFfiConverterOptionalString.read(buf),
+ node_selector=_UniffiFfiConverterOptionalMapStringString.read(buf),
+ tolerations=_UniffiFfiConverterOptionalSequenceTypePreservedJson.read(buf),
+ image_pull_policy=_UniffiFfiConverterOptionalTypeImagePullPolicy.read(buf),
+ image_pull_secret=_UniffiFfiConverterOptionalString.read(buf),
+ cpu_cores=_UniffiFfiConverterOptionalUInt32.read(buf),
+ memory=_UniffiFfiConverterOptionalString.read(buf),
+ firmware=_UniffiFfiConverterOptionalTypeFirmware.read(buf),
+ probes=_UniffiFfiConverterOptionalTypePreservedJson.read(buf),
+ services=_UniffiFfiConverterOptionalSequenceTypeSandboxService.read(buf),
+ oidc=_UniffiFfiConverterOptionalTypeOidcConfig.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.container_disk_image)
+ _UniffiFfiConverterOptionalSequenceString.check_lower(value.command)
+ _UniffiFfiConverterOptionalTypeRuntimeKind.check_lower(value.runtime)
+ _UniffiFfiConverterOptionalString.check_lower(value.runtime_class_name)
+ _UniffiFfiConverterOptionalMapStringString.check_lower(value.node_selector)
+ _UniffiFfiConverterOptionalSequenceTypePreservedJson.check_lower(value.tolerations)
+ _UniffiFfiConverterOptionalTypeImagePullPolicy.check_lower(value.image_pull_policy)
+ _UniffiFfiConverterOptionalString.check_lower(value.image_pull_secret)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.cpu_cores)
+ _UniffiFfiConverterOptionalString.check_lower(value.memory)
+ _UniffiFfiConverterOptionalTypeFirmware.check_lower(value.firmware)
+ _UniffiFfiConverterOptionalTypePreservedJson.check_lower(value.probes)
+ _UniffiFfiConverterOptionalSequenceTypeSandboxService.check_lower(value.services)
+ _UniffiFfiConverterOptionalTypeOidcConfig.check_lower(value.oidc)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.container_disk_image, buf)
+ _UniffiFfiConverterOptionalSequenceString.write(value.command, buf)
+ _UniffiFfiConverterOptionalTypeRuntimeKind.write(value.runtime, buf)
+ _UniffiFfiConverterOptionalString.write(value.runtime_class_name, buf)
+ _UniffiFfiConverterOptionalMapStringString.write(value.node_selector, buf)
+ _UniffiFfiConverterOptionalSequenceTypePreservedJson.write(value.tolerations, buf)
+ _UniffiFfiConverterOptionalTypeImagePullPolicy.write(value.image_pull_policy, buf)
+ _UniffiFfiConverterOptionalString.write(value.image_pull_secret, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.cpu_cores, buf)
+ _UniffiFfiConverterOptionalString.write(value.memory, buf)
+ _UniffiFfiConverterOptionalTypeFirmware.write(value.firmware, buf)
+ _UniffiFfiConverterOptionalTypePreservedJson.write(value.probes, buf)
+ _UniffiFfiConverterOptionalSequenceTypeSandboxService.write(value.services, buf)
+ _UniffiFfiConverterOptionalTypeOidcConfig.write(value.oidc, buf)
+
+@dataclass
+class OsGymSandboxSpec:
+ def __init__(self, *, vm_template:VmTemplate):
+ self.vm_template = vm_template
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxSpec(vm_template={})".format(self.vm_template)
+ def __eq__(self, other):
+ if self.vm_template != other.vm_template:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxSpec(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxSpec(
+ vm_template=_UniffiFfiConverterTypeVmTemplate.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeVmTemplate.check_lower(value.vm_template)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeVmTemplate.write(value.vm_template, buf)
+
+@dataclass
+class OsGymSandboxStatus:
+ def __init__(self, *, phase:typing.Optional[str], runtime:typing.Optional[str], ready:typing.Optional[bool], vm_name:typing.Optional[str], service:typing.Optional[str], message:typing.Optional[str], reset_issued_at:typing.Optional[str], reset_vmi_uid:typing.Optional[str]):
+ self.phase = phase
+ self.runtime = runtime
+ self.ready = ready
+ self.vm_name = vm_name
+ self.service = service
+ self.message = message
+ self.reset_issued_at = reset_issued_at
+ self.reset_vmi_uid = reset_vmi_uid
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxStatus(phase={}, runtime={}, ready={}, vm_name={}, service={}, message={}, reset_issued_at={}, reset_vmi_uid={})".format(self.phase, self.runtime, self.ready, self.vm_name, self.service, self.message, self.reset_issued_at, self.reset_vmi_uid)
+ def __eq__(self, other):
+ if self.phase != other.phase:
+ return False
+ if self.runtime != other.runtime:
+ return False
+ if self.ready != other.ready:
+ return False
+ if self.vm_name != other.vm_name:
+ return False
+ if self.service != other.service:
+ return False
+ if self.message != other.message:
+ return False
+ if self.reset_issued_at != other.reset_issued_at:
+ return False
+ if self.reset_vmi_uid != other.reset_vmi_uid:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxStatus(
+ phase=_UniffiFfiConverterOptionalString.read(buf),
+ runtime=_UniffiFfiConverterOptionalString.read(buf),
+ ready=_UniffiFfiConverterOptionalBoolean.read(buf),
+ vm_name=_UniffiFfiConverterOptionalString.read(buf),
+ service=_UniffiFfiConverterOptionalString.read(buf),
+ message=_UniffiFfiConverterOptionalString.read(buf),
+ reset_issued_at=_UniffiFfiConverterOptionalString.read(buf),
+ reset_vmi_uid=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.phase)
+ _UniffiFfiConverterOptionalString.check_lower(value.runtime)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.ready)
+ _UniffiFfiConverterOptionalString.check_lower(value.vm_name)
+ _UniffiFfiConverterOptionalString.check_lower(value.service)
+ _UniffiFfiConverterOptionalString.check_lower(value.message)
+ _UniffiFfiConverterOptionalString.check_lower(value.reset_issued_at)
+ _UniffiFfiConverterOptionalString.check_lower(value.reset_vmi_uid)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.phase, buf)
+ _UniffiFfiConverterOptionalString.write(value.runtime, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.ready, buf)
+ _UniffiFfiConverterOptionalString.write(value.vm_name, buf)
+ _UniffiFfiConverterOptionalString.write(value.service, buf)
+ _UniffiFfiConverterOptionalString.write(value.message, buf)
+ _UniffiFfiConverterOptionalString.write(value.reset_issued_at, buf)
+ _UniffiFfiConverterOptionalString.write(value.reset_vmi_uid, buf)
+
+@dataclass
+class OsGymSandboxTemplateSpec:
+ def __init__(self, *, vm_template:VmTemplate):
+ self.vm_template = vm_template
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxTemplateSpec(vm_template={})".format(self.vm_template)
+ def __eq__(self, other):
+ if self.vm_template != other.vm_template:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxTemplateSpec(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxTemplateSpec(
+ vm_template=_UniffiFfiConverterTypeVmTemplate.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeVmTemplate.check_lower(value.vm_template)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeVmTemplate.write(value.vm_template, buf)
+
+@dataclass
+class WarmPoolAutoscaling:
+ def __init__(self, *, min_pool_size:typing.Optional[int], initial_pool_size:typing.Optional[int], max_pool_size:typing.Optional[int]):
+ self.min_pool_size = min_pool_size
+ self.initial_pool_size = initial_pool_size
+ self.max_pool_size = max_pool_size
+
+
+
+
+ def __str__(self):
+ return "WarmPoolAutoscaling(min_pool_size={}, initial_pool_size={}, max_pool_size={})".format(self.min_pool_size, self.initial_pool_size, self.max_pool_size)
+ def __eq__(self, other):
+ if self.min_pool_size != other.min_pool_size:
+ return False
+ if self.initial_pool_size != other.initial_pool_size:
+ return False
+ if self.max_pool_size != other.max_pool_size:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeWarmPoolAutoscaling(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return WarmPoolAutoscaling(
+ min_pool_size=_UniffiFfiConverterOptionalUInt32.read(buf),
+ initial_pool_size=_UniffiFfiConverterOptionalUInt32.read(buf),
+ max_pool_size=_UniffiFfiConverterOptionalUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.min_pool_size)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.initial_pool_size)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.max_pool_size)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalUInt32.write(value.min_pool_size, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.initial_pool_size, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.max_pool_size, buf)
+
+class _UniffiFfiConverterOptionalTypeWarmPoolAutoscaling(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeWarmPoolAutoscaling.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeWarmPoolAutoscaling.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeWarmPoolAutoscaling.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class OsGymSandboxWarmPoolSpec:
+ def __init__(self, *, replicas:int, sandbox_template_ref:SandboxTemplateRef, autoscaling:typing.Optional[WarmPoolAutoscaling]):
+ self.replicas = replicas
+ self.sandbox_template_ref = sandbox_template_ref
+ self.autoscaling = autoscaling
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxWarmPoolSpec(replicas={}, sandbox_template_ref={}, autoscaling={})".format(self.replicas, self.sandbox_template_ref, self.autoscaling)
+ def __eq__(self, other):
+ if self.replicas != other.replicas:
+ return False
+ if self.sandbox_template_ref != other.sandbox_template_ref:
+ return False
+ if self.autoscaling != other.autoscaling:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxWarmPoolSpec(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxWarmPoolSpec(
+ replicas=_UniffiFfiConverterUInt32.read(buf),
+ sandbox_template_ref=_UniffiFfiConverterTypeSandboxTemplateRef.read(buf),
+ autoscaling=_UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt32.check_lower(value.replicas)
+ _UniffiFfiConverterTypeSandboxTemplateRef.check_lower(value.sandbox_template_ref)
+ _UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.check_lower(value.autoscaling)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt32.write(value.replicas, buf)
+ _UniffiFfiConverterTypeSandboxTemplateRef.write(value.sandbox_template_ref, buf)
+ _UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.write(value.autoscaling, buf)
+
+@dataclass
+class OsGymSandboxWarmPoolStatus:
+ def __init__(self, *, replicas:typing.Optional[int], ready_replicas:typing.Optional[int], selector:typing.Optional[str]):
+ self.replicas = replicas
+ self.ready_replicas = ready_replicas
+ self.selector = selector
+
+
+
+
+ def __str__(self):
+ return "OsGymSandboxWarmPoolStatus(replicas={}, ready_replicas={}, selector={})".format(self.replicas, self.ready_replicas, self.selector)
+ def __eq__(self, other):
+ if self.replicas != other.replicas:
+ return False
+ if self.ready_replicas != other.ready_replicas:
+ return False
+ if self.selector != other.selector:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymSandboxWarmPoolStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymSandboxWarmPoolStatus(
+ replicas=_UniffiFfiConverterOptionalUInt32.read(buf),
+ ready_replicas=_UniffiFfiConverterOptionalUInt32.read(buf),
+ selector=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.replicas)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.ready_replicas)
+ _UniffiFfiConverterOptionalString.check_lower(value.selector)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalUInt32.write(value.replicas, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.ready_replicas, buf)
+ _UniffiFfiConverterOptionalString.write(value.selector, buf)
+
+@dataclass
+class OsGymWorkspacePoolStatus:
+ def __init__(self, *, phase:typing.Optional[str], total_count:typing.Optional[int], available_count:typing.Optional[int], claimed_count:typing.Optional[int]):
+ self.phase = phase
+ self.total_count = total_count
+ self.available_count = available_count
+ self.claimed_count = claimed_count
+
+
+
+
+ def __str__(self):
+ return "OsGymWorkspacePoolStatus(phase={}, total_count={}, available_count={}, claimed_count={})".format(self.phase, self.total_count, self.available_count, self.claimed_count)
+ def __eq__(self, other):
+ if self.phase != other.phase:
+ return False
+ if self.total_count != other.total_count:
+ return False
+ if self.available_count != other.available_count:
+ return False
+ if self.claimed_count != other.claimed_count:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeOSGymWorkspacePoolStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return OsGymWorkspacePoolStatus(
+ phase=_UniffiFfiConverterOptionalString.read(buf),
+ total_count=_UniffiFfiConverterOptionalUInt32.read(buf),
+ available_count=_UniffiFfiConverterOptionalUInt32.read(buf),
+ claimed_count=_UniffiFfiConverterOptionalUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.phase)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.total_count)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.available_count)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.claimed_count)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.phase, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.total_count, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.available_count, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.claimed_count, buf)
+
+@dataclass
+class PoolTemplate:
+ def __init__(self, *, runtime:typing.Optional[RuntimeKind], runtime_class_name:typing.Optional[str], node_selector:typing.Optional[dict[str, str]], tolerations:typing.Optional[typing.List[PreservedJson]], command:typing.Optional[typing.List[str]], container_disk_image:str, image_pull_secret:typing.Optional[str], cpu_cores:typing.Optional[int], memory:typing.Optional[str], firmware:typing.Optional[Firmware], probes:typing.Optional[PreservedJson], oidc:typing.Optional[OidcConfig]):
+ self.runtime = runtime
+ self.runtime_class_name = runtime_class_name
+ self.node_selector = node_selector
+ self.tolerations = tolerations
+ self.command = command
+ self.container_disk_image = container_disk_image
+ self.image_pull_secret = image_pull_secret
+ self.cpu_cores = cpu_cores
+ self.memory = memory
+ self.firmware = firmware
+ self.probes = probes
+ self.oidc = oidc
+
+
+
+
+ def __str__(self):
+ return "PoolTemplate(runtime={}, runtime_class_name={}, node_selector={}, tolerations={}, command={}, container_disk_image={}, image_pull_secret={}, cpu_cores={}, memory={}, firmware={}, probes={}, oidc={})".format(self.runtime, self.runtime_class_name, self.node_selector, self.tolerations, self.command, self.container_disk_image, self.image_pull_secret, self.cpu_cores, self.memory, self.firmware, self.probes, self.oidc)
+ def __eq__(self, other):
+ if self.runtime != other.runtime:
+ return False
+ if self.runtime_class_name != other.runtime_class_name:
+ return False
+ if self.node_selector != other.node_selector:
+ return False
+ if self.tolerations != other.tolerations:
+ return False
+ if self.command != other.command:
+ return False
+ if self.container_disk_image != other.container_disk_image:
+ return False
+ if self.image_pull_secret != other.image_pull_secret:
+ return False
+ if self.cpu_cores != other.cpu_cores:
+ return False
+ if self.memory != other.memory:
+ return False
+ if self.firmware != other.firmware:
+ return False
+ if self.probes != other.probes:
+ return False
+ if self.oidc != other.oidc:
+ return False
+ return True
+
+class _UniffiFfiConverterTypePoolTemplate(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return PoolTemplate(
+ runtime=_UniffiFfiConverterOptionalTypeRuntimeKind.read(buf),
+ runtime_class_name=_UniffiFfiConverterOptionalString.read(buf),
+ node_selector=_UniffiFfiConverterOptionalMapStringString.read(buf),
+ tolerations=_UniffiFfiConverterOptionalSequenceTypePreservedJson.read(buf),
+ command=_UniffiFfiConverterOptionalSequenceString.read(buf),
+ container_disk_image=_UniffiFfiConverterString.read(buf),
+ image_pull_secret=_UniffiFfiConverterOptionalString.read(buf),
+ cpu_cores=_UniffiFfiConverterOptionalUInt32.read(buf),
+ memory=_UniffiFfiConverterOptionalString.read(buf),
+ firmware=_UniffiFfiConverterOptionalTypeFirmware.read(buf),
+ probes=_UniffiFfiConverterOptionalTypePreservedJson.read(buf),
+ oidc=_UniffiFfiConverterOptionalTypeOidcConfig.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalTypeRuntimeKind.check_lower(value.runtime)
+ _UniffiFfiConverterOptionalString.check_lower(value.runtime_class_name)
+ _UniffiFfiConverterOptionalMapStringString.check_lower(value.node_selector)
+ _UniffiFfiConverterOptionalSequenceTypePreservedJson.check_lower(value.tolerations)
+ _UniffiFfiConverterOptionalSequenceString.check_lower(value.command)
+ _UniffiFfiConverterString.check_lower(value.container_disk_image)
+ _UniffiFfiConverterOptionalString.check_lower(value.image_pull_secret)
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.cpu_cores)
+ _UniffiFfiConverterOptionalString.check_lower(value.memory)
+ _UniffiFfiConverterOptionalTypeFirmware.check_lower(value.firmware)
+ _UniffiFfiConverterOptionalTypePreservedJson.check_lower(value.probes)
+ _UniffiFfiConverterOptionalTypeOidcConfig.check_lower(value.oidc)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalTypeRuntimeKind.write(value.runtime, buf)
+ _UniffiFfiConverterOptionalString.write(value.runtime_class_name, buf)
+ _UniffiFfiConverterOptionalMapStringString.write(value.node_selector, buf)
+ _UniffiFfiConverterOptionalSequenceTypePreservedJson.write(value.tolerations, buf)
+ _UniffiFfiConverterOptionalSequenceString.write(value.command, buf)
+ _UniffiFfiConverterString.write(value.container_disk_image, buf)
+ _UniffiFfiConverterOptionalString.write(value.image_pull_secret, buf)
+ _UniffiFfiConverterOptionalUInt32.write(value.cpu_cores, buf)
+ _UniffiFfiConverterOptionalString.write(value.memory, buf)
+ _UniffiFfiConverterOptionalTypeFirmware.write(value.firmware, buf)
+ _UniffiFfiConverterOptionalTypePreservedJson.write(value.probes, buf)
+ _UniffiFfiConverterOptionalTypeOidcConfig.write(value.oidc, buf)
+
+@dataclass
+class PoolSpec:
+ def __init__(self, *, replicas:int, template:PoolTemplate, autoscaling:typing.Optional[WarmPoolAutoscaling], services:typing.Optional[typing.List[SandboxService]]):
+ self.replicas = replicas
+ self.template = template
+ self.autoscaling = autoscaling
+ self.services = services
+
+ # The Rust `Eq::eq` implementation.
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, PoolSpec):
+ return NotImplemented
+
+
+ _UniffiFfiConverterTypePoolSpec.check_lower(other)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypePoolSpec.lower(self),
+ _UniffiFfiConverterTypePoolSpec.lower(other),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterBoolean.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ # The Rust `Eq::ne` implementation.
+ def __ne__(self, other: object) -> bool:
+ if not isinstance(other, PoolSpec):
+ return NotImplemented
+
+ _UniffiFfiConverterTypePoolSpec.check_lower(other)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypePoolSpec.lower(self),
+ _UniffiFfiConverterTypePoolSpec.lower(other),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterBoolean.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ # The Rust `Hash::hash` implementation.
+ def __hash__(self) -> int:
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypePoolSpec.lower(self),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterUInt64.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+
+
+
+ def __str__(self):
+ return "PoolSpec(replicas={}, template={}, autoscaling={}, services={})".format(self.replicas, self.template, self.autoscaling, self.services)
+
+class _UniffiFfiConverterTypePoolSpec(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return PoolSpec(
+ replicas=_UniffiFfiConverterUInt32.read(buf),
+ template=_UniffiFfiConverterTypePoolTemplate.read(buf),
+ autoscaling=_UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.read(buf),
+ services=_UniffiFfiConverterOptionalSequenceTypeSandboxService.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt32.check_lower(value.replicas)
+ _UniffiFfiConverterTypePoolTemplate.check_lower(value.template)
+ _UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.check_lower(value.autoscaling)
+ _UniffiFfiConverterOptionalSequenceTypeSandboxService.check_lower(value.services)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt32.write(value.replicas, buf)
+ _UniffiFfiConverterTypePoolTemplate.write(value.template, buf)
+ _UniffiFfiConverterOptionalTypeWarmPoolAutoscaling.write(value.autoscaling, buf)
+ _UniffiFfiConverterOptionalSequenceTypeSandboxService.write(value.services, buf)
+
+
+
+# JsonValueError
+# We want to define each variant as a nested class that's also a subclass,
+# which is tricky in Python. To accomplish this we're going to create each
+# class separately, then manually add the child classes to the base class's
+# __dict__. All of this happens in dummy class to avoid polluting the module
+# namespace.
+class JsonValueError(Exception):
+ pass
+
+_UniffiTempJsonValueError = JsonValueError
+
+class JsonValueError: # type: ignore
+
+ class Invalid(_UniffiTempJsonValueError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "JsonValueError.Invalid({})".format(str(self))
+ _UniffiTempJsonValueError.Invalid = Invalid # type: ignore
+
+JsonValueError = _UniffiTempJsonValueError # type: ignore
+del _UniffiTempJsonValueError
+
+
+class _UniffiFfiConverterTypeJsonValueError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return JsonValueError.Invalid(
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, JsonValueError.Invalid):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, JsonValueError.Invalid):
+ buf.write_i32(1)
+ _UniffiFfiConverterString.write(value.reason, buf)
+
+class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u64"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**64
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u64()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u64(value)
+
+__all__ = [
+ "InternalError",
+ "RuntimeKind",
+ "ImagePullPolicy",
+ "Firmware",
+ "ServiceProtocol",
+ "JsonValueError",
+ "ClaimLifecycle",
+ "SandboxTemplateRef",
+ "ClaimSpec",
+ "OsGymSandboxClaimCondition",
+ "OsGymSandboxClaimSandbox",
+ "OsGymSandboxClaimStatus",
+ "SandboxService",
+ "OidcConfig",
+ "VmTemplate",
+ "OsGymSandboxSpec",
+ "OsGymSandboxStatus",
+ "OsGymSandboxTemplateSpec",
+ "WarmPoolAutoscaling",
+ "OsGymSandboxWarmPoolSpec",
+ "OsGymSandboxWarmPoolStatus",
+ "OsGymWorkspacePoolStatus",
+ "PoolTemplate",
+ "PoolSpec",
+ "PreservedJson",
+ "PreservedJsonProtocol",
+]
diff --git a/libs/fleet/sdk-bindings/python/cyclops_sdk/_sdk.py b/libs/fleet/sdk-bindings/python/cyclops_sdk/_sdk.py
new file mode 100644
index 0000000000..90a1e8728c
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/cyclops_sdk/_sdk.py
@@ -0,0 +1,2795 @@
+# This file was autogenerated by some hot garbage in the `uniffi` crate.
+# Trust me, you don't want to mess with it!
+
+# Common helper code.
+#
+# Ideally this would live in a separate .py file where it can be unittested etc
+# in isolation, and perhaps even published as a re-useable package.
+#
+# However, it's important that the details of how this helper code works (e.g. the
+# way that different builtin types are passed across the FFI) exactly match what's
+# expected by the rust code on the other side of the interface. In practice right
+# now that means coming from the exact some version of `uniffi` that was used to
+# compile the rust component. The easiest way to ensure this is to bundle the Python
+# helpers directly inline like we're doing here.
+
+from __future__ import annotations
+import os
+import sys
+import ctypes
+from dataclasses import dataclass
+import enum
+import struct
+import contextlib
+import datetime
+import threading
+import itertools
+import traceback
+import typing
+import asyncio
+import platform
+import cyclops_sdk
+
+
+# Used for default argument values
+_DEFAULT = object() # type: typing.Any
+
+import ctypes
+import struct
+
+class _UniffiRustBuffer(ctypes.Structure):
+ _fields_ = [
+ ("capacity", ctypes.c_uint64),
+ ("len", ctypes.c_uint64),
+ ("data", ctypes.POINTER(ctypes.c_char)),
+ ]
+
+ @staticmethod
+ def default():
+ return _UniffiRustBuffer(0, 0, None)
+
+ @staticmethod
+ def alloc(size):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_rustbuffer_alloc, size)
+
+ @staticmethod
+ def reserve(rbuf, additional):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_rustbuffer_reserve, rbuf, additional)
+
+ def free(self):
+ return _uniffi_rust_call(_UniffiLib.ffi_cyclops_sdk_rustbuffer_free, self)
+
+ def __str__(self):
+ return "_UniffiRustBuffer(capacity={}, len={}, data={})".format(
+ self.capacity,
+ self.len,
+ self.data[0:self.len]
+ )
+
+ @contextlib.contextmanager
+ def alloc_with_builder(*args):
+ """Context-manger to allocate a buffer using a _UniffiRustBufferBuilder.
+
+ The allocated buffer will be automatically freed if an error occurs, ensuring that
+ we don't accidentally leak it.
+ """
+ builder = _UniffiRustBufferBuilder()
+ try:
+ yield builder
+ except:
+ builder.discard()
+ raise
+
+ @contextlib.contextmanager
+ def consume_with_stream(self):
+ """Context-manager to consume a buffer using a _UniffiRustBufferStream.
+
+ The _UniffiRustBuffer will be freed once the context-manager exits, ensuring that we don't
+ leak it even if an error occurs.
+ """
+ try:
+ s = _UniffiRustBufferStream.from_rust_buffer(self)
+ yield s
+ if s.remaining() != 0:
+ raise RuntimeError(f"junk data left in buffer at end of consume_with_stream {s.remaining()}")
+ finally:
+ self.free()
+
+ @contextlib.contextmanager
+ def read_with_stream(self):
+ """Context-manager to read a buffer using a _UniffiRustBufferStream.
+
+ This is like consume_with_stream, but doesn't free the buffer afterwards.
+ It should only be used with borrowed `_UniffiRustBuffer` data.
+ """
+ s = _UniffiRustBufferStream.from_rust_buffer(self)
+ yield s
+ if s.remaining() != 0:
+ raise RuntimeError(f"junk data left in buffer at end of read_with_stream {s.remaining()}")
+
+class _UniffiForeignBytes(ctypes.Structure):
+ _fields_ = [
+ ("len", ctypes.c_int32),
+ ("data", ctypes.POINTER(ctypes.c_char)),
+ ]
+
+ def __str__(self):
+ return "_UniffiForeignBytes(len={}, data={})".format(self.len, self.data[0:self.len])
+
+
+class _UniffiFfiConverterByRefBytes:
+ """Zero-copy converter for `&[u8]` / `[ByRef] bytes` arguments.
+
+ Only `lower` and `check_lower` are valid — zero-copy byte buffers only
+ flow foreign -> Rust, and only in argument position. `lift`, `read`, and
+ `write` have no sound implementation here.
+
+ CPython `bytes` objects are immutable and their internal buffer doesn't
+ move for the lifetime of the object; the caller must keep the source
+ `bytes` alive for the duration of the FFI call.
+ """
+
+ @staticmethod
+ def check_lower(value):
+ # Tighter than `bytes-like`: `lower` uses `ctypes.c_char_p` which only
+ # accepts `bytes`/`None`, so fail fast with a matching check.
+ if not isinstance(value, bytes):
+ raise TypeError("a bytes object is required, not {!r}".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value):
+ fb = _UniffiForeignBytes()
+ if len(value) == 0:
+ fb.len = 0
+ fb.data = None
+ else:
+ fb.len = len(value)
+ fb.data = ctypes.cast(ctypes.c_char_p(value), ctypes.POINTER(ctypes.c_char))
+ return fb
+
+ @staticmethod
+ def lift(value):
+ raise NotImplementedError("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+
+ @staticmethod
+ def read(buf):
+ raise NotImplementedError("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+ @staticmethod
+ def write(value, buf):
+ raise NotImplementedError("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+
+
+class _UniffiRustBufferStream:
+ """
+ Helper for structured reading of bytes from a _UniffiRustBuffer
+ """
+
+ def __init__(self, data, len):
+ self.data = data
+ self.len = len
+ self.offset = 0
+
+ @classmethod
+ def from_rust_buffer(cls, buf):
+ return cls(buf.data, buf.len)
+
+ def remaining(self):
+ return self.len - self.offset
+
+ def _unpack_from(self, size, format):
+ if self.offset + size > self.len:
+ raise InternalError("read past end of rust buffer")
+ value = struct.unpack(format, self.data[self.offset:self.offset+size])[0]
+ self.offset += size
+ return value
+
+ def read(self, size):
+ if self.offset + size > self.len:
+ raise InternalError("read past end of rust buffer")
+ data = self.data[self.offset:self.offset+size]
+ self.offset += size
+ return data
+
+ def read_i8(self):
+ return self._unpack_from(1, ">b")
+
+ def read_u8(self):
+ return self._unpack_from(1, ">B")
+
+ def read_i16(self):
+ return self._unpack_from(2, ">h")
+
+ def read_u16(self):
+ return self._unpack_from(2, ">H")
+
+ def read_i32(self):
+ return self._unpack_from(4, ">i")
+
+ def read_u32(self):
+ return self._unpack_from(4, ">I")
+
+ def read_i64(self):
+ return self._unpack_from(8, ">q")
+
+ def read_u64(self):
+ return self._unpack_from(8, ">Q")
+
+ def read_float(self):
+ v = self._unpack_from(4, ">f")
+ return v
+
+ def read_double(self):
+ return self._unpack_from(8, ">d")
+
+class _UniffiRustBufferBuilder:
+ """
+ Helper for structured writing of bytes into a _UniffiRustBuffer.
+ """
+
+ def __init__(self):
+ self.rbuf = _UniffiRustBuffer.alloc(16)
+ self.rbuf.len = 0
+
+ def finalize(self):
+ rbuf = self.rbuf
+ self.rbuf = None
+ return rbuf
+
+ def discard(self):
+ if self.rbuf is not None:
+ rbuf = self.finalize()
+ rbuf.free()
+
+ @contextlib.contextmanager
+ def _reserve(self, num_bytes):
+ if self.rbuf.len + num_bytes > self.rbuf.capacity:
+ self.rbuf = _UniffiRustBuffer.reserve(self.rbuf, num_bytes)
+ yield None
+ self.rbuf.len += num_bytes
+
+ def _pack_into(self, size, format, value):
+ with self._reserve(size):
+ packed = struct.pack(format, value)
+ if size > 0:
+ ctypes.memmove(ctypes.addressof(self.rbuf.data.contents) + self.rbuf.len, packed, size)
+
+ def write(self, value):
+ length = len(value)
+ with self._reserve(length):
+ if length > 0:
+ ctypes.memmove(ctypes.addressof(self.rbuf.data.contents) + self.rbuf.len, value, length)
+
+ def write_i8(self, v):
+ self._pack_into(1, ">b", v)
+
+ def write_u8(self, v):
+ self._pack_into(1, ">B", v)
+
+ def write_i16(self, v):
+ self._pack_into(2, ">h", v)
+
+ def write_u16(self, v):
+ self._pack_into(2, ">H", v)
+
+ def write_i32(self, v):
+ self._pack_into(4, ">i", v)
+
+ def write_u32(self, v):
+ self._pack_into(4, ">I", v)
+
+ def write_i64(self, v):
+ self._pack_into(8, ">q", v)
+
+ def write_u64(self, v):
+ self._pack_into(8, ">Q", v)
+
+ def write_float(self, v):
+ self._pack_into(4, ">f", v)
+
+ def write_double(self, v):
+ self._pack_into(8, ">d", v)
+
+ def write_c_size_t(self, v):
+ self._pack_into(ctypes.sizeof(ctypes.c_size_t) , "@N", v)
+# A handful of classes and functions to support the generated data structures.
+# This would be a good candidate for isolating in its own ffi-support lib.
+
+class InternalError(Exception):
+ pass
+
+class _UniffiRustCallStatus(ctypes.Structure):
+ """
+ Error runtime.
+ """
+ _fields_ = [
+ ("code", ctypes.c_int8),
+ ("error_buf", _UniffiRustBuffer),
+ ]
+
+ # These match the values from the uniffi::rustcalls module
+ CALL_SUCCESS = 0
+ CALL_ERROR = 1
+ CALL_UNEXPECTED_ERROR = 2
+
+ @staticmethod
+ def default():
+ return _UniffiRustCallStatus(code=_UniffiRustCallStatus.CALL_SUCCESS, error_buf=_UniffiRustBuffer.default())
+
+ def __str__(self):
+ if self.code == _UniffiRustCallStatus.CALL_SUCCESS:
+ return "_UniffiRustCallStatus(CALL_SUCCESS)"
+ elif self.code == _UniffiRustCallStatus.CALL_ERROR:
+ return "_UniffiRustCallStatus(CALL_ERROR)"
+ elif self.code == _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR:
+ return "_UniffiRustCallStatus(CALL_UNEXPECTED_ERROR)"
+ else:
+ return "_UniffiRustCallStatus(<invalid code>)"
+
+def _uniffi_rust_call(fn, *args):
+ # Call a rust function
+ return _uniffi_rust_call_with_error(None, fn, *args)
+
+def _uniffi_rust_call_with_error(error_ffi_converter, fn, *args):
+ # Call a rust function and handle any errors
+ #
+ # This function is used for rust calls that return Result<> and therefore can set the CALL_ERROR status code.
+ # error_ffi_converter must be set to the _UniffiConverter for the error class that corresponds to the result.
+ call_status = _UniffiRustCallStatus.default()
+
+ args_with_error = args + (ctypes.byref(call_status),)
+ result = fn(*args_with_error)
+ _uniffi_check_call_status(error_ffi_converter, call_status)
+ return result
+
+def _uniffi_check_call_status(error_ffi_converter, call_status):
+ if call_status.code == _UniffiRustCallStatus.CALL_SUCCESS:
+ pass
+ elif call_status.code == _UniffiRustCallStatus.CALL_ERROR:
+ if error_ffi_converter is None:
+ call_status.error_buf.free()
+ raise InternalError("_uniffi_rust_call_with_error: CALL_ERROR, but error_ffi_converter is None")
+ else:
+ raise error_ffi_converter.lift(call_status.error_buf)
+ elif call_status.code == _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR:
+ # When the rust code sees a panic, it tries to construct a _UniffiRustBuffer
+ # with the message. But if that code panics, then it just sends back
+ # an empty buffer.
+ if call_status.error_buf.len > 0:
+ msg = _UniffiFfiConverterString.lift(call_status.error_buf)
+ else:
+ msg = "Unknown rust panic"
+ raise InternalError(msg)
+ else:
+ raise InternalError("Invalid _UniffiRustCallStatus code: {}".format(
+ call_status.code))
+
+def _uniffi_trait_interface_call(call_status, make_call, write_return_value):
+ try:
+ return write_return_value(make_call())
+ except Exception as e:
+ call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR
+ call_status.error_buf = _UniffiFfiConverterString.lower(repr(e))
+
+def _uniffi_trait_interface_call_with_error(call_status, make_call, write_return_value, error_type, lower_error):
+ try:
+ try:
+ return write_return_value(make_call())
+ except error_type as e:
+ call_status.code = _UniffiRustCallStatus.CALL_ERROR
+ call_status.error_buf = lower_error(e)
+ except Exception as e:
+ call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR
+ call_status.error_buf = _UniffiFfiConverterString.lower(repr(e))
+# Initial value and increment amount for handles.
+# These ensure that Python-generated handles always have the lowest bit set
+_UNIFFI_HANDLEMAP_INITIAL = 1
+_UNIFFI_HANDLEMAP_DELTA = 2
+
+class _UniffiHandleMap:
+ """
+ A map where inserting, getting and removing data is synchronized with a lock.
+ """
+
+ def __init__(self):
+ # type Handle = int
+ self._map = {} # type: Dict[Handle, Any]
+ self._lock = threading.Lock()
+ self._counter = _UNIFFI_HANDLEMAP_INITIAL
+
+ def insert(self, obj):
+ with self._lock:
+ return self._insert(obj)
+
+ """Low-level insert, this assumes `self._lock` is held."""
+ def _insert(self, obj):
+ handle = self._counter
+ self._counter += _UNIFFI_HANDLEMAP_DELTA
+ self._map[handle] = obj
+ return handle
+
+ def get(self, handle):
+ try:
+ with self._lock:
+ return self._map[handle]
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.get: Invalid handle {handle}")
+
+ def clone(self, handle):
+ try:
+ with self._lock:
+ obj = self._map[handle]
+ return self._insert(obj)
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.clone: Invalid handle {handle}")
+
+ def remove(self, handle):
+ try:
+ with self._lock:
+ return self._map.pop(handle)
+ except KeyError:
+ raise InternalError(f"_UniffiHandleMap.remove: Invalid handle: {handle}")
+
+ def __len__(self):
+ return len(self._map)
+# Types conforming to `_UniffiConverterPrimitive` pass themselves directly over the FFI.
+class _UniffiConverterPrimitive:
+ @classmethod
+ def lift(cls, value):
+ return value
+
+ @classmethod
+ def lower(cls, value):
+ return value
+
+class _UniffiConverterPrimitiveInt(_UniffiConverterPrimitive):
+ @classmethod
+ def check_lower(cls, value):
+ try:
+ value = value.__index__()
+ except Exception:
+ raise TypeError("'{}' object cannot be interpreted as an integer".format(type(value).__name__))
+ if not isinstance(value, int):
+ raise TypeError("__index__ returned non-int (type {})".format(type(value).__name__))
+ if not cls.VALUE_MIN <= value < cls.VALUE_MAX:
+ raise ValueError("{} requires {} <= value < {}".format(cls.CLASS_NAME, cls.VALUE_MIN, cls.VALUE_MAX))
+
+class _UniffiConverterPrimitiveFloat(_UniffiConverterPrimitive):
+ @classmethod
+ def check_lower(cls, value):
+ try:
+ value = value.__float__()
+ except Exception:
+ raise TypeError("must be real number, not {}".format(type(value).__name__))
+ if not isinstance(value, float):
+ raise TypeError("__float__ returned non-float (type {})".format(type(value).__name__))
+
+# Helper class for wrapper types that will always go through a _UniffiRustBuffer.
+# Classes should inherit from this and implement the `read` and `write` static methods.
+class _UniffiConverterRustBuffer:
+ @classmethod
+ def lift(cls, rbuf):
+ with rbuf.consume_with_stream() as stream:
+ return cls.read(stream)
+
+ @classmethod
+ def lower(cls, value):
+ with _UniffiRustBuffer.alloc_with_builder() as builder:
+ cls.write(value, builder)
+ return builder.finalize()
+
+# Contains loading, initialization code, and the FFI Function declarations.
+# Define some ctypes FFI types that we use in the library
+
+"""
+Function pointer for a Rust task, which a callback function that takes a opaque pointer
+"""
+_UNIFFI_RUST_TASK = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int8)
+
+def _uniffi_future_callback_t(return_type):
+ """
+ Factory function to create callback function types for async functions
+ """
+ return ctypes.CFUNCTYPE(None, ctypes.c_uint64, return_type, _UniffiRustCallStatus)
+
+def _uniffi_load_indirect():
+ """
+ This is how we find and load the dynamic library provided by the component.
+ For now we just look it up by name.
+ """
+ if sys.platform == "darwin":
+ libname = "lib{}.dylib"
+ elif sys.platform.startswith("win"):
+ # As of python3.8, ctypes does not seem to search $PATH when loading DLLs.
+ # We could use `os.add_dll_directory` to configure the search path, but
+ # it doesn't feel right to mess with application-wide settings. Let's
+ # assume that the `.dll` is next to the `.py` file and load by full path.
+ libname = os.path.join(
+ os.path.dirname(__file__),
+ "{}.dll",
+ )
+ else:
+ # Anything else must be an ELF platform - Linux, *BSD, Solaris/illumos
+ libname = "lib{}.so"
+
+ libname = libname.format("cyclops_sdk")
+ path = os.path.join(os.path.dirname(__file__), libname)
+ lib = ctypes.cdll.LoadLibrary(path)
+ return lib
+
+def _uniffi_check_contract_api_version(lib):
+ # Get the bindings contract version from our ComponentInterface
+ bindings_contract_version = 30
+ # Get the scaffolding contract version by calling the into the dylib
+ scaffolding_contract_version = lib.ffi_cyclops_sdk_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version:
+ raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+
+def _uniffi_check_api_checksums(lib):
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim() != 51021:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool() != 31472:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() != 50650:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool() != 9252:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() != 55182:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool() != 44001:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 26952:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() != 25465:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() != 4680:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool() != 39705:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 53385:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect() != 48439:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() != 56420:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 11556:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+
+# A ctypes library to expose the extern-C FFI definitions.
+# This is an implementation detail which will be called internally by the public API.
+
+_UniffiLib = _uniffi_load_indirect()
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_alloc.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_alloc.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_from_bytes.argtypes = (
+ _UniffiForeignBytes,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_from_bytes.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_free.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_free.restype = None
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_reserve.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rustbuffer_reserve.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_uniffi_contract_version.argtypes = (
+)
+_UniffiLib.ffi_cyclops_sdk_uniffi_contract_version.restype = ctypes.c_uint32
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_httpclient_execute.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_httpclient_execute.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_httpclient_execute.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_httpclient_execute.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopsclient.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopsclient.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopsclient.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopsclient.restype = None
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopscredentials.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopscredentials.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopscredentials.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopscredentials.restype = None
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_httpclient.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_clone_httpclient.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_free_httpclient.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_free_httpclient.restype = None
+class _UniffiForeignFutureResultRustBuffer(ctypes.Structure):
+ _fields_ = [
+ ("return_value", _UniffiRustBuffer),
+ ("call_status", _UniffiRustCallStatus),
+ ]
+_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureResultRustBuffer,
+)
+_UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
+)
+class _UniffiForeignFutureDroppedCallbackStruct(ctypes.Structure):
+ _fields_ = [
+ ("handle", ctypes.c_uint64),
+ ("free", _UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK),
+ ]
+_UNIFFI_CALLBACK_INTERFACE_CYCLOPS_SDK_HTTP_CLIENT_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+_UNIFFI_CALLBACK_INTERFACE_CLONE_CYCLOPS_SDK_HTTP_CLIENT = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,
+)
+_UNIFFI_CALLBACK_INTERFACE_FREE_CYCLOPS_SDK_HTTP_CLIENT = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
+)
+class _UniffiVTableCallbackInterfaceCyclopsSdkHttpClient(ctypes.Structure):
+ _fields_ = [
+ ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CYCLOPS_SDK_HTTP_CLIENT),
+ ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CYCLOPS_SDK_HTTP_CLIENT),
+ ("execute", _UNIFFI_CALLBACK_INTERFACE_CYCLOPS_SDK_HTTP_CLIENT_METHOD0),
+ ]
+_UniffiLib.uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient.argtypes = (
+ ctypes.POINTER(_UniffiVTableCallbackInterfaceCyclopsSdkHttpClient),
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient.restype = None
+_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK = ctypes.CFUNCTYPE(None,ctypes.c_uint64,ctypes.c_int8,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u8.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u8.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u8.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u8.restype = ctypes.c_uint8
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u8.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i8.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i8.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i8.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i8.restype = ctypes.c_int8
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i8.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i8.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u16.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u16.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u16.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u16.restype = ctypes.c_uint16
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u16.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i16.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i16.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i16.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i16.restype = ctypes.c_int16
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i16.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i16.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u32.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u32.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u32.restype = ctypes.c_uint32
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i32.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i32.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i32.restype = ctypes.c_int32
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u64.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_u64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_u64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u64.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_u64.restype = ctypes.c_uint64
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_u64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i64.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_i64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_i64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i64.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_i64.restype = ctypes.c_int64
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_i64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_f32.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_f32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_f32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_f32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_f32.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_f32.restype = ctypes.c_float
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_f32.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_f32.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_f64.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_f64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_f64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_f64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_f64.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_f64.restype = ctypes.c_double
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_f64.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_f64.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_rust_buffer.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_rust_buffer.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer.restype = _UniffiRustBuffer
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_void.argtypes = (
+ ctypes.c_uint64,
+ _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK,
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_poll_void.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_void.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_cancel_void.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_void.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_complete_void.restype = None
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_void.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.ffi_cyclops_sdk_rust_future_free_void.restype = None
+
+_uniffi_check_contract_api_version(_UniffiLib)
+# _uniffi_check_api_checksums(_UniffiLib)
+
+# RustFuturePoll values
+_UNIFFI_RUST_FUTURE_POLL_READY = 0
+_UNIFFI_RUST_FUTURE_POLL_WAKE = 1
+
+# Stores futures for _uniffi_continuation_callback
+_UniffiContinuationHandleMap = _UniffiHandleMap()
+
+_UNIFFI_GLOBAL_EVENT_LOOP = None
+
+"""
+Set the event loop to use for async functions
+
+This is needed if some async functions run outside of the eventloop, for example:
+ - A non-eventloop thread is spawned, maybe from `EventLoop.run_in_executor` or maybe from the
+ Rust code spawning its own thread.
+ - The Rust code calls an async callback method from a sync callback function, using something
+ like `pollster` to block on the async call.
+
+In this case, we need an event loop to run the Python async function, but there's no eventloop set
+for the thread. Use `uniffi_set_event_loop` to force an eventloop to be used in this case.
+"""
+def uniffi_set_event_loop(eventloop: asyncio.BaseEventLoop):
+ global _UNIFFI_GLOBAL_EVENT_LOOP
+ _UNIFFI_GLOBAL_EVENT_LOOP = eventloop
+
+def _uniffi_get_event_loop():
+ if _UNIFFI_GLOBAL_EVENT_LOOP is not None:
+ return _UNIFFI_GLOBAL_EVENT_LOOP
+ else:
+ return asyncio.get_running_loop()
+
+# Continuation callback for async functions
+# lift the return value or error and resolve the future, causing the async function to resume.
+@_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK
+def _uniffi_continuation_callback(future_ptr, poll_code):
+ (eventloop, future) = _UniffiContinuationHandleMap.remove(future_ptr)
+ eventloop.call_soon_threadsafe(_uniffi_set_future_result, future, poll_code)
+
+def _uniffi_set_future_result(future, poll_code):
+ if not future.cancelled():
+ future.set_result(poll_code)
+
+async def _uniffi_rust_call_async(rust_future, ffi_poll, ffi_complete, ffi_free, lift_func, error_ffi_converter):
+ try:
+ eventloop = _uniffi_get_event_loop()
+
+ # Loop and poll until we see a _UNIFFI_RUST_FUTURE_POLL_READY value
+ while True:
+ future = eventloop.create_future()
+ ffi_poll(
+ rust_future,
+ _uniffi_continuation_callback,
+ _UniffiContinuationHandleMap.insert((eventloop, future)),
+ )
+ poll_code = await future
+ if poll_code == _UNIFFI_RUST_FUTURE_POLL_READY:
+ break
+
+ return lift_func(
+ _uniffi_rust_call_with_error(error_ffi_converter, ffi_complete, rust_future)
+ )
+ finally:
+ ffi_free(rust_future)
+def _uniffi_trait_interface_call_async(make_call, uniffi_out_dropped_callback, handle_success, handle_error):
+ async def make_call_and_call_callback():
+ # Note: it's important we call either `handle_success` or `handle_error` exactly once. Each
+ # call consumes an Arc reference, which means there should be no possibility of a double
+ # call. The following code is structured so that will will never call both `handle_success`
+ # and `handle_error`, even in the face of weird exceptions.
+ #
+ # In extreme circumstances we may not call either, for example if we fail to make the ctypes
+ # call to `handle_success`. This means we will leak the Arc reference, which is better than
+ # double-freeing it.
+ try:
+ call_result = await make_call()
+ except Exception as e:
+ print("UniFFI: Unhandled exception in trait interface call", file=sys.stderr)
+ traceback.print_exc(file=sys.stderr)
+ handle_error(
+ _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR,
+ _UniffiFfiConverterString.lower(repr(e)),
+ )
+ else:
+ handle_success(call_result)
+ eventloop = _uniffi_get_event_loop()
+ task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)
+ handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
+ uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+
+def _uniffi_trait_interface_call_async_with_error(make_call, uniffi_out_dropped_callback, handle_success, handle_error, error_type, lower_error):
+ async def make_call_and_call_callback():
+ # See the note in _uniffi_trait_interface_call_async for details on `handle_success` and
+ # `handle_error`.
+ try:
+ try:
+ call_result = await make_call()
+ except error_type as e:
+ handle_error(
+ _UniffiRustCallStatus.CALL_ERROR,
+ lower_error(e),
+ )
+ else:
+ handle_success(call_result)
+ except Exception as e:
+ print("UniFFI: Unhandled exception in trait interface call", file=sys.stderr)
+ traceback.print_exc(file=sys.stderr)
+ handle_error(
+ _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR,
+ _UniffiFfiConverterString.lower(repr(e)),
+ )
+ eventloop = _uniffi_get_event_loop()
+ task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)
+ handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
+ uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+
+_UNIFFI_FOREIGN_FUTURE_HANDLE_MAP = _UniffiHandleMap()
+
+@_UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK
+def _uniffi_future_dropped_callback(handle):
+ (eventloop, task) = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.remove(handle)
+ eventloop.call_soon(_uniffi_cancel_task, task)
+
+def _uniffi_cancel_task(task):
+ if not task.done():
+ task.cancel()
+
+# Public interface members begin here.
+
+
+class _UniffiFfiConverterString:
+ @staticmethod
+ def check_lower(value):
+ if not isinstance(value, str):
+ raise TypeError("argument must be str, not {}".format(type(value).__name__))
+ return value
+
+ @staticmethod
+ def read(buf):
+ size = buf.read_i32()
+ if size < 0:
+ raise InternalError("Unexpected negative string length")
+ utf8_bytes = buf.read(size)
+ return utf8_bytes.decode("utf-8")
+
+ @staticmethod
+ def write(value, buf):
+ utf8_bytes = value.encode("utf-8")
+ buf.write_i32(len(utf8_bytes))
+ buf.write(utf8_bytes)
+
+ @staticmethod
+ def lift(buf):
+ with buf.consume_with_stream() as stream:
+ return stream.read(stream.remaining()).decode("utf-8")
+
+ @staticmethod
+ def lower(value):
+ with _UniffiRustBuffer.alloc_with_builder() as builder:
+ builder.write(value.encode("utf-8"))
+ return builder.finalize()
+
+class _UniffiFfiConverterMapStringString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, items):
+ for (key, value) in items.items():
+ _UniffiFfiConverterString.check_lower(key)
+ _UniffiFfiConverterString.check_lower(value)
+
+ @classmethod
+ def write(cls, items, buf):
+ buf.write_i32(len(items))
+ for (key, value) in items.items():
+ _UniffiFfiConverterString.write(key, buf)
+ _UniffiFfiConverterString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative map size")
+
+ # It would be nice to use a dict comprehension,
+ # but in Python 3.7 and before the evaluation order is not according to spec,
+ # so we we're reading the value before the key.
+ # This loop makes the order explicit: first reading the key, then the value.
+ d = {}
+ for i in range(count):
+ key = _UniffiFfiConverterString.read(buf)
+ val = _UniffiFfiConverterString.read(buf)
+ d[key] = val
+ return d
+
+class _UniffiFfiConverterOptionalMapStringString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterMapStringString.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterMapStringString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterMapStringString.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class ResourceMetadata:
+ def __init__(self, *, namespace:str, name:str, labels:typing.Optional[dict[str, str]]):
+ self.namespace = namespace
+ self.name = name
+ self.labels = labels
+
+
+
+
+ def __str__(self):
+ return "ResourceMetadata(namespace={}, name={}, labels={})".format(self.namespace, self.name, self.labels)
+ def __eq__(self, other):
+ if self.namespace != other.namespace:
+ return False
+ if self.name != other.name:
+ return False
+ if self.labels != other.labels:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeResourceMetadata(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ResourceMetadata(
+ namespace=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ labels=_UniffiFfiConverterOptionalMapStringString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.namespace)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterOptionalMapStringString.check_lower(value.labels)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.namespace, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterOptionalMapStringString.write(value.labels, buf)
+
+
+
+
+
+class _UniffiFfiConverterOptionalTypeOSGymSandboxClaimStatus(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ cyclops_sdk._UniffiFfiConverterTypeOSGymSandboxClaimStatus.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ cyclops_sdk._UniffiFfiConverterTypeOSGymSandboxClaimStatus.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return cyclops_sdk._UniffiFfiConverterTypeOSGymSandboxClaimStatus.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class Claim:
+ def __init__(self, *, api_version:str, kind:str, metadata:ResourceMetadata, spec:cyclops_sdk.ClaimSpec, status:typing.Optional[cyclops_sdk.OsGymSandboxClaimStatus]):
+ self.api_version = api_version
+ self.kind = kind
+ self.metadata = metadata
+ self.spec = spec
+ self.status = status
+
+
+
+
+ def __str__(self):
+ return "Claim(api_version={}, kind={}, metadata={}, spec={}, status={})".format(self.api_version, self.kind, self.metadata, self.spec, self.status)
+ def __eq__(self, other):
+ if self.api_version != other.api_version:
+ return False
+ if self.kind != other.kind:
+ return False
+ if self.metadata != other.metadata:
+ return False
+ if self.spec != other.spec:
+ return False
+ if self.status != other.status:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeClaim(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return Claim(
+ api_version=_UniffiFfiConverterString.read(buf),
+ kind=_UniffiFfiConverterString.read(buf),
+ metadata=_UniffiFfiConverterTypeResourceMetadata.read(buf),
+ spec=cyclops_sdk._UniffiFfiConverterTypeClaimSpec.read(buf),
+ status=_UniffiFfiConverterOptionalTypeOSGymSandboxClaimStatus.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.api_version)
+ _UniffiFfiConverterString.check_lower(value.kind)
+ _UniffiFfiConverterTypeResourceMetadata.check_lower(value.metadata)
+ cyclops_sdk._UniffiFfiConverterTypeClaimSpec.check_lower(value.spec)
+ _UniffiFfiConverterOptionalTypeOSGymSandboxClaimStatus.check_lower(value.status)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.api_version, buf)
+ _UniffiFfiConverterString.write(value.kind, buf)
+ _UniffiFfiConverterTypeResourceMetadata.write(value.metadata, buf)
+ cyclops_sdk._UniffiFfiConverterTypeClaimSpec.write(value.spec, buf)
+ _UniffiFfiConverterOptionalTypeOSGymSandboxClaimStatus.write(value.status, buf)
+
+
+
+
+
+class _UniffiFfiConverterOptionalTypeOSGymWorkspacePoolStatus(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ cyclops_sdk._UniffiFfiConverterTypeOSGymWorkspacePoolStatus.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ cyclops_sdk._UniffiFfiConverterTypeOSGymWorkspacePoolStatus.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return cyclops_sdk._UniffiFfiConverterTypeOSGymWorkspacePoolStatus.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class Pool:
+ """
+ UniFFI cannot emit aliases for external record types. Generated bindings use
+ `OSGymWorkspacePoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
+"""
+ def __init__(self, *, api_version:str, kind:str, metadata:ResourceMetadata, spec:cyclops_sdk.PoolSpec, status:typing.Optional[cyclops_sdk.OsGymWorkspacePoolStatus]):
+ self.api_version = api_version
+ self.kind = kind
+ self.metadata = metadata
+ self.spec = spec
+ self.status = status
+
+
+
+
+ def __str__(self):
+ return "Pool(api_version={}, kind={}, metadata={}, spec={}, status={})".format(self.api_version, self.kind, self.metadata, self.spec, self.status)
+ def __eq__(self, other):
+ if self.api_version != other.api_version:
+ return False
+ if self.kind != other.kind:
+ return False
+ if self.metadata != other.metadata:
+ return False
+ if self.spec != other.spec:
+ return False
+ if self.status != other.status:
+ return False
+ return True
+
+class _UniffiFfiConverterTypePool(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return Pool(
+ api_version=_UniffiFfiConverterString.read(buf),
+ kind=_UniffiFfiConverterString.read(buf),
+ metadata=_UniffiFfiConverterTypeResourceMetadata.read(buf),
+ spec=cyclops_sdk._UniffiFfiConverterTypePoolSpec.read(buf),
+ status=_UniffiFfiConverterOptionalTypeOSGymWorkspacePoolStatus.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.api_version)
+ _UniffiFfiConverterString.check_lower(value.kind)
+ _UniffiFfiConverterTypeResourceMetadata.check_lower(value.metadata)
+ cyclops_sdk._UniffiFfiConverterTypePoolSpec.check_lower(value.spec)
+ _UniffiFfiConverterOptionalTypeOSGymWorkspacePoolStatus.check_lower(value.status)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.api_version, buf)
+ _UniffiFfiConverterString.write(value.kind, buf)
+ _UniffiFfiConverterTypeResourceMetadata.write(value.metadata, buf)
+ cyclops_sdk._UniffiFfiConverterTypePoolSpec.write(value.spec, buf)
+ _UniffiFfiConverterOptionalTypeOSGymWorkspacePoolStatus.write(value.status, buf)
+
+class _UniffiFfiConverterOptionalTypeClaimSpec(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ cyclops_sdk._UniffiFfiConverterTypeClaimSpec.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ cyclops_sdk._UniffiFfiConverterTypeClaimSpec.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return cyclops_sdk._UniffiFfiConverterTypeClaimSpec.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class CreateClaimRequest:
+ def __init__(self, *, pool:Pool, spec:typing.Optional[cyclops_sdk.ClaimSpec]):
+ self.pool = pool
+ self.spec = spec
+
+
+
+
+ def __str__(self):
+ return "CreateClaimRequest(pool={}, spec={})".format(self.pool, self.spec)
+ def __eq__(self, other):
+ if self.pool != other.pool:
+ return False
+ if self.spec != other.spec:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeCreateClaimRequest(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return CreateClaimRequest(
+ pool=_UniffiFfiConverterTypePool.read(buf),
+ spec=_UniffiFfiConverterOptionalTypeClaimSpec.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypePool.check_lower(value.pool)
+ _UniffiFfiConverterOptionalTypeClaimSpec.check_lower(value.spec)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypePool.write(value.pool, buf)
+ _UniffiFfiConverterOptionalTypeClaimSpec.write(value.spec, buf)
+
+@dataclass
+class CreatePoolRequest:
+ def __init__(self, *, namespace:str, spec:cyclops_sdk.PoolSpec):
+ self.namespace = namespace
+ self.spec = spec
+
+
+
+
+ def __str__(self):
+ return "CreatePoolRequest(namespace={}, spec={})".format(self.namespace, self.spec)
+ def __eq__(self, other):
+ if self.namespace != other.namespace:
+ return False
+ if self.spec != other.spec:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeCreatePoolRequest(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return CreatePoolRequest(
+ namespace=_UniffiFfiConverterString.read(buf),
+ spec=cyclops_sdk._UniffiFfiConverterTypePoolSpec.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.namespace)
+ cyclops_sdk._UniffiFfiConverterTypePoolSpec.check_lower(value.spec)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.namespace, buf)
+ cyclops_sdk._UniffiFfiConverterTypePoolSpec.write(value.spec, buf)
+
+
+class CyclopsCredentialsProtocol(typing.Protocol):
+
+ pass
+
+class CyclopsCredentials(CyclopsCredentialsProtocol):
+
+ _handle: ctypes.c_uint64
+ def __init__(self, client_id: str,client_secret: str):
+
+ _UniffiFfiConverterString.check_lower(client_id)
+
+ _UniffiFfiConverterString.check_lower(client_secret)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterString.lower(client_id),
+ _UniffiFfiConverterString.lower(client_secret),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCyclopsCredentials.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new,
+ *_uniffi_lowered_args,
+ )
+ self._handle = _uniffi_ffi_result
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopscredentials, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopscredentials, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+
+
+
+
+
+class _UniffiFfiConverterTypeCyclopsCredentials:
+ @staticmethod
+ def lift(value: int) -> CyclopsCredentials:
+ return CyclopsCredentials._uniffi_make_instance(value)
+
+ @staticmethod
+ def check_lower(value: CyclopsCredentials):
+ if not isinstance(value, CyclopsCredentials):
+ raise TypeError("Expected CyclopsCredentials instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: CyclopsCredentials) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> CyclopsCredentials:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: CyclopsCredentials, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u64"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**64
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u64()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u64(value)
+
+class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u32"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**32
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u32()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u32(value)
+
+@dataclass
+class CyclopsConfiguration:
+ def __init__(self, *, base_url:str, token_url:str, credentials:CyclopsCredentials, pool_poll_interval_ms:int, pool_poll_limit:int, claim_poll_interval_ms:int, claim_poll_limit:int):
+ self.base_url = base_url
+ self.token_url = token_url
+ self.credentials = credentials
+ self.pool_poll_interval_ms = pool_poll_interval_ms
+ self.pool_poll_limit = pool_poll_limit
+ self.claim_poll_interval_ms = claim_poll_interval_ms
+ self.claim_poll_limit = claim_poll_limit
+
+
+
+
+ def __str__(self):
+ return "CyclopsConfiguration(base_url={}, token_url={}, credentials={}, pool_poll_interval_ms={}, pool_poll_limit={}, claim_poll_interval_ms={}, claim_poll_limit={})".format(self.base_url, self.token_url, self.credentials, self.pool_poll_interval_ms, self.pool_poll_limit, self.claim_poll_interval_ms, self.claim_poll_limit)
+ def __eq__(self, other):
+ if self.base_url != other.base_url:
+ return False
+ if self.token_url != other.token_url:
+ return False
+ if self.credentials != other.credentials:
+ return False
+ if self.pool_poll_interval_ms != other.pool_poll_interval_ms:
+ return False
+ if self.pool_poll_limit != other.pool_poll_limit:
+ return False
+ if self.claim_poll_interval_ms != other.claim_poll_interval_ms:
+ return False
+ if self.claim_poll_limit != other.claim_poll_limit:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeCyclopsConfiguration(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return CyclopsConfiguration(
+ base_url=_UniffiFfiConverterString.read(buf),
+ token_url=_UniffiFfiConverterString.read(buf),
+ credentials=_UniffiFfiConverterTypeCyclopsCredentials.read(buf),
+ pool_poll_interval_ms=_UniffiFfiConverterUInt64.read(buf),
+ pool_poll_limit=_UniffiFfiConverterUInt32.read(buf),
+ claim_poll_interval_ms=_UniffiFfiConverterUInt64.read(buf),
+ claim_poll_limit=_UniffiFfiConverterUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.base_url)
+ _UniffiFfiConverterString.check_lower(value.token_url)
+ _UniffiFfiConverterTypeCyclopsCredentials.check_lower(value.credentials)
+ _UniffiFfiConverterUInt64.check_lower(value.pool_poll_interval_ms)
+ _UniffiFfiConverterUInt32.check_lower(value.pool_poll_limit)
+ _UniffiFfiConverterUInt64.check_lower(value.claim_poll_interval_ms)
+ _UniffiFfiConverterUInt32.check_lower(value.claim_poll_limit)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.base_url, buf)
+ _UniffiFfiConverterString.write(value.token_url, buf)
+ _UniffiFfiConverterTypeCyclopsCredentials.write(value.credentials, buf)
+ _UniffiFfiConverterUInt64.write(value.pool_poll_interval_ms, buf)
+ _UniffiFfiConverterUInt32.write(value.pool_poll_limit, buf)
+ _UniffiFfiConverterUInt64.write(value.claim_poll_interval_ms, buf)
+ _UniffiFfiConverterUInt32.write(value.claim_poll_limit, buf)
+
+@dataclass
+class HttpHeader:
+ def __init__(self, *, name:str, value:str):
+ self.name = name
+ self.value = value
+
+
+
+
+ def __str__(self):
+ return "HttpHeader(name={}, value={})".format(self.name, self.value)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.value != other.value:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeHttpHeader(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return HttpHeader(
+ name=_UniffiFfiConverterString.read(buf),
+ value=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.value)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.value, buf)
+
+class _UniffiFfiConverterSequenceTypeHttpHeader(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeHttpHeader.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeHttpHeader.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeHttpHeader.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterBytes(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ size = buf.read_i32()
+ if size < 0:
+ raise InternalError("Unexpected negative byte string length")
+ return buf.read(size)
+
+ @staticmethod
+ def check_lower(value):
+ try:
+ memoryview(value)
+ except TypeError:
+ raise TypeError("a bytes-like object is required, not {!r}".format(type(value).__name__))
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_i32(len(value))
+ buf.write(value)
+
+class _UniffiFfiConverterOptionalBytes(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterBytes.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterBytes.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterBytes.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class HttpRequest:
+ def __init__(self, *, method:str, url:str, headers:typing.List[HttpHeader], body:typing.Optional[bytes]):
+ self.method = method
+ self.url = url
+ self.headers = headers
+ self.body = body
+
+
+
+
+ def __str__(self):
+ return "HttpRequest(method={}, url={}, headers={}, body={})".format(self.method, self.url, self.headers, self.body)
+ def __eq__(self, other):
+ if self.method != other.method:
+ return False
+ if self.url != other.url:
+ return False
+ if self.headers != other.headers:
+ return False
+ if self.body != other.body:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeHttpRequest(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return HttpRequest(
+ method=_UniffiFfiConverterString.read(buf),
+ url=_UniffiFfiConverterString.read(buf),
+ headers=_UniffiFfiConverterSequenceTypeHttpHeader.read(buf),
+ body=_UniffiFfiConverterOptionalBytes.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.method)
+ _UniffiFfiConverterString.check_lower(value.url)
+ _UniffiFfiConverterSequenceTypeHttpHeader.check_lower(value.headers)
+ _UniffiFfiConverterOptionalBytes.check_lower(value.body)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.method, buf)
+ _UniffiFfiConverterString.write(value.url, buf)
+ _UniffiFfiConverterSequenceTypeHttpHeader.write(value.headers, buf)
+ _UniffiFfiConverterOptionalBytes.write(value.body, buf)
+
+class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u16"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**16
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u16()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u16(value)
+
+@dataclass
+class HttpResponse:
+ def __init__(self, *, status:int, headers:typing.List[HttpHeader], body:bytes):
+ self.status = status
+ self.headers = headers
+ self.body = body
+
+
+
+
+ def __str__(self):
+ return "HttpResponse(status={}, headers={}, body={})".format(self.status, self.headers, self.body)
+ def __eq__(self, other):
+ if self.status != other.status:
+ return False
+ if self.headers != other.headers:
+ return False
+ if self.body != other.body:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeHttpResponse(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return HttpResponse(
+ status=_UniffiFfiConverterUInt16.read(buf),
+ headers=_UniffiFfiConverterSequenceTypeHttpHeader.read(buf),
+ body=_UniffiFfiConverterBytes.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt16.check_lower(value.status)
+ _UniffiFfiConverterSequenceTypeHttpHeader.check_lower(value.headers)
+ _UniffiFfiConverterBytes.check_lower(value.body)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt16.write(value.status, buf)
+ _UniffiFfiConverterSequenceTypeHttpHeader.write(value.headers, buf)
+ _UniffiFfiConverterBytes.write(value.body, buf)
+
+class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterString.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterString.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterString.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class Sandbox:
+ def __init__(self, *, namespace:str, claim:str, name:str, services:typing.List[str]):
+ self.namespace = namespace
+ self.claim = claim
+ self.name = name
+ self.services = services
+
+
+
+
+ def __str__(self):
+ return "Sandbox(namespace={}, claim={}, name={}, services={})".format(self.namespace, self.claim, self.name, self.services)
+ def __eq__(self, other):
+ if self.namespace != other.namespace:
+ return False
+ if self.claim != other.claim:
+ return False
+ if self.name != other.name:
+ return False
+ if self.services != other.services:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSandbox(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return Sandbox(
+ namespace=_UniffiFfiConverterString.read(buf),
+ claim=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ services=_UniffiFfiConverterSequenceString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.namespace)
+ _UniffiFfiConverterString.check_lower(value.claim)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterSequenceString.check_lower(value.services)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.namespace, buf)
+ _UniffiFfiConverterString.write(value.claim, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterSequenceString.write(value.services, buf)
+
+
+
+# HttpError
+# We want to define each variant as a nested class that's also a subclass,
+# which is tricky in Python. To accomplish this we're going to create each
+# class separately, then manually add the child classes to the base class's
+# __dict__. All of this happens in dummy class to avoid polluting the module
+# namespace.
+class HttpError(Exception):
+ pass
+
+_UniffiTempHttpError = HttpError
+
+class HttpError: # type: ignore
+
+ class Transport(_UniffiTempHttpError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "HttpError.Transport({})".format(str(self))
+ _UniffiTempHttpError.Transport = Transport # type: ignore
+
+HttpError = _UniffiTempHttpError # type: ignore
+del _UniffiTempHttpError
+
+
+class _UniffiFfiConverterTypeHttpError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return HttpError.Transport(
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, HttpError.Transport):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, HttpError.Transport):
+ buf.write_i32(1)
+ _UniffiFfiConverterString.write(value.reason, buf)
+
+
+
+# SdkError
+# We want to define each variant as a nested class that's also a subclass,
+# which is tricky in Python. To accomplish this we're going to create each
+# class separately, then manually add the child classes to the base class's
+# __dict__. All of this happens in dummy class to avoid polluting the module
+# namespace.
+class SdkError(Exception):
+ pass
+
+_UniffiTempSdkError = SdkError
+
+class SdkError: # type: ignore
+
+ class Configuration(_UniffiTempSdkError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "SdkError.Configuration({})".format(str(self))
+ _UniffiTempSdkError.Configuration = Configuration # type: ignore
+ class InvalidResourceName(_UniffiTempSdkError):
+
+ def __init__(self, field, value, reason):
+ super().__init__(", ".join([
+ "field={!r}".format(field),
+ "value={!r}".format(value),
+ "reason={!r}".format(reason),
+ ]))
+ self.field = field
+ self.value = value
+ self.reason = reason
+
+ def __repr__(self):
+ return "SdkError.InvalidResourceName({})".format(str(self))
+ _UniffiTempSdkError.InvalidResourceName = InvalidResourceName # type: ignore
+ class Transport(_UniffiTempSdkError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "SdkError.Transport({})".format(str(self))
+ _UniffiTempSdkError.Transport = Transport # type: ignore
+ class Token(_UniffiTempSdkError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "SdkError.Token({})".format(str(self))
+ _UniffiTempSdkError.Token = Token # type: ignore
+ class Body(_UniffiTempSdkError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "SdkError.Body({})".format(str(self))
+ _UniffiTempSdkError.Body = Body # type: ignore
+ class Status(_UniffiTempSdkError):
+
+ def __init__(self, operation, status, body):
+ super().__init__(", ".join([
+ "operation={!r}".format(operation),
+ "status={!r}".format(status),
+ "body={!r}".format(body),
+ ]))
+ self.operation = operation
+ self.status = status
+ self.body = body
+
+ def __repr__(self):
+ return "SdkError.Status({})".format(str(self))
+ _UniffiTempSdkError.Status = Status # type: ignore
+ class UnknownService(_UniffiTempSdkError):
+
+ def __init__(self, requested, available):
+ super().__init__(", ".join([
+ "requested={!r}".format(requested),
+ "available={!r}".format(available),
+ ]))
+ self.requested = requested
+ self.available = available
+
+ def __repr__(self):
+ return "SdkError.UnknownService({})".format(str(self))
+ _UniffiTempSdkError.UnknownService = UnknownService # type: ignore
+ class InvalidServicePath(_UniffiTempSdkError):
+
+ def __init__(self, path):
+ super().__init__(", ".join([
+ "path={!r}".format(path),
+ ]))
+ self.path = path
+
+ def __repr__(self):
+ return "SdkError.InvalidServicePath({})".format(str(self))
+ _UniffiTempSdkError.InvalidServicePath = InvalidServicePath # type: ignore
+ class ClaimFailed(_UniffiTempSdkError):
+
+ def __init__(self, phase, status):
+ super().__init__(", ".join([
+ "phase={!r}".format(phase),
+ "status={!r}".format(status),
+ ]))
+ self.phase = phase
+ self.status = status
+
+ def __repr__(self):
+ return "SdkError.ClaimFailed({})".format(str(self))
+ _UniffiTempSdkError.ClaimFailed = ClaimFailed # type: ignore
+ class ClaimTimeout(_UniffiTempSdkError):
+
+ def __init__(self):
+ pass
+
+ def __repr__(self):
+ return "SdkError.ClaimTimeout({})".format(str(self))
+ _UniffiTempSdkError.ClaimTimeout = ClaimTimeout # type: ignore
+
+SdkError = _UniffiTempSdkError # type: ignore
+del _UniffiTempSdkError
+
+
+class _UniffiFfiConverterTypeSdkError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return SdkError.Configuration(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 2:
+ return SdkError.InvalidResourceName(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 3:
+ return SdkError.Transport(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 4:
+ return SdkError.Token(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 5:
+ return SdkError.Body(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 6:
+ return SdkError.Status(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterUInt16.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 7:
+ return SdkError.UnknownService(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterSequenceString.read(buf),
+ )
+ if variant == 8:
+ return SdkError.InvalidServicePath(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 9:
+ return SdkError.ClaimFailed(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 10:
+ return SdkError.ClaimTimeout(
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, SdkError.Configuration):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, SdkError.InvalidResourceName):
+ _UniffiFfiConverterString.check_lower(value.field)
+ _UniffiFfiConverterString.check_lower(value.value)
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, SdkError.Transport):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, SdkError.Token):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, SdkError.Body):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, SdkError.Status):
+ _UniffiFfiConverterString.check_lower(value.operation)
+ _UniffiFfiConverterUInt16.check_lower(value.status)
+ _UniffiFfiConverterString.check_lower(value.body)
+ return
+ if isinstance(value, SdkError.UnknownService):
+ _UniffiFfiConverterString.check_lower(value.requested)
+ _UniffiFfiConverterSequenceString.check_lower(value.available)
+ return
+ if isinstance(value, SdkError.InvalidServicePath):
+ _UniffiFfiConverterString.check_lower(value.path)
+ return
+ if isinstance(value, SdkError.ClaimFailed):
+ _UniffiFfiConverterString.check_lower(value.phase)
+ _UniffiFfiConverterString.check_lower(value.status)
+ return
+ if isinstance(value, SdkError.ClaimTimeout):
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, SdkError.Configuration):
+ buf.write_i32(1)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, SdkError.InvalidResourceName):
+ buf.write_i32(2)
+ _UniffiFfiConverterString.write(value.field, buf)
+ _UniffiFfiConverterString.write(value.value, buf)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, SdkError.Transport):
+ buf.write_i32(3)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, SdkError.Token):
+ buf.write_i32(4)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, SdkError.Body):
+ buf.write_i32(5)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, SdkError.Status):
+ buf.write_i32(6)
+ _UniffiFfiConverterString.write(value.operation, buf)
+ _UniffiFfiConverterUInt16.write(value.status, buf)
+ _UniffiFfiConverterString.write(value.body, buf)
+ if isinstance(value, SdkError.UnknownService):
+ buf.write_i32(7)
+ _UniffiFfiConverterString.write(value.requested, buf)
+ _UniffiFfiConverterSequenceString.write(value.available, buf)
+ if isinstance(value, SdkError.InvalidServicePath):
+ buf.write_i32(8)
+ _UniffiFfiConverterString.write(value.path, buf)
+ if isinstance(value, SdkError.ClaimFailed):
+ buf.write_i32(9)
+ _UniffiFfiConverterString.write(value.phase, buf)
+ _UniffiFfiConverterString.write(value.status, buf)
+ if isinstance(value, SdkError.ClaimTimeout):
+ buf.write_i32(10)
+
+class _UniffiFfiConverterSequenceTypeClaim(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeClaim.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeClaim.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeClaim.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterSequenceTypePool(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypePool.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypePool.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypePool.read(buf) for i in range(count)
+ ]
+
+
+class CyclopsClientProtocol(typing.Protocol):
+
+ async def create_claim(self, request: CreateClaimRequest) -> Claim:
+ raise NotImplementedError
+ async def create_pool(self, request: CreatePoolRequest) -> Pool:
+ raise NotImplementedError
+ async def delete_claim(self, claim: Claim) -> None:
+ raise NotImplementedError
+ async def delete_pool(self, pool: Pool) -> None:
+ raise NotImplementedError
+ async def get_claim(self, claim: Claim) -> Claim:
+ raise NotImplementedError
+ async def get_pool(self, pool: Pool) -> Pool:
+ raise NotImplementedError
+ async def list_claims(self, namespace: str) -> typing.List[Claim]:
+ raise NotImplementedError
+ async def list_pools(self, namespace: str) -> typing.List[Pool]:
+ raise NotImplementedError
+ async def service_request(self, sandbox: Sandbox,service: str,path: str,request: HttpRequest) -> HttpResponse:
+ raise NotImplementedError
+ async def update_pool(self, pool: Pool) -> Pool:
+ raise NotImplementedError
+ async def wait_claim(self, claim: Claim) -> Sandbox:
+ raise NotImplementedError
+
+class CyclopsClient(CyclopsClientProtocol):
+
+ _handle: ctypes.c_uint64
+ @classmethod
+ def connect(cls, configuration: CyclopsConfiguration,http_client: HttpClient) -> CyclopsClient:
+
+ _UniffiFfiConverterTypeCyclopsConfiguration.check_lower(configuration)
+
+ _UniffiFfiConverterTypeHttpClient.check_lower(http_client)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeCyclopsConfiguration.lower(configuration),
+ _UniffiFfiConverterTypeHttpClient.lower(http_client),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCyclopsClient.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_free_cyclopsclient, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_clone_cyclopsclient, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ async def create_claim(self, request: CreateClaimRequest) -> Claim:
+
+ _UniffiFfiConverterTypeCreateClaimRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeCreateClaimRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeClaim.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def create_pool(self, request: CreatePoolRequest) -> Pool:
+
+ _UniffiFfiConverterTypeCreatePoolRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeCreatePoolRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypePool.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def delete_claim(self, claim: Claim) -> None:
+
+ _UniffiFfiConverterTypeClaim.check_lower(claim)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeClaim.lower(claim),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def delete_pool(self, pool: Pool) -> None:
+
+ _UniffiFfiConverterTypePool.check_lower(pool)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypePool.lower(pool),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_claim(self, claim: Claim) -> Claim:
+
+ _UniffiFfiConverterTypeClaim.check_lower(claim)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeClaim.lower(claim),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeClaim.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_pool(self, pool: Pool) -> Pool:
+
+ _UniffiFfiConverterTypePool.check_lower(pool)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypePool.lower(pool),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypePool.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def list_claims(self, namespace: str) -> typing.List[Claim]:
+
+ _UniffiFfiConverterString.check_lower(namespace)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(namespace),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeClaim.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def list_pools(self, namespace: str) -> typing.List[Pool]:
+
+ _UniffiFfiConverterString.check_lower(namespace)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(namespace),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypePool.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def service_request(self, sandbox: Sandbox,service: str,path: str,request: HttpRequest) -> HttpResponse:
+
+ _UniffiFfiConverterTypeSandbox.check_lower(sandbox)
+
+ _UniffiFfiConverterString.check_lower(service)
+
+ _UniffiFfiConverterString.check_lower(path)
+
+ _UniffiFfiConverterTypeHttpRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeSandbox.lower(sandbox),
+ _UniffiFfiConverterString.lower(service),
+ _UniffiFfiConverterString.lower(path),
+ _UniffiFfiConverterTypeHttpRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeHttpResponse.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def update_pool(self, pool: Pool) -> Pool:
+
+ _UniffiFfiConverterTypePool.check_lower(pool)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypePool.lower(pool),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypePool.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def wait_claim(self, claim: Claim) -> Sandbox:
+
+ _UniffiFfiConverterTypeClaim.check_lower(claim)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeClaim.lower(claim),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSandbox.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+
+
+
+
+
+class _UniffiFfiConverterTypeCyclopsClient:
+ @staticmethod
+ def lift(value: int) -> CyclopsClient:
+ return CyclopsClient._uniffi_make_instance(value)
+
+ @staticmethod
+ def check_lower(value: CyclopsClient):
+ if not isinstance(value, CyclopsClient):
+ raise TypeError("Expected CyclopsClient instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: CyclopsClient) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> CyclopsClient:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: CyclopsClient, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+
+class HttpClient():
+
+ async def execute(self, request: HttpRequest) -> HttpResponse:
+ raise NotImplementedError
+
+class HttpClientImpl(HttpClient):
+
+ _handle: ctypes.c_uint64
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_free_httpclient, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cyclops_sdk_fn_clone_httpclient, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ async def execute(self, request: HttpRequest) -> HttpResponse:
+
+ _UniffiFfiConverterTypeHttpRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeHttpRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeHttpResponse.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeHttpError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_httpclient_execute(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+
+
+
+
+# Put all the bits inside a class to keep the top-level namespace clean
+class _UniffiTraitImplHttpClientImpl:
+ # For each method, generate a callback function to pass to Rust
+
+ @_UNIFFI_CALLBACK_INTERFACE_CYCLOPS_SDK_HTTP_CLIENT_METHOD0
+ def execute(
+ uniffi_handle,
+ request,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeHttpClient._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterTypeHttpRequest.lift(request), )
+ uniffi_method = uniffi_obj.execute
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiFfiConverterTypeHttpResponse.lower(return_value),
+ _UniffiRustCallStatus.default()
+ )
+ )
+
+ def handle_error(status_code, rust_buffer):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiRustBuffer.default(),
+ _UniffiRustCallStatus(status_code, rust_buffer),
+ )
+ )
+ _uniffi_trait_interface_call_async_with_error(
+ make_call,
+ uniffi_out_dropped_callback,
+ handle_success,
+ handle_error,
+ HttpError,
+ _UniffiFfiConverterTypeHttpError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_FREE_CYCLOPS_SDK_HTTP_CLIENT
+ def _uniffi_free(uniffi_handle):
+ _UniffiFfiConverterTypeHttpClient._handle_map.remove(uniffi_handle)
+
+ @_UNIFFI_CALLBACK_INTERFACE_CLONE_CYCLOPS_SDK_HTTP_CLIENT
+ def _uniffi_clone(uniffi_handle):
+ return _UniffiFfiConverterTypeHttpClient._handle_map.clone(uniffi_handle)
+
+ # Generate the FFI VTable. This has a field for each callback interface method.
+ _uniffi_vtable = _UniffiVTableCallbackInterfaceCyclopsSdkHttpClient(
+ _uniffi_free,
+ _uniffi_clone,
+ execute,
+ )
+ # Send Rust a pointer to the VTable. Note: this means we need to keep the struct alive forever,
+ # or else bad things will happen when Rust tries to access it.
+ _UniffiLib.uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(ctypes.byref(_uniffi_vtable))
+
+class _UniffiFfiConverterTypeHttpClient:
+ _handle_map = _UniffiHandleMap()
+
+ @staticmethod
+ def lift(value: int):
+ if (value & 1) == 0:
+ # Rust-generated handle, construct a new class that uses the handle to implement the
+ # interface
+ return HttpClientImpl._uniffi_make_instance(value)
+ else:
+ # Python-generated handle, get the object from the handle map
+ return _UniffiFfiConverterTypeHttpClient._handle_map.remove(value)
+
+ @staticmethod
+ def check_lower(value: HttpClient):
+ if not isinstance(value, HttpClient):
+ raise TypeError("Expected HttpClient subclass, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: HttpClient):
+ if isinstance(value, HttpClientImpl):
+ # Rust-implementated object. Clone the handle and return it
+ return value._uniffi_clone_handle()
+ else:
+ # Python-implementated object, generate a new vtable handle and return that.
+ return _UniffiFfiConverterTypeHttpClient._handle_map.insert(value)
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer):
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: HttpClient, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+__all__ = [
+ "InternalError",
+ "HttpError",
+ "SdkError",
+ "ResourceMetadata",
+ "Claim",
+ "Pool",
+ "CreateClaimRequest",
+ "CreatePoolRequest",
+ "CyclopsConfiguration",
+ "HttpHeader",
+ "HttpRequest",
+ "HttpResponse",
+ "Sandbox",
+ "CyclopsCredentials",
+ "CyclopsCredentialsProtocol",
+ "CyclopsClient",
+ "CyclopsClientProtocol",
+ "HttpClientImpl",
+ "HttpClient",
+]
diff --git a/libs/fleet/sdk-bindings/python/cyclops_sdk/generated_crd.py b/libs/fleet/sdk-bindings/python/cyclops_sdk/generated_crd.py
deleted file mode 100644
index c928464606..0000000000
--- a/libs/fleet/sdk-bindings/python/cyclops_sdk/generated_crd.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-from __future__ import annotations
-
-from typing import Any, Literal, NotRequired, TypedDict
-
-class ClaimSpec(TypedDict):
- bindDeadline: NotRequired[int]
- lifecycle: NotRequired[ClaimSpecLifecycle]
- sandboxTemplateRef: SandboxTemplateRef
- warmpool: NotRequired[str]
-
-class ClaimSpecLifecycle(TypedDict):
- autoRenew: NotRequired[bool]
- shutdownPolicy: NotRequired[str]
- shutdownTime: NotRequired[str]
-
-class PoolSpec(TypedDict):
- autoscaling: NotRequired[PoolSpecAutoscaling]
- replicas: int
- services: NotRequired[list[PoolSpecService]]
- template: PoolTemplate
-
-class PoolSpecAutoscaling(TypedDict):
- initialPoolSize: NotRequired[int]
- maxPoolSize: NotRequired[int]
- minPoolSize: NotRequired[int]
-
-class PoolSpecService(TypedDict):
- name: str
- protocol: NotRequired[PoolSpecServiceProtocol]
- targetPort: int
-
-PoolSpecServiceProtocol = Literal["TCP", "UDP"]
-
-class PoolTemplate(TypedDict):
- command: NotRequired[list[str]]
- containerDiskImage: str
- cpuCores: NotRequired[int]
- firmware: NotRequired[PoolTemplateFirmware]
- imagePullSecret: NotRequired[str]
- memory: NotRequired[str]
- nodeSelector: NotRequired[dict[str, str]]
- oidc: NotRequired[PoolTemplateOidc]
- probes: NotRequired[Any]
- runtime: NotRequired[PoolTemplateRuntime]
- runtimeClassName: NotRequired[str]
- tolerations: NotRequired[list[Any]]
-
-PoolTemplateFirmware = Literal["bios", "efi"]
-
-class PoolTemplateOidc(TypedDict):
- awsRegion: NotRequired[str]
- awsRoleArn: NotRequired[str]
- credentialsSecret: str
- refreshIntervalSeconds: NotRequired[int]
- tokenUrl: str
-
-PoolTemplateRuntime = Literal["kubevirt", "macos", "gvisor"]
-
-class SandboxTemplateRef(TypedDict):
- name: str
-
diff --git a/libs/fleet/sdk-bindings/python/pyproject.toml b/libs/fleet/sdk-bindings/python/pyproject.toml
deleted file mode 100644
index 358a217b9d..0000000000
--- a/libs/fleet/sdk-bindings/python/pyproject.toml
+++ /dev/null
@@ -1,10 +0,0 @@
-[build-system]
-requires = ["hatchling"]
-build-backend = "hatchling.build"
-[project]
-name = "cyclops-sdk"
-version = "0.1.0"
-requires-python = ">=3.10"
-dependencies = ["httpx>=0.27,<1"]
-[tool.hatch.build.targets.wheel]
-packages = ["cyclops_sdk"]
diff --git a/libs/fleet/sdk-bindings/python/tests/test_async_client.py b/libs/fleet/sdk-bindings/python/tests/test_async_client.py
new file mode 100644
index 0000000000..93a6dfd7b1
--- /dev/null
+++ b/libs/fleet/sdk-bindings/python/tests/test_async_client.py
@@ -0,0 +1,52 @@
+import asyncio
+import unittest
+from contract_fixture import (ScriptedHttpClient, client, expected_lifecycle,
+ expected_service_calls, offline_sandbox, pool_spec, run_lifecycle,
+ service_request)
+from cyclops_sdk import CreatePoolRequest, HttpClient, HttpError, SdkError
+
+class AsyncClientContractTest(unittest.IsolatedAsyncioTestCase):
+ async def test_full_typed_lifecycle_has_exact_native_callback_contract(self):
+ pool, claim, sandbox, service = await run_lifecycle(ScriptedHttpClient(expected_lifecycle()))
+ self.assertEqual((pool.metadata.name, claim.metadata.name, sandbox.name, service.status), ('default','default','offline-sandbox',202))
+ async def test_callback_http_error_propagates_through_native_async_call(self):
+ class FailingHttpClient(HttpClient):
+ async def execute(self, request):
+ raise HttpError.Transport('offline transport')
+ with self.assertRaises(SdkError.Transport) as raised:
+ await client(FailingHttpClient()).create_pool(CreatePoolRequest(namespace='default', spec=pool_spec()))
+ self.assertEqual(raised.exception.reason, 'offline transport')
+
+ async def test_native_callback_distinguishes_absent_empty_and_binary_bodies(self):
+ transport = ScriptedHttpClient(expected_service_calls(
+ (None, b''),
+ (b'', b'\x00\xff'),
+ (b'\x00\xff', b'\xff\x00'),
+ ))
+ sdk = client(transport)
+ responses = [
+ await sdk.service_request(offline_sandbox(), 'mcp', '/mcp', service_request(None)),
+ await sdk.service_request(offline_sandbox(), 'mcp', '/mcp', service_request(b'')),
+ await sdk.service_request(offline_sandbox(), 'mcp', '/mcp', service_request(b'\x00\xff')),
+ ]
+ self.assertIsNone(transport.requests[1].body)
+ self.assertEqual(transport.requests[2].body, b'')
+ self.assertEqual(transport.requests[3].body, b'\x00\xff')
+ self.assertEqual([response.body for response in responses], [b'', b'\x00\xff', b'\xff\x00'])
+ transport.assert_exhausted()
+
+ async def test_concurrent_sdk_calls_share_one_locked_callback_queue(self):
+ transport = ScriptedHttpClient(expected_service_calls(
+ (b'parallel', b'first'),
+ (b'parallel', b'second'),
+ ))
+ sdk = client(transport)
+ first, second = await asyncio.gather(
+ sdk.service_request(offline_sandbox(), 'mcp', '/mcp', service_request(b'parallel')),
+ sdk.service_request(offline_sandbox(), 'mcp', '/mcp', service_request(b'parallel')),
+ )
+ self.assertEqual({first.body, second.body}, {b'first', b'second'})
+ self.assertEqual(len(transport.requests), 3)
+ transport.assert_exhausted()
+
+if __name__ == '__main__': unittest.main()
diff --git a/libs/fleet/sdk-bindings/python/tests/test_examples.py b/libs/fleet/sdk-bindings/python/tests/test_examples.py
deleted file mode 100644
index c6704b226e..0000000000
--- a/libs/fleet/sdk-bindings/python/tests/test_examples.py
+++ /dev/null
@@ -1,112 +0,0 @@
-from pathlib import Path
-import unittest
-
-
-ROOT = Path(__file__).resolve().parents[3]
-EXAMPLES = {
- "python": ROOT / "sdk-bindings/examples/python/app_controlled.py",
- "typescript": ROOT / "sdk-bindings/examples/typescript/app-controlled.ts",
- "go": ROOT / "sdk-bindings/go/examples/app_controlled.go",
- "rust": ROOT / "sdk-bindings/rust/examples/app_controlled.rs",
-}
-
-
-class ExampleContractTest(unittest.TestCase):
- def test_examples_use_app_controlled_sequence(self):
- sequences = {
- "python": ["connect(", "create_pool(", "create_claim(", "wait_claim(", "run_agent(sdk, sandbox)", "print(", "finally:", "delete_claim(", "delete_pool(", "close("],
- "typescript": ["connect(", "createPool(", "createClaim(", "waitClaim(", "runAgent(sdk, sandbox)", "console.log(", "finally {", "deleteClaim(", "deletePool(", "close("],
- "go": ["Connect(", "sdk.Close()", "CreatePool(", "sdk.DeletePool(pool)", "CreateClaim(", "sdk.DeleteClaim(claim)", "WaitClaim(", "runAgent(sdk, sandbox)", "fmt.Println("],
- "rust": ["Sdk::connect(", "create_pool(", "create_claim(", "wait_claim(", "run_agent(&mut sdk, sandbox)", "println!(", "delete_claim(", "delete_pool(", "close("],
- }
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- flow = source[source.index("def main"):] if language == "python" else source[source.index("const sdk"):] if language == "typescript" else source[source.index("func main"):] if language == "go" else source[source.index("fn main"):]
- positions = [flow.index(token) for token in sequences[language]]
- self.assertEqual(positions, sorted(positions), language)
- self.assertIn("initialize", source, language)
- self.assertRegex(source, r"service_client|serviceFetch|ServiceClient", language)
- self.assertIn("/mcp", source, language)
- self.assertNotIn("external run_agent", source.lower(), language)
-
- def test_examples_emit_machine_readable_resource_results(self):
- tokens = {
- "python": ['sandbox["claim"]', "json.dumps(result"],
- "typescript": ["sandbox.claim", "JSON.stringify(result)"],
- "go": ["sandbox.Claim", "json.Marshal(result)"],
- "rust": ['"claim": sandbox.claim', 'println!("{result}")'],
- }
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- for token in tokens[language]:
- self.assertIn(token, source, language)
-
-
- def test_examples_create_mcp_service_alias(self):
- tokens = {
- "python": ['"services": [{"name": "mcp", "targetPort": 3000, "protocol": "TCP"}]'],
- "typescript": ['services: [{ name: "mcp", targetPort: 3000, protocol: "TCP" }]'],
- "go": ['Services: []cyclopssdk.PoolSpecService{', 'Name: "mcp"', 'TargetPort: 3000'],
- "rust": ['PoolSpecService::builder()', '.name("mcp".into())', '.target_port(3000)'],
- }
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- for token in tokens[language]:
- self.assertIn(token, source, language)
-
- def test_examples_retry_transient_mcp_gateway_errors(self):
- tokens = {
- "python": ["time.monotonic()", "(502, 503, 504)", "time.sleep("],
- "typescript": ["Date.now()", "[502, 503, 504]", "setTimeout"],
- "go": ["time.Now()", "response.StatusCode == 502", "time.Sleep("],
- "rust": ["Instant::now()", "matches!(response.status, 502..=504)", "thread::sleep("],
- }
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- for token in tokens[language]:
- self.assertIn(token, source, language)
-
- def test_examples_use_named_service_clients_with_relative_paths(self):
- tokens = {
- "python": ['service_client(sandbox, "mcp")', "mcp.post(", '"/mcp"'],
- "typescript": ['serviceFetch(sandbox, "mcp")', 'mcp("/mcp"'],
- "go": ['ServiceClient(sandbox, "mcp")', 'NewRequest("POST", "/mcp"'],
- "rust": ['service_client(&sandbox, "mcp")', '.post("/mcp")'],
- }
- prohibited = ["mcp_url", "MCPURL", "mcpUrl", "-mcp"]
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- for token in tokens[language]:
- self.assertIn(token, source, language)
- for token in prohibited:
- self.assertNotIn(token, source, language)
-
- def test_bindings_do_not_expose_url_based_http_clients(self):
- binding_files = [
- ROOT / "sdk-bindings/python/cyclops_sdk/__init__.py",
- ROOT / "sdk-bindings/typescript/src/index.ts",
- ROOT / "sdk-bindings/go/sdk.go",
- ROOT / "sdk-bindings/rust/src/lib.rs",
- ROOT / "sdk-core/wit/cyclops-sdk.wit",
- ]
- prohibited = ["raw_client", "rawClient", "RawClient", "raw-request", '"raw_request"']
- for path in binding_files:
- source = path.read_text(encoding="utf-8")
- for token in prohibited:
- self.assertNotIn(token, source, path)
-
- def test_private_image_examples_pass_pull_secret(self):
- tokens = {
- "python": ['os.environ["CUA_IMAGE_PULL_SECRET"]', '"imagePullSecret"'],
- "typescript": ['required("CUA_IMAGE_PULL_SECRET")', 'imagePullSecret'],
- "go": ['required("CUA_IMAGE_PULL_SECRET")', 'ImagePullSecret'],
- "rust": ['required("CUA_IMAGE_PULL_SECRET")', '.image_pull_secret('],
- }
- for language, path in EXAMPLES.items():
- source = path.read_text(encoding="utf-8")
- for token in tokens[language]:
- self.assertIn(token, source, language)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/libs/fleet/sdk-bindings/python/tests/test_public_api.py b/libs/fleet/sdk-bindings/python/tests/test_public_api.py
deleted file mode 100644
index 4426f7593a..0000000000
--- a/libs/fleet/sdk-bindings/python/tests/test_public_api.py
+++ /dev/null
@@ -1,104 +0,0 @@
-import inspect
-import unittest
-
-import cyclops_sdk
-import httpx
-
-
-class PublicApiTest(unittest.TestCase):
- def test_typed_resource_api_only(self):
- self.assertEqual(list(inspect.signature(cyclops_sdk.connect).parameters), ["configuration"])
- expected = {
- "create_pool": ["self", "request"],
- "list_pools": ["self", "namespace"],
- "get_pool": ["self", "pool"],
- "update_pool": ["self", "pool"],
- "delete_pool": ["self", "pool"],
- "create_claim": ["self", "request"],
- "list_claims": ["self", "namespace"],
- "get_claim": ["self", "claim"],
- "update_claim": ["self", "claim"],
- "delete_claim": ["self", "claim"],
- "wait_claim": ["self", "claim"],
- "service_client": ["self", "sandbox", "service"],
- "close": ["self"],
- }
- public = {
- name: value
- for name, value in inspect.getmembers(cyclops_sdk.SDK, inspect.isfunction)
- if not name.startswith("_")
- }
- self.assertEqual(set(public), set(expected))
- for name, parameters in expected.items():
- self.assertEqual(list(inspect.signature(public[name]).parameters), parameters)
- expected_annotations = {
- "create_pool": ({"request": cyclops_sdk.CreatePoolRequest}, cyclops_sdk.Pool),
- "list_pools": ({"namespace": str}, list[cyclops_sdk.Pool]),
- "get_pool": ({"pool": cyclops_sdk.Pool}, cyclops_sdk.Pool),
- "update_pool": ({"pool": cyclops_sdk.Pool}, cyclops_sdk.Pool),
- "delete_pool": ({"pool": cyclops_sdk.Pool}, None),
- "create_claim": ({"request": cyclops_sdk.CreateClaimRequest}, cyclops_sdk.Claim),
- "list_claims": ({"namespace": str}, list[cyclops_sdk.Claim]),
- "get_claim": ({"claim": cyclops_sdk.Claim}, cyclops_sdk.Claim),
- "update_claim": ({"claim": cyclops_sdk.Claim}, cyclops_sdk.Claim),
- "delete_claim": ({"claim": cyclops_sdk.Claim}, None),
- "wait_claim": ({"claim": cyclops_sdk.Claim}, cyclops_sdk.Sandbox),
- "service_client": ({"sandbox": cyclops_sdk.Sandbox, "service": str}, httpx.Client),
- }
- for name, (parameters, return_annotation) in expected_annotations.items():
- signature = inspect.signature(public[name])
- self.assertEqual(
- {parameter: signature.parameters[parameter].annotation for parameter in parameters},
- parameters,
- )
- self.assertEqual(signature.return_annotation, return_annotation)
- self.assertFalse(hasattr(cyclops_sdk, "RawClient"))
- self.assertTrue(hasattr(cyclops_sdk, "CreatePoolRequest"))
- self.assertTrue(hasattr(cyclops_sdk, "CreateClaimRequest"))
- self.assertTrue(hasattr(cyclops_sdk, "Pool"))
- self.assertTrue(hasattr(cyclops_sdk, "PoolSpec"))
- self.assertTrue(hasattr(cyclops_sdk, "Claim"))
- self.assertTrue(hasattr(cyclops_sdk, "ClaimSpec"))
- self.assertTrue(hasattr(cyclops_sdk, "Sandbox"))
- self.assertTrue(issubclass(cyclops_sdk.UnknownServiceError, ValueError))
-
- def test_service_client_sends_relative_request_through_core(self):
- sdk = object.__new__(cyclops_sdk.SDK)
- calls = []
-
- def call(request):
- calls.append(request)
- return {"status": 201, "body": "initialized"}
-
- sdk._call = call
- sandbox = {
- "namespace": "pool-one",
- "claim": "claim-one",
- "sandbox": "sandbox-one",
- "services": ["mcp"],
- }
- with sdk.service_client(sandbox, "mcp") as client:
- response = client.post("/mcp?session=one", json={"jsonrpc": "2.0"})
- self.assertEqual(response.status_code, 201)
- self.assertEqual(response.text, "initialized")
- self.assertEqual(calls[0]["op"], "service_request")
- self.assertEqual(calls[0]["service"], "mcp")
- self.assertEqual(calls[0]["request"]["path"], "/mcp?session=one")
- self.assertNotIn("url", calls[0]["request"])
-
- def test_unknown_service_error_lists_available_names(self):
- sdk = object.__new__(cyclops_sdk.SDK)
- sandbox = {
- "namespace": "pool-one",
- "claim": "claim-one",
- "sandbox": "sandbox-one",
- "services": ["novnc", "mcp", "mcp"],
- }
- with self.assertRaises(cyclops_sdk.UnknownServiceError) as raised:
- sdk.service_client(sandbox, "metrics")
- self.assertEqual(raised.exception.requested, "metrics")
- self.assertEqual(raised.exception.available, ["mcp", "novnc"])
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/libs/fleet/sdk-bindings/python/uv.lock b/libs/fleet/sdk-bindings/python/uv.lock
deleted file mode 100644
index 403793fe0d..0000000000
--- a/libs/fleet/sdk-bindings/python/uv.lock
+++ /dev/null
@@ -1,104 +0,0 @@
-version = 1
-revision = 3
-requires-python = ">=3.10"
-
-[[package]]
-name = "anyio"
-version = "4.14.2"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
- { name = "idna" },
- { name = "typing-extensions", marker = "python_full_version < '3.13'" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" },
-]
-
-[[package]]
-name = "certifi"
-version = "2026.6.17"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/c9/c7/424b75da314c1045981bd9777432fad05a9e0c69daa4ed7e308bbaffe405/certifi-2026.6.17.tar.gz", hash = "sha256:024c88eeec92ca068db80f02b8b07c9cef7b9fe261d1d535abfd5abd6f6af432", size = 134594, upload-time = "2026-06-17T10:31:07.894Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl", hash = "sha256:2227dcbaafe0d2f59279d1762ddddc37783ed4354594f194ffc31d20f41fc3db", size = 133289, upload-time = "2026-06-17T10:31:06.348Z" },
-]
-
-[[package]]
-name = "cyclops-sdk"
-version = "0.1.0"
-source = { editable = "." }
-dependencies = [
- { name = "httpx" },
-]
-
-[package.metadata]
-requires-dist = [{ name = "httpx", specifier = ">=0.27,<1" }]
-
-[[package]]
-name = "exceptiongroup"
-version = "1.3.1"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
-]
-
-[[package]]
-name = "h11"
-version = "0.16.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
-]
-
-[[package]]
-name = "httpcore"
-version = "1.0.9"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "certifi" },
- { name = "h11" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
-]
-
-[[package]]
-name = "httpx"
-version = "0.28.1"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "anyio" },
- { name = "certifi" },
- { name = "httpcore" },
- { name = "idna" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
-]
-
-[[package]]
-name = "idna"
-version = "3.18"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" },
-]
-
-[[package]]
-name = "typing-extensions"
-version = "4.16.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
-]
diff --git a/libs/fleet/sdk-bindings/ruby/.cyclops-sdk-generated-files b/libs/fleet/sdk-bindings/ruby/.cyclops-sdk-generated-files
new file mode 100644
index 0000000000..9ce8967c46
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/.cyclops-sdk-generated-files
@@ -0,0 +1,4 @@
+d cyclops_sdk
+f cyclops_sdk.rb
+f cyclops_sdk/schema.rb
+f cyclops_sdk/sdk.rb
diff --git a/libs/fleet/sdk-bindings/ruby/README.md b/libs/fleet/sdk-bindings/ruby/README.md
new file mode 100644
index 0000000000..3cad3accdd
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/README.md
@@ -0,0 +1,12 @@
+# Ruby Contract Binding
+
+Run from any working directory after setting `REPO_ROOT` to the absolute path of
+this clone (for example, `REPO_ROOT=/path/to/clone`):
+
+```bash
+REPO_ROOT=/path/to/clone
+$REPO_ROOT/cyclops-cs/scripts/run-ruby-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/ruby/tests/test_async_client.rb"
+$REPO_ROOT/cyclops-cs/scripts/run-ruby-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/ruby/app_controlled.rb"
+```
+
+The launcher stages the Ruby files and native library in a temporary load path, preserving the generated source tree.
diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk.rb
new file mode 100644
index 0000000000..252b75e5c7
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk.rb
@@ -0,0 +1,59 @@
+require_relative "cyclops_sdk/schema"
+require_relative "cyclops_sdk/sdk"
+
+module CyclopsSdk
+ CyclopsSdkSchema.constants(false).each do |name|
+ const_set(name, CyclopsSdkSchema.const_get(name)) unless const_defined?(name, false)
+ end
+ SCHEMA_CHECK_LOWER_METHODS = %i[
+ check_lower_TypeClaimSpec
+ check_lower_TypeOSGymSandboxClaimStatus
+ check_lower_TypeOSGymWorkspacePoolStatus
+ check_lower_TypePoolSpec
+ ].freeze
+ SCHEMA_READ_METHODS = %i[
+ read_TypeClaimSpec
+ read_TypeOSGymSandboxClaimStatus
+ read_TypeOSGymWorkspacePoolStatus
+ read_TypePoolSpec
+ ].freeze
+ SCHEMA_WRITE_METHODS = %i[
+ write_TypeClaimSpec
+ write_TypeOSGymSandboxClaimStatus
+ write_TypeOSGymWorkspacePoolStatus
+ write_TypePoolSpec
+ ].freeze
+
+ schema_rust_buffer = CyclopsSdkSchema::RustBuffer
+ schema_stream = CyclopsSdkSchema.const_get(:RustBufferStream, false)
+
+ SCHEMA_CHECK_LOWER_METHODS.each do |method_name|
+ RustBuffer.define_singleton_method(method_name) do |value|
+ schema_rust_buffer.public_send(method_name, value)
+ end
+ end
+
+ SCHEMA_READ_METHODS.each do |method_name|
+ RustBufferStream.define_method(method_name) do
+ schema_buffer = schema_rust_buffer.new(@rbuf.pointer)
+ external_stream = schema_stream.new(schema_buffer)
+ external_stream.instance_variable_set(:@offset, @offset)
+ value = external_stream.public_send(method_name)
+ @offset = external_stream.instance_variable_get(:@offset)
+ value
+ end
+ end
+
+ SCHEMA_WRITE_METHODS.each do |method_name|
+ RustBufferBuilder.define_method(method_name) do |value|
+ buffer = schema_rust_buffer.public_send(method_name.to_s.sub("write_", "alloc_from_"), value)
+ begin
+ write(buffer.data.read_bytes(buffer.len))
+ ensure
+ buffer.free
+ end
+ end
+ end
+
+ private_constant :SCHEMA_CHECK_LOWER_METHODS, :SCHEMA_READ_METHODS, :SCHEMA_WRITE_METHODS
+end
diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/schema.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/schema.rb
new file mode 100644
index 0000000000..bd8721c1ca
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/schema.rb
@@ -0,0 +1,3633 @@
+# This file was autogenerated by some hot garbage in the `uniffi` crate.
+# Trust me, you don't want to mess with it!
+
+# Common helper code.
+#
+# Ideally this would live in a separate .rb file where it can be unittested etc
+# in isolation, and perhaps even published as a re-useable package.
+#
+# However, it's important that the details of how this helper code works (e.g. the
+# way that different builtin types are passed across the FFI) exactly match what's
+# expected by the rust code on the other side of the interface. In practice right
+# now that means coming from the exact some version of `uniffi` that was used to
+# compile the rust component. The easiest way to ensure this is to bundle the Ruby
+# helpers directly inline like we're doing here.
+
+require 'ffi'
+require 'set'
+
+module CyclopsSdkSchema
+ def self.uniffi_in_range(i, type_name, min, max)
+ raise TypeError, "no implicit conversion of #{i} into Integer" unless i.respond_to?(:to_int)
+ i = i.to_int
+ raise RangeError, "#{type_name} requires #{min} <= value < #{max}" unless (min <= i && i < max)
+ i
+end
+
+def self.uniffi_utf8(v)
+ raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str)
+ v = v.to_str.encode(Encoding::UTF_8)
+ raise Encoding::InvalidByteSequenceError, "not a valid UTF-8 encoded string" unless v.valid_encoding?
+ v
+end
+
+def self.uniffi_bytes(v)
+ raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str)
+ v.to_str
+end
+
+# Callback return codes
+UNIFFI_CALLBACK_SUCCESS = 0
+UNIFFI_CALLBACK_ERROR = 1
+UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2
+
+# Call a method on a callback interface object, catching and reporting errors
+# to Rust via the call_status.
+# If error_type is provided, known errors of that type are reported as UNIFFI_CALLBACK_ERROR;
+# all other errors are reported as UNIFFI_CALLBACK_UNEXPECTED_ERROR.
+def self.uniffi_trait_interface_call(call_status, make_call, write_return_value, error_type = nil, lower_error = nil)
+ begin
+ write_return_value.call make_call.call
+ rescue StandardError => e
+ buf = if !error_type.nil? && uniffi_is_error_type?(e, error_type)
+ call_status[:code] = UNIFFI_CALLBACK_ERROR
+ lower_error.call e
+ else
+ call_status[:code] = UNIFFI_CALLBACK_UNEXPECTED_ERROR
+ RustBuffer.alloc_from_string(e.inspect)
+ end
+
+ error_buf = call_status[:error_buf]
+ error_buf[:capacity] = buf[:capacity]
+ error_buf[:len] = buf[:len]
+ error_buf[:data] = buf[:data]
+ end
+end
+
+# Check if an exception is a variant of the given error type.
+# Error types in Ruby are either modules (non-flat enums) or classes (flat enums),
+# with variant classes as constant within them.
+def self.uniffi_is_error_type?(e, error_type)
+ # Object-as-error: error_type is a class itself (e.g. MyError < StandardError)
+ if error_type.is_a?(Class) && e.is_a?(error_type)
+ return true
+ end
+
+ # Enum error: error_type is a module with class constants for each variant
+ error_type.constants.any? do |c|
+ klass = error_type.const_get c
+ klass.is_a?(Class) && e.is_a?(klass)
+ end
+end
+ class RustBuffer < FFI::Struct
+ layout :capacity, :uint64,
+ :len, :uint64,
+ :data, :pointer
+
+ def self.alloc(size)
+ return ::CyclopsSdkSchema.rust_call(:ffi_cyclops_sdk_schema_rustbuffer_alloc, size)
+ end
+
+ def self.reserve(rbuf, additional)
+ return ::CyclopsSdkSchema.rust_call(:ffi_cyclops_sdk_schema_rustbuffer_reserve, rbuf, additional)
+ end
+
+ def free
+ ::CyclopsSdkSchema.rust_call(:ffi_cyclops_sdk_schema_rustbuffer_free, self)
+ end
+
+ def capacity
+ self[:capacity]
+ end
+
+ def len
+ self[:len]
+ end
+
+ def len=(value)
+ self[:len] = value
+ end
+
+ def data
+ self[:data]
+ end
+
+ def to_s
+ "RustBuffer(capacity=#{capacity}, len=#{len}, data=#{data.read_bytes len})"
+ end
+
+ # The allocated buffer will be automatically freed if an error occurs, ensuring that
+ # we don't accidentally leak it.
+ def self.allocWithBuilder
+ builder = RustBufferBuilder.new
+
+ begin
+ yield builder
+ rescue => e
+ builder.discard
+ raise e
+ end
+ end
+
+ # The RustBuffer will be freed once the context-manager exits, ensuring that we don't
+ # leak it even if an error occurs.
+ def consumeWithStream
+ stream = RustBufferStream.new self
+
+ yield stream
+
+ raise RuntimeError, 'junk data left in buffer after consuming' if stream.remaining != 0
+ ensure
+ free
+ end# The primitive String type.
+
+ def self.alloc_from_string(value)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write value.encode('utf-8')
+ return builder.finalize
+ end
+ end
+
+ def consume_into_string
+ consumeWithStream do |stream|
+ return stream.read(stream.remaining).force_encoding(Encoding::UTF_8)
+ end
+ end
+
+ # The Record type ClaimLifecycle.
+
+ def self.check_lower_TypeClaimLifecycle(v)
+ RustBuffer.check_lower_Optionalstring(v.shutdown_time)
+ RustBuffer.check_lower_Optionalstring(v.shutdown_policy)
+ RustBuffer.check_lower_Optionalbool(v.auto_renew)
+ end
+
+ def self.alloc_from_TypeClaimLifecycle(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeClaimLifecycle(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeClaimLifecycle
+ consumeWithStream do |stream|
+ return stream.read_TypeClaimLifecycle
+ end
+ end
+
+ # The Record type ClaimSpec.
+
+ def self.check_lower_TypeClaimSpec(v)
+ RustBuffer.check_lower_TypeSandboxTemplateRef(v.sandbox_template_ref)
+ RustBuffer.check_lower_Optionalstring(v.warmpool)
+ RustBuffer.check_lower_Optionalu32(v.bind_deadline)
+ RustBuffer.check_lower_OptionalTypeClaimLifecycle(v.lifecycle)
+ end
+
+ def self.alloc_from_TypeClaimSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeClaimSpec(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeClaimSpec
+ consumeWithStream do |stream|
+ return stream.read_TypeClaimSpec
+ end
+ end
+
+ # The Record type OSGymSandboxClaimCondition.
+
+ def self.check_lower_TypeOSGymSandboxClaimCondition(v)
+ RustBuffer.check_lower_Optionalstring(v.type)
+ RustBuffer.check_lower_Optionalstring(v.status)
+ RustBuffer.check_lower_Optionalstring(v.reason)
+ RustBuffer.check_lower_Optionalstring(v.message)
+ RustBuffer.check_lower_Optionalstring(v.last_transition_time)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxClaimCondition(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxClaimCondition(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxClaimCondition
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxClaimCondition
+ end
+ end
+
+ # The Record type OSGymSandboxClaimSandbox.
+
+ def self.check_lower_TypeOSGymSandboxClaimSandbox(v)
+ RustBuffer.check_lower_Optionalstring(v.name)
+ RustBuffer.check_lower_Optionalstring(v.service)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxClaimSandbox(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxClaimSandbox(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxClaimSandbox
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxClaimSandbox
+ end
+ end
+
+ # The Record type OSGymSandboxClaimStatus.
+
+ def self.check_lower_TypeOSGymSandboxClaimStatus(v)
+ RustBuffer.check_lower_Optionalstring(v.phase)
+ RustBuffer.check_lower_OptionalSequenceTypeOSGymSandboxClaimCondition(v.conditions)
+ RustBuffer.check_lower_OptionalTypeOSGymSandboxClaimSandbox(v.sandbox)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxClaimStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxClaimStatus(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxClaimStatus
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxClaimStatus
+ end
+ end
+
+ # The Record type OSGymSandboxSpec.
+
+ def self.check_lower_TypeOSGymSandboxSpec(v)
+ RustBuffer.check_lower_TypeVmTemplate(v.vm_template)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxSpec(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxSpec
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxSpec
+ end
+ end
+
+ # The Record type OSGymSandboxStatus.
+
+ def self.check_lower_TypeOSGymSandboxStatus(v)
+ RustBuffer.check_lower_Optionalstring(v.phase)
+ RustBuffer.check_lower_Optionalstring(v.runtime)
+ RustBuffer.check_lower_Optionalbool(v.ready)
+ RustBuffer.check_lower_Optionalstring(v.vm_name)
+ RustBuffer.check_lower_Optionalstring(v.service)
+ RustBuffer.check_lower_Optionalstring(v.message)
+ RustBuffer.check_lower_Optionalstring(v.reset_issued_at)
+ RustBuffer.check_lower_Optionalstring(v.reset_vmi_uid)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxStatus(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxStatus
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxStatus
+ end
+ end
+
+ # The Record type OSGymSandboxTemplateSpec.
+
+ def self.check_lower_TypeOSGymSandboxTemplateSpec(v)
+ RustBuffer.check_lower_TypeVmTemplate(v.vm_template)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxTemplateSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxTemplateSpec(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxTemplateSpec
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxTemplateSpec
+ end
+ end
+
+ # The Record type OSGymSandboxWarmPoolSpec.
+
+ def self.check_lower_TypeOSGymSandboxWarmPoolSpec(v)
+
+ RustBuffer.check_lower_TypeSandboxTemplateRef(v.sandbox_template_ref)
+ RustBuffer.check_lower_OptionalTypeWarmPoolAutoscaling(v.autoscaling)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxWarmPoolSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxWarmPoolSpec(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxWarmPoolSpec
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxWarmPoolSpec
+ end
+ end
+
+ # The Record type OSGymSandboxWarmPoolStatus.
+
+ def self.check_lower_TypeOSGymSandboxWarmPoolStatus(v)
+ RustBuffer.check_lower_Optionalu32(v.replicas)
+ RustBuffer.check_lower_Optionalu32(v.ready_replicas)
+ RustBuffer.check_lower_Optionalstring(v.selector)
+ end
+
+ def self.alloc_from_TypeOSGymSandboxWarmPoolStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymSandboxWarmPoolStatus(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymSandboxWarmPoolStatus
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymSandboxWarmPoolStatus
+ end
+ end
+
+ # The Record type OSGymWorkspacePoolStatus.
+
+ def self.check_lower_TypeOSGymWorkspacePoolStatus(v)
+ RustBuffer.check_lower_Optionalstring(v.phase)
+ RustBuffer.check_lower_Optionalu32(v.total_count)
+ RustBuffer.check_lower_Optionalu32(v.available_count)
+ RustBuffer.check_lower_Optionalu32(v.claimed_count)
+ end
+
+ def self.alloc_from_TypeOSGymWorkspacePoolStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOSGymWorkspacePoolStatus(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOSGymWorkspacePoolStatus
+ consumeWithStream do |stream|
+ return stream.read_TypeOSGymWorkspacePoolStatus
+ end
+ end
+
+ # The Record type OidcConfig.
+
+ def self.check_lower_TypeOidcConfig(v)
+
+
+ RustBuffer.check_lower_Optionalstring(v.aws_role_arn)
+ RustBuffer.check_lower_Optionalstring(v.aws_region)
+ RustBuffer.check_lower_Optionalu32(v.refresh_interval_seconds)
+ end
+
+ def self.alloc_from_TypeOidcConfig(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeOidcConfig(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeOidcConfig
+ consumeWithStream do |stream|
+ return stream.read_TypeOidcConfig
+ end
+ end
+
+ # The Record type PoolSpec.
+
+ def self.check_lower_TypePoolSpec(v)
+
+ RustBuffer.check_lower_TypePoolTemplate(v.template)
+ RustBuffer.check_lower_OptionalTypeWarmPoolAutoscaling(v.autoscaling)
+ RustBuffer.check_lower_OptionalSequenceTypeSandboxService(v.services)
+ end
+
+ def self.alloc_from_TypePoolSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypePoolSpec(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypePoolSpec
+ consumeWithStream do |stream|
+ return stream.read_TypePoolSpec
+ end
+ end
+
+ # The Record type PoolTemplate.
+
+ def self.check_lower_TypePoolTemplate(v)
+ RustBuffer.check_lower_OptionalTypeRuntimeKind(v.runtime)
+ RustBuffer.check_lower_Optionalstring(v.runtime_class_name)
+ RustBuffer.check_lower_OptionalMapStringString(v.node_selector)
+ RustBuffer.check_lower_OptionalSequenceTypePreservedJson(v.tolerations)
+ RustBuffer.check_lower_OptionalSequencestring(v.command)
+
+ RustBuffer.check_lower_Optionalstring(v.image_pull_secret)
+ RustBuffer.check_lower_Optionalu32(v.cpu_cores)
+ RustBuffer.check_lower_Optionalstring(v.memory)
+ RustBuffer.check_lower_OptionalTypeFirmware(v.firmware)
+ RustBuffer.check_lower_OptionalTypePreservedJson(v.probes)
+ RustBuffer.check_lower_OptionalTypeOidcConfig(v.oidc)
+ end
+
+ def self.alloc_from_TypePoolTemplate(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypePoolTemplate(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypePoolTemplate
+ consumeWithStream do |stream|
+ return stream.read_TypePoolTemplate
+ end
+ end
+
+ # The Record type SandboxService.
+
+ def self.check_lower_TypeSandboxService(v)
+
+
+ RustBuffer.check_lower_OptionalTypeServiceProtocol(v.protocol)
+ end
+
+ def self.alloc_from_TypeSandboxService(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeSandboxService(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeSandboxService
+ consumeWithStream do |stream|
+ return stream.read_TypeSandboxService
+ end
+ end
+
+ # The Record type SandboxTemplateRef.
+
+ def self.check_lower_TypeSandboxTemplateRef(v)
+
+ end
+
+ def self.alloc_from_TypeSandboxTemplateRef(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeSandboxTemplateRef(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeSandboxTemplateRef
+ consumeWithStream do |stream|
+ return stream.read_TypeSandboxTemplateRef
+ end
+ end
+
+ # The Record type VmTemplate.
+
+ def self.check_lower_TypeVmTemplate(v)
+
+ RustBuffer.check_lower_OptionalSequencestring(v.command)
+ RustBuffer.check_lower_OptionalTypeRuntimeKind(v.runtime)
+ RustBuffer.check_lower_Optionalstring(v.runtime_class_name)
+ RustBuffer.check_lower_OptionalMapStringString(v.node_selector)
+ RustBuffer.check_lower_OptionalSequenceTypePreservedJson(v.tolerations)
+ RustBuffer.check_lower_OptionalTypeImagePullPolicy(v.image_pull_policy)
+ RustBuffer.check_lower_Optionalstring(v.image_pull_secret)
+ RustBuffer.check_lower_Optionalu32(v.cpu_cores)
+ RustBuffer.check_lower_Optionalstring(v.memory)
+ RustBuffer.check_lower_OptionalTypeFirmware(v.firmware)
+ RustBuffer.check_lower_OptionalTypePreservedJson(v.probes)
+ RustBuffer.check_lower_OptionalSequenceTypeSandboxService(v.services)
+ RustBuffer.check_lower_OptionalTypeOidcConfig(v.oidc)
+ end
+
+ def self.alloc_from_TypeVmTemplate(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeVmTemplate(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeVmTemplate
+ consumeWithStream do |stream|
+ return stream.read_TypeVmTemplate
+ end
+ end
+
+ # The Record type WarmPoolAutoscaling.
+
+ def self.check_lower_TypeWarmPoolAutoscaling(v)
+ RustBuffer.check_lower_Optionalu32(v.min_pool_size)
+ RustBuffer.check_lower_Optionalu32(v.initial_pool_size)
+ RustBuffer.check_lower_Optionalu32(v.max_pool_size)
+ end
+
+ def self.alloc_from_TypeWarmPoolAutoscaling(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeWarmPoolAutoscaling(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeWarmPoolAutoscaling
+ consumeWithStream do |stream|
+ return stream.read_TypeWarmPoolAutoscaling
+ end
+ end
+
+ # The Enum type Firmware.
+
+ def self.check_lower_TypeFirmware(v)
+ end
+
+ def self.alloc_from_TypeFirmware(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeFirmware(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeFirmware
+ consumeWithStream do |stream|
+ return stream.read_TypeFirmware
+ end
+ end
+
+
+ # The Enum type ImagePullPolicy.
+
+ def self.check_lower_TypeImagePullPolicy(v)
+ end
+
+ def self.alloc_from_TypeImagePullPolicy(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeImagePullPolicy(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeImagePullPolicy
+ consumeWithStream do |stream|
+ return stream.read_TypeImagePullPolicy
+ end
+ end
+
+
+ # Error enum - generate alloc_from for callback error serialization
+ def self.alloc_from_TypeJsonValueError(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeJsonValueError(v)
+ return builder.finalize
+ end
+ end
+
+ # Enum used as error - generate consume_into_ for use as a return value
+ def consume_into_TypeJsonValueError
+ consumeWithStream do |stream|
+ return stream.read_TypeJsonValueError
+ end
+ end
+
+
+ # The Enum type RuntimeKind.
+
+ def self.check_lower_TypeRuntimeKind(v)
+ end
+
+ def self.alloc_from_TypeRuntimeKind(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeRuntimeKind(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeRuntimeKind
+ consumeWithStream do |stream|
+ return stream.read_TypeRuntimeKind
+ end
+ end
+
+
+ # The Enum type ServiceProtocol.
+
+ def self.check_lower_TypeServiceProtocol(v)
+ end
+
+ def self.alloc_from_TypeServiceProtocol(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeServiceProtocol(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeServiceProtocol
+ consumeWithStream do |stream|
+ return stream.read_TypeServiceProtocol
+ end
+ end
+
+
+ # The Optional<T> type for u32.
+
+ def self.check_lower_Optionalu32(v)
+ if !v.nil?
+
+ end
+ end
+
+ def self.alloc_from_Optionalu32(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Optionalu32(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Optionalu32
+ consumeWithStream do |stream|
+ return stream.read_Optionalu32
+ end
+ end
+
+ # The Optional<T> type for bool.
+
+ def self.check_lower_Optionalbool(v)
+ if !v.nil?
+
+ end
+ end
+
+ def self.alloc_from_Optionalbool(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Optionalbool(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Optionalbool
+ consumeWithStream do |stream|
+ return stream.read_Optionalbool
+ end
+ end
+
+ # The Optional<T> type for string.
+
+ def self.check_lower_Optionalstring(v)
+ if !v.nil?
+
+ end
+ end
+
+ def self.alloc_from_Optionalstring(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Optionalstring(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Optionalstring
+ consumeWithStream do |stream|
+ return stream.read_Optionalstring
+ end
+ end
+
+ # The Optional<T> type for TypePreservedJson.
+
+ def self.check_lower_OptionalTypePreservedJson(v)
+ if !v.nil?
+ (PreservedJson.uniffi_check_lower v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypePreservedJson(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypePreservedJson(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypePreservedJson
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypePreservedJson
+ end
+ end
+
+ # The Optional<T> type for TypeClaimLifecycle.
+
+ def self.check_lower_OptionalTypeClaimLifecycle(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeClaimLifecycle(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeClaimLifecycle(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeClaimLifecycle(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeClaimLifecycle
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeClaimLifecycle
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymSandboxClaimSandbox.
+
+ def self.check_lower_OptionalTypeOSGymSandboxClaimSandbox(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeOSGymSandboxClaimSandbox(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeOSGymSandboxClaimSandbox(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeOSGymSandboxClaimSandbox(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeOSGymSandboxClaimSandbox
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeOSGymSandboxClaimSandbox
+ end
+ end
+
+ # The Optional<T> type for TypeOidcConfig.
+
+ def self.check_lower_OptionalTypeOidcConfig(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeOidcConfig(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeOidcConfig(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeOidcConfig(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeOidcConfig
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeOidcConfig
+ end
+ end
+
+ # The Optional<T> type for TypeWarmPoolAutoscaling.
+
+ def self.check_lower_OptionalTypeWarmPoolAutoscaling(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeWarmPoolAutoscaling(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeWarmPoolAutoscaling(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeWarmPoolAutoscaling(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeWarmPoolAutoscaling
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeWarmPoolAutoscaling
+ end
+ end
+
+ # The Optional<T> type for TypeFirmware.
+
+ def self.check_lower_OptionalTypeFirmware(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeFirmware(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeFirmware(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeFirmware(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeFirmware
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeFirmware
+ end
+ end
+
+ # The Optional<T> type for TypeImagePullPolicy.
+
+ def self.check_lower_OptionalTypeImagePullPolicy(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeImagePullPolicy(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeImagePullPolicy(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeImagePullPolicy(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeImagePullPolicy
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeImagePullPolicy
+ end
+ end
+
+ # The Optional<T> type for TypeRuntimeKind.
+
+ def self.check_lower_OptionalTypeRuntimeKind(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeRuntimeKind(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeRuntimeKind(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeRuntimeKind(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeRuntimeKind
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeRuntimeKind
+ end
+ end
+
+ # The Optional<T> type for TypeServiceProtocol.
+
+ def self.check_lower_OptionalTypeServiceProtocol(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeServiceProtocol(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeServiceProtocol(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeServiceProtocol(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeServiceProtocol
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeServiceProtocol
+ end
+ end
+
+ # The Optional<T> type for Sequencestring.
+
+ def self.check_lower_OptionalSequencestring(v)
+ if !v.nil?
+ RustBuffer.check_lower_Sequencestring(v)
+ end
+ end
+
+ def self.alloc_from_OptionalSequencestring(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalSequencestring(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalSequencestring
+ consumeWithStream do |stream|
+ return stream.read_OptionalSequencestring
+ end
+ end
+
+ # The Optional<T> type for SequenceTypePreservedJson.
+
+ def self.check_lower_OptionalSequenceTypePreservedJson(v)
+ if !v.nil?
+ RustBuffer.check_lower_SequenceTypePreservedJson(v)
+ end
+ end
+
+ def self.alloc_from_OptionalSequenceTypePreservedJson(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalSequenceTypePreservedJson(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalSequenceTypePreservedJson
+ consumeWithStream do |stream|
+ return stream.read_OptionalSequenceTypePreservedJson
+ end
+ end
+
+ # The Optional<T> type for SequenceTypeOSGymSandboxClaimCondition.
+
+ def self.check_lower_OptionalSequenceTypeOSGymSandboxClaimCondition(v)
+ if !v.nil?
+ RustBuffer.check_lower_SequenceTypeOSGymSandboxClaimCondition(v)
+ end
+ end
+
+ def self.alloc_from_OptionalSequenceTypeOSGymSandboxClaimCondition(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalSequenceTypeOSGymSandboxClaimCondition(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalSequenceTypeOSGymSandboxClaimCondition
+ consumeWithStream do |stream|
+ return stream.read_OptionalSequenceTypeOSGymSandboxClaimCondition
+ end
+ end
+
+ # The Optional<T> type for SequenceTypeSandboxService.
+
+ def self.check_lower_OptionalSequenceTypeSandboxService(v)
+ if !v.nil?
+ RustBuffer.check_lower_SequenceTypeSandboxService(v)
+ end
+ end
+
+ def self.alloc_from_OptionalSequenceTypeSandboxService(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalSequenceTypeSandboxService(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalSequenceTypeSandboxService
+ consumeWithStream do |stream|
+ return stream.read_OptionalSequenceTypeSandboxService
+ end
+ end
+
+ # The Optional<T> type for MapStringString.
+
+ def self.check_lower_OptionalMapStringString(v)
+ if !v.nil?
+ RustBuffer.check_lower_MapStringString(v)
+ end
+ end
+
+ def self.alloc_from_OptionalMapStringString(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalMapStringString(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalMapStringString
+ consumeWithStream do |stream|
+ return stream.read_OptionalMapStringString
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def self.check_lower_Sequencestring(v)
+ v.each do |item|
+
+ end
+ end
+
+ def self.alloc_from_Sequencestring(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Sequencestring(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Sequencestring
+ consumeWithStream do |stream|
+ return stream.read_Sequencestring
+ end
+ end
+
+ # The Sequence<T> type for TypePreservedJson.
+
+ def self.check_lower_SequenceTypePreservedJson(v)
+ v.each do |item|
+ (PreservedJson.uniffi_check_lower item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypePreservedJson(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypePreservedJson(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypePreservedJson
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypePreservedJson
+ end
+ end
+
+ # The Sequence<T> type for TypeOSGymSandboxClaimCondition.
+
+ def self.check_lower_SequenceTypeOSGymSandboxClaimCondition(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeOSGymSandboxClaimCondition(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeOSGymSandboxClaimCondition(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeOSGymSandboxClaimCondition(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypeOSGymSandboxClaimCondition
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypeOSGymSandboxClaimCondition
+ end
+ end
+
+ # The Sequence<T> type for TypeSandboxService.
+
+ def self.check_lower_SequenceTypeSandboxService(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeSandboxService(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeSandboxService(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeSandboxService(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypeSandboxService
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypeSandboxService
+ end
+ end
+
+
+ # The Map<T> type for MapStringString.
+
+ def self.check_lower_MapStringString(v)
+ v.each do |k, v|
+
+
+ end
+ end
+
+ def self.alloc_from_MapStringString(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_MapStringString(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_MapStringString
+ consumeWithStream do |stream|
+ return stream.read_MapStringString
+ end
+ end
+end
+
+module UniFFILib
+ class ForeignBytes < FFI::Struct
+ layout :len, :int32,
+ :data, :pointer
+
+ def len
+ self[:len]
+ end
+
+ def data
+ self[:data]
+ end
+
+ def to_s
+ "ForeignBytes(len=#{len}, data=#{data.read_bytes(len)})"
+ end
+ end
+end
+
+private_constant :UniFFILib
+
+# Helper for structured reading of values from a RustBuffer.
+class RustBufferStream
+
+ def initialize(rbuf)
+ @rbuf = rbuf
+ @offset = 0
+ end
+
+ def remaining
+ @rbuf.len - @offset
+ end
+
+ def read(size)
+ raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len
+
+ data = @rbuf.data.get_bytes @offset, size
+
+ @offset += size
+
+ data
+ end
+
+ def read_u16
+ unpack_from 2, 'S>'
+ end
+
+ def read_u32
+ unpack_from 4, 'L>'
+ end
+
+ def read_u64
+ unpack_from 8, 'Q>'
+ end
+
+ def read_bool
+ v = unpack_from 1, 'c'
+
+ return false if v == 0
+ return true if v == 1
+
+ raise InternalError, 'Unexpected byte for Boolean type'
+ end
+
+ def read_string
+ size = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative string length' if size.negative?
+
+ read(size).force_encoding(Encoding::UTF_8)
+ end
+
+ # The Object type PreservedJson.
+
+ def read_TypePreservedJson
+ handle = unpack_from 8, 'Q>'
+ return PreservedJson.uniffi_lift(handle)
+ end
+
+ # The Record type ClaimLifecycle.
+
+ def read_TypeClaimLifecycle
+ ClaimLifecycle.new(
+ shutdown_time: read_Optionalstring,
+ shutdown_policy: read_Optionalstring,
+ auto_renew: read_Optionalbool
+ )
+ end
+
+ # The Record type ClaimSpec.
+
+ def read_TypeClaimSpec
+ ClaimSpec.new(
+ sandbox_template_ref: read_TypeSandboxTemplateRef,
+ warmpool: read_Optionalstring,
+ bind_deadline: read_Optionalu32,
+ lifecycle: read_OptionalTypeClaimLifecycle
+ )
+ end
+
+ # The Record type OSGymSandboxClaimCondition.
+
+ def read_TypeOSGymSandboxClaimCondition
+ OsGymSandboxClaimCondition.new(
+ type: read_Optionalstring,
+ status: read_Optionalstring,
+ reason: read_Optionalstring,
+ message: read_Optionalstring,
+ last_transition_time: read_Optionalstring
+ )
+ end
+
+ # The Record type OSGymSandboxClaimSandbox.
+
+ def read_TypeOSGymSandboxClaimSandbox
+ OsGymSandboxClaimSandbox.new(
+ name: read_Optionalstring,
+ service: read_Optionalstring
+ )
+ end
+
+ # The Record type OSGymSandboxClaimStatus.
+
+ def read_TypeOSGymSandboxClaimStatus
+ OsGymSandboxClaimStatus.new(
+ phase: read_Optionalstring,
+ conditions: read_OptionalSequenceTypeOSGymSandboxClaimCondition,
+ sandbox: read_OptionalTypeOSGymSandboxClaimSandbox
+ )
+ end
+
+ # The Record type OSGymSandboxSpec.
+
+ def read_TypeOSGymSandboxSpec
+ OsGymSandboxSpec.new(
+ vm_template: read_TypeVmTemplate
+ )
+ end
+
+ # The Record type OSGymSandboxStatus.
+
+ def read_TypeOSGymSandboxStatus
+ OsGymSandboxStatus.new(
+ phase: read_Optionalstring,
+ runtime: read_Optionalstring,
+ ready: read_Optionalbool,
+ vm_name: read_Optionalstring,
+ service: read_Optionalstring,
+ message: read_Optionalstring,
+ reset_issued_at: read_Optionalstring,
+ reset_vmi_uid: read_Optionalstring
+ )
+ end
+
+ # The Record type OSGymSandboxTemplateSpec.
+
+ def read_TypeOSGymSandboxTemplateSpec
+ OsGymSandboxTemplateSpec.new(
+ vm_template: read_TypeVmTemplate
+ )
+ end
+
+ # The Record type OSGymSandboxWarmPoolSpec.
+
+ def read_TypeOSGymSandboxWarmPoolSpec
+ OsGymSandboxWarmPoolSpec.new(
+ replicas: read_u32,
+ sandbox_template_ref: read_TypeSandboxTemplateRef,
+ autoscaling: read_OptionalTypeWarmPoolAutoscaling
+ )
+ end
+
+ # The Record type OSGymSandboxWarmPoolStatus.
+
+ def read_TypeOSGymSandboxWarmPoolStatus
+ OsGymSandboxWarmPoolStatus.new(
+ replicas: read_Optionalu32,
+ ready_replicas: read_Optionalu32,
+ selector: read_Optionalstring
+ )
+ end
+
+ # The Record type OSGymWorkspacePoolStatus.
+
+ def read_TypeOSGymWorkspacePoolStatus
+ OsGymWorkspacePoolStatus.new(
+ phase: read_Optionalstring,
+ total_count: read_Optionalu32,
+ available_count: read_Optionalu32,
+ claimed_count: read_Optionalu32
+ )
+ end
+
+ # The Record type OidcConfig.
+
+ def read_TypeOidcConfig
+ OidcConfig.new(
+ credentials_secret: read_string,
+ token_url: read_string,
+ aws_role_arn: read_Optionalstring,
+ aws_region: read_Optionalstring,
+ refresh_interval_seconds: read_Optionalu32
+ )
+ end
+
+ # The Record type PoolSpec.
+
+ def read_TypePoolSpec
+ PoolSpec.new(
+ replicas: read_u32,
+ template: read_TypePoolTemplate,
+ autoscaling: read_OptionalTypeWarmPoolAutoscaling,
+ services: read_OptionalSequenceTypeSandboxService
+ )
+ end
+
+ # The Record type PoolTemplate.
+
+ def read_TypePoolTemplate
+ PoolTemplate.new(
+ runtime: read_OptionalTypeRuntimeKind,
+ runtime_class_name: read_Optionalstring,
+ node_selector: read_OptionalMapStringString,
+ tolerations: read_OptionalSequenceTypePreservedJson,
+ command: read_OptionalSequencestring,
+ container_disk_image: read_string,
+ image_pull_secret: read_Optionalstring,
+ cpu_cores: read_Optionalu32,
+ memory: read_Optionalstring,
+ firmware: read_OptionalTypeFirmware,
+ probes: read_OptionalTypePreservedJson,
+ oidc: read_OptionalTypeOidcConfig
+ )
+ end
+
+ # The Record type SandboxService.
+
+ def read_TypeSandboxService
+ SandboxService.new(
+ name: read_string,
+ target_port: read_u16,
+ protocol: read_OptionalTypeServiceProtocol
+ )
+ end
+
+ # The Record type SandboxTemplateRef.
+
+ def read_TypeSandboxTemplateRef
+ SandboxTemplateRef.new(
+ name: read_string
+ )
+ end
+
+ # The Record type VmTemplate.
+
+ def read_TypeVmTemplate
+ VmTemplate.new(
+ container_disk_image: read_string,
+ command: read_OptionalSequencestring,
+ runtime: read_OptionalTypeRuntimeKind,
+ runtime_class_name: read_Optionalstring,
+ node_selector: read_OptionalMapStringString,
+ tolerations: read_OptionalSequenceTypePreservedJson,
+ image_pull_policy: read_OptionalTypeImagePullPolicy,
+ image_pull_secret: read_Optionalstring,
+ cpu_cores: read_Optionalu32,
+ memory: read_Optionalstring,
+ firmware: read_OptionalTypeFirmware,
+ probes: read_OptionalTypePreservedJson,
+ services: read_OptionalSequenceTypeSandboxService,
+ oidc: read_OptionalTypeOidcConfig
+ )
+ end
+
+ # The Record type WarmPoolAutoscaling.
+
+ def read_TypeWarmPoolAutoscaling
+ WarmPoolAutoscaling.new(
+ min_pool_size: read_Optionalu32,
+ initial_pool_size: read_Optionalu32,
+ max_pool_size: read_Optionalu32
+ )
+ end
+
+
+
+ # The Enum type Firmware.
+
+ def read_TypeFirmware
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return Firmware::BIOS
+ end
+ if variant == 2
+ return Firmware::EFI
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeFirmware'
+ end
+
+
+
+
+
+ # The Enum type ImagePullPolicy.
+
+ def read_TypeImagePullPolicy
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return ImagePullPolicy::ALWAYS
+ end
+ if variant == 2
+ return ImagePullPolicy::IF_NOT_PRESENT
+ end
+ if variant == 3
+ return ImagePullPolicy::NEVER
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeImagePullPolicy'
+ end
+
+
+
+
+
+
+
+ # The Error type JsonValueError
+
+ def read_TypeJsonValueError
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return JsonValueError::Invalid.new(
+ reason: read_string()
+ )
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeJsonValueError'
+ end
+
+
+
+
+ # The Enum type RuntimeKind.
+
+ def read_TypeRuntimeKind
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return RuntimeKind::KUBEVIRT
+ end
+ if variant == 2
+ return RuntimeKind::MACOS
+ end
+ if variant == 3
+ return RuntimeKind::GVISOR
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeRuntimeKind'
+ end
+
+
+
+
+
+ # The Enum type ServiceProtocol.
+
+ def read_TypeServiceProtocol
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return ServiceProtocol::TCP
+ end
+ if variant == 2
+ return ServiceProtocol::UDP
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeServiceProtocol'
+ end
+
+
+
+
+ # The Optional<T> type for u32.
+
+ def read_Optionalu32
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_u32
+ else
+ raise InternalError, 'Unexpected flag byte for Optionalu32'
+ end
+ end
+
+
+ # The Optional<T> type for bool.
+
+ def read_Optionalbool
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_bool
+ else
+ raise InternalError, 'Unexpected flag byte for Optionalbool'
+ end
+ end
+
+
+ # The Optional<T> type for string.
+
+ def read_Optionalstring
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_string
+ else
+ raise InternalError, 'Unexpected flag byte for Optionalstring'
+ end
+ end
+
+
+ # The Optional<T> type for TypePreservedJson.
+
+ def read_OptionalTypePreservedJson
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypePreservedJson
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypePreservedJson'
+ end
+ end
+
+
+ # The Optional<T> type for TypeClaimLifecycle.
+
+ def read_OptionalTypeClaimLifecycle
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeClaimLifecycle
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeClaimLifecycle'
+ end
+ end
+
+
+ # The Optional<T> type for TypeOSGymSandboxClaimSandbox.
+
+ def read_OptionalTypeOSGymSandboxClaimSandbox
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeOSGymSandboxClaimSandbox
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeOSGymSandboxClaimSandbox'
+ end
+ end
+
+
+ # The Optional<T> type for TypeOidcConfig.
+
+ def read_OptionalTypeOidcConfig
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeOidcConfig
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeOidcConfig'
+ end
+ end
+
+
+ # The Optional<T> type for TypeWarmPoolAutoscaling.
+
+ def read_OptionalTypeWarmPoolAutoscaling
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeWarmPoolAutoscaling
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeWarmPoolAutoscaling'
+ end
+ end
+
+
+ # The Optional<T> type for TypeFirmware.
+
+ def read_OptionalTypeFirmware
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeFirmware
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeFirmware'
+ end
+ end
+
+
+ # The Optional<T> type for TypeImagePullPolicy.
+
+ def read_OptionalTypeImagePullPolicy
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeImagePullPolicy
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeImagePullPolicy'
+ end
+ end
+
+
+ # The Optional<T> type for TypeRuntimeKind.
+
+ def read_OptionalTypeRuntimeKind
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeRuntimeKind
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeRuntimeKind'
+ end
+ end
+
+
+ # The Optional<T> type for TypeServiceProtocol.
+
+ def read_OptionalTypeServiceProtocol
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeServiceProtocol
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeServiceProtocol'
+ end
+ end
+
+
+ # The Optional<T> type for Sequencestring.
+
+ def read_OptionalSequencestring
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_Sequencestring
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalSequencestring'
+ end
+ end
+
+
+ # The Optional<T> type for SequenceTypePreservedJson.
+
+ def read_OptionalSequenceTypePreservedJson
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_SequenceTypePreservedJson
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalSequenceTypePreservedJson'
+ end
+ end
+
+
+ # The Optional<T> type for SequenceTypeOSGymSandboxClaimCondition.
+
+ def read_OptionalSequenceTypeOSGymSandboxClaimCondition
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_SequenceTypeOSGymSandboxClaimCondition
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalSequenceTypeOSGymSandboxClaimCondition'
+ end
+ end
+
+
+ # The Optional<T> type for SequenceTypeSandboxService.
+
+ def read_OptionalSequenceTypeSandboxService
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_SequenceTypeSandboxService
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalSequenceTypeSandboxService'
+ end
+ end
+
+
+ # The Optional<T> type for MapStringString.
+
+ def read_OptionalMapStringString
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_MapStringString
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalMapStringString'
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def read_Sequencestring
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_string
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypePreservedJson.
+
+ def read_SequenceTypePreservedJson
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypePreservedJson
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypeOSGymSandboxClaimCondition.
+
+ def read_SequenceTypeOSGymSandboxClaimCondition
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypeOSGymSandboxClaimCondition
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypeSandboxService.
+
+ def read_SequenceTypeSandboxService
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypeSandboxService
+ end
+
+ items
+ end
+
+ # The Map<T> type for MapStringString.
+
+ def read_MapStringString
+ count = unpack_from 4, 'l>'
+ raise InternalError, 'Unexpected negative map size' if count.negative?
+
+ items = {}
+ count.times do
+ key = read_string
+ items[key] = read_string
+ end
+
+ items
+ end
+
+
+
+ def unpack_from(size, format)
+ raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len
+
+ value = @rbuf.data.get_bytes(@offset, size).unpack format
+
+ @offset += size
+
+ # TODO: verify this
+ raise 'more than one element!!!' if value.size > 1
+
+ value[0]
+ end
+end
+
+private_constant :RustBufferStream
+
+# Helper for structured writing of values into a RustBuffer.
+class RustBufferBuilder
+ def initialize
+ @rust_buf = RustBuffer.alloc 16
+ @rust_buf.len = 0
+ end
+
+ def finalize
+ rbuf = @rust_buf
+
+ @rust_buf = nil
+
+ rbuf
+ end
+
+ def discard
+ return if @rust_buf.nil?
+
+ rbuf = finalize
+ rbuf.free
+ end
+
+ def write(value)
+ reserve(value.bytes.size) do
+ @rust_buf.data.put_array_of_char @rust_buf.len, value.bytes
+ end
+ end
+
+ def write_u16(v)
+ v = ::CyclopsSdkSchema::uniffi_in_range(v, "u16", 0, 2**16)
+ pack_into(2, 'S>', v)
+ end
+
+ def write_u32(v)
+ v = ::CyclopsSdkSchema::uniffi_in_range(v, "u32", 0, 2**32)
+ pack_into(4, 'L>', v)
+ end
+
+ def write_u64(v)
+ v = ::CyclopsSdkSchema::uniffi_in_range(v, "u64", 0, 2**64)
+ pack_into(8, 'Q>', v)
+ end
+
+ def write_bool(v)
+ pack_into(1, 'c', v ? 1 : 0)
+ end
+
+ def write_string(v)
+ v = ::CyclopsSdkSchema::uniffi_utf8(v)
+ pack_into 4, 'l>', v.bytes.size
+ write v
+ end
+
+ # The Object type PreservedJson.
+
+ def write_TypePreservedJson(obj)
+ handle = PreservedJson.uniffi_lower obj
+ pack_into(8, 'Q>', handle)
+ end
+
+ # The Record type ClaimLifecycle.
+
+ def write_TypeClaimLifecycle(v)
+ self.write_Optionalstring(v.shutdown_time)
+ self.write_Optionalstring(v.shutdown_policy)
+ self.write_Optionalbool(v.auto_renew)
+ end
+
+ # The Record type ClaimSpec.
+
+ def write_TypeClaimSpec(v)
+ self.write_TypeSandboxTemplateRef(v.sandbox_template_ref)
+ self.write_Optionalstring(v.warmpool)
+ self.write_Optionalu32(v.bind_deadline)
+ self.write_OptionalTypeClaimLifecycle(v.lifecycle)
+ end
+
+ # The Record type OSGymSandboxClaimCondition.
+
+ def write_TypeOSGymSandboxClaimCondition(v)
+ self.write_Optionalstring(v.type)
+ self.write_Optionalstring(v.status)
+ self.write_Optionalstring(v.reason)
+ self.write_Optionalstring(v.message)
+ self.write_Optionalstring(v.last_transition_time)
+ end
+
+ # The Record type OSGymSandboxClaimSandbox.
+
+ def write_TypeOSGymSandboxClaimSandbox(v)
+ self.write_Optionalstring(v.name)
+ self.write_Optionalstring(v.service)
+ end
+
+ # The Record type OSGymSandboxClaimStatus.
+
+ def write_TypeOSGymSandboxClaimStatus(v)
+ self.write_Optionalstring(v.phase)
+ self.write_OptionalSequenceTypeOSGymSandboxClaimCondition(v.conditions)
+ self.write_OptionalTypeOSGymSandboxClaimSandbox(v.sandbox)
+ end
+
+ # The Record type OSGymSandboxSpec.
+
+ def write_TypeOSGymSandboxSpec(v)
+ self.write_TypeVmTemplate(v.vm_template)
+ end
+
+ # The Record type OSGymSandboxStatus.
+
+ def write_TypeOSGymSandboxStatus(v)
+ self.write_Optionalstring(v.phase)
+ self.write_Optionalstring(v.runtime)
+ self.write_Optionalbool(v.ready)
+ self.write_Optionalstring(v.vm_name)
+ self.write_Optionalstring(v.service)
+ self.write_Optionalstring(v.message)
+ self.write_Optionalstring(v.reset_issued_at)
+ self.write_Optionalstring(v.reset_vmi_uid)
+ end
+
+ # The Record type OSGymSandboxTemplateSpec.
+
+ def write_TypeOSGymSandboxTemplateSpec(v)
+ self.write_TypeVmTemplate(v.vm_template)
+ end
+
+ # The Record type OSGymSandboxWarmPoolSpec.
+
+ def write_TypeOSGymSandboxWarmPoolSpec(v)
+ self.write_u32(v.replicas)
+ self.write_TypeSandboxTemplateRef(v.sandbox_template_ref)
+ self.write_OptionalTypeWarmPoolAutoscaling(v.autoscaling)
+ end
+
+ # The Record type OSGymSandboxWarmPoolStatus.
+
+ def write_TypeOSGymSandboxWarmPoolStatus(v)
+ self.write_Optionalu32(v.replicas)
+ self.write_Optionalu32(v.ready_replicas)
+ self.write_Optionalstring(v.selector)
+ end
+
+ # The Record type OSGymWorkspacePoolStatus.
+
+ def write_TypeOSGymWorkspacePoolStatus(v)
+ self.write_Optionalstring(v.phase)
+ self.write_Optionalu32(v.total_count)
+ self.write_Optionalu32(v.available_count)
+ self.write_Optionalu32(v.claimed_count)
+ end
+
+ # The Record type OidcConfig.
+
+ def write_TypeOidcConfig(v)
+ self.write_string(v.credentials_secret)
+ self.write_string(v.token_url)
+ self.write_Optionalstring(v.aws_role_arn)
+ self.write_Optionalstring(v.aws_region)
+ self.write_Optionalu32(v.refresh_interval_seconds)
+ end
+
+ # The Record type PoolSpec.
+
+ def write_TypePoolSpec(v)
+ self.write_u32(v.replicas)
+ self.write_TypePoolTemplate(v.template)
+ self.write_OptionalTypeWarmPoolAutoscaling(v.autoscaling)
+ self.write_OptionalSequenceTypeSandboxService(v.services)
+ end
+
+ # The Record type PoolTemplate.
+
+ def write_TypePoolTemplate(v)
+ self.write_OptionalTypeRuntimeKind(v.runtime)
+ self.write_Optionalstring(v.runtime_class_name)
+ self.write_OptionalMapStringString(v.node_selector)
+ self.write_OptionalSequenceTypePreservedJson(v.tolerations)
+ self.write_OptionalSequencestring(v.command)
+ self.write_string(v.container_disk_image)
+ self.write_Optionalstring(v.image_pull_secret)
+ self.write_Optionalu32(v.cpu_cores)
+ self.write_Optionalstring(v.memory)
+ self.write_OptionalTypeFirmware(v.firmware)
+ self.write_OptionalTypePreservedJson(v.probes)
+ self.write_OptionalTypeOidcConfig(v.oidc)
+ end
+
+ # The Record type SandboxService.
+
+ def write_TypeSandboxService(v)
+ self.write_string(v.name)
+ self.write_u16(v.target_port)
+ self.write_OptionalTypeServiceProtocol(v.protocol)
+ end
+
+ # The Record type SandboxTemplateRef.
+
+ def write_TypeSandboxTemplateRef(v)
+ self.write_string(v.name)
+ end
+
+ # The Record type VmTemplate.
+
+ def write_TypeVmTemplate(v)
+ self.write_string(v.container_disk_image)
+ self.write_OptionalSequencestring(v.command)
+ self.write_OptionalTypeRuntimeKind(v.runtime)
+ self.write_Optionalstring(v.runtime_class_name)
+ self.write_OptionalMapStringString(v.node_selector)
+ self.write_OptionalSequenceTypePreservedJson(v.tolerations)
+ self.write_OptionalTypeImagePullPolicy(v.image_pull_policy)
+ self.write_Optionalstring(v.image_pull_secret)
+ self.write_Optionalu32(v.cpu_cores)
+ self.write_Optionalstring(v.memory)
+ self.write_OptionalTypeFirmware(v.firmware)
+ self.write_OptionalTypePreservedJson(v.probes)
+ self.write_OptionalSequenceTypeSandboxService(v.services)
+ self.write_OptionalTypeOidcConfig(v.oidc)
+ end
+
+ # The Record type WarmPoolAutoscaling.
+
+ def write_TypeWarmPoolAutoscaling(v)
+ self.write_Optionalu32(v.min_pool_size)
+ self.write_Optionalu32(v.initial_pool_size)
+ self.write_Optionalu32(v.max_pool_size)
+ end
+
+ # The Enum type Firmware.
+
+ def write_TypeFirmware(v)
+ if v == Firmware::BIOS
+ pack_into(4, 'l>', 1)
+ end
+ if v == Firmware::EFI
+ pack_into(4, 'l>', 2)
+ end
+ end
+
+
+ # The Enum type ImagePullPolicy.
+
+ def write_TypeImagePullPolicy(v)
+ if v == ImagePullPolicy::ALWAYS
+ pack_into(4, 'l>', 1)
+ end
+ if v == ImagePullPolicy::IF_NOT_PRESENT
+ pack_into(4, 'l>', 2)
+ end
+ if v == ImagePullPolicy::NEVER
+ pack_into(4, 'l>', 3)
+ end
+ end
+
+
+ # The Error type JsonValueError - write for callback error returns.
+
+ def write_TypeJsonValueError(v)
+ if v.is_a?(JsonValueError::Invalid)
+ pack_into 4, 'l>', 1
+ self.write_string(v.reason)
+ return
+ end
+ end
+
+
+ # The Enum type RuntimeKind.
+
+ def write_TypeRuntimeKind(v)
+ if v == RuntimeKind::KUBEVIRT
+ pack_into(4, 'l>', 1)
+ end
+ if v == RuntimeKind::MACOS
+ pack_into(4, 'l>', 2)
+ end
+ if v == RuntimeKind::GVISOR
+ pack_into(4, 'l>', 3)
+ end
+ end
+
+
+ # The Enum type ServiceProtocol.
+
+ def write_TypeServiceProtocol(v)
+ if v == ServiceProtocol::TCP
+ pack_into(4, 'l>', 1)
+ end
+ if v == ServiceProtocol::UDP
+ pack_into(4, 'l>', 2)
+ end
+ end
+
+
+ # The Optional<T> type for u32.
+
+ def write_Optionalu32(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_u32(v)
+ end
+ end
+
+ # The Optional<T> type for bool.
+
+ def write_Optionalbool(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_bool(v)
+ end
+ end
+
+ # The Optional<T> type for string.
+
+ def write_Optionalstring(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_string(v)
+ end
+ end
+
+ # The Optional<T> type for TypePreservedJson.
+
+ def write_OptionalTypePreservedJson(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypePreservedJson(v)
+ end
+ end
+
+ # The Optional<T> type for TypeClaimLifecycle.
+
+ def write_OptionalTypeClaimLifecycle(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeClaimLifecycle(v)
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymSandboxClaimSandbox.
+
+ def write_OptionalTypeOSGymSandboxClaimSandbox(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeOSGymSandboxClaimSandbox(v)
+ end
+ end
+
+ # The Optional<T> type for TypeOidcConfig.
+
+ def write_OptionalTypeOidcConfig(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeOidcConfig(v)
+ end
+ end
+
+ # The Optional<T> type for TypeWarmPoolAutoscaling.
+
+ def write_OptionalTypeWarmPoolAutoscaling(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeWarmPoolAutoscaling(v)
+ end
+ end
+
+ # The Optional<T> type for TypeFirmware.
+
+ def write_OptionalTypeFirmware(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeFirmware(v)
+ end
+ end
+
+ # The Optional<T> type for TypeImagePullPolicy.
+
+ def write_OptionalTypeImagePullPolicy(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeImagePullPolicy(v)
+ end
+ end
+
+ # The Optional<T> type for TypeRuntimeKind.
+
+ def write_OptionalTypeRuntimeKind(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeRuntimeKind(v)
+ end
+ end
+
+ # The Optional<T> type for TypeServiceProtocol.
+
+ def write_OptionalTypeServiceProtocol(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeServiceProtocol(v)
+ end
+ end
+
+ # The Optional<T> type for Sequencestring.
+
+ def write_OptionalSequencestring(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_Sequencestring(v)
+ end
+ end
+
+ # The Optional<T> type for SequenceTypePreservedJson.
+
+ def write_OptionalSequenceTypePreservedJson(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_SequenceTypePreservedJson(v)
+ end
+ end
+
+ # The Optional<T> type for SequenceTypeOSGymSandboxClaimCondition.
+
+ def write_OptionalSequenceTypeOSGymSandboxClaimCondition(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_SequenceTypeOSGymSandboxClaimCondition(v)
+ end
+ end
+
+ # The Optional<T> type for SequenceTypeSandboxService.
+
+ def write_OptionalSequenceTypeSandboxService(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_SequenceTypeSandboxService(v)
+ end
+ end
+
+ # The Optional<T> type for MapStringString.
+
+ def write_OptionalMapStringString(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_MapStringString(v)
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def write_Sequencestring(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_string(item)
+ end
+ end
+
+ # The Sequence<T> type for TypePreservedJson.
+
+ def write_SequenceTypePreservedJson(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypePreservedJson(item)
+ end
+ end
+
+ # The Sequence<T> type for TypeOSGymSandboxClaimCondition.
+
+ def write_SequenceTypeOSGymSandboxClaimCondition(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeOSGymSandboxClaimCondition(item)
+ end
+ end
+
+ # The Sequence<T> type for TypeSandboxService.
+
+ def write_SequenceTypeSandboxService(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeSandboxService(item)
+ end
+ end
+
+ # The Map<T> type for MapStringString.
+
+ def write_MapStringString(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |k, v|
+ self.write_string(k)
+ self.write_string(v)
+ end
+ end
+
+
+
+ private
+
+ def reserve(num_bytes)
+ if @rust_buf.len + num_bytes > @rust_buf.capacity
+ @rust_buf = RustBuffer.reserve(@rust_buf, num_bytes)
+ end
+
+ yield
+
+ @rust_buf.len += num_bytes
+ end
+
+ def pack_into(size, format, value)
+ reserve(size) do
+ @rust_buf.data.put_array_of_char @rust_buf.len, [value].pack(format).bytes
+ end
+ end
+end
+
+private_constant :RustBufferBuilder
+
+ # Error definitions
+ class RustCallStatus < FFI::Struct
+ layout :code, :int8,
+ :error_buf, RustBuffer
+
+ def code
+ self[:code]
+ end
+
+ def error_buf
+ self[:error_buf]
+ end
+
+ def to_s
+ "RustCallStatus(code=#{self[:code]})"
+ end
+end
+
+# These match the values from the uniffi::rustcalls module
+CALL_SUCCESS = 0
+CALL_ERROR = 1
+CALL_PANIC = 2
+
+
+
+
+
+
+module JsonValueError
+ class Invalid < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+
+end
+
+
+# Map error modules to the RustBuffer method name that reads them
+ERROR_MODULE_TO_READER_METHOD = {
+JsonValueError => :read_TypeJsonValueError,
+}
+
+private_constant :ERROR_MODULE_TO_READER_METHOD, :CALL_SUCCESS, :CALL_ERROR, :CALL_PANIC,
+ :RustCallStatus
+
+def self.consume_buffer_into_error(error_module, rust_buffer)
+ rust_buffer.consumeWithStream do |stream|
+ reader_method = ERROR_MODULE_TO_READER_METHOD[error_module] ||
+ ERROR_MODULE_TO_READER_METHOD[error_module.name&.split('::')&.last]
+ return stream.send(reader_method)
+ end
+end
+
+class InternalError < StandardError
+end
+
+def self.rust_call(fn_name, *args)
+ # Call a rust function
+ rust_call_with_error(nil, fn_name, *args)
+end
+
+def self.rust_call_with_error(error_module, fn_name, *args)
+ # Call a rust function and handle errors
+ #
+ # Use this when the rust function returns a Result<>. error_module must be the error_module that corresponds to that Result.
+
+
+ # Note: RustCallStatus.new zeroes out the struct, which is exactly what we
+ # want to pass to Rust (code=0, error_buf=RustBuffer(len=0, capacity=0,
+ # data=NULL))
+ status = RustCallStatus.new
+ args << status
+
+ result = UniFFILib.public_send(fn_name, *args)
+
+ case status.code
+ when CALL_SUCCESS
+ result
+ when CALL_ERROR
+ if error_module.nil?
+ status.error_buf.free
+ raise InternalError, "CALL_ERROR with no error_module set"
+ else
+ raise consume_buffer_into_error(error_module, status.error_buf)
+ end
+ when CALL_PANIC
+ # When the rust code sees a panic, it tries to construct a RustBuffer
+ # with the message. But if that code panics, then it just sends back
+ # an empty buffer.
+ if status.error_buf.len > 0
+ raise InternalError, status.error_buf.consume_into_string
+ else
+ raise InternalError, "Rust panic"
+ end
+ else
+ raise InternalError, "Unknown call status: #{status.code}"
+ end
+end
+
+private_class_method :consume_buffer_into_error
+
+ # This is how we find and load the dynamic library provided by the component.
+# For now we just look it up by name.
+module UniFFILib
+ extend FFI::Library
+
+
+ ffi_lib 'cyclops_sdk'
+
+
+ # Define FFI callback types and structs (vtables, etc.)
+
+ callback :RustFutureContinuationCallback,
+ [:uint64, :int8, ],
+ :void
+
+ callback :ForeignFutureDroppedCallback,
+ [:uint64, ],
+ :void
+
+ callback :CallbackInterfaceFree,
+ [:uint64, ],
+ :void
+
+ callback :CallbackInterfaceClone,
+ [:uint64, ],
+ :uint64
+
+ class ForeignFutureDroppedCallbackStruct < FFI::Struct
+ layout(
+ :handle, :uint64,
+ :free, :ForeignFutureDroppedCallback
+ )
+ end
+
+ class ForeignFutureResultU8 < FFI::Struct
+ layout(
+ :return_value, :uint8,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU8,
+ [:uint64, ForeignFutureResultU8.by_value, ],
+ :void
+
+ class ForeignFutureResultI8 < FFI::Struct
+ layout(
+ :return_value, :int8,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI8,
+ [:uint64, ForeignFutureResultI8.by_value, ],
+ :void
+
+ class ForeignFutureResultU16 < FFI::Struct
+ layout(
+ :return_value, :uint16,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU16,
+ [:uint64, ForeignFutureResultU16.by_value, ],
+ :void
+
+ class ForeignFutureResultI16 < FFI::Struct
+ layout(
+ :return_value, :int16,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI16,
+ [:uint64, ForeignFutureResultI16.by_value, ],
+ :void
+
+ class ForeignFutureResultU32 < FFI::Struct
+ layout(
+ :return_value, :uint32,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU32,
+ [:uint64, ForeignFutureResultU32.by_value, ],
+ :void
+
+ class ForeignFutureResultI32 < FFI::Struct
+ layout(
+ :return_value, :int32,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI32,
+ [:uint64, ForeignFutureResultI32.by_value, ],
+ :void
+
+ class ForeignFutureResultU64 < FFI::Struct
+ layout(
+ :return_value, :uint64,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU64,
+ [:uint64, ForeignFutureResultU64.by_value, ],
+ :void
+
+ class ForeignFutureResultI64 < FFI::Struct
+ layout(
+ :return_value, :int64,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI64,
+ [:uint64, ForeignFutureResultI64.by_value, ],
+ :void
+
+ class ForeignFutureResultF32 < FFI::Struct
+ layout(
+ :return_value, :float,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteF32,
+ [:uint64, ForeignFutureResultF32.by_value, ],
+ :void
+
+ class ForeignFutureResultF64 < FFI::Struct
+ layout(
+ :return_value, :double,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteF64,
+ [:uint64, ForeignFutureResultF64.by_value, ],
+ :void
+
+ class ForeignFutureResultRustBuffer < FFI::Struct
+ layout(
+ :return_value, RustBuffer.by_value,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteRustBuffer,
+ [:uint64, ForeignFutureResultRustBuffer.by_value, ],
+ :void
+
+ class ForeignFutureResultVoid < FFI::Struct
+ layout(
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteVoid,
+ [:uint64, ForeignFutureResultVoid.by_value, ],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_clone_preservedjson,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_free_preservedjson,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json,
+ [RustBuffer.by_value, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json,
+ [:uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq,
+ [RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref],
+ :int8
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne,
+ [RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref],
+ :int8
+
+ attach_function :uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash,
+ [RustBuffer.by_value, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :ffi_cyclops_sdk_schema_rustbuffer_alloc,
+ [:uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_schema_rustbuffer_from_bytes,
+ [ForeignBytes, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_schema_rustbuffer_free,
+ [RustBuffer.by_value, RustCallStatus.by_ref],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rustbuffer_reserve,
+ [RustBuffer.by_value, :uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_u8,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_u8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_u8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_u8,
+ [:uint64, RustCallStatus.by_ref],
+ :uint8
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_i8,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_i8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_i8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_i8,
+ [:uint64, RustCallStatus.by_ref],
+ :int8
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_u16,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_u16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_u16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_u16,
+ [:uint64, RustCallStatus.by_ref],
+ :uint16
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_i16,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_i16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_i16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_i16,
+ [:uint64, RustCallStatus.by_ref],
+ :int16
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_u32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_u32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_u32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_u32,
+ [:uint64, RustCallStatus.by_ref],
+ :uint32
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_i32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_i32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_i32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_i32,
+ [:uint64, RustCallStatus.by_ref],
+ :int32
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_u64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_u64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_u64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_u64,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_i64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_i64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_i64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_i64,
+ [:uint64, RustCallStatus.by_ref],
+ :int64
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_f32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_f32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_f32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_f32,
+ [:uint64, RustCallStatus.by_ref],
+ :float
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_f64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_f64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_f64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_f64,
+ [:uint64, RustCallStatus.by_ref],
+ :double
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_rust_buffer,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_rust_buffer,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_rust_buffer,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_rust_buffer,
+ [:uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_poll_void,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_cancel_void,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_free_void,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_schema_rust_future_complete_void,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json,
+ [],
+ :uint16
+
+ attach_function :ffi_cyclops_sdk_schema_uniffi_contract_version,
+ [],
+ :uint32
+
+end
+
+ # Custom type definitions.
+
+ # Public interface members begin here.
+
+
+
+
+
+class Firmware
+ BIOS = 0
+ EFI = 1
+
+end
+
+
+
+
+
+
+class ImagePullPolicy
+ ALWAYS = 0
+ IF_NOT_PRESENT = 1
+ NEVER = 2
+
+end
+
+
+
+
+
+
+class RuntimeKind
+ KUBEVIRT = 0
+ MACOS = 1
+ GVISOR = 2
+
+end
+
+
+
+
+
+
+class ServiceProtocol
+ TCP = 0
+ UDP = 1
+
+end
+
+
+
+
+ # Record type ClaimLifecycle
+class ClaimLifecycle
+ attr_reader :shutdown_time, :shutdown_policy, :auto_renew
+
+ def initialize(shutdown_time:, shutdown_policy:, auto_renew:)
+ @shutdown_time = shutdown_time
+ @shutdown_policy = shutdown_policy
+ @auto_renew = auto_renew
+ end
+
+ def ==(other)
+ if @shutdown_time != other.shutdown_time
+ return false
+ end
+ if @shutdown_policy != other.shutdown_policy
+ return false
+ end
+ if @auto_renew != other.auto_renew
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type ClaimSpec
+class ClaimSpec
+ attr_reader :sandbox_template_ref, :warmpool, :bind_deadline, :lifecycle
+
+ def initialize(sandbox_template_ref:, warmpool:, bind_deadline:, lifecycle:)
+ @sandbox_template_ref = sandbox_template_ref
+ @warmpool = warmpool
+ @bind_deadline = bind_deadline
+ @lifecycle = lifecycle
+ end
+
+ def ==(other)
+ if @sandbox_template_ref != other.sandbox_template_ref
+ return false
+ end
+ if @warmpool != other.warmpool
+ return false
+ end
+ if @bind_deadline != other.bind_deadline
+ return false
+ end
+ if @lifecycle != other.lifecycle
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxClaimCondition
+class OsGymSandboxClaimCondition
+ attr_reader :type, :status, :reason, :message, :last_transition_time
+
+ def initialize(type:, status:, reason:, message:, last_transition_time:)
+ @type = type
+ @status = status
+ @reason = reason
+ @message = message
+ @last_transition_time = last_transition_time
+ end
+
+ def ==(other)
+ if @type != other.type
+ return false
+ end
+ if @status != other.status
+ return false
+ end
+ if @reason != other.reason
+ return false
+ end
+ if @message != other.message
+ return false
+ end
+ if @last_transition_time != other.last_transition_time
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxClaimSandbox
+class OsGymSandboxClaimSandbox
+ attr_reader :name, :service
+
+ def initialize(name:, service:)
+ @name = name
+ @service = service
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+ if @service != other.service
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxClaimStatus
+class OsGymSandboxClaimStatus
+ attr_reader :phase, :conditions, :sandbox
+
+ def initialize(phase:, conditions:, sandbox:)
+ @phase = phase
+ @conditions = conditions
+ @sandbox = sandbox
+ end
+
+ def ==(other)
+ if @phase != other.phase
+ return false
+ end
+ if @conditions != other.conditions
+ return false
+ end
+ if @sandbox != other.sandbox
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OidcConfig
+class OidcConfig
+ attr_reader :credentials_secret, :token_url, :aws_role_arn, :aws_region, :refresh_interval_seconds
+
+ def initialize(credentials_secret:, token_url:, aws_role_arn:, aws_region:, refresh_interval_seconds:)
+ @credentials_secret = credentials_secret
+ @token_url = token_url
+ @aws_role_arn = aws_role_arn
+ @aws_region = aws_region
+ @refresh_interval_seconds = refresh_interval_seconds
+ end
+
+ def ==(other)
+ if @credentials_secret != other.credentials_secret
+ return false
+ end
+ if @token_url != other.token_url
+ return false
+ end
+ if @aws_role_arn != other.aws_role_arn
+ return false
+ end
+ if @aws_region != other.aws_region
+ return false
+ end
+ if @refresh_interval_seconds != other.refresh_interval_seconds
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type SandboxService
+class SandboxService
+ attr_reader :name, :target_port, :protocol
+
+ def initialize(name:, target_port:, protocol:)
+ @name = name
+ @target_port = target_port
+ @protocol = protocol
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+ if @target_port != other.target_port
+ return false
+ end
+ if @protocol != other.protocol
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type SandboxTemplateRef
+class SandboxTemplateRef
+ attr_reader :name
+
+ def initialize(name:)
+ @name = name
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type VmTemplate
+class VmTemplate
+ attr_reader :container_disk_image, :command, :runtime, :runtime_class_name, :node_selector, :tolerations, :image_pull_policy, :image_pull_secret, :cpu_cores, :memory, :firmware, :probes, :services, :oidc
+
+ def initialize(container_disk_image:, command:, runtime:, runtime_class_name:, node_selector:, tolerations:, image_pull_policy:, image_pull_secret:, cpu_cores:, memory:, firmware:, probes:, services:, oidc:)
+ @container_disk_image = container_disk_image
+ @command = command
+ @runtime = runtime
+ @runtime_class_name = runtime_class_name
+ @node_selector = node_selector
+ @tolerations = tolerations
+ @image_pull_policy = image_pull_policy
+ @image_pull_secret = image_pull_secret
+ @cpu_cores = cpu_cores
+ @memory = memory
+ @firmware = firmware
+ @probes = probes
+ @services = services
+ @oidc = oidc
+ end
+
+ def ==(other)
+ if @container_disk_image != other.container_disk_image
+ return false
+ end
+ if @command != other.command
+ return false
+ end
+ if @runtime != other.runtime
+ return false
+ end
+ if @runtime_class_name != other.runtime_class_name
+ return false
+ end
+ if @node_selector != other.node_selector
+ return false
+ end
+ if @tolerations != other.tolerations
+ return false
+ end
+ if @image_pull_policy != other.image_pull_policy
+ return false
+ end
+ if @image_pull_secret != other.image_pull_secret
+ return false
+ end
+ if @cpu_cores != other.cpu_cores
+ return false
+ end
+ if @memory != other.memory
+ return false
+ end
+ if @firmware != other.firmware
+ return false
+ end
+ if @probes != other.probes
+ return false
+ end
+ if @services != other.services
+ return false
+ end
+ if @oidc != other.oidc
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxSpec
+class OsGymSandboxSpec
+ attr_reader :vm_template
+
+ def initialize(vm_template:)
+ @vm_template = vm_template
+ end
+
+ def ==(other)
+ if @vm_template != other.vm_template
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxStatus
+class OsGymSandboxStatus
+ attr_reader :phase, :runtime, :ready, :vm_name, :service, :message, :reset_issued_at, :reset_vmi_uid
+
+ def initialize(phase:, runtime:, ready:, vm_name:, service:, message:, reset_issued_at:, reset_vmi_uid:)
+ @phase = phase
+ @runtime = runtime
+ @ready = ready
+ @vm_name = vm_name
+ @service = service
+ @message = message
+ @reset_issued_at = reset_issued_at
+ @reset_vmi_uid = reset_vmi_uid
+ end
+
+ def ==(other)
+ if @phase != other.phase
+ return false
+ end
+ if @runtime != other.runtime
+ return false
+ end
+ if @ready != other.ready
+ return false
+ end
+ if @vm_name != other.vm_name
+ return false
+ end
+ if @service != other.service
+ return false
+ end
+ if @message != other.message
+ return false
+ end
+ if @reset_issued_at != other.reset_issued_at
+ return false
+ end
+ if @reset_vmi_uid != other.reset_vmi_uid
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxTemplateSpec
+class OsGymSandboxTemplateSpec
+ attr_reader :vm_template
+
+ def initialize(vm_template:)
+ @vm_template = vm_template
+ end
+
+ def ==(other)
+ if @vm_template != other.vm_template
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxWarmPoolSpec
+class OsGymSandboxWarmPoolSpec
+ attr_reader :replicas, :sandbox_template_ref, :autoscaling
+
+ def initialize(replicas:, sandbox_template_ref:, autoscaling:)
+ @replicas = replicas
+ @sandbox_template_ref = sandbox_template_ref
+ @autoscaling = autoscaling
+ end
+
+ def ==(other)
+ if @replicas != other.replicas
+ return false
+ end
+ if @sandbox_template_ref != other.sandbox_template_ref
+ return false
+ end
+ if @autoscaling != other.autoscaling
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymSandboxWarmPoolStatus
+class OsGymSandboxWarmPoolStatus
+ attr_reader :replicas, :ready_replicas, :selector
+
+ def initialize(replicas:, ready_replicas:, selector:)
+ @replicas = replicas
+ @ready_replicas = ready_replicas
+ @selector = selector
+ end
+
+ def ==(other)
+ if @replicas != other.replicas
+ return false
+ end
+ if @ready_replicas != other.ready_replicas
+ return false
+ end
+ if @selector != other.selector
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type WarmPoolAutoscaling
+class WarmPoolAutoscaling
+ attr_reader :min_pool_size, :initial_pool_size, :max_pool_size
+
+ def initialize(min_pool_size:, initial_pool_size:, max_pool_size:)
+ @min_pool_size = min_pool_size
+ @initial_pool_size = initial_pool_size
+ @max_pool_size = max_pool_size
+ end
+
+ def ==(other)
+ if @min_pool_size != other.min_pool_size
+ return false
+ end
+ if @initial_pool_size != other.initial_pool_size
+ return false
+ end
+ if @max_pool_size != other.max_pool_size
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type OSGymWorkspacePoolStatus
+class OsGymWorkspacePoolStatus
+ attr_reader :phase, :total_count, :available_count, :claimed_count
+
+ def initialize(phase:, total_count:, available_count:, claimed_count:)
+ @phase = phase
+ @total_count = total_count
+ @available_count = available_count
+ @claimed_count = claimed_count
+ end
+
+ def ==(other)
+ if @phase != other.phase
+ return false
+ end
+ if @total_count != other.total_count
+ return false
+ end
+ if @available_count != other.available_count
+ return false
+ end
+ if @claimed_count != other.claimed_count
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type PoolSpec
+class PoolSpec
+ attr_reader :replicas, :template, :autoscaling, :services
+
+ def initialize(replicas:, template:, autoscaling:, services:)
+ @replicas = replicas
+ @template = template
+ @autoscaling = autoscaling
+ @services = services
+ end
+
+# The Rust `Eq::eq` implementation.
+def ==(other)
+ return false unless other.is_a?(self.class)
+ result = ::CyclopsSdkSchema.rust_call(
+ :uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq,
+ RustBuffer.alloc_from_TypePoolSpec(self),
+ RustBuffer.alloc_from_TypePoolSpec(other)
+ )
+ 1 == result
+end
+# The Rust `Hash::hash` implementation.
+def hash
+ result = ::CyclopsSdkSchema.rust_call(
+ :uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash,
+ RustBuffer.alloc_from_TypePoolSpec(self)
+ )
+ result.to_i
+end
+
+def eql?(other)
+ self == other
+end
+end
+
+ # Record type PoolTemplate
+class PoolTemplate
+ attr_reader :runtime, :runtime_class_name, :node_selector, :tolerations, :command, :container_disk_image, :image_pull_secret, :cpu_cores, :memory, :firmware, :probes, :oidc
+
+ def initialize(runtime:, runtime_class_name:, node_selector:, tolerations:, command:, container_disk_image:, image_pull_secret:, cpu_cores:, memory:, firmware:, probes:, oidc:)
+ @runtime = runtime
+ @runtime_class_name = runtime_class_name
+ @node_selector = node_selector
+ @tolerations = tolerations
+ @command = command
+ @container_disk_image = container_disk_image
+ @image_pull_secret = image_pull_secret
+ @cpu_cores = cpu_cores
+ @memory = memory
+ @firmware = firmware
+ @probes = probes
+ @oidc = oidc
+ end
+
+ def ==(other)
+ if @runtime != other.runtime
+ return false
+ end
+ if @runtime_class_name != other.runtime_class_name
+ return false
+ end
+ if @node_selector != other.node_selector
+ return false
+ end
+ if @tolerations != other.tolerations
+ return false
+ end
+ if @command != other.command
+ return false
+ end
+ if @container_disk_image != other.container_disk_image
+ return false
+ end
+ if @image_pull_secret != other.image_pull_secret
+ return false
+ end
+ if @cpu_cores != other.cpu_cores
+ return false
+ end
+ if @memory != other.memory
+ return false
+ end
+ if @firmware != other.firmware
+ return false
+ end
+ if @probes != other.probes
+ return false
+ end
+ if @oidc != other.oidc
+ return false
+ end
+
+ true
+ end
+
+end
+
+
+
+
+
+ class PreservedJson
+
+ # A private helper for initializing instances of the class from a raw handle,
+ # bypassing any initialization logic and ensuring they are GC'd properly.
+ def self.uniffi_allocate(handle)
+ inst = allocate
+ inst.instance_variable_set :@handle, handle
+ ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_handle(handle, inst.object_id))
+ return inst
+ end
+
+ # A private helper for registering an object finalizer.
+ # N.B. it's important that this does not capture a reference
+ # to the actual instance, only its underlying handle.
+ def self.uniffi_define_finalizer_by_handle(handle, object_id)
+ Proc.new do |_id|
+ ::CyclopsSdkSchema.rust_call(
+ :uniffi_cyclops_sdk_schema_fn_free_preservedjson,
+ handle
+ )
+ end
+ end
+ # A private helper for lowering instances into a raw handle.
+ # This does an explicit typecheck, because accidentally lowering a different type of
+ # object in a place where this type is expected, could lead to memory unsafety.
+ def self.uniffi_check_lower(inst)
+ if !inst.is_a? self
+ raise TypeError.new "Expected a PreservedJson instance, got #{inst}"
+ end
+ end
+
+ def uniffi_clone_handle()
+ return ::CyclopsSdkSchema.rust_call(
+ :uniffi_cyclops_sdk_schema_fn_clone_preservedjson,
+ @handle
+ )
+ end
+
+ def self.uniffi_lower(inst)
+ return inst.uniffi_clone_handle()
+ end
+
+ def self.uniffi_lift(handle)
+ uniffi_allocate handle
+ end
+
+
+ def self.from_json(value)
+ value = ::CyclopsSdkSchema::uniffi_utf8(value)
+
+ # Call the (fallible) function before creating any half-baked object instances.
+ # Lightly yucky way to bypass the usual "initialize" logic
+ # and just create a new instance with the required handle.
+ return uniffi_allocate(::CyclopsSdkSchema.rust_call_with_error(JsonValueError,:uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json,RustBuffer.alloc_from_string(value)))
+ end
+
+
+ def to_json()
+ result = ::CyclopsSdkSchema.rust_call(:uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json,uniffi_clone_handle(),)
+ return result.consume_into_string
+ end
+
+end
+
+
+
+end
diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
new file mode 100644
index 0000000000..dda4920bf2
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
@@ -0,0 +1,3267 @@
+# This file was autogenerated by some hot garbage in the `uniffi` crate.
+# Trust me, you don't want to mess with it!
+
+# Common helper code.
+#
+# Ideally this would live in a separate .rb file where it can be unittested etc
+# in isolation, and perhaps even published as a re-useable package.
+#
+# However, it's important that the details of how this helper code works (e.g. the
+# way that different builtin types are passed across the FFI) exactly match what's
+# expected by the rust code on the other side of the interface. In practice right
+# now that means coming from the exact some version of `uniffi` that was used to
+# compile the rust component. The easiest way to ensure this is to bundle the Ruby
+# helpers directly inline like we're doing here.
+
+require 'ffi'
+require 'set'
+require 'monitor'
+
+module CyclopsSdk
+ def self.uniffi_in_range(i, type_name, min, max)
+ raise TypeError, "no implicit conversion of #{i} into Integer" unless i.respond_to?(:to_int)
+ i = i.to_int
+ raise RangeError, "#{type_name} requires #{min} <= value < #{max}" unless (min <= i && i < max)
+ i
+end
+
+def self.uniffi_utf8(v)
+ raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str)
+ v = v.to_str.encode(Encoding::UTF_8)
+ raise Encoding::InvalidByteSequenceError, "not a valid UTF-8 encoded string" unless v.valid_encoding?
+ v
+end
+
+def self.uniffi_bytes(v)
+ raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str)
+ v.to_str
+end
+
+# Callback return codes
+UNIFFI_CALLBACK_SUCCESS = 0
+UNIFFI_CALLBACK_ERROR = 1
+UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2
+
+# Call a method on a callback interface object, catching and reporting errors
+# to Rust via the call_status.
+# If error_type is provided, known errors of that type are reported as UNIFFI_CALLBACK_ERROR;
+# all other errors are reported as UNIFFI_CALLBACK_UNEXPECTED_ERROR.
+def self.uniffi_trait_interface_call(call_status, make_call, write_return_value, error_type = nil, lower_error = nil)
+ begin
+ write_return_value.call make_call.call
+ rescue StandardError => e
+ buf = if !error_type.nil? && uniffi_is_error_type?(e, error_type)
+ call_status[:code] = UNIFFI_CALLBACK_ERROR
+ lower_error.call e
+ else
+ call_status[:code] = UNIFFI_CALLBACK_UNEXPECTED_ERROR
+ RustBuffer.alloc_from_string(e.inspect)
+ end
+
+ error_buf = call_status[:error_buf]
+ error_buf[:capacity] = buf[:capacity]
+ error_buf[:len] = buf[:len]
+ error_buf[:data] = buf[:data]
+ end
+end
+
+# Check if an exception is a variant of the given error type.
+# Error types in Ruby are either modules (non-flat enums) or classes (flat enums),
+# with variant classes as constant within them.
+def self.uniffi_is_error_type?(e, error_type)
+ # Object-as-error: error_type is a class itself (e.g. MyError < StandardError)
+ if error_type.is_a?(Class) && e.is_a?(error_type)
+ return true
+ end
+
+ # Enum error: error_type is a module with class constants for each variant
+ error_type.constants.any? do |c|
+ klass = error_type.const_get c
+ klass.is_a?(Class) && e.is_a?(klass)
+ end
+end
+ # A handle map for converting Ruby objects to/from integer handles.
+#
+# When passing callback interface or trait interface objects to Ruby, we store
+# the Ruby object in this map and pass the integer handle to Rust. When Rust
+# calls back, we look up the Ruby object by its handle.
+#
+# Ruby-created handles are always odd (staring at 1, incrementing by 2).
+# Rust-created handles are always even. This convention lets us distinguish
+# the source in lift/lower without extra metadata.
+
+
+class UniffiHandleMap
+ def initialize
+ @lock = Monitor.new
+ @map = {}
+ @counter = 1 # Start at 1 (odd), increment by 2
+ end
+
+ def insert(obj)
+ @lock.synchronize do
+ handle = @counter
+ @counter += 2
+ @map[handle] = obj
+ handle
+ end
+ end
+
+ def get(handle)
+ @lock.synchronize do
+ obj = @map[handle]
+ raise InternalError, "UniffiHandleMap.get: invalid handle #{handle}" if obj.nil?
+ obj
+ end
+ end
+
+ def clone_handle(handle)
+ @lock.synchronize do
+ obj = @map[handle]
+ raise InternalError, "UniffiHandleMap.clone_handle: invalid handle #{handle}" if obj.nil?
+ new_handle = @counter
+ @counter += 2
+ @map[new_handle] = obj
+ new_handle
+ end
+ end
+
+ def remove(handle)
+ @lock.synchronize do
+ obj = @map.delete(handle)
+ raise InternalError, "UniffiHandleMap.remove: invalid handle #{handle}" if obj.nil?
+ obj
+ end
+ end
+
+ # Used for testing/debugging purposes
+ def size
+ @lock.synchronize { @map.size }
+ end
+end
+
+private_constant :UniffiHandleMap
+ class RustBuffer < FFI::Struct
+ layout :capacity, :uint64,
+ :len, :uint64,
+ :data, :pointer
+
+ def self.alloc(size)
+ return ::CyclopsSdk.rust_call(:ffi_cyclops_sdk_rustbuffer_alloc, size)
+ end
+
+ def self.reserve(rbuf, additional)
+ return ::CyclopsSdk.rust_call(:ffi_cyclops_sdk_rustbuffer_reserve, rbuf, additional)
+ end
+
+ def free
+ ::CyclopsSdk.rust_call(:ffi_cyclops_sdk_rustbuffer_free, self)
+ end
+
+ def capacity
+ self[:capacity]
+ end
+
+ def len
+ self[:len]
+ end
+
+ def len=(value)
+ self[:len] = value
+ end
+
+ def data
+ self[:data]
+ end
+
+ def to_s
+ "RustBuffer(capacity=#{capacity}, len=#{len}, data=#{data.read_bytes len})"
+ end
+
+ # The allocated buffer will be automatically freed if an error occurs, ensuring that
+ # we don't accidentally leak it.
+ def self.allocWithBuilder
+ builder = RustBufferBuilder.new
+
+ begin
+ yield builder
+ rescue => e
+ builder.discard
+ raise e
+ end
+ end
+
+ # The RustBuffer will be freed once the context-manager exits, ensuring that we don't
+ # leak it even if an error occurs.
+ def consumeWithStream
+ stream = RustBufferStream.new self
+
+ yield stream
+
+ raise RuntimeError, 'junk data left in buffer after consuming' if stream.remaining != 0
+ ensure
+ free
+ end# The primitive String type.
+
+ def self.alloc_from_string(value)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write value.encode('utf-8')
+ return builder.finalize
+ end
+ end
+
+ def consume_into_string
+ consumeWithStream do |stream|
+ return stream.read(stream.remaining).force_encoding(Encoding::UTF_8)
+ end
+ end
+
+ # The primitive Bytes type.
+
+ def self.alloc_from_bytes(value)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_bytes(value)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_bytes
+ consumeWithStream do |stream|
+ return stream.read_bytes
+ end
+ end
+
+ # The Record type Claim.
+
+ def self.check_lower_TypeClaim(v)
+
+
+ RustBuffer.check_lower_TypeResourceMetadata(v.metadata)
+ RustBuffer.check_lower_TypeClaimSpec(v.spec)
+ RustBuffer.check_lower_OptionalTypeOSGymSandboxClaimStatus(v.status)
+ end
+
+ def self.alloc_from_TypeClaim(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeClaim(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeClaim
+ consumeWithStream do |stream|
+ return stream.read_TypeClaim
+ end
+ end
+
+ # The Record type CreateClaimRequest.
+
+ def self.check_lower_TypeCreateClaimRequest(v)
+ RustBuffer.check_lower_TypePool(v.pool)
+ RustBuffer.check_lower_OptionalTypeClaimSpec(v.spec)
+ end
+
+ def self.alloc_from_TypeCreateClaimRequest(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeCreateClaimRequest(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeCreateClaimRequest
+ consumeWithStream do |stream|
+ return stream.read_TypeCreateClaimRequest
+ end
+ end
+
+ # The Record type CreatePoolRequest.
+
+ def self.check_lower_TypeCreatePoolRequest(v)
+
+ RustBuffer.check_lower_TypePoolSpec(v.spec)
+ end
+
+ def self.alloc_from_TypeCreatePoolRequest(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeCreatePoolRequest(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeCreatePoolRequest
+ consumeWithStream do |stream|
+ return stream.read_TypeCreatePoolRequest
+ end
+ end
+
+ # The Record type CyclopsConfiguration.
+
+ def self.check_lower_TypeCyclopsConfiguration(v)
+
+
+ (CyclopsCredentials.uniffi_check_lower v.credentials)
+
+
+
+
+ end
+
+ def self.alloc_from_TypeCyclopsConfiguration(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeCyclopsConfiguration(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeCyclopsConfiguration
+ consumeWithStream do |stream|
+ return stream.read_TypeCyclopsConfiguration
+ end
+ end
+
+ # The Record type HttpHeader.
+
+ def self.check_lower_TypeHttpHeader(v)
+
+
+ end
+
+ def self.alloc_from_TypeHttpHeader(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeHttpHeader(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeHttpHeader
+ consumeWithStream do |stream|
+ return stream.read_TypeHttpHeader
+ end
+ end
+
+ # The Record type HttpRequest.
+
+ def self.check_lower_TypeHttpRequest(v)
+
+
+ RustBuffer.check_lower_SequenceTypeHttpHeader(v.headers)
+ RustBuffer.check_lower_Optionalbytes(v.body)
+ end
+
+ def self.alloc_from_TypeHttpRequest(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeHttpRequest(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeHttpRequest
+ consumeWithStream do |stream|
+ return stream.read_TypeHttpRequest
+ end
+ end
+
+ # The Record type HttpResponse.
+
+ def self.check_lower_TypeHttpResponse(v)
+
+ RustBuffer.check_lower_SequenceTypeHttpHeader(v.headers)
+
+ end
+
+ def self.alloc_from_TypeHttpResponse(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeHttpResponse(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeHttpResponse
+ consumeWithStream do |stream|
+ return stream.read_TypeHttpResponse
+ end
+ end
+
+ # The Record type Pool.
+
+ def self.check_lower_TypePool(v)
+
+
+ RustBuffer.check_lower_TypeResourceMetadata(v.metadata)
+ RustBuffer.check_lower_TypePoolSpec(v.spec)
+ RustBuffer.check_lower_OptionalTypeOSGymWorkspacePoolStatus(v.status)
+ end
+
+ def self.alloc_from_TypePool(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypePool(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypePool
+ consumeWithStream do |stream|
+ return stream.read_TypePool
+ end
+ end
+
+ # The Record type ResourceMetadata.
+
+ def self.check_lower_TypeResourceMetadata(v)
+
+
+ RustBuffer.check_lower_OptionalMapStringString(v.labels)
+ end
+
+ def self.alloc_from_TypeResourceMetadata(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeResourceMetadata(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeResourceMetadata
+ consumeWithStream do |stream|
+ return stream.read_TypeResourceMetadata
+ end
+ end
+
+ # The Record type Sandbox.
+
+ def self.check_lower_TypeSandbox(v)
+
+
+
+ RustBuffer.check_lower_Sequencestring(v.services)
+ end
+
+ def self.alloc_from_TypeSandbox(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeSandbox(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_TypeSandbox
+ consumeWithStream do |stream|
+ return stream.read_TypeSandbox
+ end
+ end
+
+ # Error enum - generate alloc_from for callback error serialization
+ def self.alloc_from_TypeHttpError(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeHttpError(v)
+ return builder.finalize
+ end
+ end
+
+ # Enum used as error - generate consume_into_ for use as a return value
+ def consume_into_TypeHttpError
+ consumeWithStream do |stream|
+ return stream.read_TypeHttpError
+ end
+ end
+
+
+ # Error enum - generate alloc_from for callback error serialization
+ def self.alloc_from_TypeSdkError(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeSdkError(v)
+ return builder.finalize
+ end
+ end
+
+ # Enum used as error - generate consume_into_ for use as a return value
+ def consume_into_TypeSdkError
+ consumeWithStream do |stream|
+ return stream.read_TypeSdkError
+ end
+ end
+
+
+ # The Optional<T> type for bytes.
+
+ def self.check_lower_Optionalbytes(v)
+ if !v.nil?
+
+ end
+ end
+
+ def self.alloc_from_Optionalbytes(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Optionalbytes(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Optionalbytes
+ consumeWithStream do |stream|
+ return stream.read_Optionalbytes
+ end
+ end
+
+ # The Optional<T> type for TypeClaimSpec.
+
+ def self.check_lower_OptionalTypeClaimSpec(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeClaimSpec(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeClaimSpec(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeClaimSpec(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeClaimSpec
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeClaimSpec
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymSandboxClaimStatus.
+
+ def self.check_lower_OptionalTypeOSGymSandboxClaimStatus(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeOSGymSandboxClaimStatus(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeOSGymSandboxClaimStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeOSGymSandboxClaimStatus(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeOSGymSandboxClaimStatus
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeOSGymSandboxClaimStatus
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymWorkspacePoolStatus.
+
+ def self.check_lower_OptionalTypeOSGymWorkspacePoolStatus(v)
+ if !v.nil?
+ RustBuffer.check_lower_TypeOSGymWorkspacePoolStatus(v)
+ end
+ end
+
+ def self.alloc_from_OptionalTypeOSGymWorkspacePoolStatus(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalTypeOSGymWorkspacePoolStatus(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalTypeOSGymWorkspacePoolStatus
+ consumeWithStream do |stream|
+ return stream.read_OptionalTypeOSGymWorkspacePoolStatus
+ end
+ end
+
+ # The Optional<T> type for MapStringString.
+
+ def self.check_lower_OptionalMapStringString(v)
+ if !v.nil?
+ RustBuffer.check_lower_MapStringString(v)
+ end
+ end
+
+ def self.alloc_from_OptionalMapStringString(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_OptionalMapStringString(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_OptionalMapStringString
+ consumeWithStream do |stream|
+ return stream.read_OptionalMapStringString
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def self.check_lower_Sequencestring(v)
+ v.each do |item|
+
+ end
+ end
+
+ def self.alloc_from_Sequencestring(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Sequencestring(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_Sequencestring
+ consumeWithStream do |stream|
+ return stream.read_Sequencestring
+ end
+ end
+
+ # The Sequence<T> type for TypeClaim.
+
+ def self.check_lower_SequenceTypeClaim(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeClaim(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeClaim(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeClaim(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypeClaim
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypeClaim
+ end
+ end
+
+ # The Sequence<T> type for TypeHttpHeader.
+
+ def self.check_lower_SequenceTypeHttpHeader(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeHttpHeader(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeHttpHeader(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeHttpHeader(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypeHttpHeader
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypeHttpHeader
+ end
+ end
+
+ # The Sequence<T> type for TypePool.
+
+ def self.check_lower_SequenceTypePool(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypePool(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypePool(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypePool(v)
+ return builder.finalize()
+ end
+ end
+
+ def consume_into_SequenceTypePool
+ consumeWithStream do |stream|
+ return stream.read_SequenceTypePool
+ end
+ end
+
+
+ # The Map<T> type for MapStringString.
+
+ def self.check_lower_MapStringString(v)
+ v.each do |k, v|
+
+
+ end
+ end
+
+ def self.alloc_from_MapStringString(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_MapStringString(v)
+ return builder.finalize
+ end
+ end
+
+ def consume_into_MapStringString
+ consumeWithStream do |stream|
+ return stream.read_MapStringString
+ end
+ end
+end
+
+module UniFFILib
+ class ForeignBytes < FFI::Struct
+ layout :len, :int32,
+ :data, :pointer
+
+ def len
+ self[:len]
+ end
+
+ def data
+ self[:data]
+ end
+
+ def to_s
+ "ForeignBytes(len=#{len}, data=#{data.read_bytes(len)})"
+ end
+ end
+end
+
+private_constant :UniFFILib
+
+# Helper for structured reading of values from a RustBuffer.
+class RustBufferStream
+
+ def initialize(rbuf)
+ @rbuf = rbuf
+ @offset = 0
+ end
+
+ def remaining
+ @rbuf.len - @offset
+ end
+
+ def read(size)
+ raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len
+
+ data = @rbuf.data.get_bytes @offset, size
+
+ @offset += size
+
+ data
+ end
+
+ def read_u16
+ unpack_from 2, 'S>'
+ end
+
+ def read_u32
+ unpack_from 4, 'L>'
+ end
+
+ def read_u64
+ unpack_from 8, 'Q>'
+ end
+
+ def read_string
+ size = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative string length' if size.negative?
+
+ read(size).force_encoding(Encoding::UTF_8)
+ end
+
+ def read_bytes
+ size = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative byte string length' if size.negative?
+
+ read(size).force_encoding(Encoding::BINARY)
+ end
+
+ # The Object type CyclopsClient.
+
+ def read_TypeCyclopsClient
+ handle = unpack_from 8, 'Q>'
+ return CyclopsClient.uniffi_lift(handle)
+ end
+
+ # The Object type CyclopsCredentials.
+
+ def read_TypeCyclopsCredentials
+ handle = unpack_from 8, 'Q>'
+ return CyclopsCredentials.uniffi_lift(handle)
+ end
+
+ # The Object type HttpClient.
+
+ def read_TypeHttpClient
+ handle = unpack_from 8, 'Q>'
+ return HttpClient.uniffi_lift(handle)
+ end
+
+ # The Record type Claim.
+
+ def read_TypeClaim
+ Claim.new(
+ api_version: read_string,
+ kind: read_string,
+ metadata: read_TypeResourceMetadata,
+ spec: read_TypeClaimSpec,
+ status: read_OptionalTypeOSGymSandboxClaimStatus
+ )
+ end
+
+ # The Record type CreateClaimRequest.
+
+ def read_TypeCreateClaimRequest
+ CreateClaimRequest.new(
+ pool: read_TypePool,
+ spec: read_OptionalTypeClaimSpec
+ )
+ end
+
+ # The Record type CreatePoolRequest.
+
+ def read_TypeCreatePoolRequest
+ CreatePoolRequest.new(
+ namespace: read_string,
+ spec: read_TypePoolSpec
+ )
+ end
+
+ # The Record type CyclopsConfiguration.
+
+ def read_TypeCyclopsConfiguration
+ CyclopsConfiguration.new(
+ base_url: read_string,
+ token_url: read_string,
+ credentials: read_TypeCyclopsCredentials,
+ pool_poll_interval_ms: read_u64,
+ pool_poll_limit: read_u32,
+ claim_poll_interval_ms: read_u64,
+ claim_poll_limit: read_u32
+ )
+ end
+
+ # The Record type HttpHeader.
+
+ def read_TypeHttpHeader
+ HttpHeader.new(
+ name: read_string,
+ value: read_string
+ )
+ end
+
+ # The Record type HttpRequest.
+
+ def read_TypeHttpRequest
+ HttpRequest.new(
+ method: read_string,
+ url: read_string,
+ headers: read_SequenceTypeHttpHeader,
+ body: read_Optionalbytes
+ )
+ end
+
+ # The Record type HttpResponse.
+
+ def read_TypeHttpResponse
+ HttpResponse.new(
+ status: read_u16,
+ headers: read_SequenceTypeHttpHeader,
+ body: read_bytes
+ )
+ end
+
+ # The Record type Pool.
+
+ def read_TypePool
+ Pool.new(
+ api_version: read_string,
+ kind: read_string,
+ metadata: read_TypeResourceMetadata,
+ spec: read_TypePoolSpec,
+ status: read_OptionalTypeOSGymWorkspacePoolStatus
+ )
+ end
+
+ # The Record type ResourceMetadata.
+
+ def read_TypeResourceMetadata
+ ResourceMetadata.new(
+ namespace: read_string,
+ name: read_string,
+ labels: read_OptionalMapStringString
+ )
+ end
+
+ # The Record type Sandbox.
+
+ def read_TypeSandbox
+ Sandbox.new(
+ namespace: read_string,
+ claim: read_string,
+ name: read_string,
+ services: read_Sequencestring
+ )
+ end
+
+
+
+
+
+ # The Error type HttpError
+
+ def read_TypeHttpError
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return HttpError::Transport.new(
+ reason: read_string()
+ )
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeHttpError'
+ end
+
+
+
+
+
+
+ # The Error type SdkError
+
+ def read_TypeSdkError
+ variant = unpack_from 4, 'l>'
+
+ if variant == 1
+ return SdkError::Configuration.new(
+ reason: read_string()
+ )
+ end
+ if variant == 2
+ return SdkError::InvalidResourceName.new(
+ field: read_string(),
+ value: read_string(),
+ reason: read_string()
+ )
+ end
+ if variant == 3
+ return SdkError::Transport.new(
+ reason: read_string()
+ )
+ end
+ if variant == 4
+ return SdkError::Token.new(
+ reason: read_string()
+ )
+ end
+ if variant == 5
+ return SdkError::Body.new(
+ reason: read_string()
+ )
+ end
+ if variant == 6
+ return SdkError::Status.new(
+ operation: read_string(),
+ status: read_u16(),
+ body: read_string()
+ )
+ end
+ if variant == 7
+ return SdkError::UnknownService.new(
+ requested: read_string(),
+ available: read_Sequencestring()
+ )
+ end
+ if variant == 8
+ return SdkError::InvalidServicePath.new(
+ path: read_string()
+ )
+ end
+ if variant == 9
+ return SdkError::ClaimFailed.new(
+ phase: read_string(),
+ status: read_string()
+ )
+ end
+ if variant == 10
+ return SdkError::ClaimTimeout.new
+ end
+
+ raise InternalError, 'Unexpected variant tag for TypeSdkError'
+ end
+
+
+
+ # The Optional<T> type for bytes.
+
+ def read_Optionalbytes
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_bytes
+ else
+ raise InternalError, 'Unexpected flag byte for Optionalbytes'
+ end
+ end
+
+
+ # The Optional<T> type for TypeClaimSpec.
+
+ def read_OptionalTypeClaimSpec
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeClaimSpec
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeClaimSpec'
+ end
+ end
+
+
+ # The Optional<T> type for TypeOSGymSandboxClaimStatus.
+
+ def read_OptionalTypeOSGymSandboxClaimStatus
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeOSGymSandboxClaimStatus
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeOSGymSandboxClaimStatus'
+ end
+ end
+
+
+ # The Optional<T> type for TypeOSGymWorkspacePoolStatus.
+
+ def read_OptionalTypeOSGymWorkspacePoolStatus
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_TypeOSGymWorkspacePoolStatus
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalTypeOSGymWorkspacePoolStatus'
+ end
+ end
+
+
+ # The Optional<T> type for MapStringString.
+
+ def read_OptionalMapStringString
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return read_MapStringString
+ else
+ raise InternalError, 'Unexpected flag byte for OptionalMapStringString'
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def read_Sequencestring
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_string
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypeClaim.
+
+ def read_SequenceTypeClaim
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypeClaim
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypeHttpHeader.
+
+ def read_SequenceTypeHttpHeader
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypeHttpHeader
+ end
+
+ items
+ end
+
+ # The Sequence<T> type for TypePool.
+
+ def read_SequenceTypePool
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append read_TypePool
+ end
+
+ items
+ end
+
+ # The Map<T> type for MapStringString.
+
+ def read_MapStringString
+ count = unpack_from 4, 'l>'
+ raise InternalError, 'Unexpected negative map size' if count.negative?
+
+ items = {}
+ count.times do
+ key = read_string
+ items[key] = read_string
+ end
+
+ items
+ end
+
+
+
+ def unpack_from(size, format)
+ raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len
+
+ value = @rbuf.data.get_bytes(@offset, size).unpack format
+
+ @offset += size
+
+ # TODO: verify this
+ raise 'more than one element!!!' if value.size > 1
+
+ value[0]
+ end
+end
+
+private_constant :RustBufferStream
+
+# Helper for structured writing of values into a RustBuffer.
+class RustBufferBuilder
+ def initialize
+ @rust_buf = RustBuffer.alloc 16
+ @rust_buf.len = 0
+ end
+
+ def finalize
+ rbuf = @rust_buf
+
+ @rust_buf = nil
+
+ rbuf
+ end
+
+ def discard
+ return if @rust_buf.nil?
+
+ rbuf = finalize
+ rbuf.free
+ end
+
+ def write(value)
+ reserve(value.bytes.size) do
+ @rust_buf.data.put_array_of_char @rust_buf.len, value.bytes
+ end
+ end
+
+ def write_u16(v)
+ v = ::CyclopsSdk::uniffi_in_range(v, "u16", 0, 2**16)
+ pack_into(2, 'S>', v)
+ end
+
+ def write_u32(v)
+ v = ::CyclopsSdk::uniffi_in_range(v, "u32", 0, 2**32)
+ pack_into(4, 'L>', v)
+ end
+
+ def write_u64(v)
+ v = ::CyclopsSdk::uniffi_in_range(v, "u64", 0, 2**64)
+ pack_into(8, 'Q>', v)
+ end
+
+ def write_string(v)
+ v = ::CyclopsSdk::uniffi_utf8(v)
+ pack_into 4, 'l>', v.bytes.size
+ write v
+ end
+
+ def write_bytes(v)
+ v = ::CyclopsSdk::uniffi_bytes(v)
+ pack_into 4, 'l>', v.bytes.size
+ write v
+ end
+
+ # The Object type CyclopsClient.
+
+ def write_TypeCyclopsClient(obj)
+ handle = CyclopsClient.uniffi_lower obj
+ pack_into(8, 'Q>', handle)
+ end
+
+ # The Object type CyclopsCredentials.
+
+ def write_TypeCyclopsCredentials(obj)
+ handle = CyclopsCredentials.uniffi_lower obj
+ pack_into(8, 'Q>', handle)
+ end
+
+ # The Object type HttpClient.
+
+ def write_TypeHttpClient(obj)
+ handle = HttpClient.uniffi_lower obj
+ pack_into(8, 'Q>', handle)
+ end
+
+ # The Record type Claim.
+
+ def write_TypeClaim(v)
+ self.write_string(v.api_version)
+ self.write_string(v.kind)
+ self.write_TypeResourceMetadata(v.metadata)
+ self.write_TypeClaimSpec(v.spec)
+ self.write_OptionalTypeOSGymSandboxClaimStatus(v.status)
+ end
+
+ # The Record type CreateClaimRequest.
+
+ def write_TypeCreateClaimRequest(v)
+ self.write_TypePool(v.pool)
+ self.write_OptionalTypeClaimSpec(v.spec)
+ end
+
+ # The Record type CreatePoolRequest.
+
+ def write_TypeCreatePoolRequest(v)
+ self.write_string(v.namespace)
+ self.write_TypePoolSpec(v.spec)
+ end
+
+ # The Record type CyclopsConfiguration.
+
+ def write_TypeCyclopsConfiguration(v)
+ self.write_string(v.base_url)
+ self.write_string(v.token_url)
+ self.write_TypeCyclopsCredentials(v.credentials)
+ self.write_u64(v.pool_poll_interval_ms)
+ self.write_u32(v.pool_poll_limit)
+ self.write_u64(v.claim_poll_interval_ms)
+ self.write_u32(v.claim_poll_limit)
+ end
+
+ # The Record type HttpHeader.
+
+ def write_TypeHttpHeader(v)
+ self.write_string(v.name)
+ self.write_string(v.value)
+ end
+
+ # The Record type HttpRequest.
+
+ def write_TypeHttpRequest(v)
+ self.write_string(v.method)
+ self.write_string(v.url)
+ self.write_SequenceTypeHttpHeader(v.headers)
+ self.write_Optionalbytes(v.body)
+ end
+
+ # The Record type HttpResponse.
+
+ def write_TypeHttpResponse(v)
+ self.write_u16(v.status)
+ self.write_SequenceTypeHttpHeader(v.headers)
+ self.write_bytes(v.body)
+ end
+
+ # The Record type Pool.
+
+ def write_TypePool(v)
+ self.write_string(v.api_version)
+ self.write_string(v.kind)
+ self.write_TypeResourceMetadata(v.metadata)
+ self.write_TypePoolSpec(v.spec)
+ self.write_OptionalTypeOSGymWorkspacePoolStatus(v.status)
+ end
+
+ # The Record type ResourceMetadata.
+
+ def write_TypeResourceMetadata(v)
+ self.write_string(v.namespace)
+ self.write_string(v.name)
+ self.write_OptionalMapStringString(v.labels)
+ end
+
+ # The Record type Sandbox.
+
+ def write_TypeSandbox(v)
+ self.write_string(v.namespace)
+ self.write_string(v.claim)
+ self.write_string(v.name)
+ self.write_Sequencestring(v.services)
+ end
+
+ # The Error type HttpError - write for callback error returns.
+
+ def write_TypeHttpError(v)
+ if v.is_a?(HttpError::Transport)
+ pack_into 4, 'l>', 1
+ self.write_string(v.reason)
+ return
+ end
+ end
+
+
+ # The Error type SdkError - write for callback error returns.
+
+ def write_TypeSdkError(v)
+ if v.is_a?(SdkError::Configuration)
+ pack_into 4, 'l>', 1
+ self.write_string(v.reason)
+ return
+ end
+ if v.is_a?(SdkError::InvalidResourceName)
+ pack_into 4, 'l>', 2
+ self.write_string(v.field)
+ self.write_string(v.value)
+ self.write_string(v.reason)
+ return
+ end
+ if v.is_a?(SdkError::Transport)
+ pack_into 4, 'l>', 3
+ self.write_string(v.reason)
+ return
+ end
+ if v.is_a?(SdkError::Token)
+ pack_into 4, 'l>', 4
+ self.write_string(v.reason)
+ return
+ end
+ if v.is_a?(SdkError::Body)
+ pack_into 4, 'l>', 5
+ self.write_string(v.reason)
+ return
+ end
+ if v.is_a?(SdkError::Status)
+ pack_into 4, 'l>', 6
+ self.write_string(v.operation)
+ self.write_u16(v.status)
+ self.write_string(v.body)
+ return
+ end
+ if v.is_a?(SdkError::UnknownService)
+ pack_into 4, 'l>', 7
+ self.write_string(v.requested)
+ self.write_Sequencestring(v.available)
+ return
+ end
+ if v.is_a?(SdkError::InvalidServicePath)
+ pack_into 4, 'l>', 8
+ self.write_string(v.path)
+ return
+ end
+ if v.is_a?(SdkError::ClaimFailed)
+ pack_into 4, 'l>', 9
+ self.write_string(v.phase)
+ self.write_string(v.status)
+ return
+ end
+ if v.is_a?(SdkError::ClaimTimeout)
+ pack_into 4, 'l>', 10
+ return
+ end
+ end
+
+
+ # The Optional<T> type for bytes.
+
+ def write_Optionalbytes(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_bytes(v)
+ end
+ end
+
+ # The Optional<T> type for TypeClaimSpec.
+
+ def write_OptionalTypeClaimSpec(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeClaimSpec(v)
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymSandboxClaimStatus.
+
+ def write_OptionalTypeOSGymSandboxClaimStatus(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeOSGymSandboxClaimStatus(v)
+ end
+ end
+
+ # The Optional<T> type for TypeOSGymWorkspacePoolStatus.
+
+ def write_OptionalTypeOSGymWorkspacePoolStatus(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_TypeOSGymWorkspacePoolStatus(v)
+ end
+ end
+
+ # The Optional<T> type for MapStringString.
+
+ def write_OptionalMapStringString(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_MapStringString(v)
+ end
+ end
+
+ # The Sequence<T> type for string.
+
+ def write_Sequencestring(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_string(item)
+ end
+ end
+
+ # The Sequence<T> type for TypeClaim.
+
+ def write_SequenceTypeClaim(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeClaim(item)
+ end
+ end
+
+ # The Sequence<T> type for TypeHttpHeader.
+
+ def write_SequenceTypeHttpHeader(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeHttpHeader(item)
+ end
+ end
+
+ # The Sequence<T> type for TypePool.
+
+ def write_SequenceTypePool(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypePool(item)
+ end
+ end
+
+ # The Map<T> type for MapStringString.
+
+ def write_MapStringString(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |k, v|
+ self.write_string(k)
+ self.write_string(v)
+ end
+ end
+
+
+
+ private
+
+ def reserve(num_bytes)
+ if @rust_buf.len + num_bytes > @rust_buf.capacity
+ @rust_buf = RustBuffer.reserve(@rust_buf, num_bytes)
+ end
+
+ yield
+
+ @rust_buf.len += num_bytes
+ end
+
+ def pack_into(size, format, value)
+ reserve(size) do
+ @rust_buf.data.put_array_of_char @rust_buf.len, [value].pack(format).bytes
+ end
+ end
+end
+
+private_constant :RustBufferBuilder
+
+ # Error definitions
+ class RustCallStatus < FFI::Struct
+ layout :code, :int8,
+ :error_buf, RustBuffer
+
+ def code
+ self[:code]
+ end
+
+ def error_buf
+ self[:error_buf]
+ end
+
+ def to_s
+ "RustCallStatus(code=#{self[:code]})"
+ end
+end
+
+# These match the values from the uniffi::rustcalls module
+CALL_SUCCESS = 0
+CALL_ERROR = 1
+CALL_PANIC = 2
+
+
+module HttpError
+ class Transport < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+
+end
+
+
+
+module SdkError
+ class Configuration < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+ class InvalidResourceName < StandardError
+ def initialize(field:, value:, reason:)
+
+ @field = field
+
+ @value = value
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :field, :value, :reason
+
+
+ def to_s
+ "#{self.class.name}(field=#{@field.inspect}, value=#{@value.inspect}, reason=#{@reason.inspect})"
+
+ end
+ end
+ class Transport < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+ class Token < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+ class Body < StandardError
+ def initialize(reason:)
+
+ @reason = reason
+
+ super()
+ end
+
+
+ attr_reader :reason
+
+
+ def to_s
+ "#{self.class.name}(reason=#{@reason.inspect})"
+
+ end
+ end
+ class Status < StandardError
+ def initialize(operation:, status:, body:)
+
+ @operation = operation
+
+ @status = status
+
+ @body = body
+
+ super()
+ end
+
+
+ attr_reader :operation, :status, :body
+
+
+ def to_s
+ "#{self.class.name}(operation=#{@operation.inspect}, status=#{@status.inspect}, body=#{@body.inspect})"
+
+ end
+ end
+ class UnknownService < StandardError
+ def initialize(requested:, available:)
+
+ @requested = requested
+
+ @available = available
+
+ super()
+ end
+
+
+ attr_reader :requested, :available
+
+
+ def to_s
+ "#{self.class.name}(requested=#{@requested.inspect}, available=#{@available.inspect})"
+
+ end
+ end
+ class InvalidServicePath < StandardError
+ def initialize(path:)
+
+ @path = path
+
+ super()
+ end
+
+
+ attr_reader :path
+
+
+ def to_s
+ "#{self.class.name}(path=#{@path.inspect})"
+
+ end
+ end
+ class ClaimFailed < StandardError
+ def initialize(phase:, status:)
+
+ @phase = phase
+
+ @status = status
+
+ super()
+ end
+
+
+ attr_reader :phase, :status
+
+
+ def to_s
+ "#{self.class.name}(phase=#{@phase.inspect}, status=#{@status.inspect})"
+
+ end
+ end
+ class ClaimTimeout < StandardError
+ def initialize()
+
+ super()
+ end
+
+
+ def to_s
+ "#{self.class.name}()"
+
+ end
+ end
+
+end
+
+
+# Map error modules to the RustBuffer method name that reads them
+ERROR_MODULE_TO_READER_METHOD = {
+HttpError => :read_TypeHttpError,
+SdkError => :read_TypeSdkError,
+}
+
+private_constant :ERROR_MODULE_TO_READER_METHOD, :CALL_SUCCESS, :CALL_ERROR, :CALL_PANIC,
+ :RustCallStatus
+
+def self.consume_buffer_into_error(error_module, rust_buffer)
+ rust_buffer.consumeWithStream do |stream|
+ reader_method = ERROR_MODULE_TO_READER_METHOD[error_module] ||
+ ERROR_MODULE_TO_READER_METHOD[error_module.name&.split('::')&.last]
+ return stream.send(reader_method)
+ end
+end
+
+class InternalError < StandardError
+end
+
+def self.rust_call(fn_name, *args)
+ # Call a rust function
+ rust_call_with_error(nil, fn_name, *args)
+end
+
+def self.rust_call_with_error(error_module, fn_name, *args)
+ # Call a rust function and handle errors
+ #
+ # Use this when the rust function returns a Result<>. error_module must be the error_module that corresponds to that Result.
+
+
+ # Note: RustCallStatus.new zeroes out the struct, which is exactly what we
+ # want to pass to Rust (code=0, error_buf=RustBuffer(len=0, capacity=0,
+ # data=NULL))
+ status = RustCallStatus.new
+ args << status
+
+ result = UniFFILib.public_send(fn_name, *args)
+
+ case status.code
+ when CALL_SUCCESS
+ result
+ when CALL_ERROR
+ if error_module.nil?
+ status.error_buf.free
+ raise InternalError, "CALL_ERROR with no error_module set"
+ else
+ raise consume_buffer_into_error(error_module, status.error_buf)
+ end
+ when CALL_PANIC
+ # When the rust code sees a panic, it tries to construct a RustBuffer
+ # with the message. But if that code panics, then it just sends back
+ # an empty buffer.
+ if status.error_buf.len > 0
+ raise InternalError, status.error_buf.consume_into_string
+ else
+ raise InternalError, "Rust panic"
+ end
+ else
+ raise InternalError, "Unknown call status: #{status.code}"
+ end
+end
+
+private_class_method :consume_buffer_into_error
+
+ # This is how we find and load the dynamic library provided by the component.
+# For now we just look it up by name.
+module UniFFILib
+ extend FFI::Library
+
+
+ ffi_lib 'cyclops_sdk'
+
+
+ # Define FFI callback types and structs (vtables, etc.)
+
+ callback :RustFutureContinuationCallback,
+ [:uint64, :int8, ],
+ :void
+
+ callback :ForeignFutureDroppedCallback,
+ [:uint64, ],
+ :void
+
+ callback :CallbackInterfaceFree,
+ [:uint64, ],
+ :void
+
+ callback :CallbackInterfaceClone,
+ [:uint64, ],
+ :uint64
+
+ class ForeignFutureDroppedCallbackStruct < FFI::Struct
+ layout(
+ :handle, :uint64,
+ :free, :ForeignFutureDroppedCallback
+ )
+ end
+
+ class ForeignFutureResultU8 < FFI::Struct
+ layout(
+ :return_value, :uint8,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU8,
+ [:uint64, ForeignFutureResultU8.by_value, ],
+ :void
+
+ class ForeignFutureResultI8 < FFI::Struct
+ layout(
+ :return_value, :int8,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI8,
+ [:uint64, ForeignFutureResultI8.by_value, ],
+ :void
+
+ class ForeignFutureResultU16 < FFI::Struct
+ layout(
+ :return_value, :uint16,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU16,
+ [:uint64, ForeignFutureResultU16.by_value, ],
+ :void
+
+ class ForeignFutureResultI16 < FFI::Struct
+ layout(
+ :return_value, :int16,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI16,
+ [:uint64, ForeignFutureResultI16.by_value, ],
+ :void
+
+ class ForeignFutureResultU32 < FFI::Struct
+ layout(
+ :return_value, :uint32,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU32,
+ [:uint64, ForeignFutureResultU32.by_value, ],
+ :void
+
+ class ForeignFutureResultI32 < FFI::Struct
+ layout(
+ :return_value, :int32,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI32,
+ [:uint64, ForeignFutureResultI32.by_value, ],
+ :void
+
+ class ForeignFutureResultU64 < FFI::Struct
+ layout(
+ :return_value, :uint64,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteU64,
+ [:uint64, ForeignFutureResultU64.by_value, ],
+ :void
+
+ class ForeignFutureResultI64 < FFI::Struct
+ layout(
+ :return_value, :int64,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteI64,
+ [:uint64, ForeignFutureResultI64.by_value, ],
+ :void
+
+ class ForeignFutureResultF32 < FFI::Struct
+ layout(
+ :return_value, :float,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteF32,
+ [:uint64, ForeignFutureResultF32.by_value, ],
+ :void
+
+ class ForeignFutureResultF64 < FFI::Struct
+ layout(
+ :return_value, :double,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteF64,
+ [:uint64, ForeignFutureResultF64.by_value, ],
+ :void
+
+ class ForeignFutureResultRustBuffer < FFI::Struct
+ layout(
+ :return_value, RustBuffer.by_value,
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteRustBuffer,
+ [:uint64, ForeignFutureResultRustBuffer.by_value, ],
+ :void
+
+ class ForeignFutureResultVoid < FFI::Struct
+ layout(
+ :call_status, RustCallStatus
+ )
+ end
+
+ callback :ForeignFutureCompleteVoid,
+ [:uint64, ForeignFutureResultVoid.by_value, ],
+ :void
+
+ callback :CallbackInterfaceHttpClientMethod0,
+ [:uint64, RustBuffer.by_value, :ForeignFutureCompleteRustBuffer, :uint64, ForeignFutureDroppedCallbackStruct.by_ref, ],
+ :void
+
+ class VTableCallbackInterfaceHttpClient < FFI::Struct
+ layout(
+ :uniffi_free, :CallbackInterfaceFree,
+ :uniffi_clone, :CallbackInterfaceClone,
+ :execute, :CallbackInterfaceHttpClientMethod0
+ )
+ end
+
+ attach_function :uniffi_cyclops_sdk_fn_clone_cyclopsclient,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_free_cyclopsclient,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect,
+ [RustBuffer.by_value, :uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request,
+ [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_clone_httpclient,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_free_httpclient,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient,
+ [VTableCallbackInterfaceHttpClient.by_ref, ],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_fn_method_httpclient_execute,
+ [:uint64, RustBuffer.by_value, ],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_clone_cyclopscredentials,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :uniffi_cyclops_sdk_fn_free_cyclopscredentials,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new,
+ [RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :ffi_cyclops_sdk_rustbuffer_alloc,
+ [:uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_rustbuffer_from_bytes,
+ [ForeignBytes, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_rustbuffer_free,
+ [RustBuffer.by_value, RustCallStatus.by_ref],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rustbuffer_reserve,
+ [RustBuffer.by_value, :uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_u8,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_u8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_u8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_u8,
+ [:uint64, RustCallStatus.by_ref],
+ :uint8
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_i8,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_i8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_i8,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_i8,
+ [:uint64, RustCallStatus.by_ref],
+ :int8
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_u16,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_u16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_u16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_u16,
+ [:uint64, RustCallStatus.by_ref],
+ :uint16
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_i16,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_i16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_i16,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_i16,
+ [:uint64, RustCallStatus.by_ref],
+ :int16
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_u32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_u32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_u32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_u32,
+ [:uint64, RustCallStatus.by_ref],
+ :uint32
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_i32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_i32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_i32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_i32,
+ [:uint64, RustCallStatus.by_ref],
+ :int32
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_u64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_u64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_u64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_u64,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_i64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_i64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_i64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_i64,
+ [:uint64, RustCallStatus.by_ref],
+ :int64
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_f32,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_f32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_f32,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_f32,
+ [:uint64, RustCallStatus.by_ref],
+ :float
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_f64,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_f64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_f64,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_f64,
+ [:uint64, RustCallStatus.by_ref],
+ :double
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ [:uint64, RustCallStatus.by_ref],
+ RustBuffer.by_value
+
+ attach_function :ffi_cyclops_sdk_rust_future_poll_void,
+ [:uint64, :RustFutureContinuationCallback, :uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_cancel_void,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_free_void,
+ [:uint64, ],
+ :void
+
+ attach_function :ffi_cyclops_sdk_rust_future_complete_void,
+ [:uint64, RustCallStatus.by_ref],
+ :void
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_method_httpclient_execute,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect,
+ [],
+ :uint16
+
+ attach_function :uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new,
+ [],
+ :uint16
+
+ attach_function :ffi_cyclops_sdk_uniffi_contract_version,
+ [],
+ :uint32
+
+end
+ # RustFuture poll codes
+UNIFFI_RUST_FUTURE_POLL_READY = 0
+UNIFFI_RUST_FUTURE_POLL_WAKE = 1
+
+# Handle map for storing write-end IO objects used by the continuation callbacks.
+UNIFFI_ASYNC_HANDLE_MAP = UniffiHandleMap.new
+
+# Continuation callback for async functions.
+# Called by Rust when the future is ready to make progress.
+# Writes the poll code to the pipe so the waiting thread/fiber can continue.
+#
+# Exceptions must never escape this Proc.
+# Rust invokes it directly via FFI, so any unhandled Ruby exception would be caught
+# by Ruby-FFI, which swallows it (prints a warning) and returns a garbage value to Rust.
+# The poll code Rust receives would be invalid, causing the Ruby polling loop to
+# never see POLL_READY and block forever.
+UNIFFI_CONTINUATION_CALLBACK = Proc.new do |data, poll_code|
+ begin
+ wr = UNIFFI_ASYNC_HANDLE_MAP.get data
+
+ # This can only be blocking if pipe if full. Rust will never try to call continuation
+ # callback more than once (so will not fill it up), hence this call should never block.
+ wr.putc poll_code
+ rescue Exception
+ # Swallow exception. A leak or a hang is better than a hard VM segfault.
+ end
+end
+
+# Poll a Rust future to completion.
+#
+# This works both with and without a Fiber::Scheduler:
+# - Without scheduler: wait_readable blocks with a timeout, releasing the GVL
+# so the callback can fire from foreign threads (works around MRI limitation
+# where rb_thread_call_with_gvl cannot wake up threads in indefinite sleep).
+# - With scheduler: wait_readable hooks into io_wait, yielding the fiber.
+#
+# cancel_fn is called in the ensure block when exception interrupts an in-flight poll.
+# This guarantees Rust fires the continuation callback so the handle-map entry is released
+# and the pipe is drained before we free the future.
+def self.uniffi_rust_call_async(rust_future, poll_fn, cancel_fn, complete_fn, free_fn, lift_func, error_ffi_converter)
+ rd = wr = nil
+ handle = nil
+ poll_in_flight = false
+
+ begin
+ rd, wr = IO.pipe
+ wr.sync = true # avoid buffering and delayed read for rd.wait_readable
+ handle = UNIFFI_ASYNC_HANDLE_MAP.insert wr
+
+ loop do
+ poll_in_flight = true
+ UniFFILib.public_send(poll_fn, rust_future, UNIFFI_CONTINUATION_CALLBACK, handle)
+
+ # Blocks until the continuation callback writes to the pipe.
+ # Releases the GVL so the callback can fire from foreign threads.
+ # With a Fiber::Scheduler, this hooks into io_wait for non-blocking concurrency.
+ rd.wait_readable
+ poll_code = rd.getbyte
+ poll_in_flight = false
+
+ break if poll_code == UNIFFI_RUST_FUTURE_POLL_READY
+ end
+
+ result = if error_ffi_converter.nil?
+ ::CyclopsSdk.rust_call(complete_fn, rust_future)
+ else
+ ::CyclopsSdk.rust_call_with_error(error_ffi_converter, complete_fn, rust_future)
+ end
+
+ lift_func.call(result)
+ ensure
+ # Defer any further Thread#raise / Timeout during cleanup so all steps execute
+ # automatically. Without this, a second raise during wait_readable(0.5) would skip
+ # handle-map removal, pipe close, and free_fn - leaking FDs and Rust memory.
+ Thread.handle_interrupt(Exception => :never) do
+ if poll_in_flight
+ # An exception interrupted an in-flight poll. Cancel and drain the byte
+ # the continuation callback will write so we don't leak the pipe.
+ UniFFILib.public_send(cancel_fn, rust_future)
+ # rd.wait_readable may time out and return nil if the poll was never actually sent
+ # (raise landed between poll_in_flight=true and the FFI call).
+ if rd.wait_readable(0.5)
+ rd.getbyte
+ end
+ end
+
+ # Remove handle first so any late-firing callback's `get` raises (swallowed by rescue).
+ UNIFFI_ASYNC_HANDLE_MAP.remove(handle) rescue nil if handle
+ rd&.close rescue nil
+ wr&.close rescue nil
+ UniFFILib.public_send(free_fn, rust_future)
+ end
+ end
+end
+# Exception raised when a foreign future is canceled.
+class UniffiInternalCancelled < RuntimeError; end
+
+# User callback that raises it will be considered a Rust-side cancellation.
+private_constant :UniffiInternalCancelled
+
+# Handle map for storing Threads executing foreign async callbacks.
+UNIFFI_FOREIGN_FUTURE_HANDLE_MAP = UniffiHandleMap.new
+
+# One-shot claim flag: the first caller to `claim!` wins; all subsequent callers
+# are no-ops. Used to enforce the at-most-once contract on uniffi_future_callback.
+class UniffiOnceFlag
+ def initialize
+ @mutex = Mutex.new
+ @claimed = false
+ end
+
+ # Returns true if this caller won the race (first to claim), false otherwise.
+ def claim!
+ @mutex.synchronize do
+ first = !@claimed
+ @claimed = true
+ first
+ end
+ end
+end
+
+# Called by Rust when the foreign future is dropped (i.e. canceled or completed successfully).
+# Raises UniffiInternalCancelled in the worker thread so make_call can exit early,
+# but only if the thread hasn't already completed and claimed the once flag.
+# Stored as a constant to prevent GC from collecting the Proc while Rust holds the pointer.
+UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK = Proc.new do |handle|
+ thread, once = UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.remove handle
+ thread.raise(UniffiInternalCancelled, 'Future was canceled') if once.claim! && thread&.alive?
+end
+
+# Execute a foreign async callback method in a background thread.
+# Enforces the at-most-once guarantee on handle_success / handle_error: whichever
+# fires first (normal completion or Rust-side drop) suppresses the other.
+def self.uniffi_trait_interface_call_async(make_call, uniffi_out_dropped_callback, handle_success, handle_error, error_type = nil, lower_error = nil)
+ once = UniffiOnceFlag.new
+
+ thread = Thread.new do
+ begin
+ # Phase 1: run the user's async method.
+ # UniffiInternalCancelled exits silently. Other exceptions are forwarded as errors.
+ # handle_success is intentionally called outside this rescue so exceptions from it
+ # cannot re-enter handle_error (which would be a double-call on the Rust sender).
+ begin
+ result = make_call.call
+ rescue UniffiInternalCancelled
+ next
+ rescue Exception => e # We have to catch all errors to prevent Rust future from hanging forever.
+ next unless once.claim!
+
+ if !error_type.nil? && ::CyclopsSdk.uniffi_is_error_type?(e, error_type)
+ handle_error.call(UNIFFI_CALLBACK_ERROR, lower_error.call(e))
+ else
+ handle_error.call(UNIFFI_CALLBACK_UNEXPECTED_ERROR, RustBuffer.alloc_from_string(e.inspect))
+ end
+ next
+ end
+
+ # Phase 2: deliver the result to Rust. Skipped if dropped_callback already fired.
+ handle_success.call(result) if once.claim!
+ rescue UniffiInternalCancelled
+ # Thread#raise landed between phases or during Phase 2 - silently exit.
+ # Rust already dropped the future (that's why dropped_callback fired), so no response needed.
+ rescue Exception => e
+ # handle_success/handle_error/lower_error raised - send a generic error so Rust doesn't hang.
+ # once was already claimed, so only attempt this if we can still claim (e.g. lowering failed
+ # before handle_error was called due to short-circuit evaluation).
+ begin
+ handle_error.call(UNIFFI_CALLBACK_UNEXPECTED_ERROR, RustBuffer.alloc_from_string(e.inspect))
+ rescue Exception
+ # If even this fails, Rust will hang. Nothing more we can do.
+ end
+ end
+ end
+
+ # Note: the thread may have already completed by this point, but that's safe.
+ # Rust cannot invoke dropped_callback until this function returns.
+ # possesses the ForeignFuture struct we're populating here.
+ handle = UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert([thread, once])
+ uniffi_out_dropped_callback[:handle] = handle
+ uniffi_out_dropped_callback[:free] = UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK
+end
+ # Base class for callback interface FfiConverters.
+# Stores Ruby callback objects in a handle map, and converts to/from integer handles.
+
+class CallbackInterfaceFfiConverter
+ attr_reader :handle_map
+
+ def initialize
+ @handle_map = UniffiHandleMap.new
+ end
+
+ def lift(handle)
+ @handle_map.get handle
+ end
+
+ def lower(cb)
+ @handle_map.insert cb
+ end
+end
+
+private_constant :CallbackInterfaceFfiConverter
+
+ # Custom type definitions.
+
+ # Public interface members begin here.
+
+
+
+
+ # Record type Claim
+class Claim
+ attr_reader :api_version, :kind, :metadata, :spec, :status
+
+ def initialize(api_version:, kind:, metadata:, spec:, status:)
+ @api_version = api_version
+ @kind = kind
+ @metadata = metadata
+ @spec = spec
+ @status = status
+ end
+
+ def ==(other)
+ if @api_version != other.api_version
+ return false
+ end
+ if @kind != other.kind
+ return false
+ end
+ if @metadata != other.metadata
+ return false
+ end
+ if @spec != other.spec
+ return false
+ end
+ if @status != other.status
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type CreateClaimRequest
+class CreateClaimRequest
+ attr_reader :pool, :spec
+
+ def initialize(pool:, spec:)
+ @pool = pool
+ @spec = spec
+ end
+
+ def ==(other)
+ if @pool != other.pool
+ return false
+ end
+ if @spec != other.spec
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type CreatePoolRequest
+class CreatePoolRequest
+ attr_reader :namespace, :spec
+
+ def initialize(namespace:, spec:)
+ @namespace = namespace
+ @spec = spec
+ end
+
+ def ==(other)
+ if @namespace != other.namespace
+ return false
+ end
+ if @spec != other.spec
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type CyclopsConfiguration
+class CyclopsConfiguration
+ attr_reader :base_url, :token_url, :credentials, :pool_poll_interval_ms, :pool_poll_limit, :claim_poll_interval_ms, :claim_poll_limit
+
+ def initialize(base_url:, token_url:, credentials:, pool_poll_interval_ms:, pool_poll_limit:, claim_poll_interval_ms:, claim_poll_limit:)
+ @base_url = base_url
+ @token_url = token_url
+ @credentials = credentials
+ @pool_poll_interval_ms = pool_poll_interval_ms
+ @pool_poll_limit = pool_poll_limit
+ @claim_poll_interval_ms = claim_poll_interval_ms
+ @claim_poll_limit = claim_poll_limit
+ end
+
+ def ==(other)
+ if @base_url != other.base_url
+ return false
+ end
+ if @token_url != other.token_url
+ return false
+ end
+ if @credentials != other.credentials
+ return false
+ end
+ if @pool_poll_interval_ms != other.pool_poll_interval_ms
+ return false
+ end
+ if @pool_poll_limit != other.pool_poll_limit
+ return false
+ end
+ if @claim_poll_interval_ms != other.claim_poll_interval_ms
+ return false
+ end
+ if @claim_poll_limit != other.claim_poll_limit
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type HttpHeader
+class HttpHeader
+ attr_reader :name, :value
+
+ def initialize(name:, value:)
+ @name = name
+ @value = value
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+ if @value != other.value
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type HttpRequest
+class HttpRequest
+ attr_reader :method, :url, :headers, :body
+
+ def initialize(method:, url:, headers:, body:)
+ @method = method
+ @url = url
+ @headers = headers
+ @body = body
+ end
+
+ def ==(other)
+ if @method != other.method
+ return false
+ end
+ if @url != other.url
+ return false
+ end
+ if @headers != other.headers
+ return false
+ end
+ if @body != other.body
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type HttpResponse
+class HttpResponse
+ attr_reader :status, :headers, :body
+
+ def initialize(status:, headers:, body:)
+ @status = status
+ @headers = headers
+ @body = body
+ end
+
+ def ==(other)
+ if @status != other.status
+ return false
+ end
+ if @headers != other.headers
+ return false
+ end
+ if @body != other.body
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type Pool
+class Pool
+ attr_reader :api_version, :kind, :metadata, :spec, :status
+
+ def initialize(api_version:, kind:, metadata:, spec:, status:)
+ @api_version = api_version
+ @kind = kind
+ @metadata = metadata
+ @spec = spec
+ @status = status
+ end
+
+ def ==(other)
+ if @api_version != other.api_version
+ return false
+ end
+ if @kind != other.kind
+ return false
+ end
+ if @metadata != other.metadata
+ return false
+ end
+ if @spec != other.spec
+ return false
+ end
+ if @status != other.status
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type ResourceMetadata
+class ResourceMetadata
+ attr_reader :namespace, :name, :labels
+
+ def initialize(namespace:, name:, labels:)
+ @namespace = namespace
+ @name = name
+ @labels = labels
+ end
+
+ def ==(other)
+ if @namespace != other.namespace
+ return false
+ end
+ if @name != other.name
+ return false
+ end
+ if @labels != other.labels
+ return false
+ end
+
+ true
+ end
+
+end
+
+ # Record type Sandbox
+class Sandbox
+ attr_reader :namespace, :claim, :name, :services
+
+ def initialize(namespace:, claim:, name:, services:)
+ @namespace = namespace
+ @claim = claim
+ @name = name
+ @services = services
+ end
+
+ def ==(other)
+ if @namespace != other.namespace
+ return false
+ end
+ if @claim != other.claim
+ return false
+ end
+ if @name != other.name
+ return false
+ end
+ if @services != other.services
+ return false
+ end
+
+ true
+ end
+
+end
+
+
+
+
+
+ class CyclopsClient
+
+ # A private helper for initializing instances of the class from a raw handle,
+ # bypassing any initialization logic and ensuring they are GC'd properly.
+ def self.uniffi_allocate(handle)
+ inst = allocate
+ inst.instance_variable_set :@handle, handle
+ ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_handle(handle, inst.object_id))
+ return inst
+ end
+
+ # A private helper for registering an object finalizer.
+ # N.B. it's important that this does not capture a reference
+ # to the actual instance, only its underlying handle.
+ def self.uniffi_define_finalizer_by_handle(handle, object_id)
+ Proc.new do |_id|
+ ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_free_cyclopsclient,
+ handle
+ )
+ end
+ end
+ # A private helper for lowering instances into a raw handle.
+ # This does an explicit typecheck, because accidentally lowering a different type of
+ # object in a place where this type is expected, could lead to memory unsafety.
+ def self.uniffi_check_lower(inst)
+ if !inst.is_a? self
+ raise TypeError.new "Expected a CyclopsClient instance, got #{inst}"
+ end
+ end
+
+ def uniffi_clone_handle()
+ return ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_clone_cyclopsclient,
+ @handle
+ )
+ end
+
+ def self.uniffi_lower(inst)
+ return inst.uniffi_clone_handle()
+ end
+
+ def self.uniffi_lift(handle)
+ uniffi_allocate handle
+ end
+
+
+ def self.connect(configuration, http_client)
+ configuration = configuration
+ RustBuffer.check_lower_TypeCyclopsConfiguration(configuration)
+ http_client = http_client
+ (HttpClient.uniffi_check_lower http_client)
+ # Call the (fallible) function before creating any half-baked object instances.
+ # Lightly yucky way to bypass the usual "initialize" logic
+ # and just create a new instance with the required handle.
+ return uniffi_allocate(::CyclopsSdk.rust_call_with_error(SdkError,:uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect,RustBuffer.alloc_from_TypeCyclopsConfiguration(configuration),(HttpClient.uniffi_lower http_client)))
+ end
+
+
+
+ def create_claim(request)
+ request = request
+ RustBuffer.check_lower_TypeCreateClaimRequest(request)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(uniffi_clone_handle(),RustBuffer.alloc_from_TypeCreateClaimRequest(request)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypeClaim },
+ SdkError
+ )
+ end
+
+ def delete_claim(claim)
+ claim = claim
+ RustBuffer.check_lower_TypeClaim(claim)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(uniffi_clone_handle(),RustBuffer.alloc_from_TypeClaim(claim)),
+ :ffi_cyclops_sdk_rust_future_poll_void,
+ :ffi_cyclops_sdk_rust_future_cancel_void,
+ :ffi_cyclops_sdk_rust_future_complete_void,
+ :ffi_cyclops_sdk_rust_future_free_void,
+ Proc.new { |v| nil },
+ SdkError
+ )
+ end
+
+ def get_claim(claim)
+ claim = claim
+ RustBuffer.check_lower_TypeClaim(claim)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(uniffi_clone_handle(),RustBuffer.alloc_from_TypeClaim(claim)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypeClaim },
+ SdkError
+ )
+ end
+
+ def list_claims(namespace)
+ namespace = ::CyclopsSdk::uniffi_utf8(namespace)
+
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uniffi_clone_handle(),RustBuffer.alloc_from_string(namespace)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_SequenceTypeClaim },
+ SdkError
+ )
+ end
+
+ def wait_claim(claim)
+ claim = claim
+ RustBuffer.check_lower_TypeClaim(claim)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uniffi_clone_handle(),RustBuffer.alloc_from_TypeClaim(claim)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypeSandbox },
+ SdkError
+ )
+ end
+
+ def create_pool(request)
+ request = request
+ RustBuffer.check_lower_TypeCreatePoolRequest(request)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uniffi_clone_handle(),RustBuffer.alloc_from_TypeCreatePoolRequest(request)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypePool },
+ SdkError
+ )
+ end
+
+ def delete_pool(pool)
+ pool = pool
+ RustBuffer.check_lower_TypePool(pool)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(uniffi_clone_handle(),RustBuffer.alloc_from_TypePool(pool)),
+ :ffi_cyclops_sdk_rust_future_poll_void,
+ :ffi_cyclops_sdk_rust_future_cancel_void,
+ :ffi_cyclops_sdk_rust_future_complete_void,
+ :ffi_cyclops_sdk_rust_future_free_void,
+ Proc.new { |v| nil },
+ SdkError
+ )
+ end
+
+ def get_pool(pool)
+ pool = pool
+ RustBuffer.check_lower_TypePool(pool)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(uniffi_clone_handle(),RustBuffer.alloc_from_TypePool(pool)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypePool },
+ SdkError
+ )
+ end
+
+ def list_pools(namespace)
+ namespace = ::CyclopsSdk::uniffi_utf8(namespace)
+
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(uniffi_clone_handle(),RustBuffer.alloc_from_string(namespace)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_SequenceTypePool },
+ SdkError
+ )
+ end
+
+ def update_pool(pool)
+ pool = pool
+ RustBuffer.check_lower_TypePool(pool)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(uniffi_clone_handle(),RustBuffer.alloc_from_TypePool(pool)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypePool },
+ SdkError
+ )
+ end
+
+ def service_request(sandbox, service, path, request)
+ sandbox = sandbox
+ RustBuffer.check_lower_TypeSandbox(sandbox)
+ service = ::CyclopsSdk::uniffi_utf8(service)
+
+ path = ::CyclopsSdk::uniffi_utf8(path)
+
+ request = request
+ RustBuffer.check_lower_TypeHttpRequest(request)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(uniffi_clone_handle(),RustBuffer.alloc_from_TypeSandbox(sandbox),RustBuffer.alloc_from_string(service),RustBuffer.alloc_from_string(path),RustBuffer.alloc_from_TypeHttpRequest(request)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypeHttpResponse },
+ SdkError
+ )
+ end
+
+end
+
+ class HttpClient
+
+ # A private helper for initializing instances of the class from a raw handle,
+ # bypassing any initialization logic and ensuring they are GC'd properly.
+ def self.uniffi_allocate(handle)
+ inst = allocate
+ inst.instance_variable_set :@handle, handle
+ ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_handle(handle, inst.object_id))
+ return inst
+ end
+
+ # A private helper for registering an object finalizer.
+ # N.B. it's important that this does not capture a reference
+ # to the actual instance, only its underlying handle.
+ def self.uniffi_define_finalizer_by_handle(handle, object_id)
+ Proc.new do |_id|
+ ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_free_httpclient,
+ handle
+ )
+ end
+ end
+ # HandleMap for trait interface: stores Ruby-native objects keyed by odd handles.
+ @uniffi_handle_map = UniffiHandleMap.new
+
+ class << self
+ attr_reader :uniffi_handle_map
+ end
+
+ # For trait interfaces: check that the object is either a Rust-backed instance or
+ # responds to the required interface methods.
+ def self.uniffi_check_lower(inst)
+ if !inst.respond_to?(:execute)
+ raise TypeError.new "Expected a HttpClient instance or an object implementing the interface, got #{inst}"
+ end
+ end
+
+ def uniffi_clone_handle
+ return ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_clone_httpclient,
+ @handle
+ )
+ end
+
+ # For trait interfaces: lowering distinguishes between Rust-backed and Ruby-native instances.
+ def self.uniffi_lower(inst)
+ if inst.is_a?(self) && inst.instance_variable_defined?(:@handle)
+ inst.uniffi_clone_handle()
+ else
+ @uniffi_handle_map.insert(inst)
+ end
+ end
+
+ # For trait interfaces: lifting distinguishes even handles (Rust) from odd handles (Ruby).
+ def self.uniffi_lift(handle)
+ if (handle & 1) == 0
+ uniffi_allocate handle
+ else
+ @uniffi_handle_map.remove handle
+ end
+ end
+
+
+
+
+ def execute(request)
+ request = request
+ RustBuffer.check_lower_TypeHttpRequest(request)
+ ::CyclopsSdk.uniffi_rust_call_async(
+ UniFFILib.uniffi_cyclops_sdk_fn_method_httpclient_execute(uniffi_clone_handle(),RustBuffer.alloc_from_TypeHttpRequest(request)),
+ :ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ :ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ Proc.new { |v| v.consume_into_TypeHttpResponse },
+ HttpError
+ )
+ end
+
+end
+
+
+# Trait interface vtable implementation for HttpClient.
+module UniffiCallbackInterfaceHttpClient
+ # Async callback method for execute
+ EXECUTE_CALLBACK = Proc.new do |uniffi_handle, request, uniffi_future_callback, uniffi_callback_data, uniffi_out_dropped_callback|
+ uniffi_obj = HttpClient.uniffi_handle_map.get(uniffi_handle)
+ make_call = Proc.new do
+ uniffi_obj.execute(
+ request.consume_into_TypeHttpRequest
+ )
+ end
+ handle_success = Proc.new do |return_value|
+ result_struct = UniFFILib::ForeignFutureResultRustBuffer.new
+ result_struct[:return_value] = RustBuffer.alloc_from_TypeHttpResponse(return_value)
+ result_struct[:call_status] = RustCallStatus.new
+ uniffi_future_callback.call(uniffi_callback_data, result_struct)
+ end
+ handle_error = Proc.new do |status_code, error_buf|
+ result_struct = UniFFILib::ForeignFutureResultRustBuffer.new
+ result_struct[:return_value] = RustBuffer.new
+
+ error_status = RustCallStatus.new
+ error_status[:code] = status_code
+ error_status[:error_buf] = error_buf
+
+ result_struct[:call_status] = error_status
+
+ uniffi_future_callback.call(uniffi_callback_data, result_struct)
+ end
+ ::CyclopsSdk.uniffi_trait_interface_call_async(
+ make_call,
+ uniffi_out_dropped_callback,
+ handle_success,
+ handle_error,
+ HttpError,
+ Proc.new { |e| RustBuffer.alloc_from_TypeHttpError(e) }
+ )
+ end
+
+ # Free callback: removes the handle from the map.
+ UNIFFI_FREE_CALLBACK = Proc.new do |uniffi_handle|
+ HttpClient.uniffi_handle_map.remove uniffi_handle
+ end
+
+ # Clone callback: clones the handle in the map.
+ UNIFFI_CLONE_CALLBACK = Proc.new do |uniffi_handle|
+ HttpClient.uniffi_handle_map.clone_handle(uniffi_handle)
+ end
+
+ # Create the VTable struct instance.
+ UNIFFI_VTABLE = UniFFILib::VTableCallbackInterfaceHttpClient.new
+ UNIFFI_VTABLE[:uniffi_free] = UNIFFI_FREE_CALLBACK
+ UNIFFI_VTABLE[:uniffi_clone] = UNIFFI_CLONE_CALLBACK
+ UNIFFI_VTABLE[:execute] = EXECUTE_CALLBACK
+
+ # Register the VTable with Rust.
+ UniFFILib.uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(UNIFFI_VTABLE)
+end
+
+ class CyclopsCredentials
+
+ # A private helper for initializing instances of the class from a raw handle,
+ # bypassing any initialization logic and ensuring they are GC'd properly.
+ def self.uniffi_allocate(handle)
+ inst = allocate
+ inst.instance_variable_set :@handle, handle
+ ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_handle(handle, inst.object_id))
+ return inst
+ end
+
+ # A private helper for registering an object finalizer.
+ # N.B. it's important that this does not capture a reference
+ # to the actual instance, only its underlying handle.
+ def self.uniffi_define_finalizer_by_handle(handle, object_id)
+ Proc.new do |_id|
+ ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_free_cyclopscredentials,
+ handle
+ )
+ end
+ end
+ # A private helper for lowering instances into a raw handle.
+ # This does an explicit typecheck, because accidentally lowering a different type of
+ # object in a place where this type is expected, could lead to memory unsafety.
+ def self.uniffi_check_lower(inst)
+ if !inst.is_a? self
+ raise TypeError.new "Expected a CyclopsCredentials instance, got #{inst}"
+ end
+ end
+
+ def uniffi_clone_handle()
+ return ::CyclopsSdk.rust_call(
+ :uniffi_cyclops_sdk_fn_clone_cyclopscredentials,
+ @handle
+ )
+ end
+
+ def self.uniffi_lower(inst)
+ return inst.uniffi_clone_handle()
+ end
+
+ def self.uniffi_lift(handle)
+ uniffi_allocate handle
+ end
+ def initialize(client_id, client_secret)
+ client_id = ::CyclopsSdk::uniffi_utf8(client_id)
+
+ client_secret = ::CyclopsSdk::uniffi_utf8(client_secret)
+
+ handle = ::CyclopsSdk.rust_call(:uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new,RustBuffer.alloc_from_string(client_id),RustBuffer.alloc_from_string(client_secret))
+ @handle = handle
+ ObjectSpace.define_finalizer(self, self.class.uniffi_define_finalizer_by_handle(handle, self.object_id))
+ end
+
+
+
+
+end
+
+
+
+end
diff --git a/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
new file mode 100644
index 0000000000..70b3c89edd
--- /dev/null
+++ b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
@@ -0,0 +1,136 @@
+require 'json'
+require 'cyclops_sdk'
+
+Expected = Struct.new(:method, :url, :headers, :body, :status, :response)
+BASE = 'https://cyclops.invalid'
+TOKEN = 'https://keycloak.invalid/token'
+JSON_HEADERS = [['accept', 'application/json'], ['content-type', 'application/json'], ['authorization', 'Bearer offline-token']]
+
+def pool_json
+ { apiVersion: 'cua.ai/v1', kind: 'OSGymWorkspacePool', metadata: { namespace: 'default', name: 'default', labels: nil }, spec: { replicas: 1, template: { containerDiskImage: 'registry.example/desktop:offline' }, services: [{ name: 'mcp', targetPort: 8080 }] }, status: nil }
+end
+
+def claim_json(bound = false)
+ value = { apiVersion: 'osgym.cua.ai/v1alpha1', kind: 'OSGymSandboxClaim', metadata: { namespace: 'default', name: 'default', labels: nil }, spec: { sandboxTemplateRef: { name: 'default' } }, status: nil }
+ value[:status] = { phase: 'Bound', sandbox: { name: 'offline-sandbox' } } if bound
+ value
+end
+
+def token_expected
+ Expected.new('POST', TOKEN, [['accept', 'application/json'], ['content-type', 'application/x-www-form-urlencoded']], 'grant_type=client_credentials&client_id=client-id&client_secret=client-secret'.b, 200, { access_token: 'offline-token', expires_in: 3600 })
+end
+
+def service_expected(body, response)
+ Expected.new('POST', "#{BASE}/api/svc/default/offline-sandbox-mcp/mcp", [['authorization', 'Bearer offline-token']], body, 202, response)
+end
+
+def lifecycle_queue
+ pool_url = "#{BASE}/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default"
+ claim_url = "#{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default"
+ pool_body = JSON.generate(pool_json).b
+ claim_body = '{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"claim-1","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":null}'.b
+ [
+ token_expected,
+ Expected.new('POST', "#{BASE}/api/namespaces", JSON_HEADERS, '{"name":"default"}'.b, 201, {}),
+ Expected.new('POST', pool_url.sub(%r{/default\z}, ''), JSON_HEADERS, pool_body, 201, pool_json),
+ Expected.new('POST', claim_url.sub(%r{/default\z}, ''), JSON_HEADERS, claim_body, 201, claim_json),
+ Expected.new('GET', claim_url, JSON_HEADERS, nil, 200, claim_json(true)),
+ Expected.new('GET', pool_url, JSON_HEADERS, nil, 200, pool_json),
+ service_expected('{"offline":true}'.b, 'offline service accepted'),
+ Expected.new('DELETE', claim_url, JSON_HEADERS, nil, 204, ''),
+ Expected.new('DELETE', pool_url, JSON_HEADERS, nil, 204, ''),
+ Expected.new('DELETE', "#{BASE}/api/namespaces/default", JSON_HEADERS, nil, 204, ''),
+ ]
+end
+
+class ScriptedHttpClient < CyclopsSdk::HttpClient
+ def initialize(expected)
+ @expected = expected
+ @mutex = Mutex.new
+ @requests = []
+ end
+
+ def execute(request)
+ @mutex.synchronize do
+ item = @expected.shift or raise 'unexpected request'
+ actual = [request.method, request.url, request.headers.map { |header| [header.name, header.value] }, request.body]
+ raise "request mismatch: #{actual.inspect}" unless actual == [item.method, item.url, item.headers, item.body]
+ @requests << request
+ body = item.response.is_a?(String) ? item.response.b : JSON.generate(item.response).b
+ CyclopsSdk::HttpResponse.new(status: item.status, headers: [], body: body)
+ end
+ end
+
+ def assert_exhausted!
+ @mutex.synchronize { raise @expected.inspect unless @expected.empty? }
+ end
+
+ def request_count
+ @mutex.synchronize { @requests.length }
+ end
+end
+
+class FailingHttpClient < CyclopsSdk::HttpClient
+ def execute(request)
+ raise CyclopsSdk::HttpError::Transport.new(reason: 'scripted callback failure')
+ end
+end
+
+def configuration
+ CyclopsSdk::CyclopsConfiguration.new(base_url: BASE, token_url: TOKEN, credentials: CyclopsSdk::CyclopsCredentials.new('client-id', 'client-secret'), pool_poll_interval_ms: 1, pool_poll_limit: 1, claim_poll_interval_ms: 1, claim_poll_limit: 2)
+end
+
+def service_request(body)
+ CyclopsSdk::HttpRequest.new(method: 'POST', url: 'https://ignored.invalid/mcp', headers: [], body: body)
+end
+
+sandbox = CyclopsSdk::Sandbox.new(namespace: 'default', claim: 'default', name: 'offline-sandbox', services: ['mcp'])
+vm_template = CyclopsSdk::VmTemplate.new(container_disk_image: 'registry.example/desktop:offline', command: nil, runtime: nil, runtime_class_name: nil, node_selector: nil, tolerations: nil, image_pull_policy: nil, image_pull_secret: nil, cpu_cores: nil, memory: nil, firmware: nil, probes: nil, services: nil, oidc: nil)
+spec = CyclopsSdk::PoolSpec.new(replicas: 1, template: CyclopsSdk::PoolTemplate.new(runtime: nil, runtime_class_name: nil, node_selector: nil, tolerations: nil, command: nil, container_disk_image: vm_template.container_disk_image, image_pull_secret: nil, cpu_cores: nil, memory: nil, firmware: nil, probes: nil, oidc: nil), autoscaling: nil, services: [CyclopsSdk::SandboxService.new(name: 'mcp', target_port: 8080, protocol: nil)])
+transport = ScriptedHttpClient.new(lifecycle_queue)
+client = CyclopsSdk::CyclopsClient.connect(configuration, transport)
+pool = client.create_pool(CyclopsSdk::CreatePoolRequest.new(namespace: 'default', spec: spec))
+claim = client.create_claim(CyclopsSdk::CreateClaimRequest.new(pool: pool, spec: CyclopsSdk::ClaimSpec.new(sandbox_template_ref: CyclopsSdk::SandboxTemplateRef.new(name: pool.metadata.name), warmpool: nil, bind_deadline: nil, lifecycle: nil)))
+created_sandbox = client.wait_claim(claim)
+service = client.service_request(created_sandbox, 'mcp', '/mcp', service_request('{"offline":true}'.b))
+client.delete_claim(claim)
+client.delete_pool(pool)
+transport.assert_exhausted!
+raise 'unexpected service response' unless service.status == 202
+
+failing_client = CyclopsSdk::CyclopsClient.connect(configuration, FailingHttpClient.new)
+begin
+ failing_client.service_request(sandbox, 'mcp', '/mcp', service_request(nil))
+ raise 'expected generated SdkError::Transport'
+rescue CyclopsSdk::SdkError::Transport => error
+ raise error unless error.reason == 'scripted callback failure'
+end
+
+body_transport = ScriptedHttpClient.new([
+ token_expected,
+ service_expected(nil, "".b),
+ service_expected("".b, "\x00\x7f\xff".b),
+])
+body_client = CyclopsSdk::CyclopsClient.connect(configuration, body_transport)
+raise 'expected empty service body' unless body_client.service_request(sandbox, 'mcp', '/mcp', service_request(nil)).body.empty?
+raise 'expected binary service body' unless body_client.service_request(sandbox, 'mcp', '/mcp', service_request("".b)).body == "\x00\x7f\xff".b
+body_transport.assert_exhausted!
+
+concurrent_transport = ScriptedHttpClient.new([
+ token_expected,
+ service_expected(nil, 'warm'),
+ service_expected('parallel'.b, 'first'),
+ service_expected('parallel'.b, 'second'),
+])
+concurrent_client = CyclopsSdk::CyclopsClient.connect(configuration, concurrent_transport)
+concurrent_client.service_request(sandbox, 'mcp', '/mcp', service_request(nil))
+threads = 2.times.map do
+ Thread.new do
+ concurrent_client.service_request(sandbox, 'mcp', '/mcp', service_request('parallel'.b))
+ end
+end
+responses = threads.map(&:value)
+raise 'concurrent SDK calls did not both complete' unless responses.map { |response| response.body }.sort == %w[first second]
+concurrent_transport.assert_exhausted!
+raise 'concurrent queue recording mismatch' unless concurrent_transport.request_count == 4
+puts "pool=#{pool.metadata.name} claim=#{claim.metadata.name} sandbox=#{created_sandbox.name} service_status=#{service.status}"
diff --git a/libs/fleet/sdk-bindings/rust/Cargo.toml b/libs/fleet/sdk-bindings/rust/Cargo.toml
deleted file mode 100644
index 839e829878..0000000000
--- a/libs/fleet/sdk-bindings/rust/Cargo.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-[package]
-name="cyclops-sdk-host"
-version="0.1.0"
-edition="2021"
-[dependencies]
-cyclops-sdk-core={path="../../sdk-core"}
-serde_json="1.0.150"
-ureq={version="3.1.4",features=["json"]}
diff --git a/libs/fleet/sdk-bindings/rust/examples/app_controlled.rs b/libs/fleet/sdk-bindings/rust/examples/app_controlled.rs
deleted file mode 100644
index df5a3805a5..0000000000
--- a/libs/fleet/sdk-bindings/rust/examples/app_controlled.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use cyclops_sdk_host::{
- Claim, Configuration, CreateClaimRequest, CreatePoolRequest, OAuthConfiguration, Pool,
- PoolSpec, PoolSpecService, PoolSpecServiceProtocol, PoolTemplate, Sandbox, Sdk,
-};
-use std::{
- env, thread,
- time::{Duration, Instant, SystemTime, UNIX_EPOCH},
-};
-
-fn run_agent(sdk: &mut Sdk, sandbox: Sandbox) -> Result<serde_json::Value, String> {
- let body = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"cyclops-sdk-rust-example","version":"0.1.0"}}}"#;
- let deadline = Instant::now() + Duration::from_secs(300);
- let mut mcp = sdk
- .service_client(&sandbox, "mcp")
- .map_err(|error| error.to_string())?;
- loop {
- let response = mcp
- .post("/mcp")
- .header("accept", "application/json, text/event-stream")
- .header("content-type", "application/json")
- .body(body)
- .send()
- .map_err(|error| error.to_string())?;
- if (200..300).contains(&response.status) {
- return Ok(
- serde_json::json!({"namespace": sandbox.namespace, "claim": sandbox.claim, "sandbox": sandbox.sandbox, "mcp_status": response.status}),
- );
- }
- if !matches!(response.status, 502..=504) || Instant::now() >= deadline {
- return Err(format!(
- "MCP initialize failed with HTTP {}: {}",
- response.status, response.body
- ));
- }
- thread::sleep(Duration::from_secs(5));
- }
-}
-
-fn main() -> Result<(), String> {
- let suffix = format!(
- "{:08x}",
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map_err(|error| error.to_string())?
- .as_nanos() as u32
- );
- let namespace =
- env::var("CYCLOPS_NAMESPACE").unwrap_or_else(|_| format!("sdk-example-{suffix}"));
- let mut sdk = Sdk::connect(Configuration {
- base_url: env::var("CUA_BASE_URL").unwrap_or_else(|_| "https://run.cua.ai".into()),
- oauth: OAuthConfiguration {
- token_url: env::var("CUA_TOKEN_URL").unwrap_or_else(|_| {
- "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token".into()
- }),
- client_id: required("CUA_CLIENT_ID")?,
- client_secret: required("CUA_CLIENT_SECRET")?,
- },
- })?;
- let mut pool: Option<Pool> = None;
- let mut claim: Option<Claim> = None;
- let result = (|| {
- let created_pool = sdk.create_pool(CreatePoolRequest {
- namespace: namespace.clone(),
- spec: PoolSpec::builder()
- .replicas(1)
- .services(vec![PoolSpecService::builder()
- .name("mcp".into())
- .target_port(3000)
- .protocol(PoolSpecServiceProtocol::TCP)
- .build()?])
- .template(
- PoolTemplate::builder()
- .container_disk_image(required("CUA_IMAGE")?)
- .image_pull_secret(required("CUA_IMAGE_PULL_SECRET")?)
- .cpu_cores(4)
- .memory("4Gi".into())
- .build()?,
- )
- .build()?,
- })?;
- pool = Some(created_pool.clone());
- let created_claim = sdk.create_claim(CreateClaimRequest {
- pool: created_pool,
- spec: None,
- })?;
- claim = Some(created_claim.clone());
- let sandbox = sdk.wait_claim(created_claim)?;
- let result = run_agent(&mut sdk, sandbox)?;
- println!("{result}");
- Ok(())
- })();
- let claim_cleanup = claim.map_or(Ok(()), |claim| sdk.delete_claim(claim));
- let pool_cleanup = pool.map_or(Ok(()), |pool| sdk.delete_pool(pool));
- sdk.close();
- result.and(claim_cleanup).and(pool_cleanup)
-}
-
-fn required(name: &str) -> Result<String, String> {
- env::var(name).map_err(|_| format!("{name} is required"))
-}
diff --git a/libs/fleet/sdk-bindings/rust/src/lib.rs b/libs/fleet/sdk-bindings/rust/src/lib.rs
deleted file mode 100644
index 5baf4c255f..0000000000
--- a/libs/fleet/sdk-bindings/rust/src/lib.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-use cyclops_sdk_core::{
- AccessToken, Configuration as CoreConfiguration, HttpRequest, HttpResponse, OAuthCredentials,
- Platform, PlatformError,
-};
-use std::time::Duration;
-
-pub use cyclops_sdk_core::generated_crd::*;
-pub use cyclops_sdk_core::{
- Claim, CreateClaimRequest, CreatePoolRequest, Pool, Sandbox, SdkError, ServiceHttpRequest,
- ServiceHttpResponse,
-};
-
-#[derive(Debug, Clone)]
-pub struct OAuthConfiguration {
- pub token_url: String,
- pub client_id: String,
- pub client_secret: String,
-}
-#[derive(Debug, Clone)]
-pub struct Configuration {
- pub base_url: String,
- pub oauth: OAuthConfiguration,
-}
-#[derive(Default)]
-struct NativePlatform {
- oauth: Option<OAuthCredentials>,
- token: Option<AccessToken>,
-}
-pub struct Sdk {
- core: cyclops_sdk_core::Sdk<NativePlatform>,
-}
-pub struct ServiceClient<'a> {
- core: &'a mut cyclops_sdk_core::Sdk<NativePlatform>,
- sandbox: Sandbox,
- service: String,
-}
-pub struct ServiceRequestBuilder<'client, 'sdk> {
- client: &'client mut ServiceClient<'sdk>,
- request: ServiceHttpRequest,
-}
-
-impl<'sdk> ServiceClient<'sdk> {
- pub fn request<'client>(
- &'client mut self,
- method: impl Into<String>,
- path: impl Into<String>,
- ) -> ServiceRequestBuilder<'client, 'sdk> {
- ServiceRequestBuilder {
- client: self,
- request: ServiceHttpRequest::new(method, path, None),
- }
- }
- pub fn get<'client>(
- &'client mut self,
- path: impl Into<String>,
- ) -> ServiceRequestBuilder<'client, 'sdk> {
- self.request("GET", path)
- }
- pub fn post<'client>(
- &'client mut self,
- path: impl Into<String>,
- ) -> ServiceRequestBuilder<'client, 'sdk> {
- self.request("POST", path)
- }
-}
-
-impl ServiceRequestBuilder<'_, '_> {
- pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
- self.request.headers.push((name.into(), value.into()));
- self
- }
- pub fn body(mut self, body: impl Into<String>) -> Self {
- self.request.body = Some(body.into());
- self
- }
- pub fn send(self) -> Result<ServiceHttpResponse, SdkError> {
- self.client
- .core
- .service_request(&self.client.sandbox, &self.client.service, self.request)
- }
-}
-
-impl Sdk {
- pub fn connect(configuration: Configuration) -> Result<Self, String> {
- let platform = NativePlatform {
- oauth: Some(OAuthCredentials {
- token_url: configuration.oauth.token_url,
- client_id: configuration.oauth.client_id,
- client_secret: configuration.oauth.client_secret,
- }),
- token: None,
- };
- let core = cyclops_sdk_core::Sdk::connect(
- platform,
- CoreConfiguration {
- protocol_version: cyclops_sdk_core::PROTOCOL_VERSION,
- base_url: configuration.base_url,
- },
- )
- .map_err(|error| error.to_string())?;
- Ok(Self { core })
- }
- pub fn create_pool(&mut self, request: CreatePoolRequest) -> Result<Pool, String> {
- self.core
- .create_pool(request)
- .map_err(|error| error.to_string())
- }
- pub fn list_pools(&mut self, namespace: &str) -> Result<Vec<Pool>, String> {
- self.core
- .list_pools(namespace)
- .map_err(|error| error.to_string())
- }
- pub fn get_pool(&mut self, pool: Pool) -> Result<Pool, String> {
- self.core.get_pool(pool).map_err(|error| error.to_string())
- }
- pub fn update_pool(&mut self, pool: Pool) -> Result<Pool, String> {
- self.core
- .update_pool(pool)
- .map_err(|error| error.to_string())
- }
- pub fn delete_pool(&mut self, pool: Pool) -> Result<(), String> {
- self.core
- .delete_pool(pool)
- .map_err(|error| error.to_string())
- }
- pub fn create_claim(&mut self, request: CreateClaimRequest) -> Result<Claim, String> {
- self.core
- .create_claim(request)
- .map_err(|error| error.to_string())
- }
- pub fn list_claims(&mut self, namespace: &str) -> Result<Vec<Claim>, String> {
- self.core
- .list_claims(namespace)
- .map_err(|error| error.to_string())
- }
- pub fn get_claim(&mut self, claim: Claim) -> Result<Claim, String> {
- self.core
- .get_claim(claim)
- .map_err(|error| error.to_string())
- }
- pub fn update_claim(&mut self, claim: Claim) -> Result<Claim, String> {
- self.core
- .update_claim(claim)
- .map_err(|error| error.to_string())
- }
- pub fn delete_claim(&mut self, claim: Claim) -> Result<(), String> {
- self.core
- .delete_claim(claim)
- .map_err(|error| error.to_string())
- }
- pub fn wait_claim(&mut self, claim: Claim) -> Result<Sandbox, String> {
- self.core
- .wait_claim(claim)
- .map_err(|error| error.to_string())
- }
- pub fn service_client<'a>(
- &'a mut self,
- sandbox: &Sandbox,
- service: &str,
- ) -> Result<ServiceClient<'a>, SdkError> {
- if !sandbox
- .services
- .iter()
- .any(|available| available == service)
- {
- let mut available = sandbox.services.clone();
- available.sort();
- available.dedup();
- return Err(SdkError::UnknownService {
- requested: service.into(),
- available,
- });
- }
- Ok(ServiceClient {
- core: &mut self.core,
- sandbox: sandbox.clone(),
- service: service.into(),
- })
- }
- pub fn close(self) {}
-}
-
-fn send_without_body(
- mut request: ureq::RequestBuilder<ureq::typestate::WithoutBody>,
- headers: Vec<(String, String)>,
-) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> {
- for (name, value) in headers {
- request = request.header(&name, &value);
- }
- request.call()
-}
-fn send_with_body(
- mut request: ureq::RequestBuilder<ureq::typestate::WithBody>,
- headers: Vec<(String, String)>,
- body: Option<String>,
-) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> {
- for (name, value) in headers {
- request = request.header(&name, &value);
- }
- match body {
- Some(body) => request.send(body),
- None => request.send_empty(),
- }
-}
-impl Platform for NativePlatform {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError> {
- let response = match request.method.as_str() {
- "GET" => send_without_body(ureq::get(&request.url), request.headers),
- "DELETE" => send_without_body(ureq::delete(&request.url), request.headers),
- "HEAD" => send_without_body(ureq::head(&request.url), request.headers),
- "OPTIONS" => send_without_body(ureq::options(&request.url), request.headers),
- "POST" => send_with_body(ureq::post(&request.url), request.headers, request.body),
- "PUT" => send_with_body(ureq::put(&request.url), request.headers, request.body),
- "PATCH" => send_with_body(ureq::patch(&request.url), request.headers, request.body),
- method => {
- return Err(PlatformError::Transport(format!(
- "unsupported HTTP method {method}"
- )))
- }
- };
- match response {
- Ok(mut response) => {
- let status = response.status().as_u16();
- let body = response
- .body_mut()
- .read_to_string()
- .map_err(|error| PlatformError::Transport(error.to_string()))?;
- Ok(HttpResponse { status, body })
- }
- Err(ureq::Error::StatusCode(status)) => Ok(HttpResponse {
- status,
- body: String::new(),
- }),
- Err(error) => Err(PlatformError::Transport(error.to_string())),
- }
- }
- fn sleep(&mut self, milliseconds: u64) -> Result<(), PlatformError> {
- std::thread::sleep(Duration::from_millis(milliseconds));
- Ok(())
- }
- fn now_ms(&mut self) -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_millis() as u64
- }
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError> {
- self.oauth
- .clone()
- .ok_or_else(|| PlatformError::Credentials("OAuth is not configured".into()))
- }
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError> {
- Ok(self.token.clone())
- }
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError> {
- self.token = Some(token.clone());
- Ok(())
- }
-}
diff --git a/libs/fleet/sdk-bindings/rust/tests/public_api.rs b/libs/fleet/sdk-bindings/rust/tests/public_api.rs
deleted file mode 100644
index 93d79b0d34..0000000000
--- a/libs/fleet/sdk-bindings/rust/tests/public_api.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use cyclops_sdk_host::{
- Claim, Configuration, CreateClaimRequest, CreatePoolRequest, Pool, Sandbox, Sdk, SdkError,
- ServiceHttpResponse,
-};
-
-#[test]
-fn typed_resource_api_only() {
- let _: fn(Configuration) -> Result<Sdk, String> = Sdk::connect;
- let _: fn(&mut Sdk, CreatePoolRequest) -> Result<Pool, String> = Sdk::create_pool;
- let _: fn(&mut Sdk, &str) -> Result<Vec<Pool>, String> = Sdk::list_pools;
- let _: fn(&mut Sdk, Pool) -> Result<Pool, String> = Sdk::get_pool;
- let _: fn(&mut Sdk, Pool) -> Result<Pool, String> = Sdk::update_pool;
- let _: fn(&mut Sdk, Pool) -> Result<(), String> = Sdk::delete_pool;
- let _: fn(&mut Sdk, CreateClaimRequest) -> Result<Claim, String> = Sdk::create_claim;
- let _: fn(&mut Sdk, &str) -> Result<Vec<Claim>, String> = Sdk::list_claims;
- let _: fn(&mut Sdk, Claim) -> Result<Claim, String> = Sdk::get_claim;
- let _: fn(&mut Sdk, Claim) -> Result<Claim, String> = Sdk::update_claim;
- let _: fn(&mut Sdk, Claim) -> Result<(), String> = Sdk::delete_claim;
- let _: fn(&mut Sdk, Claim) -> Result<cyclops_sdk_host::Sandbox, String> = Sdk::wait_claim;
-}
-
-fn service_http_contract(sdk: &mut Sdk, sandbox: &Sandbox) -> Result<(), SdkError> {
- let mut service = sdk.service_client(sandbox, "mcp")?;
- let _: ServiceHttpResponse = service
- .post("/mcp")
- .header("content-type", "application/json")
- .body("{}")
- .send()?;
- Ok(())
-}
-
-#[test]
-fn service_http_is_sdk_owned() {
- let _: fn(&mut Sdk, &Sandbox) -> Result<(), SdkError> = service_http_contract;
-}
diff --git a/libs/fleet/sdk-bindings/swift/.cyclops-sdk-generated-files b/libs/fleet/sdk-bindings/swift/.cyclops-sdk-generated-files
new file mode 100644
index 0000000000..bbb78e3654
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/.cyclops-sdk-generated-files
@@ -0,0 +1,7 @@
+f CyclopsSdk.modulemap
+f CyclopsSdk.swift
+f CyclopsSdkFFI.h
+f CyclopsSdkFFI.modulemap
+f CyclopsSdkSchema.swift
+f CyclopsSdkSchemaFFI.h
+f CyclopsSdkSchemaFFI.modulemap
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.modulemap b/libs/fleet/sdk-bindings/swift/CyclopsSdk.modulemap
new file mode 100644
index 0000000000..2bf537a4d1
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.modulemap
@@ -0,0 +1,13 @@
+module CyclopsSdkFFI {
+ header "CyclopsSdkFFI.h"
+ export *
+ use "Darwin"
+ use "_Builtin_stdbool"
+ use "_Builtin_stdint"
+}module CyclopsSdkSchemaFFI {
+ header "CyclopsSdkSchemaFFI.h"
+ export *
+ use "Darwin"
+ use "_Builtin_stdbool"
+ use "_Builtin_stdint"
+}
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
new file mode 100644
index 0000000000..c5c61c14a0
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
@@ -0,0 +1,2557 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+// swiftlint:disable all
+import Foundation
+
+// Depending on the consumer's build setup, the low-level FFI code
+// might be in a separate module, or it might be compiled inline into
+// this module. This is a bit of light hackery to work with both.
+#if canImport(CyclopsSdkFFI)
+import CyclopsSdkFFI
+#endif
+
+fileprivate extension RustBuffer {
+ // Allocate a new buffer, copying the contents of a `UInt8` array.
+ init(bytes: [UInt8]) {
+ let rbuf = bytes.withUnsafeBufferPointer { ptr in
+ RustBuffer.from(ptr)
+ }
+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
+ }
+
+ static func empty() -> RustBuffer {
+ RustBuffer(capacity: 0, len:0, data: nil)
+ }
+
+ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
+ try! rustCall { ffi_cyclops_sdk_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
+ }
+
+ // Frees the buffer in place.
+ // The buffer must not be used after this is called.
+ func deallocate() {
+ try! rustCall { ffi_cyclops_sdk_rustbuffer_free(self, $0) }
+ }
+}
+
+fileprivate extension ForeignBytes {
+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {
+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
+ }
+
+ init(rawBufferPointer: UnsafeRawBufferPointer) {
+ self.init(
+ len: Int32(rawBufferPointer.count),
+ data: rawBufferPointer.baseAddress?.assumingMemoryBound(to: UInt8.self)
+ )
+ }
+}
+
+// Converter for `&[u8]` / `[ByRef] bytes` arguments.
+//
+// Conforms to `FfiConverter` so the compiler enforces the full converter
+// method set. Only the scope-bound `lower(_:_body:)` overload is sound —
+// zero-copy byte buffers only flow foreign -> Rust, and only in argument
+// position. The four protocol-witness methods (`lift`, `lower`, `read`,
+// `write`) `fatalError` at runtime if anyone reaches them.
+//
+// The scope-bound `lower` takes a closure because the `ForeignBytes`
+// pointer is only guaranteed valid for the duration of
+// `Data.withUnsafeBytes`. Callers must run the full FFI call inside
+// the closure body.
+fileprivate enum FfiConverterByRefBytes: FfiConverter {
+ typealias SwiftType = Data
+ typealias FfiType = ForeignBytes
+
+ static func lower<R>(_ value: Data, _ body: (ForeignBytes) throws -> R) rethrows -> R {
+ return try value.withUnsafeBytes { rawBuf in
+ try body(ForeignBytes(rawBufferPointer: rawBuf))
+ }
+ }
+
+ static func lower(_ value: Data) -> ForeignBytes {
+ fatalError("ByRef bytes cannot use the plain lower: returning ForeignBytes escapes the Data.withUnsafeBytes scope. Use the scope-bound lower(_:_body:) overload instead.")
+ }
+
+ static func lift(_ value: ForeignBytes) throws -> Data {
+ fatalError("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+ }
+
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Data {
+ fatalError("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+ }
+
+ static func write(_ value: Data, into buf: inout [UInt8]) {
+ fatalError("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+ }
+}
+
+// For every type used in the interface, we provide helper methods for conveniently
+// lifting and lowering that type from C-compatible data, and for reading and writing
+// values of that type in a buffer.
+
+// Helper classes/extensions that don't change.
+// Someday, this will be in a library of its own.
+
+fileprivate extension Data {
+ init(rustBuffer: RustBuffer) {
+ self.init(
+ bytesNoCopy: rustBuffer.data!,
+ count: Int(rustBuffer.len),
+ deallocator: .none
+ )
+ }
+}
+
+// Define reader functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work.
+//
+// With external types, one swift source file needs to be able to call the read
+// method on another source file's FfiConverter, but then what visibility
+// should Reader have?
+// - If Reader is fileprivate, then this means the read() must also
+// be fileprivate, which doesn't work with external types.
+// - If Reader is internal/public, we'll get compile errors since both source
+// files will try define the same type.
+//
+// Instead, the read() method and these helper functions input a tuple of data
+
+fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
+ (data: data, offset: 0)
+}
+
+// Reads an integer at the current offset, in big-endian order, and advances
+// the offset on success. Throws if reading the integer would move the
+// offset past the end of the buffer.
+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ if T.self == UInt8.self {
+ let value = reader.data[reader.offset]
+ reader.offset += 1
+ return value as! T
+ }
+ var value: T = 0
+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
+ reader.offset = range.upperBound
+ return value.bigEndian
+}
+
+// Reads an arbitrary number of bytes, to be used to read
+// raw bytes, this is useful when lifting strings
+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
+ let range = reader.offset..<(reader.offset+count)
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ var value = [UInt8](repeating: 0, count: count)
+ value.withUnsafeMutableBufferPointer({ buffer in
+ reader.data.copyBytes(to: buffer, from: range)
+ })
+ reader.offset = range.upperBound
+ return value
+}
+
+// Reads a float at the current offset.
+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return Float(bitPattern: try readInt(&reader))
+}
+
+// Reads a float at the current offset.
+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return Double(bitPattern: try readInt(&reader))
+}
+
+// Indicates if the offset has reached the end of the buffer.
+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
+ return reader.offset < reader.data.count
+}
+
+// Define writer functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work. See the above discussion on Readers for details.
+
+fileprivate func createWriter() -> [UInt8] {
+ return []
+}
+
+fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
+ writer.append(contentsOf: byteArr)
+}
+
+// Writes an integer in big-endian order.
+//
+// Warning: make sure what you are trying to write
+// is in the correct type!
+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
+ var value = value.bigEndian
+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
+}
+
+fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
+ writeInt(&writer, value.bitPattern)
+}
+
+fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
+ writeInt(&writer, value.bitPattern)
+}
+
+// Protocol for types that transfer other types across the FFI. This is
+// analogous to the Rust trait of the same name.
+fileprivate protocol FfiConverter {
+ associatedtype FfiType
+ associatedtype SwiftType
+
+ static func lift(_ value: FfiType) throws -> SwiftType
+ static func lower(_ value: SwiftType) -> FfiType
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
+ static func write(_ value: SwiftType, into buf: inout [UInt8])
+}
+
+// Types conforming to `Primitive` pass themselves directly over the FFI.
+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
+
+extension FfiConverterPrimitive {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ value: FfiType) throws -> SwiftType {
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> FfiType {
+ return value
+ }
+}
+
+// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
+// Used for complex types where it's hard to write a custom lift/lower.
+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
+
+extension FfiConverterRustBuffer {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {
+ var reader = createReader(data: Data(rustBuffer: buf))
+ let value = try read(from: &reader)
+ if hasRemaining(reader) {
+ throw UniffiInternalError.incompleteData
+ }
+ buf.deallocate()
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> RustBuffer {
+ var writer = createWriter()
+ write(value, into: &writer)
+ return RustBuffer(bytes: writer)
+ }
+}
+// An error type for FFI errors. These errors occur at the UniFFI level, not
+// the library level.
+fileprivate enum UniffiInternalError: LocalizedError {
+ case bufferOverflow
+ case incompleteData
+ case unexpectedOptionalTag
+ case unexpectedEnumCase
+ case unexpectedNullPointer
+ case unexpectedRustCallStatusCode
+ case unexpectedRustCallError
+ case unexpectedStaleHandle
+ case rustPanic(_ message: String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
+ case .incompleteData: return "The buffer still has data after lifting its containing value"
+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
+ case .unexpectedNullPointer: return "Raw pointer value was null"
+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
+ case let .rustPanic(message): return message
+ }
+ }
+}
+
+fileprivate extension NSLock {
+ func withLock<T>(f: () throws -> T) rethrows -> T {
+ self.lock()
+ defer { self.unlock() }
+ return try f()
+ }
+}
+
+fileprivate let CALL_SUCCESS: Int8 = 0
+fileprivate let CALL_ERROR: Int8 = 1
+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
+fileprivate let CALL_CANCELLED: Int8 = 3
+
+fileprivate extension RustCallStatus {
+ init() {
+ self.init(
+ code: CALL_SUCCESS,
+ errorBuf: RustBuffer.init(
+ capacity: 0,
+ len: 0,
+ data: nil
+ )
+ )
+ }
+}
+
+private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ let neverThrow: ((RustBuffer) throws -> Never)? = nil
+ return try makeRustCall(callback, errorHandler: neverThrow)
+}
+
+private func rustCallWithError<T, E: Swift.Error>(
+ _ errorHandler: @escaping (RustBuffer) throws -> E,
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ try makeRustCall(callback, errorHandler: errorHandler)
+}
+
+private func makeRustCall<T, E: Swift.Error>(
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws -> T {
+ uniffiEnsureCyclopsSdkInitialized()
+ var callStatus = RustCallStatus.init()
+ let returnedVal = callback(&callStatus)
+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
+ return returnedVal
+}
+
+private func uniffiCheckCallStatus<E: Swift.Error>(
+ callStatus: RustCallStatus,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws {
+ switch callStatus.code {
+ case CALL_SUCCESS:
+ return
+
+ case CALL_ERROR:
+ if let errorHandler = errorHandler {
+ throw try errorHandler(callStatus.errorBuf)
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.unexpectedRustCallError
+ }
+
+ case CALL_UNEXPECTED_ERROR:
+ // When the rust code sees a panic, it tries to construct a RustBuffer
+ // with the message. But if that code panics, then it just sends back
+ // an empty buffer.
+ if callStatus.errorBuf.len > 0 {
+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.rustPanic("Rust panic")
+ }
+
+ case CALL_CANCELLED:
+ fatalError("Cancellation not supported yet")
+
+ default:
+ throw UniffiInternalError.unexpectedRustCallStatusCode
+ }
+}
+
+private func uniffiTraitInterfaceCall<T>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> ()
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+
+private func uniffiTraitInterfaceCallWithError<T, E>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> (),
+ lowerError: (E) -> RustBuffer
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error as E {
+ callStatus.pointee.code = CALL_ERROR
+ callStatus.pointee.errorBuf = lowerError(error)
+ } catch {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that SWIFT handles always have the lowest bit set
+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
+
+fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
+ private let lock = NSLock()
+ private var map: [UInt64: T] = [:]
+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
+
+ func insert(obj: T) -> UInt64 {
+ lock.withLock {
+ return doInsert(obj)
+ }
+ }
+
+ // Low-level insert function, this assumes `lock` is held.
+ private func doInsert(_ obj: T) -> UInt64 {
+ let handle = currentHandle
+ currentHandle += UNIFFI_HANDLEMAP_DELTA
+ map[handle] = obj
+ return handle
+ }
+
+ func get(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ func clone(handle: UInt64) throws -> UInt64 {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return doInsert(obj)
+ }
+ }
+
+ @discardableResult
+ func remove(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map.removeValue(forKey: handle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ var count: Int {
+ get {
+ map.count
+ }
+ }
+}
+
+
+// Public interface members begin here.
+// Magic number for the Rust proxy to call using the same mechanism as every other method,
+// to free the callback once it's dropped by Rust.
+private let IDX_CALLBACK_FREE: Int32 = 0
+// Callback return codes
+private let UNIFFI_CALLBACK_SUCCESS: Int32 = 0
+private let UNIFFI_CALLBACK_ERROR: Int32 = 1
+private let UNIFFI_CALLBACK_UNEXPECTED_ERROR: Int32 = 2
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt16: FfiConverterPrimitive {
+ typealias FfiType = UInt16
+ typealias SwiftType = UInt16
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt16 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt32: FfiConverterPrimitive {
+ typealias FfiType = UInt32
+ typealias SwiftType = UInt32
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt32 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt64: FfiConverterPrimitive {
+ typealias FfiType = UInt64
+ typealias SwiftType = UInt64
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterString: FfiConverter {
+ typealias SwiftType = String
+ typealias FfiType = RustBuffer
+
+ public static func lift(_ value: RustBuffer) throws -> String {
+ defer {
+ value.deallocate()
+ }
+ if value.data == nil {
+ return String()
+ }
+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
+ // Use Swift's native UTF-8 decoder; `String(bytes:encoding:.utf8)` goes
+ // through Foundation's NSString and silently strips a leading U+FEFF BOM.
+ // Invalid UTF-8 substitutes U+FFFD instead of trapping (unreachable
+ // given Rust's `String` invariant).
+ return String(decoding: bytes, as: UTF8.self)
+ }
+
+ public static func lower(_ value: String) -> RustBuffer {
+ return value.utf8CString.withUnsafeBufferPointer { ptr in
+ // The swift string gives us int8_t, we want uint8_t.
+ ptr.withMemoryRebound(to: UInt8.self) { ptr in
+ // The swift string gives us a trailing null byte, we don't want it.
+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
+ return RustBuffer.from(buf)
+ }
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
+ let len: Int32 = try readInt(&buf)
+ // See `lift` above for why we avoid Foundation's NSString-backed decoder here.
+ return String(decoding: try readBytes(&buf, count: Int(len)), as: UTF8.self)
+ }
+
+ public static func write(_ value: String, into buf: inout [UInt8]) {
+ let len = Int32(value.utf8.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value.utf8)
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterData: FfiConverterRustBuffer {
+ typealias SwiftType = Data
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Data {
+ let len: Int32 = try readInt(&buf)
+ return Data(try readBytes(&buf, count: Int(len)))
+ }
+
+ public static func write(_ value: Data, into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value)
+ }
+}
+
+
+
+
+public protocol CyclopsClientProtocol: AnyObject, Sendable {
+
+ func createClaim(request: CreateClaimRequest) async throws -> Claim
+
+ func deleteClaim(claim: Claim) async throws
+
+ func getClaim(claim: Claim) async throws -> Claim
+
+ func listClaims(namespace: String) async throws -> [Claim]
+
+ func waitClaim(claim: Claim) async throws -> Sandbox
+
+ func createPool(request: CreatePoolRequest) async throws -> Pool
+
+ func deletePool(pool: Pool) async throws
+
+ func getPool(pool: Pool) async throws -> Pool
+
+ func listPools(namespace: String) async throws -> [Pool]
+
+ func updatePool(pool: Pool) async throws -> Pool
+
+ func serviceRequest(sandbox: Sandbox, service: String, path: String, request: HttpRequest) async throws -> HttpResponse
+
+}
+open class CyclopsClient: CyclopsClientProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_cyclops_sdk_fn_clone_cyclopsclient(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_cyclops_sdk_fn_free_cyclopsclient(handle, $0) }
+ }
+
+
+public static func connect(configuration: CyclopsConfiguration, httpClient: HttpClient)throws -> CyclopsClient {
+ return try FfiConverterTypeCyclopsClient_lift(try rustCallWithError(FfiConverterTypeSdkError_lift) {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect(
+ FfiConverterTypeCyclopsConfiguration_lower(configuration),
+ FfiConverterTypeHttpClient_lower(httpClient),uniffiCallStatus
+ )
+})
+}
+
+
+
+open func createClaim(request: CreateClaimRequest)async throws -> Claim {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(
+ self.uniffiCloneHandle(),FfiConverterTypeCreateClaimRequest_lower(request)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeClaim_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func deleteClaim(claim: Claim)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(
+ self.uniffiCloneHandle(),FfiConverterTypeClaim_lower(claim)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_void,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_void,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func getClaim(claim: Claim)async throws -> Claim {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(
+ self.uniffiCloneHandle(),FfiConverterTypeClaim_lower(claim)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeClaim_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func listClaims(namespace: String)async throws -> [Claim] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(
+ self.uniffiCloneHandle(),FfiConverterString.lower(namespace)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeClaim.lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func waitClaim(claim: Claim)async throws -> Sandbox {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(
+ self.uniffiCloneHandle(),FfiConverterTypeClaim_lower(claim)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSandbox_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func createPool(request: CreatePoolRequest)async throws -> Pool {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(
+ self.uniffiCloneHandle(),FfiConverterTypeCreatePoolRequest_lower(request)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypePool_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func deletePool(pool: Pool)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(
+ self.uniffiCloneHandle(),FfiConverterTypePool_lower(pool)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_void,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_void,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func getPool(pool: Pool)async throws -> Pool {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(
+ self.uniffiCloneHandle(),FfiConverterTypePool_lower(pool)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypePool_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func listPools(namespace: String)async throws -> [Pool] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(
+ self.uniffiCloneHandle(),FfiConverterString.lower(namespace)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypePool.lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func updatePool(pool: Pool)async throws -> Pool {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(
+ self.uniffiCloneHandle(),FfiConverterTypePool_lower(pool)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypePool_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func serviceRequest(sandbox: Sandbox, service: String, path: String, request: HttpRequest)async throws -> HttpResponse {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(
+ self.uniffiCloneHandle(),FfiConverterTypeSandbox_lower(sandbox),FfiConverterString.lower(service),FfiConverterString.lower(path),FfiConverterTypeHttpRequest_lower(request)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeHttpResponse_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCyclopsClient: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = CyclopsClient
+
+ public static func lift(_ handle: UInt64) throws -> CyclopsClient {
+ return CyclopsClient(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: CyclopsClient) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CyclopsClient {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: CyclopsClient, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsClient_lift(_ handle: UInt64) throws -> CyclopsClient {
+ return try FfiConverterTypeCyclopsClient.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsClient_lower(_ value: CyclopsClient) -> UInt64 {
+ return FfiConverterTypeCyclopsClient.lower(value)
+}
+
+
+
+
+
+
+public protocol CyclopsCredentialsProtocol: AnyObject, Sendable {
+
+}
+open class CyclopsCredentials: CyclopsCredentialsProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_cyclops_sdk_fn_clone_cyclopscredentials(self.handle, $0) }
+ }
+public convenience init(clientId: String, clientSecret: String) {
+ let handle =
+ try! rustCall() {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new(
+ FfiConverterString.lower(clientId),
+ FfiConverterString.lower(clientSecret),uniffiCallStatus
+ )
+}
+ self.init(unsafeFromHandle: handle)
+}
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_cyclops_sdk_fn_free_cyclopscredentials(handle, $0) }
+ }
+
+
+
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCyclopsCredentials: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = CyclopsCredentials
+
+ public static func lift(_ handle: UInt64) throws -> CyclopsCredentials {
+ return CyclopsCredentials(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: CyclopsCredentials) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CyclopsCredentials {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: CyclopsCredentials, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsCredentials_lift(_ handle: UInt64) throws -> CyclopsCredentials {
+ return try FfiConverterTypeCyclopsCredentials.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsCredentials_lower(_ value: CyclopsCredentials) -> UInt64 {
+ return FfiConverterTypeCyclopsCredentials.lower(value)
+}
+
+
+
+
+
+
+public protocol HttpClient: AnyObject, Sendable {
+
+ func execute(request: HttpRequest) async throws -> HttpResponse
+
+}
+open class HttpClientImpl: HttpClient, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_cyclops_sdk_fn_clone_httpclient(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_cyclops_sdk_fn_free_httpclient(handle, $0) }
+ }
+
+
+
+
+open func execute(request: HttpRequest)async throws -> HttpResponse {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_httpclient_execute(
+ self.uniffiCloneHandle(),FfiConverterTypeHttpRequest_lower(request)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeHttpResponse_lift,
+ errorHandler: FfiConverterTypeHttpError_lift
+ )
+}
+
+
+
+}
+
+
+
+// Put the implementation in a struct so we don't pollute the top-level namespace
+fileprivate struct UniffiCallbackInterfaceHttpClient {
+
+ // Create the VTable using a series of closures.
+ // Swift automatically converts these into C callback functions.
+ //
+ // Store the vtable directly.
+ static let vtable: UniffiVTableCallbackInterfaceHttpClient = UniffiVTableCallbackInterfaceHttpClient(
+ uniffiFree: { (uniffiHandle: UInt64) -> () in
+ do {
+ try FfiConverterTypeHttpClient.handleMap.remove(handle: uniffiHandle)
+ } catch {
+ print("Uniffi callback interface HttpClient: handle missing in uniffiFree")
+ }
+ },
+ uniffiClone: { (uniffiHandle: UInt64) -> UInt64 in
+ do {
+ return try FfiConverterTypeHttpClient.handleMap.clone(handle: uniffiHandle)
+ } catch {
+ fatalError("Uniffi callback interface HttpClient: handle missing in uniffiClone")
+ }
+ },
+ execute: { (
+ uniffiHandle: UInt64,
+ request: RustBuffer,
+ uniffiFutureCallback: @escaping UniffiForeignFutureCompleteRustBuffer,
+ uniffiCallbackData: UInt64,
+ uniffiOutDroppedCallback: UnsafeMutablePointer<UniffiForeignFutureDroppedCallbackStruct>
+ ) in
+ let makeCall = {
+ () async throws -> HttpResponse in
+ guard let uniffiObj = try? FfiConverterTypeHttpClient.handleMap.get(handle: uniffiHandle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return try await uniffiObj.execute(
+ request: try FfiConverterTypeHttpRequest_lift(request)
+ )
+ }
+
+ let uniffiHandleSuccess = { (returnValue: HttpResponse) in
+ uniffiFutureCallback(
+ uniffiCallbackData,
+ UniffiForeignFutureResultRustBuffer(
+ returnValue: FfiConverterTypeHttpResponse_lower(returnValue),
+ callStatus: RustCallStatus()
+ )
+ )
+ }
+ let uniffiHandleError = { (statusCode, errorBuf) in
+ uniffiFutureCallback(
+ uniffiCallbackData,
+ UniffiForeignFutureResultRustBuffer(
+ returnValue: RustBuffer.empty(),
+ callStatus: RustCallStatus(code: statusCode, errorBuf: errorBuf)
+ )
+ )
+ }
+ uniffiTraitInterfaceCallAsyncWithError(
+ makeCall: makeCall,
+ handleSuccess: uniffiHandleSuccess,
+ handleError: uniffiHandleError,
+ lowerError: FfiConverterTypeHttpError_lower,
+ droppedCallback: uniffiOutDroppedCallback
+ )
+ }
+ )
+
+ // Rust stores this pointer for future callback invocations, so it must live
+ // for the process lifetime (not just for the init function call).
+ //
+ // `nonisolated(unsafe)` is needed under Swift 6 strict concurrency.
+ // This is safe because the pointee is initialized once during static init
+ // and never mutated by either side of the FFI. Its fields are C function pointers.
+ nonisolated(unsafe) static let vtablePtr: UnsafePointer<UniffiVTableCallbackInterfaceHttpClient> = {
+ let ptr = UnsafeMutablePointer<UniffiVTableCallbackInterfaceHttpClient>.allocate(capacity: 1)
+ ptr.initialize(to: vtable)
+ return UnsafePointer(ptr)
+ }()
+}
+
+private func uniffiCallbackInitHttpClient() {
+ uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(UniffiCallbackInterfaceHttpClient.vtablePtr)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHttpClient: FfiConverter {
+ fileprivate static let handleMap = UniffiHandleMap<HttpClient>()
+
+ typealias FfiType = UInt64
+ typealias SwiftType = HttpClient
+
+ public static func lift(_ handle: UInt64) throws -> HttpClient {
+ if ((handle & 1) == 0) {
+ // Rust-generated handle, construct a new class that uses the handle to implement the
+ // interface
+ return HttpClientImpl(unsafeFromHandle: handle)
+ } else {
+ // Swift-generated handle, get the object from the handle map
+ return try handleMap.remove(handle: handle)
+ }
+ }
+
+ public static func lower(_ value: HttpClient) -> UInt64 {
+ if let rustImpl = value as? HttpClientImpl {
+ // Rust-implemented object. Clone the handle and return it
+ return rustImpl.uniffiCloneHandle()
+ } else {
+ // Swift object, generate a new vtable handle and return that.
+ return handleMap.insert(obj: value)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HttpClient {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: HttpClient, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpClient_lift(_ handle: UInt64) throws -> HttpClient {
+ return try FfiConverterTypeHttpClient.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpClient_lower(_ value: HttpClient) -> UInt64 {
+ return FfiConverterTypeHttpClient.lower(value)
+}
+
+
+
+
+public struct Claim: Equatable, Hashable {
+ public var apiVersion: String
+ public var kind: String
+ public var metadata: ResourceMetadata
+ public var spec: ClaimSpec
+ public var status: OsGymSandboxClaimStatus?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(apiVersion: String, kind: String, metadata: ResourceMetadata, spec: ClaimSpec, status: OsGymSandboxClaimStatus?) {
+ self.apiVersion = apiVersion
+ self.kind = kind
+ self.metadata = metadata
+ self.spec = spec
+ self.status = status
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Claim: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClaim: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Claim {
+ return
+ try Claim(
+ apiVersion: FfiConverterString.read(from: &buf),
+ kind: FfiConverterString.read(from: &buf),
+ metadata: FfiConverterTypeResourceMetadata.read(from: &buf),
+ spec: FfiConverterTypeClaimSpec.read(from: &buf),
+ status: FfiConverterOptionTypeOSGymSandboxClaimStatus.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Claim, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.apiVersion, into: &buf)
+ FfiConverterString.write(value.kind, into: &buf)
+ FfiConverterTypeResourceMetadata.write(value.metadata, into: &buf)
+ FfiConverterTypeClaimSpec.write(value.spec, into: &buf)
+ FfiConverterOptionTypeOSGymSandboxClaimStatus.write(value.status, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaim_lift(_ buf: RustBuffer) throws -> Claim {
+ return try FfiConverterTypeClaim.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaim_lower(_ value: Claim) -> RustBuffer {
+ return FfiConverterTypeClaim.lower(value)
+}
+
+
+public struct CreateClaimRequest: Equatable, Hashable {
+ public var pool: Pool
+ public var spec: ClaimSpec?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(pool: Pool, spec: ClaimSpec?) {
+ self.pool = pool
+ self.spec = spec
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension CreateClaimRequest: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCreateClaimRequest: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CreateClaimRequest {
+ return
+ try CreateClaimRequest(
+ pool: FfiConverterTypePool.read(from: &buf),
+ spec: FfiConverterOptionTypeClaimSpec.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: CreateClaimRequest, into buf: inout [UInt8]) {
+ FfiConverterTypePool.write(value.pool, into: &buf)
+ FfiConverterOptionTypeClaimSpec.write(value.spec, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreateClaimRequest_lift(_ buf: RustBuffer) throws -> CreateClaimRequest {
+ return try FfiConverterTypeCreateClaimRequest.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreateClaimRequest_lower(_ value: CreateClaimRequest) -> RustBuffer {
+ return FfiConverterTypeCreateClaimRequest.lower(value)
+}
+
+
+public struct CreatePoolRequest: Equatable, Hashable {
+ public var namespace: String
+ public var spec: PoolSpec
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(namespace: String, spec: PoolSpec) {
+ self.namespace = namespace
+ self.spec = spec
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension CreatePoolRequest: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCreatePoolRequest: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CreatePoolRequest {
+ return
+ try CreatePoolRequest(
+ namespace: FfiConverterString.read(from: &buf),
+ spec: FfiConverterTypePoolSpec.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: CreatePoolRequest, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.namespace, into: &buf)
+ FfiConverterTypePoolSpec.write(value.spec, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreatePoolRequest_lift(_ buf: RustBuffer) throws -> CreatePoolRequest {
+ return try FfiConverterTypeCreatePoolRequest.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreatePoolRequest_lower(_ value: CreatePoolRequest) -> RustBuffer {
+ return FfiConverterTypeCreatePoolRequest.lower(value)
+}
+
+
+public struct CyclopsConfiguration {
+ public var baseUrl: String
+ public var tokenUrl: String
+ public var credentials: CyclopsCredentials
+ public var poolPollIntervalMs: UInt64
+ public var poolPollLimit: UInt32
+ public var claimPollIntervalMs: UInt64
+ public var claimPollLimit: UInt32
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(baseUrl: String, tokenUrl: String, credentials: CyclopsCredentials, poolPollIntervalMs: UInt64, poolPollLimit: UInt32, claimPollIntervalMs: UInt64, claimPollLimit: UInt32) {
+ self.baseUrl = baseUrl
+ self.tokenUrl = tokenUrl
+ self.credentials = credentials
+ self.poolPollIntervalMs = poolPollIntervalMs
+ self.poolPollLimit = poolPollLimit
+ self.claimPollIntervalMs = claimPollIntervalMs
+ self.claimPollLimit = claimPollLimit
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension CyclopsConfiguration: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCyclopsConfiguration: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CyclopsConfiguration {
+ return
+ try CyclopsConfiguration(
+ baseUrl: FfiConverterString.read(from: &buf),
+ tokenUrl: FfiConverterString.read(from: &buf),
+ credentials: FfiConverterTypeCyclopsCredentials.read(from: &buf),
+ poolPollIntervalMs: FfiConverterUInt64.read(from: &buf),
+ poolPollLimit: FfiConverterUInt32.read(from: &buf),
+ claimPollIntervalMs: FfiConverterUInt64.read(from: &buf),
+ claimPollLimit: FfiConverterUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: CyclopsConfiguration, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.baseUrl, into: &buf)
+ FfiConverterString.write(value.tokenUrl, into: &buf)
+ FfiConverterTypeCyclopsCredentials.write(value.credentials, into: &buf)
+ FfiConverterUInt64.write(value.poolPollIntervalMs, into: &buf)
+ FfiConverterUInt32.write(value.poolPollLimit, into: &buf)
+ FfiConverterUInt64.write(value.claimPollIntervalMs, into: &buf)
+ FfiConverterUInt32.write(value.claimPollLimit, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsConfiguration_lift(_ buf: RustBuffer) throws -> CyclopsConfiguration {
+ return try FfiConverterTypeCyclopsConfiguration.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCyclopsConfiguration_lower(_ value: CyclopsConfiguration) -> RustBuffer {
+ return FfiConverterTypeCyclopsConfiguration.lower(value)
+}
+
+
+public struct HttpHeader: Equatable, Hashable {
+ public var name: String
+ public var value: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, value: String) {
+ self.name = name
+ self.value = value
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension HttpHeader: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHttpHeader: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HttpHeader {
+ return
+ try HttpHeader(
+ name: FfiConverterString.read(from: &buf),
+ value: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: HttpHeader, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.value, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpHeader_lift(_ buf: RustBuffer) throws -> HttpHeader {
+ return try FfiConverterTypeHttpHeader.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpHeader_lower(_ value: HttpHeader) -> RustBuffer {
+ return FfiConverterTypeHttpHeader.lower(value)
+}
+
+
+public struct HttpRequest: Equatable, Hashable {
+ public var method: String
+ public var url: String
+ public var headers: [HttpHeader]
+ public var body: Data?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(method: String, url: String, headers: [HttpHeader], body: Data?) {
+ self.method = method
+ self.url = url
+ self.headers = headers
+ self.body = body
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension HttpRequest: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHttpRequest: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HttpRequest {
+ return
+ try HttpRequest(
+ method: FfiConverterString.read(from: &buf),
+ url: FfiConverterString.read(from: &buf),
+ headers: FfiConverterSequenceTypeHttpHeader.read(from: &buf),
+ body: FfiConverterOptionData.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: HttpRequest, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.method, into: &buf)
+ FfiConverterString.write(value.url, into: &buf)
+ FfiConverterSequenceTypeHttpHeader.write(value.headers, into: &buf)
+ FfiConverterOptionData.write(value.body, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpRequest_lift(_ buf: RustBuffer) throws -> HttpRequest {
+ return try FfiConverterTypeHttpRequest.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpRequest_lower(_ value: HttpRequest) -> RustBuffer {
+ return FfiConverterTypeHttpRequest.lower(value)
+}
+
+
+public struct HttpResponse: Equatable, Hashable {
+ public var status: UInt16
+ public var headers: [HttpHeader]
+ public var body: Data
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(status: UInt16, headers: [HttpHeader], body: Data) {
+ self.status = status
+ self.headers = headers
+ self.body = body
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension HttpResponse: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHttpResponse: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HttpResponse {
+ return
+ try HttpResponse(
+ status: FfiConverterUInt16.read(from: &buf),
+ headers: FfiConverterSequenceTypeHttpHeader.read(from: &buf),
+ body: FfiConverterData.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: HttpResponse, into buf: inout [UInt8]) {
+ FfiConverterUInt16.write(value.status, into: &buf)
+ FfiConverterSequenceTypeHttpHeader.write(value.headers, into: &buf)
+ FfiConverterData.write(value.body, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpResponse_lift(_ buf: RustBuffer) throws -> HttpResponse {
+ return try FfiConverterTypeHttpResponse.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpResponse_lower(_ value: HttpResponse) -> RustBuffer {
+ return FfiConverterTypeHttpResponse.lower(value)
+}
+
+
+/**
+ * UniFFI cannot emit aliases for external record types. Generated bindings use
+ * `OSGymWorkspacePoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
+ */
+public struct Pool: Equatable, Hashable {
+ public var apiVersion: String
+ public var kind: String
+ public var metadata: ResourceMetadata
+ public var spec: PoolSpec
+ public var status: OsGymWorkspacePoolStatus?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(apiVersion: String, kind: String, metadata: ResourceMetadata, spec: PoolSpec, status: OsGymWorkspacePoolStatus?) {
+ self.apiVersion = apiVersion
+ self.kind = kind
+ self.metadata = metadata
+ self.spec = spec
+ self.status = status
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Pool: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePool: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Pool {
+ return
+ try Pool(
+ apiVersion: FfiConverterString.read(from: &buf),
+ kind: FfiConverterString.read(from: &buf),
+ metadata: FfiConverterTypeResourceMetadata.read(from: &buf),
+ spec: FfiConverterTypePoolSpec.read(from: &buf),
+ status: FfiConverterOptionTypeOSGymWorkspacePoolStatus.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Pool, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.apiVersion, into: &buf)
+ FfiConverterString.write(value.kind, into: &buf)
+ FfiConverterTypeResourceMetadata.write(value.metadata, into: &buf)
+ FfiConverterTypePoolSpec.write(value.spec, into: &buf)
+ FfiConverterOptionTypeOSGymWorkspacePoolStatus.write(value.status, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePool_lift(_ buf: RustBuffer) throws -> Pool {
+ return try FfiConverterTypePool.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePool_lower(_ value: Pool) -> RustBuffer {
+ return FfiConverterTypePool.lower(value)
+}
+
+
+public struct ResourceMetadata: Equatable, Hashable {
+ public var namespace: String
+ public var name: String
+ public var labels: [String: String]?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(namespace: String, name: String, labels: [String: String]?) {
+ self.namespace = namespace
+ self.name = name
+ self.labels = labels
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ResourceMetadata: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeResourceMetadata: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ResourceMetadata {
+ return
+ try ResourceMetadata(
+ namespace: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ labels: FfiConverterOptionDictionaryStringString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ResourceMetadata, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.namespace, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterOptionDictionaryStringString.write(value.labels, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeResourceMetadata_lift(_ buf: RustBuffer) throws -> ResourceMetadata {
+ return try FfiConverterTypeResourceMetadata.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeResourceMetadata_lower(_ value: ResourceMetadata) -> RustBuffer {
+ return FfiConverterTypeResourceMetadata.lower(value)
+}
+
+
+public struct Sandbox: Equatable, Hashable {
+ public var namespace: String
+ public var claim: String
+ public var name: String
+ public var services: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(namespace: String, claim: String, name: String, services: [String]) {
+ self.namespace = namespace
+ self.claim = claim
+ self.name = name
+ self.services = services
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Sandbox: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSandbox: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Sandbox {
+ return
+ try Sandbox(
+ namespace: FfiConverterString.read(from: &buf),
+ claim: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ services: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Sandbox, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.namespace, into: &buf)
+ FfiConverterString.write(value.claim, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterSequenceString.write(value.services, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandbox_lift(_ buf: RustBuffer) throws -> Sandbox {
+ return try FfiConverterTypeSandbox.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandbox_lower(_ value: Sandbox) -> RustBuffer {
+ return FfiConverterTypeSandbox.lower(value)
+}
+
+
+public
+enum HttpError: Swift.Error, Equatable, Hashable, Foundation.LocalizedError {
+
+
+
+ case Transport(reason: String
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension HttpError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHttpError: FfiConverterRustBuffer {
+ typealias SwiftType = HttpError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HttpError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Transport(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: HttpError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Transport(reason):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(reason, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpError_lift(_ buf: RustBuffer) throws -> HttpError {
+ return try FfiConverterTypeHttpError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHttpError_lower(_ value: HttpError) -> RustBuffer {
+ return FfiConverterTypeHttpError.lower(value)
+}
+
+
+public
+enum SdkError: Swift.Error, Equatable, Hashable, Foundation.LocalizedError {
+
+
+
+ case Configuration(reason: String
+ )
+ case InvalidResourceName(field: String, value: String, reason: String
+ )
+ case Transport(reason: String
+ )
+ case Token(reason: String
+ )
+ case Body(reason: String
+ )
+ case Status(operation: String, status: UInt16, body: String
+ )
+ case UnknownService(requested: String, available: [String]
+ )
+ case InvalidServicePath(path: String
+ )
+ case ClaimFailed(phase: String, status: String
+ )
+ case ClaimTimeout
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension SdkError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSdkError: FfiConverterRustBuffer {
+ typealias SwiftType = SdkError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SdkError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Configuration(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .InvalidResourceName(
+ field: try FfiConverterString.read(from: &buf),
+ value: try FfiConverterString.read(from: &buf),
+ reason: try FfiConverterString.read(from: &buf)
+ )
+ case 3: return .Transport(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+ case 4: return .Token(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+ case 5: return .Body(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+ case 6: return .Status(
+ operation: try FfiConverterString.read(from: &buf),
+ status: try FfiConverterUInt16.read(from: &buf),
+ body: try FfiConverterString.read(from: &buf)
+ )
+ case 7: return .UnknownService(
+ requested: try FfiConverterString.read(from: &buf),
+ available: try FfiConverterSequenceString.read(from: &buf)
+ )
+ case 8: return .InvalidServicePath(
+ path: try FfiConverterString.read(from: &buf)
+ )
+ case 9: return .ClaimFailed(
+ phase: try FfiConverterString.read(from: &buf),
+ status: try FfiConverterString.read(from: &buf)
+ )
+ case 10: return .ClaimTimeout
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: SdkError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Configuration(reason):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(reason, into: &buf)
+
+
+ case let .InvalidResourceName(field,value,reason):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(field, into: &buf)
+ FfiConverterString.write(value, into: &buf)
+ FfiConverterString.write(reason, into: &buf)
+
+
+ case let .Transport(reason):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(reason, into: &buf)
+
+
+ case let .Token(reason):
+ writeInt(&buf, Int32(4))
+ FfiConverterString.write(reason, into: &buf)
+
+
+ case let .Body(reason):
+ writeInt(&buf, Int32(5))
+ FfiConverterString.write(reason, into: &buf)
+
+
+ case let .Status(operation,status,body):
+ writeInt(&buf, Int32(6))
+ FfiConverterString.write(operation, into: &buf)
+ FfiConverterUInt16.write(status, into: &buf)
+ FfiConverterString.write(body, into: &buf)
+
+
+ case let .UnknownService(requested,available):
+ writeInt(&buf, Int32(7))
+ FfiConverterString.write(requested, into: &buf)
+ FfiConverterSequenceString.write(available, into: &buf)
+
+
+ case let .InvalidServicePath(path):
+ writeInt(&buf, Int32(8))
+ FfiConverterString.write(path, into: &buf)
+
+
+ case let .ClaimFailed(phase,status):
+ writeInt(&buf, Int32(9))
+ FfiConverterString.write(phase, into: &buf)
+ FfiConverterString.write(status, into: &buf)
+
+
+ case .ClaimTimeout:
+ writeInt(&buf, Int32(10))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSdkError_lift(_ buf: RustBuffer) throws -> SdkError {
+ return try FfiConverterTypeSdkError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSdkError_lower(_ value: SdkError) -> RustBuffer {
+ return FfiConverterTypeSdkError.lower(value)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionData: FfiConverterRustBuffer {
+ typealias SwiftType = Data?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterData.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterData.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeClaimSpec: FfiConverterRustBuffer {
+ typealias SwiftType = ClaimSpec?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeClaimSpec.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeClaimSpec.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeOSGymSandboxClaimStatus: FfiConverterRustBuffer {
+ typealias SwiftType = OsGymSandboxClaimStatus?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeOSGymSandboxClaimStatus.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeOSGymSandboxClaimStatus.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeOSGymWorkspacePoolStatus: FfiConverterRustBuffer {
+ typealias SwiftType = OsGymWorkspacePoolStatus?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeOSGymWorkspacePoolStatus.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeOSGymWorkspacePoolStatus.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionDictionaryStringString: FfiConverterRustBuffer {
+ typealias SwiftType = [String: String]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterDictionaryStringString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterDictionaryStringString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceString: FfiConverterRustBuffer {
+ typealias SwiftType = [String]
+
+ public static func write(_ value: [String], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterString.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [String]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterString.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeClaim: FfiConverterRustBuffer {
+ typealias SwiftType = [Claim]
+
+ public static func write(_ value: [Claim], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeClaim.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Claim] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Claim]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeClaim.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeHttpHeader: FfiConverterRustBuffer {
+ typealias SwiftType = [HttpHeader]
+
+ public static func write(_ value: [HttpHeader], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeHttpHeader.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [HttpHeader] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [HttpHeader]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeHttpHeader.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypePool: FfiConverterRustBuffer {
+ typealias SwiftType = [Pool]
+
+ public static func write(_ value: [Pool], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypePool.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Pool] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Pool]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypePool.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDictionaryStringString: FfiConverterRustBuffer {
+ public static func write(_ value: [String: String], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for (key, value) in value {
+ FfiConverterString.write(key, into: &buf)
+ FfiConverterString.write(value, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: String] {
+ let len: Int32 = try readInt(&buf)
+ var dict = [String: String]()
+ dict.reserveCapacity(Int(len))
+ for _ in 0..<len {
+ let key = try FfiConverterString.read(from: &buf)
+ let value = try FfiConverterString.read(from: &buf)
+ dict[key] = value
+ }
+ return dict
+ }
+}
+private let UNIFFI_RUST_FUTURE_POLL_READY: Int8 = 0
+private let UNIFFI_RUST_FUTURE_POLL_WAKE: Int8 = 1
+
+fileprivate let uniffiContinuationHandleMap = UniffiHandleMap<UnsafeContinuation<Int8, Never>>()
+
+fileprivate func uniffiRustCallAsync<F, T>(
+ rustFutureFunc: () -> UInt64,
+ pollFunc: (UInt64, @escaping UniffiRustFutureContinuationCallback, UInt64) -> (),
+ completeFunc: (UInt64, UnsafeMutablePointer<RustCallStatus>) -> F,
+ freeFunc: (UInt64) -> (),
+ liftFunc: (F) throws -> T,
+ errorHandler: ((RustBuffer) throws -> Swift.Error)?
+) async throws -> T {
+ // Make sure to call the ensure init function since future creation doesn't have a
+ // RustCallStatus param, so doesn't use makeRustCall()
+ uniffiEnsureCyclopsSdkInitialized()
+ let rustFuture = rustFutureFunc()
+ defer {
+ freeFunc(rustFuture)
+ }
+ var pollResult: Int8;
+ repeat {
+ pollResult = await withUnsafeContinuation {
+ pollFunc(
+ rustFuture,
+ { handle, pollResult in
+ uniffiFutureContinuationCallback(handle: handle, pollResult: pollResult)
+ },
+ uniffiContinuationHandleMap.insert(obj: $0)
+ )
+ }
+ } while pollResult != UNIFFI_RUST_FUTURE_POLL_READY
+
+ return try liftFunc(makeRustCall(
+ { completeFunc(rustFuture, $0) },
+ errorHandler: errorHandler
+ ))
+}
+
+// Callback handlers for an async calls. These are invoked by Rust when the future is ready. They
+// lift the return value or error and resume the suspended function.
+fileprivate func uniffiFutureContinuationCallback(handle: UInt64, pollResult: Int8) {
+ if let continuation = try? uniffiContinuationHandleMap.remove(handle: handle) {
+ continuation.resume(returning: pollResult)
+ } else {
+ print("uniffiFutureContinuationCallback invalid handle")
+ }
+}
+private func uniffiTraitInterfaceCallAsync<T>(
+ makeCall: @escaping () async throws -> T,
+ handleSuccess: @escaping (T) -> (),
+ handleError: @escaping (Int8, RustBuffer) -> (),
+ droppedCallback: UnsafeMutablePointer<UniffiForeignFutureDroppedCallbackStruct>
+) {
+ let task = Task {
+ // Note: it's important we call either `handleSuccess` or `handleError` exactly once. Each
+ // call consumes an Arc reference, which means there should be no possibility of a double
+ // call. The following code is structured so that will will never call both `handleSuccess`
+ // and `handleError`, even in the face of weird errors.
+ //
+ // On platforms that need extra machinery to make C-ABI calls, like JNA or ctypes, it's
+ // possible that we fail to make either call. However, it doesn't seem like this is
+ // possible on Swift since swift can just make the C call directly.
+ var callResult: T
+ do {
+ callResult = try await makeCall()
+ } catch {
+ handleError(CALL_UNEXPECTED_ERROR, FfiConverterString.lower(String(describing: error)))
+ return
+ }
+ handleSuccess(callResult)
+ }
+ let handle = UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert(obj: task)
+ droppedCallback.pointee = UniffiForeignFutureDroppedCallbackStruct(
+ handle: handle,
+ free: uniffiForeignFutureDroppedCallback
+ )
+}
+
+private func uniffiTraitInterfaceCallAsyncWithError<T, E>(
+ makeCall: @escaping () async throws -> T,
+ handleSuccess: @escaping (T) -> (),
+ handleError: @escaping (Int8, RustBuffer) -> (),
+ lowerError: @escaping (E) -> RustBuffer,
+ droppedCallback: UnsafeMutablePointer<UniffiForeignFutureDroppedCallbackStruct>
+) {
+ let task = Task {
+ // See the note in uniffiTraitInterfaceCallAsync for details on `handleSuccess` and
+ // `handleError`.
+ var callResult: T
+ do {
+ callResult = try await makeCall()
+ } catch let error as E {
+ handleError(CALL_ERROR, lowerError(error))
+ return
+ } catch {
+ handleError(CALL_UNEXPECTED_ERROR, FfiConverterString.lower(String(describing: error)))
+ return
+ }
+ handleSuccess(callResult)
+ }
+ let handle = UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert(obj: task)
+ droppedCallback.pointee = UniffiForeignFutureDroppedCallbackStruct(
+ handle: handle,
+ free: uniffiForeignFutureDroppedCallback
+ )
+}
+
+// Borrow the callback handle map implementation to store foreign future handles
+// TODO: consolidate the handle-map code (https://github.com/mozilla/uniffi-rs/pull/1823)
+fileprivate let UNIFFI_FOREIGN_FUTURE_HANDLE_MAP = UniffiHandleMap<UniffiForeignFutureTask>()
+
+// Protocol for tasks that handle foreign futures.
+//
+// Defining a protocol allows all tasks to be stored in the same handle map. This can't be done
+// with the task object itself, since has generic parameters.
+fileprivate protocol UniffiForeignFutureTask {
+ func cancel()
+}
+
+extension Task: UniffiForeignFutureTask {}
+
+private func uniffiForeignFutureDroppedCallback(handle: UInt64) {
+ do {
+ let task = try UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.remove(handle: handle)
+ // Set the cancellation flag on the task. If it's still running, the code can check the
+ // cancellation flag or call `Task.checkCancellation()`. If the task has completed, this is
+ // a no-op.
+ task.cancel()
+ } catch {
+ print("uniffiForeignFutureDroppedCallback: handle missing from handlemap")
+ }
+}
+
+// For testing
+public func uniffiForeignFutureHandleCountCyclopsSdk() -> Int {
+ UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.count
+}
+
+private enum InitializationResult {
+ case ok
+ case contractVersionMismatch
+ case apiChecksumMismatch
+}
+// Use a global variable to perform the versioning checks. Swift ensures that
+// the code inside is only computed once.
+private let initializationResult: InitializationResult = {
+ // Get the bindings contract version from our ComponentInterface
+ let bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ let scaffolding_contract_version = ffi_cyclops_sdk_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version {
+ return InitializationResult.contractVersionMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim() != 51021) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() != 50650) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() != 55182) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 26952) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 53385) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool() != 31472) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool() != 9252) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool() != 44001) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() != 25465) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool() != 39705) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() != 4680) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 11556) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect() != 48439) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() != 56420) {
+ return InitializationResult.apiChecksumMismatch
+ }
+
+ uniffiCallbackInitHttpClient()
+ uniffiEnsureCyclopsSdkSchemaInitialized()
+ return InitializationResult.ok
+}()
+
+// Make the ensure init function public so that other modules which have external type references to
+// our types can call it.
+public func uniffiEnsureCyclopsSdkInitialized() {
+ switch initializationResult {
+ case .ok:
+ break
+ case .contractVersionMismatch:
+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ case .apiChecksumMismatch:
+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+// swiftlint:enable all
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
new file mode 100644
index 0000000000..8c1b2bec4c
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
@@ -0,0 +1,715 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+// The following structs are used to implement the lowest level
+// of the FFI, and thus useful to multiple uniffied crates.
+// We ensure they are declared exactly once, with a header guard, UNIFFI_SHARED_H.
+#ifdef UNIFFI_SHARED_H
+ // We also try to prevent mixing versions of shared uniffi header structs.
+ // If you add anything to the #else block, you must increment the version suffix in UNIFFI_SHARED_HEADER_V4
+ #ifndef UNIFFI_SHARED_HEADER_V4
+ #error Combining helper code from multiple versions of uniffi is not supported
+ #endif // ndef UNIFFI_SHARED_HEADER_V4
+#else
+#define UNIFFI_SHARED_H
+#define UNIFFI_SHARED_HEADER_V4
+// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️
+// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️
+
+typedef struct RustBuffer
+{
+ uint64_t capacity;
+ uint64_t len;
+ uint8_t *_Nullable data;
+} RustBuffer;
+
+typedef struct ForeignBytes
+{
+ int32_t len;
+ const uint8_t *_Nullable data;
+} ForeignBytes;
+
+// Error definitions
+typedef struct RustCallStatus {
+ int8_t code;
+ RustBuffer errorBuf;
+} RustCallStatus;
+
+// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️
+// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️
+#endif // def UNIFFI_SHARED_H
+#ifndef UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK
+#define UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK
+typedef void (*UniffiRustFutureContinuationCallback)(uint64_t, int8_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK
+typedef void (*UniffiForeignFutureDroppedCallback)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE
+#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE
+typedef void (*UniffiCallbackInterfaceFree)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_CLONE
+#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_CLONE
+typedef uint64_t (*UniffiCallbackInterfaceClone)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK_STRUCT
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK_STRUCT
+typedef struct UniffiForeignFutureDroppedCallbackStruct {
+ uint64_t handle;
+ UniffiForeignFutureDroppedCallback _Nonnull free;
+} UniffiForeignFutureDroppedCallbackStruct;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U8
+typedef struct UniffiForeignFutureResultU8 {
+ uint8_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU8;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8
+typedef void (*UniffiForeignFutureCompleteU8)(uint64_t, UniffiForeignFutureResultU8
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I8
+typedef struct UniffiForeignFutureResultI8 {
+ int8_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI8;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8
+typedef void (*UniffiForeignFutureCompleteI8)(uint64_t, UniffiForeignFutureResultI8
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U16
+typedef struct UniffiForeignFutureResultU16 {
+ uint16_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU16;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16
+typedef void (*UniffiForeignFutureCompleteU16)(uint64_t, UniffiForeignFutureResultU16
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I16
+typedef struct UniffiForeignFutureResultI16 {
+ int16_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI16;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16
+typedef void (*UniffiForeignFutureCompleteI16)(uint64_t, UniffiForeignFutureResultI16
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U32
+typedef struct UniffiForeignFutureResultU32 {
+ uint32_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32
+typedef void (*UniffiForeignFutureCompleteU32)(uint64_t, UniffiForeignFutureResultU32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I32
+typedef struct UniffiForeignFutureResultI32 {
+ int32_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32
+typedef void (*UniffiForeignFutureCompleteI32)(uint64_t, UniffiForeignFutureResultI32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U64
+typedef struct UniffiForeignFutureResultU64 {
+ uint64_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64
+typedef void (*UniffiForeignFutureCompleteU64)(uint64_t, UniffiForeignFutureResultU64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I64
+typedef struct UniffiForeignFutureResultI64 {
+ int64_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64
+typedef void (*UniffiForeignFutureCompleteI64)(uint64_t, UniffiForeignFutureResultI64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F32
+typedef struct UniffiForeignFutureResultF32 {
+ float returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultF32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32
+typedef void (*UniffiForeignFutureCompleteF32)(uint64_t, UniffiForeignFutureResultF32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F64
+typedef struct UniffiForeignFutureResultF64 {
+ double returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultF64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64
+typedef void (*UniffiForeignFutureCompleteF64)(uint64_t, UniffiForeignFutureResultF64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_RUST_BUFFER
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_RUST_BUFFER
+typedef struct UniffiForeignFutureResultRustBuffer {
+ RustBuffer returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultRustBuffer;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER
+typedef void (*UniffiForeignFutureCompleteRustBuffer)(uint64_t, UniffiForeignFutureResultRustBuffer
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_VOID
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_VOID
+typedef struct UniffiForeignFutureResultVoid {
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultVoid;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID
+typedef void (*UniffiForeignFutureCompleteVoid)(uint64_t, UniffiForeignFutureResultVoid
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_HTTP_CLIENT_METHOD0
+#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_HTTP_CLIENT_METHOD0
+typedef void (*UniffiCallbackInterfaceHttpClientMethod0)(uint64_t, RustBuffer, UniffiForeignFutureCompleteRustBuffer _Nonnull, uint64_t, UniffiForeignFutureDroppedCallbackStruct* _Nonnull
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_V_TABLE_CALLBACK_INTERFACE_HTTP_CLIENT
+#define UNIFFI_FFIDEF_V_TABLE_CALLBACK_INTERFACE_HTTP_CLIENT
+typedef struct UniffiVTableCallbackInterfaceHttpClient {
+ UniffiCallbackInterfaceFree _Nonnull uniffiFree;
+ UniffiCallbackInterfaceClone _Nonnull uniffiClone;
+ UniffiCallbackInterfaceHttpClientMethod0 _Nonnull execute;
+} UniffiVTableCallbackInterfaceHttpClient;
+
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_CYCLOPSCLIENT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_CYCLOPSCLIENT
+uint64_t uniffi_cyclops_sdk_fn_clone_cyclopsclient(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_CYCLOPSCLIENT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_CYCLOPSCLIENT
+void uniffi_cyclops_sdk_fn_free_cyclopsclient(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CONSTRUCTOR_CYCLOPSCLIENT_CONNECT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CONSTRUCTOR_CYCLOPSCLIENT_CONNECT
+uint64_t uniffi_cyclops_sdk_fn_constructor_cyclopsclient_connect(RustBuffer configuration, uint64_t http_client, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_CLAIM
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(uint64_t ptr, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_CLAIM
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(uint64_t ptr, RustBuffer claim
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_GET_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_GET_CLAIM
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(uint64_t ptr, RustBuffer claim
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_CLAIMS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_CLAIMS
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uint64_t ptr, RustBuffer namespace
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, RustBuffer claim
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uint64_t ptr, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_POOL
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(uint64_t ptr, RustBuffer pool
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_GET_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_GET_POOL
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(uint64_t ptr, RustBuffer pool
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_POOLS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_POOLS
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(uint64_t ptr, RustBuffer namespace
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPDATE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPDATE_POOL
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(uint64_t ptr, RustBuffer pool
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_SERVICE_REQUEST
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_SERVICE_REQUEST
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(uint64_t ptr, RustBuffer sandbox, RustBuffer service, RustBuffer path, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_HTTPCLIENT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_HTTPCLIENT
+uint64_t uniffi_cyclops_sdk_fn_clone_httpclient(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_HTTPCLIENT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_HTTPCLIENT
+void uniffi_cyclops_sdk_fn_free_httpclient(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_INIT_CALLBACK_VTABLE_HTTPCLIENT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_INIT_CALLBACK_VTABLE_HTTPCLIENT
+void uniffi_cyclops_sdk_fn_init_callback_vtable_httpclient(const UniffiVTableCallbackInterfaceHttpClient* _Nonnull vtable
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPCLIENT_EXECUTE
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_HTTPCLIENT_EXECUTE
+uint64_t uniffi_cyclops_sdk_fn_method_httpclient_execute(uint64_t ptr, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_CYCLOPSCREDENTIALS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_CYCLOPSCREDENTIALS
+uint64_t uniffi_cyclops_sdk_fn_clone_cyclopscredentials(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_CYCLOPSCREDENTIALS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_FREE_CYCLOPSCREDENTIALS
+void uniffi_cyclops_sdk_fn_free_cyclopscredentials(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CONSTRUCTOR_CYCLOPSCREDENTIALS_NEW
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CONSTRUCTOR_CYCLOPSCREDENTIALS_NEW
+uint64_t uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new(RustBuffer client_id, RustBuffer client_secret, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_ALLOC
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_ALLOC
+RustBuffer ffi_cyclops_sdk_rustbuffer_alloc(uint64_t size, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_FROM_BYTES
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_FROM_BYTES
+RustBuffer ffi_cyclops_sdk_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_FREE
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_FREE
+void ffi_cyclops_sdk_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_RESERVE
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUSTBUFFER_RESERVE
+RustBuffer ffi_cyclops_sdk_rustbuffer_reserve(RustBuffer buf, uint64_t additional, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U8
+void ffi_cyclops_sdk_rust_future_poll_u8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U8
+void ffi_cyclops_sdk_rust_future_cancel_u8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U8
+void ffi_cyclops_sdk_rust_future_free_u8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U8
+uint8_t ffi_cyclops_sdk_rust_future_complete_u8(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I8
+void ffi_cyclops_sdk_rust_future_poll_i8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I8
+void ffi_cyclops_sdk_rust_future_cancel_i8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I8
+void ffi_cyclops_sdk_rust_future_free_i8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I8
+int8_t ffi_cyclops_sdk_rust_future_complete_i8(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U16
+void ffi_cyclops_sdk_rust_future_poll_u16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U16
+void ffi_cyclops_sdk_rust_future_cancel_u16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U16
+void ffi_cyclops_sdk_rust_future_free_u16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U16
+uint16_t ffi_cyclops_sdk_rust_future_complete_u16(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I16
+void ffi_cyclops_sdk_rust_future_poll_i16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I16
+void ffi_cyclops_sdk_rust_future_cancel_i16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I16
+void ffi_cyclops_sdk_rust_future_free_i16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I16
+int16_t ffi_cyclops_sdk_rust_future_complete_i16(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U32
+void ffi_cyclops_sdk_rust_future_poll_u32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U32
+void ffi_cyclops_sdk_rust_future_cancel_u32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U32
+void ffi_cyclops_sdk_rust_future_free_u32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U32
+uint32_t ffi_cyclops_sdk_rust_future_complete_u32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I32
+void ffi_cyclops_sdk_rust_future_poll_i32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I32
+void ffi_cyclops_sdk_rust_future_cancel_i32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I32
+void ffi_cyclops_sdk_rust_future_free_i32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I32
+int32_t ffi_cyclops_sdk_rust_future_complete_i32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_U64
+void ffi_cyclops_sdk_rust_future_poll_u64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_U64
+void ffi_cyclops_sdk_rust_future_cancel_u64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_U64
+void ffi_cyclops_sdk_rust_future_free_u64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_U64
+uint64_t ffi_cyclops_sdk_rust_future_complete_u64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_I64
+void ffi_cyclops_sdk_rust_future_poll_i64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_I64
+void ffi_cyclops_sdk_rust_future_cancel_i64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_I64
+void ffi_cyclops_sdk_rust_future_free_i64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_I64
+int64_t ffi_cyclops_sdk_rust_future_complete_i64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_F32
+void ffi_cyclops_sdk_rust_future_poll_f32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_F32
+void ffi_cyclops_sdk_rust_future_cancel_f32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_F32
+void ffi_cyclops_sdk_rust_future_free_f32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_F32
+float ffi_cyclops_sdk_rust_future_complete_f32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_F64
+void ffi_cyclops_sdk_rust_future_poll_f64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_F64
+void ffi_cyclops_sdk_rust_future_cancel_f64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_F64
+void ffi_cyclops_sdk_rust_future_free_f64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_F64
+double ffi_cyclops_sdk_rust_future_complete_f64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_RUST_BUFFER
+void ffi_cyclops_sdk_rust_future_poll_rust_buffer(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_RUST_BUFFER
+void ffi_cyclops_sdk_rust_future_cancel_rust_buffer(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_RUST_BUFFER
+void ffi_cyclops_sdk_rust_future_free_rust_buffer(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_RUST_BUFFER
+RustBuffer ffi_cyclops_sdk_rust_future_complete_rust_buffer(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_POLL_VOID
+void ffi_cyclops_sdk_rust_future_poll_void(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_CANCEL_VOID
+void ffi_cyclops_sdk_rust_future_cancel_void(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_FREE_VOID
+void ffi_cyclops_sdk_rust_future_free_void(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_RUST_FUTURE_COMPLETE_VOID
+void ffi_cyclops_sdk_rust_future_complete_void(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_CLAIM
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_CLAIM
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_GET_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_GET_CLAIM
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_CLAIMS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_CLAIMS
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_POOL
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_POOL
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_GET_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_GET_POOL
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_POOLS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_POOLS
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPDATE_POOL
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPDATE_POOL
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_SERVICE_REQUEST
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_SERVICE_REQUEST
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPCLIENT_EXECUTE
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_HTTPCLIENT_EXECUTE
+uint16_t uniffi_cyclops_sdk_checksum_method_httpclient_execute(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_CONSTRUCTOR_CYCLOPSCLIENT_CONNECT
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_CONSTRUCTOR_CYCLOPSCLIENT_CONNECT
+uint16_t uniffi_cyclops_sdk_checksum_constructor_cyclopsclient_connect(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_CONSTRUCTOR_CYCLOPSCREDENTIALS_NEW
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_CONSTRUCTOR_CYCLOPSCREDENTIALS_NEW
+uint16_t uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_UNIFFI_CONTRACT_VERSION
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_UNIFFI_CONTRACT_VERSION
+uint32_t ffi_cyclops_sdk_uniffi_contract_version(void
+
+);
+#endif
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.modulemap b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.modulemap
new file mode 100644
index 0000000000..a6155a0c14
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.modulemap
@@ -0,0 +1,7 @@
+module CyclopsSdkFFI {
+ header "CyclopsSdkFFI.h"
+ export *
+ use "Darwin"
+ use "_Builtin_stdbool"
+ use "_Builtin_stdint"
+}
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkSchema.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchema.swift
new file mode 100644
index 0000000000..6b35598ca5
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchema.swift
@@ -0,0 +1,2802 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+// swiftlint:disable all
+import Foundation
+
+// Depending on the consumer's build setup, the low-level FFI code
+// might be in a separate module, or it might be compiled inline into
+// this module. This is a bit of light hackery to work with both.
+#if canImport(CyclopsSdkSchemaFFI)
+import CyclopsSdkSchemaFFI
+#endif
+
+fileprivate extension RustBuffer {
+ // Allocate a new buffer, copying the contents of a `UInt8` array.
+ init(bytes: [UInt8]) {
+ let rbuf = bytes.withUnsafeBufferPointer { ptr in
+ RustBuffer.from(ptr)
+ }
+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
+ }
+
+ static func empty() -> RustBuffer {
+ RustBuffer(capacity: 0, len:0, data: nil)
+ }
+
+ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
+ try! rustCall { ffi_cyclops_sdk_schema_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
+ }
+
+ // Frees the buffer in place.
+ // The buffer must not be used after this is called.
+ func deallocate() {
+ try! rustCall { ffi_cyclops_sdk_schema_rustbuffer_free(self, $0) }
+ }
+}
+
+fileprivate extension ForeignBytes {
+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {
+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
+ }
+
+ init(rawBufferPointer: UnsafeRawBufferPointer) {
+ self.init(
+ len: Int32(rawBufferPointer.count),
+ data: rawBufferPointer.baseAddress?.assumingMemoryBound(to: UInt8.self)
+ )
+ }
+}
+
+// Converter for `&[u8]` / `[ByRef] bytes` arguments.
+//
+// Conforms to `FfiConverter` so the compiler enforces the full converter
+// method set. Only the scope-bound `lower(_:_body:)` overload is sound —
+// zero-copy byte buffers only flow foreign -> Rust, and only in argument
+// position. The four protocol-witness methods (`lift`, `lower`, `read`,
+// `write`) `fatalError` at runtime if anyone reaches them.
+//
+// The scope-bound `lower` takes a closure because the `ForeignBytes`
+// pointer is only guaranteed valid for the duration of
+// `Data.withUnsafeBytes`. Callers must run the full FFI call inside
+// the closure body.
+fileprivate enum FfiConverterByRefBytes: FfiConverter {
+ typealias SwiftType = Data
+ typealias FfiType = ForeignBytes
+
+ static func lower<R>(_ value: Data, _ body: (ForeignBytes) throws -> R) rethrows -> R {
+ return try value.withUnsafeBytes { rawBuf in
+ try body(ForeignBytes(rawBufferPointer: rawBuf))
+ }
+ }
+
+ static func lower(_ value: Data) -> ForeignBytes {
+ fatalError("ByRef bytes cannot use the plain lower: returning ForeignBytes escapes the Data.withUnsafeBytes scope. Use the scope-bound lower(_:_body:) overload instead.")
+ }
+
+ static func lift(_ value: ForeignBytes) throws -> Data {
+ fatalError("ByRef bytes cannot be lifted: zero-copy &[u8] only flows foreign->Rust")
+ }
+
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Data {
+ fatalError("ByRef bytes cannot be read from a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+ }
+
+ static func write(_ value: Data, into buf: inout [UInt8]) {
+ fatalError("ByRef bytes cannot be written to a buffer: zero-copy &[u8] is only supported in argument position, not nested in records/options/etc.")
+ }
+}
+
+// For every type used in the interface, we provide helper methods for conveniently
+// lifting and lowering that type from C-compatible data, and for reading and writing
+// values of that type in a buffer.
+
+// Helper classes/extensions that don't change.
+// Someday, this will be in a library of its own.
+
+fileprivate extension Data {
+ init(rustBuffer: RustBuffer) {
+ self.init(
+ bytesNoCopy: rustBuffer.data!,
+ count: Int(rustBuffer.len),
+ deallocator: .none
+ )
+ }
+}
+
+// Define reader functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work.
+//
+// With external types, one swift source file needs to be able to call the read
+// method on another source file's FfiConverter, but then what visibility
+// should Reader have?
+// - If Reader is fileprivate, then this means the read() must also
+// be fileprivate, which doesn't work with external types.
+// - If Reader is internal/public, we'll get compile errors since both source
+// files will try define the same type.
+//
+// Instead, the read() method and these helper functions input a tuple of data
+
+fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
+ (data: data, offset: 0)
+}
+
+// Reads an integer at the current offset, in big-endian order, and advances
+// the offset on success. Throws if reading the integer would move the
+// offset past the end of the buffer.
+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ if T.self == UInt8.self {
+ let value = reader.data[reader.offset]
+ reader.offset += 1
+ return value as! T
+ }
+ var value: T = 0
+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
+ reader.offset = range.upperBound
+ return value.bigEndian
+}
+
+// Reads an arbitrary number of bytes, to be used to read
+// raw bytes, this is useful when lifting strings
+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
+ let range = reader.offset..<(reader.offset+count)
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ var value = [UInt8](repeating: 0, count: count)
+ value.withUnsafeMutableBufferPointer({ buffer in
+ reader.data.copyBytes(to: buffer, from: range)
+ })
+ reader.offset = range.upperBound
+ return value
+}
+
+// Reads a float at the current offset.
+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return Float(bitPattern: try readInt(&reader))
+}
+
+// Reads a float at the current offset.
+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return Double(bitPattern: try readInt(&reader))
+}
+
+// Indicates if the offset has reached the end of the buffer.
+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
+ return reader.offset < reader.data.count
+}
+
+// Define writer functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work. See the above discussion on Readers for details.
+
+fileprivate func createWriter() -> [UInt8] {
+ return []
+}
+
+fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
+ writer.append(contentsOf: byteArr)
+}
+
+// Writes an integer in big-endian order.
+//
+// Warning: make sure what you are trying to write
+// is in the correct type!
+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
+ var value = value.bigEndian
+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
+}
+
+fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
+ writeInt(&writer, value.bitPattern)
+}
+
+fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
+ writeInt(&writer, value.bitPattern)
+}
+
+// Protocol for types that transfer other types across the FFI. This is
+// analogous to the Rust trait of the same name.
+fileprivate protocol FfiConverter {
+ associatedtype FfiType
+ associatedtype SwiftType
+
+ static func lift(_ value: FfiType) throws -> SwiftType
+ static func lower(_ value: SwiftType) -> FfiType
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
+ static func write(_ value: SwiftType, into buf: inout [UInt8])
+}
+
+// Types conforming to `Primitive` pass themselves directly over the FFI.
+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
+
+extension FfiConverterPrimitive {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ value: FfiType) throws -> SwiftType {
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> FfiType {
+ return value
+ }
+}
+
+// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
+// Used for complex types where it's hard to write a custom lift/lower.
+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
+
+extension FfiConverterRustBuffer {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {
+ var reader = createReader(data: Data(rustBuffer: buf))
+ let value = try read(from: &reader)
+ if hasRemaining(reader) {
+ throw UniffiInternalError.incompleteData
+ }
+ buf.deallocate()
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> RustBuffer {
+ var writer = createWriter()
+ write(value, into: &writer)
+ return RustBuffer(bytes: writer)
+ }
+}
+// An error type for FFI errors. These errors occur at the UniFFI level, not
+// the library level.
+fileprivate enum UniffiInternalError: LocalizedError {
+ case bufferOverflow
+ case incompleteData
+ case unexpectedOptionalTag
+ case unexpectedEnumCase
+ case unexpectedNullPointer
+ case unexpectedRustCallStatusCode
+ case unexpectedRustCallError
+ case unexpectedStaleHandle
+ case rustPanic(_ message: String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
+ case .incompleteData: return "The buffer still has data after lifting its containing value"
+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
+ case .unexpectedNullPointer: return "Raw pointer value was null"
+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
+ case let .rustPanic(message): return message
+ }
+ }
+}
+
+fileprivate extension NSLock {
+ func withLock<T>(f: () throws -> T) rethrows -> T {
+ self.lock()
+ defer { self.unlock() }
+ return try f()
+ }
+}
+
+fileprivate let CALL_SUCCESS: Int8 = 0
+fileprivate let CALL_ERROR: Int8 = 1
+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
+fileprivate let CALL_CANCELLED: Int8 = 3
+
+fileprivate extension RustCallStatus {
+ init() {
+ self.init(
+ code: CALL_SUCCESS,
+ errorBuf: RustBuffer.init(
+ capacity: 0,
+ len: 0,
+ data: nil
+ )
+ )
+ }
+}
+
+private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ let neverThrow: ((RustBuffer) throws -> Never)? = nil
+ return try makeRustCall(callback, errorHandler: neverThrow)
+}
+
+private func rustCallWithError<T, E: Swift.Error>(
+ _ errorHandler: @escaping (RustBuffer) throws -> E,
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ try makeRustCall(callback, errorHandler: errorHandler)
+}
+
+private func makeRustCall<T, E: Swift.Error>(
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws -> T {
+ uniffiEnsureCyclopsSdkSchemaInitialized()
+ var callStatus = RustCallStatus.init()
+ let returnedVal = callback(&callStatus)
+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
+ return returnedVal
+}
+
+private func uniffiCheckCallStatus<E: Swift.Error>(
+ callStatus: RustCallStatus,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws {
+ switch callStatus.code {
+ case CALL_SUCCESS:
+ return
+
+ case CALL_ERROR:
+ if let errorHandler = errorHandler {
+ throw try errorHandler(callStatus.errorBuf)
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.unexpectedRustCallError
+ }
+
+ case CALL_UNEXPECTED_ERROR:
+ // When the rust code sees a panic, it tries to construct a RustBuffer
+ // with the message. But if that code panics, then it just sends back
+ // an empty buffer.
+ if callStatus.errorBuf.len > 0 {
+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.rustPanic("Rust panic")
+ }
+
+ case CALL_CANCELLED:
+ fatalError("Cancellation not supported yet")
+
+ default:
+ throw UniffiInternalError.unexpectedRustCallStatusCode
+ }
+}
+
+private func uniffiTraitInterfaceCall<T>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> ()
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+
+private func uniffiTraitInterfaceCallWithError<T, E>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> (),
+ lowerError: (E) -> RustBuffer
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error as E {
+ callStatus.pointee.code = CALL_ERROR
+ callStatus.pointee.errorBuf = lowerError(error)
+ } catch {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that SWIFT handles always have the lowest bit set
+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
+
+fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
+ private let lock = NSLock()
+ private var map: [UInt64: T] = [:]
+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
+
+ func insert(obj: T) -> UInt64 {
+ lock.withLock {
+ return doInsert(obj)
+ }
+ }
+
+ // Low-level insert function, this assumes `lock` is held.
+ private func doInsert(_ obj: T) -> UInt64 {
+ let handle = currentHandle
+ currentHandle += UNIFFI_HANDLEMAP_DELTA
+ map[handle] = obj
+ return handle
+ }
+
+ func get(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ func clone(handle: UInt64) throws -> UInt64 {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return doInsert(obj)
+ }
+ }
+
+ @discardableResult
+ func remove(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map.removeValue(forKey: handle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ var count: Int {
+ get {
+ map.count
+ }
+ }
+}
+
+
+// Public interface members begin here.
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt16: FfiConverterPrimitive {
+ typealias FfiType = UInt16
+ typealias SwiftType = UInt16
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt16 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt32: FfiConverterPrimitive {
+ typealias FfiType = UInt32
+ typealias SwiftType = UInt32
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt32 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt64: FfiConverterPrimitive {
+ typealias FfiType = UInt64
+ typealias SwiftType = UInt64
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterBool : FfiConverter {
+ typealias FfiType = Int8
+ typealias SwiftType = Bool
+
+ public static func lift(_ value: Int8) throws -> Bool {
+ return value != 0
+ }
+
+ public static func lower(_ value: Bool) -> Int8 {
+ return value ? 1 : 0
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: Bool, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterString: FfiConverter {
+ typealias SwiftType = String
+ typealias FfiType = RustBuffer
+
+ public static func lift(_ value: RustBuffer) throws -> String {
+ defer {
+ value.deallocate()
+ }
+ if value.data == nil {
+ return String()
+ }
+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
+ // Use Swift's native UTF-8 decoder; `String(bytes:encoding:.utf8)` goes
+ // through Foundation's NSString and silently strips a leading U+FEFF BOM.
+ // Invalid UTF-8 substitutes U+FFFD instead of trapping (unreachable
+ // given Rust's `String` invariant).
+ return String(decoding: bytes, as: UTF8.self)
+ }
+
+ public static func lower(_ value: String) -> RustBuffer {
+ return value.utf8CString.withUnsafeBufferPointer { ptr in
+ // The swift string gives us int8_t, we want uint8_t.
+ ptr.withMemoryRebound(to: UInt8.self) { ptr in
+ // The swift string gives us a trailing null byte, we don't want it.
+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
+ return RustBuffer.from(buf)
+ }
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
+ let len: Int32 = try readInt(&buf)
+ // See `lift` above for why we avoid Foundation's NSString-backed decoder here.
+ return String(decoding: try readBytes(&buf, count: Int(len)), as: UTF8.self)
+ }
+
+ public static func write(_ value: String, into buf: inout [UInt8]) {
+ let len = Int32(value.utf8.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value.utf8)
+ }
+}
+
+
+
+
+public protocol PreservedJsonProtocol: AnyObject, Sendable {
+
+ func toJson() -> String
+
+}
+open class PreservedJson: PreservedJsonProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_cyclops_sdk_schema_fn_clone_preservedjson(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_cyclops_sdk_schema_fn_free_preservedjson(handle, $0) }
+ }
+
+
+public static func fromJson(value: String)throws -> PreservedJson {
+ return try FfiConverterTypePreservedJson_lift(try rustCallWithError(FfiConverterTypeJsonValueError_lift) {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json(
+ FfiConverterString.lower(value),uniffiCallStatus
+ )
+})
+}
+
+
+
+open func toJson() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json(
+ self.uniffiCloneHandle(),uniffiCallStatus
+ )
+})
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePreservedJson: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = PreservedJson
+
+ public static func lift(_ handle: UInt64) throws -> PreservedJson {
+ return PreservedJson(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: PreservedJson) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PreservedJson {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: PreservedJson, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePreservedJson_lift(_ handle: UInt64) throws -> PreservedJson {
+ return try FfiConverterTypePreservedJson.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePreservedJson_lower(_ value: PreservedJson) -> UInt64 {
+ return FfiConverterTypePreservedJson.lower(value)
+}
+
+
+
+
+public struct ClaimLifecycle: Equatable, Hashable {
+ public var shutdownTime: String?
+ public var shutdownPolicy: String?
+ public var autoRenew: Bool?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(shutdownTime: String?, shutdownPolicy: String?, autoRenew: Bool?) {
+ self.shutdownTime = shutdownTime
+ self.shutdownPolicy = shutdownPolicy
+ self.autoRenew = autoRenew
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClaimLifecycle: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClaimLifecycle: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClaimLifecycle {
+ return
+ try ClaimLifecycle(
+ shutdownTime: FfiConverterOptionString.read(from: &buf),
+ shutdownPolicy: FfiConverterOptionString.read(from: &buf),
+ autoRenew: FfiConverterOptionBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClaimLifecycle, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.shutdownTime, into: &buf)
+ FfiConverterOptionString.write(value.shutdownPolicy, into: &buf)
+ FfiConverterOptionBool.write(value.autoRenew, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaimLifecycle_lift(_ buf: RustBuffer) throws -> ClaimLifecycle {
+ return try FfiConverterTypeClaimLifecycle.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaimLifecycle_lower(_ value: ClaimLifecycle) -> RustBuffer {
+ return FfiConverterTypeClaimLifecycle.lower(value)
+}
+
+
+public struct ClaimSpec: Equatable, Hashable {
+ public var sandboxTemplateRef: SandboxTemplateRef
+ public var warmpool: String?
+ public var bindDeadline: UInt32?
+ public var lifecycle: ClaimLifecycle?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(sandboxTemplateRef: SandboxTemplateRef, warmpool: String?, bindDeadline: UInt32?, lifecycle: ClaimLifecycle?) {
+ self.sandboxTemplateRef = sandboxTemplateRef
+ self.warmpool = warmpool
+ self.bindDeadline = bindDeadline
+ self.lifecycle = lifecycle
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClaimSpec: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClaimSpec: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClaimSpec {
+ return
+ try ClaimSpec(
+ sandboxTemplateRef: FfiConverterTypeSandboxTemplateRef.read(from: &buf),
+ warmpool: FfiConverterOptionString.read(from: &buf),
+ bindDeadline: FfiConverterOptionUInt32.read(from: &buf),
+ lifecycle: FfiConverterOptionTypeClaimLifecycle.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClaimSpec, into buf: inout [UInt8]) {
+ FfiConverterTypeSandboxTemplateRef.write(value.sandboxTemplateRef, into: &buf)
+ FfiConverterOptionString.write(value.warmpool, into: &buf)
+ FfiConverterOptionUInt32.write(value.bindDeadline, into: &buf)
+ FfiConverterOptionTypeClaimLifecycle.write(value.lifecycle, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaimSpec_lift(_ buf: RustBuffer) throws -> ClaimSpec {
+ return try FfiConverterTypeClaimSpec.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClaimSpec_lower(_ value: ClaimSpec) -> RustBuffer {
+ return FfiConverterTypeClaimSpec.lower(value)
+}
+
+
+public struct OsGymSandboxClaimCondition: Equatable, Hashable {
+ public var type: String?
+ public var status: String?
+ public var reason: String?
+ public var message: String?
+ public var lastTransitionTime: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(type: String?, status: String?, reason: String?, message: String?, lastTransitionTime: String?) {
+ self.type = type
+ self.status = status
+ self.reason = reason
+ self.message = message
+ self.lastTransitionTime = lastTransitionTime
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxClaimCondition: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxClaimCondition {
+ return
+ try OsGymSandboxClaimCondition(
+ type: FfiConverterOptionString.read(from: &buf),
+ status: FfiConverterOptionString.read(from: &buf),
+ reason: FfiConverterOptionString.read(from: &buf),
+ message: FfiConverterOptionString.read(from: &buf),
+ lastTransitionTime: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxClaimCondition, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.type, into: &buf)
+ FfiConverterOptionString.write(value.status, into: &buf)
+ FfiConverterOptionString.write(value.reason, into: &buf)
+ FfiConverterOptionString.write(value.message, into: &buf)
+ FfiConverterOptionString.write(value.lastTransitionTime, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimCondition_lift(_ buf: RustBuffer) throws -> OsGymSandboxClaimCondition {
+ return try FfiConverterTypeOSGymSandboxClaimCondition.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimCondition_lower(_ value: OsGymSandboxClaimCondition) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxClaimCondition.lower(value)
+}
+
+
+public struct OsGymSandboxClaimSandbox: Equatable, Hashable {
+ public var name: String?
+ public var service: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String?, service: String?) {
+ self.name = name
+ self.service = service
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxClaimSandbox: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxClaimSandbox: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxClaimSandbox {
+ return
+ try OsGymSandboxClaimSandbox(
+ name: FfiConverterOptionString.read(from: &buf),
+ service: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxClaimSandbox, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.name, into: &buf)
+ FfiConverterOptionString.write(value.service, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimSandbox_lift(_ buf: RustBuffer) throws -> OsGymSandboxClaimSandbox {
+ return try FfiConverterTypeOSGymSandboxClaimSandbox.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimSandbox_lower(_ value: OsGymSandboxClaimSandbox) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxClaimSandbox.lower(value)
+}
+
+
+public struct OsGymSandboxClaimStatus: Equatable, Hashable {
+ public var phase: String?
+ public var conditions: [OsGymSandboxClaimCondition]?
+ public var sandbox: OsGymSandboxClaimSandbox?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(phase: String?, conditions: [OsGymSandboxClaimCondition]?, sandbox: OsGymSandboxClaimSandbox?) {
+ self.phase = phase
+ self.conditions = conditions
+ self.sandbox = sandbox
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxClaimStatus: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxClaimStatus: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxClaimStatus {
+ return
+ try OsGymSandboxClaimStatus(
+ phase: FfiConverterOptionString.read(from: &buf),
+ conditions: FfiConverterOptionSequenceTypeOSGymSandboxClaimCondition.read(from: &buf),
+ sandbox: FfiConverterOptionTypeOSGymSandboxClaimSandbox.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxClaimStatus, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.phase, into: &buf)
+ FfiConverterOptionSequenceTypeOSGymSandboxClaimCondition.write(value.conditions, into: &buf)
+ FfiConverterOptionTypeOSGymSandboxClaimSandbox.write(value.sandbox, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimStatus_lift(_ buf: RustBuffer) throws -> OsGymSandboxClaimStatus {
+ return try FfiConverterTypeOSGymSandboxClaimStatus.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxClaimStatus_lower(_ value: OsGymSandboxClaimStatus) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxClaimStatus.lower(value)
+}
+
+
+public struct OsGymSandboxSpec {
+ public var vmTemplate: VmTemplate
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(vmTemplate: VmTemplate) {
+ self.vmTemplate = vmTemplate
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxSpec: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxSpec: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxSpec {
+ return
+ try OsGymSandboxSpec(
+ vmTemplate: FfiConverterTypeVmTemplate.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxSpec, into buf: inout [UInt8]) {
+ FfiConverterTypeVmTemplate.write(value.vmTemplate, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxSpec_lift(_ buf: RustBuffer) throws -> OsGymSandboxSpec {
+ return try FfiConverterTypeOSGymSandboxSpec.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxSpec_lower(_ value: OsGymSandboxSpec) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxSpec.lower(value)
+}
+
+
+public struct OsGymSandboxStatus: Equatable, Hashable {
+ public var phase: String?
+ public var runtime: String?
+ public var ready: Bool?
+ public var vmName: String?
+ public var service: String?
+ public var message: String?
+ public var resetIssuedAt: String?
+ public var resetVmiUid: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(phase: String?, runtime: String?, ready: Bool?, vmName: String?, service: String?, message: String?, resetIssuedAt: String?, resetVmiUid: String?) {
+ self.phase = phase
+ self.runtime = runtime
+ self.ready = ready
+ self.vmName = vmName
+ self.service = service
+ self.message = message
+ self.resetIssuedAt = resetIssuedAt
+ self.resetVmiUid = resetVmiUid
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxStatus: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxStatus: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxStatus {
+ return
+ try OsGymSandboxStatus(
+ phase: FfiConverterOptionString.read(from: &buf),
+ runtime: FfiConverterOptionString.read(from: &buf),
+ ready: FfiConverterOptionBool.read(from: &buf),
+ vmName: FfiConverterOptionString.read(from: &buf),
+ service: FfiConverterOptionString.read(from: &buf),
+ message: FfiConverterOptionString.read(from: &buf),
+ resetIssuedAt: FfiConverterOptionString.read(from: &buf),
+ resetVmiUid: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxStatus, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.phase, into: &buf)
+ FfiConverterOptionString.write(value.runtime, into: &buf)
+ FfiConverterOptionBool.write(value.ready, into: &buf)
+ FfiConverterOptionString.write(value.vmName, into: &buf)
+ FfiConverterOptionString.write(value.service, into: &buf)
+ FfiConverterOptionString.write(value.message, into: &buf)
+ FfiConverterOptionString.write(value.resetIssuedAt, into: &buf)
+ FfiConverterOptionString.write(value.resetVmiUid, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxStatus_lift(_ buf: RustBuffer) throws -> OsGymSandboxStatus {
+ return try FfiConverterTypeOSGymSandboxStatus.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxStatus_lower(_ value: OsGymSandboxStatus) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxStatus.lower(value)
+}
+
+
+public struct OsGymSandboxTemplateSpec {
+ public var vmTemplate: VmTemplate
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(vmTemplate: VmTemplate) {
+ self.vmTemplate = vmTemplate
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxTemplateSpec: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxTemplateSpec: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxTemplateSpec {
+ return
+ try OsGymSandboxTemplateSpec(
+ vmTemplate: FfiConverterTypeVmTemplate.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxTemplateSpec, into buf: inout [UInt8]) {
+ FfiConverterTypeVmTemplate.write(value.vmTemplate, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxTemplateSpec_lift(_ buf: RustBuffer) throws -> OsGymSandboxTemplateSpec {
+ return try FfiConverterTypeOSGymSandboxTemplateSpec.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxTemplateSpec_lower(_ value: OsGymSandboxTemplateSpec) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxTemplateSpec.lower(value)
+}
+
+
+public struct OsGymSandboxWarmPoolSpec: Equatable, Hashable {
+ public var replicas: UInt32
+ public var sandboxTemplateRef: SandboxTemplateRef
+ public var autoscaling: WarmPoolAutoscaling?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(replicas: UInt32, sandboxTemplateRef: SandboxTemplateRef, autoscaling: WarmPoolAutoscaling?) {
+ self.replicas = replicas
+ self.sandboxTemplateRef = sandboxTemplateRef
+ self.autoscaling = autoscaling
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxWarmPoolSpec: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxWarmPoolSpec: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxWarmPoolSpec {
+ return
+ try OsGymSandboxWarmPoolSpec(
+ replicas: FfiConverterUInt32.read(from: &buf),
+ sandboxTemplateRef: FfiConverterTypeSandboxTemplateRef.read(from: &buf),
+ autoscaling: FfiConverterOptionTypeWarmPoolAutoscaling.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxWarmPoolSpec, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.replicas, into: &buf)
+ FfiConverterTypeSandboxTemplateRef.write(value.sandboxTemplateRef, into: &buf)
+ FfiConverterOptionTypeWarmPoolAutoscaling.write(value.autoscaling, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxWarmPoolSpec_lift(_ buf: RustBuffer) throws -> OsGymSandboxWarmPoolSpec {
+ return try FfiConverterTypeOSGymSandboxWarmPoolSpec.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxWarmPoolSpec_lower(_ value: OsGymSandboxWarmPoolSpec) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxWarmPoolSpec.lower(value)
+}
+
+
+public struct OsGymSandboxWarmPoolStatus: Equatable, Hashable {
+ public var replicas: UInt32?
+ public var readyReplicas: UInt32?
+ public var selector: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(replicas: UInt32?, readyReplicas: UInt32?, selector: String?) {
+ self.replicas = replicas
+ self.readyReplicas = readyReplicas
+ self.selector = selector
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymSandboxWarmPoolStatus: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymSandboxWarmPoolStatus: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymSandboxWarmPoolStatus {
+ return
+ try OsGymSandboxWarmPoolStatus(
+ replicas: FfiConverterOptionUInt32.read(from: &buf),
+ readyReplicas: FfiConverterOptionUInt32.read(from: &buf),
+ selector: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymSandboxWarmPoolStatus, into buf: inout [UInt8]) {
+ FfiConverterOptionUInt32.write(value.replicas, into: &buf)
+ FfiConverterOptionUInt32.write(value.readyReplicas, into: &buf)
+ FfiConverterOptionString.write(value.selector, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxWarmPoolStatus_lift(_ buf: RustBuffer) throws -> OsGymSandboxWarmPoolStatus {
+ return try FfiConverterTypeOSGymSandboxWarmPoolStatus.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymSandboxWarmPoolStatus_lower(_ value: OsGymSandboxWarmPoolStatus) -> RustBuffer {
+ return FfiConverterTypeOSGymSandboxWarmPoolStatus.lower(value)
+}
+
+
+public struct OsGymWorkspacePoolStatus: Equatable, Hashable {
+ public var phase: String?
+ public var totalCount: UInt32?
+ public var availableCount: UInt32?
+ public var claimedCount: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(phase: String?, totalCount: UInt32?, availableCount: UInt32?, claimedCount: UInt32?) {
+ self.phase = phase
+ self.totalCount = totalCount
+ self.availableCount = availableCount
+ self.claimedCount = claimedCount
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OsGymWorkspacePoolStatus: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOSGymWorkspacePoolStatus: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OsGymWorkspacePoolStatus {
+ return
+ try OsGymWorkspacePoolStatus(
+ phase: FfiConverterOptionString.read(from: &buf),
+ totalCount: FfiConverterOptionUInt32.read(from: &buf),
+ availableCount: FfiConverterOptionUInt32.read(from: &buf),
+ claimedCount: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OsGymWorkspacePoolStatus, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.phase, into: &buf)
+ FfiConverterOptionUInt32.write(value.totalCount, into: &buf)
+ FfiConverterOptionUInt32.write(value.availableCount, into: &buf)
+ FfiConverterOptionUInt32.write(value.claimedCount, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymWorkspacePoolStatus_lift(_ buf: RustBuffer) throws -> OsGymWorkspacePoolStatus {
+ return try FfiConverterTypeOSGymWorkspacePoolStatus.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOSGymWorkspacePoolStatus_lower(_ value: OsGymWorkspacePoolStatus) -> RustBuffer {
+ return FfiConverterTypeOSGymWorkspacePoolStatus.lower(value)
+}
+
+
+public struct OidcConfig: Equatable, Hashable {
+ public var credentialsSecret: String
+ public var tokenUrl: String
+ public var awsRoleArn: String?
+ public var awsRegion: String?
+ public var refreshIntervalSeconds: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(credentialsSecret: String, tokenUrl: String, awsRoleArn: String?, awsRegion: String?, refreshIntervalSeconds: UInt32?) {
+ self.credentialsSecret = credentialsSecret
+ self.tokenUrl = tokenUrl
+ self.awsRoleArn = awsRoleArn
+ self.awsRegion = awsRegion
+ self.refreshIntervalSeconds = refreshIntervalSeconds
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension OidcConfig: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeOidcConfig: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OidcConfig {
+ return
+ try OidcConfig(
+ credentialsSecret: FfiConverterString.read(from: &buf),
+ tokenUrl: FfiConverterString.read(from: &buf),
+ awsRoleArn: FfiConverterOptionString.read(from: &buf),
+ awsRegion: FfiConverterOptionString.read(from: &buf),
+ refreshIntervalSeconds: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: OidcConfig, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.credentialsSecret, into: &buf)
+ FfiConverterString.write(value.tokenUrl, into: &buf)
+ FfiConverterOptionString.write(value.awsRoleArn, into: &buf)
+ FfiConverterOptionString.write(value.awsRegion, into: &buf)
+ FfiConverterOptionUInt32.write(value.refreshIntervalSeconds, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOidcConfig_lift(_ buf: RustBuffer) throws -> OidcConfig {
+ return try FfiConverterTypeOidcConfig.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeOidcConfig_lower(_ value: OidcConfig) -> RustBuffer {
+ return FfiConverterTypeOidcConfig.lower(value)
+}
+
+
+public struct PoolSpec: Equatable, Hashable {
+ public var replicas: UInt32
+ public var template: PoolTemplate
+ public var autoscaling: WarmPoolAutoscaling?
+ public var services: [SandboxService]?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(replicas: UInt32, template: PoolTemplate, autoscaling: WarmPoolAutoscaling?, services: [SandboxService]?) {
+ self.replicas = replicas
+ self.template = template
+ self.autoscaling = autoscaling
+ self.services = services
+ }
+
+
+
+
+// The local Rust `Eq` implementation - only `eq` is used.
+public static func == (self: PoolSpec, other: PoolSpec) -> Bool {
+ return try! FfiConverterBool.lift(
+ try! rustCall() {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq(
+ FfiConverterTypePoolSpec_lower(self),
+ FfiConverterTypePoolSpec_lower(other),uniffiCallStatus
+ )
+}
+ )
+}
+// The local Rust `Hash` implementation
+public func hash(into hasher: inout Hasher) {
+ let val = try! FfiConverterUInt64.lift(
+ try! rustCall() {
+ uniffiCallStatus in
+ uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash(
+ FfiConverterTypePoolSpec_lower(self),uniffiCallStatus
+ )
+}
+ )
+ hasher.combine(val)
+}
+}
+
+#if compiler(>=6)
+extension PoolSpec: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePoolSpec: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PoolSpec {
+ return
+ try PoolSpec(
+ replicas: FfiConverterUInt32.read(from: &buf),
+ template: FfiConverterTypePoolTemplate.read(from: &buf),
+ autoscaling: FfiConverterOptionTypeWarmPoolAutoscaling.read(from: &buf),
+ services: FfiConverterOptionSequenceTypeSandboxService.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: PoolSpec, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.replicas, into: &buf)
+ FfiConverterTypePoolTemplate.write(value.template, into: &buf)
+ FfiConverterOptionTypeWarmPoolAutoscaling.write(value.autoscaling, into: &buf)
+ FfiConverterOptionSequenceTypeSandboxService.write(value.services, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePoolSpec_lift(_ buf: RustBuffer) throws -> PoolSpec {
+ return try FfiConverterTypePoolSpec.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePoolSpec_lower(_ value: PoolSpec) -> RustBuffer {
+ return FfiConverterTypePoolSpec.lower(value)
+}
+
+
+public struct PoolTemplate {
+ public var runtime: RuntimeKind?
+ public var runtimeClassName: String?
+ public var nodeSelector: [String: String]?
+ public var tolerations: [PreservedJson]?
+ public var command: [String]?
+ public var containerDiskImage: String
+ public var imagePullSecret: String?
+ public var cpuCores: UInt32?
+ public var memory: String?
+ public var firmware: Firmware?
+ public var probes: PreservedJson?
+ public var oidc: OidcConfig?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(runtime: RuntimeKind?, runtimeClassName: String?, nodeSelector: [String: String]?, tolerations: [PreservedJson]?, command: [String]?, containerDiskImage: String, imagePullSecret: String?, cpuCores: UInt32?, memory: String?, firmware: Firmware?, probes: PreservedJson?, oidc: OidcConfig?) {
+ self.runtime = runtime
+ self.runtimeClassName = runtimeClassName
+ self.nodeSelector = nodeSelector
+ self.tolerations = tolerations
+ self.command = command
+ self.containerDiskImage = containerDiskImage
+ self.imagePullSecret = imagePullSecret
+ self.cpuCores = cpuCores
+ self.memory = memory
+ self.firmware = firmware
+ self.probes = probes
+ self.oidc = oidc
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension PoolTemplate: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePoolTemplate: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PoolTemplate {
+ return
+ try PoolTemplate(
+ runtime: FfiConverterOptionTypeRuntimeKind.read(from: &buf),
+ runtimeClassName: FfiConverterOptionString.read(from: &buf),
+ nodeSelector: FfiConverterOptionDictionaryStringString.read(from: &buf),
+ tolerations: FfiConverterOptionSequenceTypePreservedJson.read(from: &buf),
+ command: FfiConverterOptionSequenceString.read(from: &buf),
+ containerDiskImage: FfiConverterString.read(from: &buf),
+ imagePullSecret: FfiConverterOptionString.read(from: &buf),
+ cpuCores: FfiConverterOptionUInt32.read(from: &buf),
+ memory: FfiConverterOptionString.read(from: &buf),
+ firmware: FfiConverterOptionTypeFirmware.read(from: &buf),
+ probes: FfiConverterOptionTypePreservedJson.read(from: &buf),
+ oidc: FfiConverterOptionTypeOidcConfig.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: PoolTemplate, into buf: inout [UInt8]) {
+ FfiConverterOptionTypeRuntimeKind.write(value.runtime, into: &buf)
+ FfiConverterOptionString.write(value.runtimeClassName, into: &buf)
+ FfiConverterOptionDictionaryStringString.write(value.nodeSelector, into: &buf)
+ FfiConverterOptionSequenceTypePreservedJson.write(value.tolerations, into: &buf)
+ FfiConverterOptionSequenceString.write(value.command, into: &buf)
+ FfiConverterString.write(value.containerDiskImage, into: &buf)
+ FfiConverterOptionString.write(value.imagePullSecret, into: &buf)
+ FfiConverterOptionUInt32.write(value.cpuCores, into: &buf)
+ FfiConverterOptionString.write(value.memory, into: &buf)
+ FfiConverterOptionTypeFirmware.write(value.firmware, into: &buf)
+ FfiConverterOptionTypePreservedJson.write(value.probes, into: &buf)
+ FfiConverterOptionTypeOidcConfig.write(value.oidc, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePoolTemplate_lift(_ buf: RustBuffer) throws -> PoolTemplate {
+ return try FfiConverterTypePoolTemplate.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePoolTemplate_lower(_ value: PoolTemplate) -> RustBuffer {
+ return FfiConverterTypePoolTemplate.lower(value)
+}
+
+
+public struct SandboxService: Equatable, Hashable {
+ public var name: String
+ public var targetPort: UInt16
+ public var `protocol`: ServiceProtocol?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, targetPort: UInt16, `protocol`: ServiceProtocol?) {
+ self.name = name
+ self.targetPort = targetPort
+ self.`protocol` = `protocol`
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SandboxService: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSandboxService: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SandboxService {
+ return
+ try SandboxService(
+ name: FfiConverterString.read(from: &buf),
+ targetPort: FfiConverterUInt16.read(from: &buf),
+ protocol: FfiConverterOptionTypeServiceProtocol.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SandboxService, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterUInt16.write(value.targetPort, into: &buf)
+ FfiConverterOptionTypeServiceProtocol.write(value.`protocol`, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandboxService_lift(_ buf: RustBuffer) throws -> SandboxService {
+ return try FfiConverterTypeSandboxService.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandboxService_lower(_ value: SandboxService) -> RustBuffer {
+ return FfiConverterTypeSandboxService.lower(value)
+}
+
+
+public struct SandboxTemplateRef: Equatable, Hashable {
+ public var name: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String) {
+ self.name = name
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SandboxTemplateRef: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSandboxTemplateRef: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SandboxTemplateRef {
+ return
+ try SandboxTemplateRef(
+ name: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SandboxTemplateRef, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandboxTemplateRef_lift(_ buf: RustBuffer) throws -> SandboxTemplateRef {
+ return try FfiConverterTypeSandboxTemplateRef.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSandboxTemplateRef_lower(_ value: SandboxTemplateRef) -> RustBuffer {
+ return FfiConverterTypeSandboxTemplateRef.lower(value)
+}
+
+
+public struct VmTemplate {
+ public var containerDiskImage: String
+ public var command: [String]?
+ public var runtime: RuntimeKind?
+ public var runtimeClassName: String?
+ public var nodeSelector: [String: String]?
+ public var tolerations: [PreservedJson]?
+ public var imagePullPolicy: ImagePullPolicy?
+ public var imagePullSecret: String?
+ public var cpuCores: UInt32?
+ public var memory: String?
+ public var firmware: Firmware?
+ public var probes: PreservedJson?
+ public var services: [SandboxService]?
+ public var oidc: OidcConfig?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(containerDiskImage: String, command: [String]?, runtime: RuntimeKind?, runtimeClassName: String?, nodeSelector: [String: String]?, tolerations: [PreservedJson]?, imagePullPolicy: ImagePullPolicy?, imagePullSecret: String?, cpuCores: UInt32?, memory: String?, firmware: Firmware?, probes: PreservedJson?, services: [SandboxService]?, oidc: OidcConfig?) {
+ self.containerDiskImage = containerDiskImage
+ self.command = command
+ self.runtime = runtime
+ self.runtimeClassName = runtimeClassName
+ self.nodeSelector = nodeSelector
+ self.tolerations = tolerations
+ self.imagePullPolicy = imagePullPolicy
+ self.imagePullSecret = imagePullSecret
+ self.cpuCores = cpuCores
+ self.memory = memory
+ self.firmware = firmware
+ self.probes = probes
+ self.services = services
+ self.oidc = oidc
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension VmTemplate: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeVmTemplate: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> VmTemplate {
+ return
+ try VmTemplate(
+ containerDiskImage: FfiConverterString.read(from: &buf),
+ command: FfiConverterOptionSequenceString.read(from: &buf),
+ runtime: FfiConverterOptionTypeRuntimeKind.read(from: &buf),
+ runtimeClassName: FfiConverterOptionString.read(from: &buf),
+ nodeSelector: FfiConverterOptionDictionaryStringString.read(from: &buf),
+ tolerations: FfiConverterOptionSequenceTypePreservedJson.read(from: &buf),
+ imagePullPolicy: FfiConverterOptionTypeImagePullPolicy.read(from: &buf),
+ imagePullSecret: FfiConverterOptionString.read(from: &buf),
+ cpuCores: FfiConverterOptionUInt32.read(from: &buf),
+ memory: FfiConverterOptionString.read(from: &buf),
+ firmware: FfiConverterOptionTypeFirmware.read(from: &buf),
+ probes: FfiConverterOptionTypePreservedJson.read(from: &buf),
+ services: FfiConverterOptionSequenceTypeSandboxService.read(from: &buf),
+ oidc: FfiConverterOptionTypeOidcConfig.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: VmTemplate, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.containerDiskImage, into: &buf)
+ FfiConverterOptionSequenceString.write(value.command, into: &buf)
+ FfiConverterOptionTypeRuntimeKind.write(value.runtime, into: &buf)
+ FfiConverterOptionString.write(value.runtimeClassName, into: &buf)
+ FfiConverterOptionDictionaryStringString.write(value.nodeSelector, into: &buf)
+ FfiConverterOptionSequenceTypePreservedJson.write(value.tolerations, into: &buf)
+ FfiConverterOptionTypeImagePullPolicy.write(value.imagePullPolicy, into: &buf)
+ FfiConverterOptionString.write(value.imagePullSecret, into: &buf)
+ FfiConverterOptionUInt32.write(value.cpuCores, into: &buf)
+ FfiConverterOptionString.write(value.memory, into: &buf)
+ FfiConverterOptionTypeFirmware.write(value.firmware, into: &buf)
+ FfiConverterOptionTypePreservedJson.write(value.probes, into: &buf)
+ FfiConverterOptionSequenceTypeSandboxService.write(value.services, into: &buf)
+ FfiConverterOptionTypeOidcConfig.write(value.oidc, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeVmTemplate_lift(_ buf: RustBuffer) throws -> VmTemplate {
+ return try FfiConverterTypeVmTemplate.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeVmTemplate_lower(_ value: VmTemplate) -> RustBuffer {
+ return FfiConverterTypeVmTemplate.lower(value)
+}
+
+
+public struct WarmPoolAutoscaling: Equatable, Hashable {
+ public var minPoolSize: UInt32?
+ public var initialPoolSize: UInt32?
+ public var maxPoolSize: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(minPoolSize: UInt32?, initialPoolSize: UInt32?, maxPoolSize: UInt32?) {
+ self.minPoolSize = minPoolSize
+ self.initialPoolSize = initialPoolSize
+ self.maxPoolSize = maxPoolSize
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension WarmPoolAutoscaling: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeWarmPoolAutoscaling: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> WarmPoolAutoscaling {
+ return
+ try WarmPoolAutoscaling(
+ minPoolSize: FfiConverterOptionUInt32.read(from: &buf),
+ initialPoolSize: FfiConverterOptionUInt32.read(from: &buf),
+ maxPoolSize: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: WarmPoolAutoscaling, into buf: inout [UInt8]) {
+ FfiConverterOptionUInt32.write(value.minPoolSize, into: &buf)
+ FfiConverterOptionUInt32.write(value.initialPoolSize, into: &buf)
+ FfiConverterOptionUInt32.write(value.maxPoolSize, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeWarmPoolAutoscaling_lift(_ buf: RustBuffer) throws -> WarmPoolAutoscaling {
+ return try FfiConverterTypeWarmPoolAutoscaling.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeWarmPoolAutoscaling_lower(_ value: WarmPoolAutoscaling) -> RustBuffer {
+ return FfiConverterTypeWarmPoolAutoscaling.lower(value)
+}
+
+
+
+public enum Firmware: Equatable, Hashable {
+
+ case bios
+ case efi
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Firmware: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeFirmware: FfiConverterRustBuffer {
+ typealias SwiftType = Firmware
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Firmware {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .bios
+
+ case 2: return .efi
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: Firmware, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .bios:
+ writeInt(&buf, Int32(1))
+
+
+ case .efi:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFirmware_lift(_ buf: RustBuffer) throws -> Firmware {
+ return try FfiConverterTypeFirmware.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFirmware_lower(_ value: Firmware) -> RustBuffer {
+ return FfiConverterTypeFirmware.lower(value)
+}
+
+
+
+
+public enum ImagePullPolicy: Equatable, Hashable {
+
+ case always
+ case ifNotPresent
+ case never
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ImagePullPolicy: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeImagePullPolicy: FfiConverterRustBuffer {
+ typealias SwiftType = ImagePullPolicy
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ImagePullPolicy {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .always
+
+ case 2: return .ifNotPresent
+
+ case 3: return .never
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ImagePullPolicy, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .always:
+ writeInt(&buf, Int32(1))
+
+
+ case .ifNotPresent:
+ writeInt(&buf, Int32(2))
+
+
+ case .never:
+ writeInt(&buf, Int32(3))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImagePullPolicy_lift(_ buf: RustBuffer) throws -> ImagePullPolicy {
+ return try FfiConverterTypeImagePullPolicy.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImagePullPolicy_lower(_ value: ImagePullPolicy) -> RustBuffer {
+ return FfiConverterTypeImagePullPolicy.lower(value)
+}
+
+
+
+public
+enum JsonValueError: Swift.Error, Equatable, Hashable, Foundation.LocalizedError {
+
+
+
+ case Invalid(reason: String
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension JsonValueError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeJsonValueError: FfiConverterRustBuffer {
+ typealias SwiftType = JsonValueError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> JsonValueError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Invalid(
+ reason: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: JsonValueError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Invalid(reason):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(reason, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeJsonValueError_lift(_ buf: RustBuffer) throws -> JsonValueError {
+ return try FfiConverterTypeJsonValueError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeJsonValueError_lower(_ value: JsonValueError) -> RustBuffer {
+ return FfiConverterTypeJsonValueError.lower(value)
+}
+
+
+
+public enum RuntimeKind: Equatable, Hashable {
+
+ case kubevirt
+ case macos
+ case gvisor
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension RuntimeKind: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRuntimeKind: FfiConverterRustBuffer {
+ typealias SwiftType = RuntimeKind
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RuntimeKind {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .kubevirt
+
+ case 2: return .macos
+
+ case 3: return .gvisor
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: RuntimeKind, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .kubevirt:
+ writeInt(&buf, Int32(1))
+
+
+ case .macos:
+ writeInt(&buf, Int32(2))
+
+
+ case .gvisor:
+ writeInt(&buf, Int32(3))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeKind_lift(_ buf: RustBuffer) throws -> RuntimeKind {
+ return try FfiConverterTypeRuntimeKind.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeKind_lower(_ value: RuntimeKind) -> RustBuffer {
+ return FfiConverterTypeRuntimeKind.lower(value)
+}
+
+
+
+
+public enum ServiceProtocol: Equatable, Hashable {
+
+ case tcp
+ case udp
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ServiceProtocol: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeServiceProtocol: FfiConverterRustBuffer {
+ typealias SwiftType = ServiceProtocol
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ServiceProtocol {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .tcp
+
+ case 2: return .udp
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ServiceProtocol, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .tcp:
+ writeInt(&buf, Int32(1))
+
+
+ case .udp:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeServiceProtocol_lift(_ buf: RustBuffer) throws -> ServiceProtocol {
+ return try FfiConverterTypeServiceProtocol.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeServiceProtocol_lower(_ value: ServiceProtocol) -> RustBuffer {
+ return FfiConverterTypeServiceProtocol.lower(value)
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionUInt32: FfiConverterRustBuffer {
+ typealias SwiftType = UInt32?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterUInt32.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterUInt32.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionBool: FfiConverterRustBuffer {
+ typealias SwiftType = Bool?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterBool.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterBool.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
+ typealias SwiftType = String?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypePreservedJson: FfiConverterRustBuffer {
+ typealias SwiftType = PreservedJson?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypePreservedJson.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypePreservedJson.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeClaimLifecycle: FfiConverterRustBuffer {
+ typealias SwiftType = ClaimLifecycle?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeClaimLifecycle.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeClaimLifecycle.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeOSGymSandboxClaimSandbox: FfiConverterRustBuffer {
+ typealias SwiftType = OsGymSandboxClaimSandbox?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeOSGymSandboxClaimSandbox.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeOSGymSandboxClaimSandbox.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeOidcConfig: FfiConverterRustBuffer {
+ typealias SwiftType = OidcConfig?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeOidcConfig.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeOidcConfig.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeWarmPoolAutoscaling: FfiConverterRustBuffer {
+ typealias SwiftType = WarmPoolAutoscaling?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeWarmPoolAutoscaling.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeWarmPoolAutoscaling.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeFirmware: FfiConverterRustBuffer {
+ typealias SwiftType = Firmware?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeFirmware.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeFirmware.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeImagePullPolicy: FfiConverterRustBuffer {
+ typealias SwiftType = ImagePullPolicy?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeImagePullPolicy.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeImagePullPolicy.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeRuntimeKind: FfiConverterRustBuffer {
+ typealias SwiftType = RuntimeKind?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeRuntimeKind.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeRuntimeKind.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeServiceProtocol: FfiConverterRustBuffer {
+ typealias SwiftType = ServiceProtocol?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeServiceProtocol.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeServiceProtocol.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceString: FfiConverterRustBuffer {
+ typealias SwiftType = [String]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceTypePreservedJson: FfiConverterRustBuffer {
+ typealias SwiftType = [PreservedJson]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceTypePreservedJson.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceTypePreservedJson.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer {
+ typealias SwiftType = [OsGymSandboxClaimCondition]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceTypeOSGymSandboxClaimCondition.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceTypeOSGymSandboxClaimCondition.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceTypeSandboxService: FfiConverterRustBuffer {
+ typealias SwiftType = [SandboxService]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceTypeSandboxService.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceTypeSandboxService.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionDictionaryStringString: FfiConverterRustBuffer {
+ typealias SwiftType = [String: String]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterDictionaryStringString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterDictionaryStringString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceString: FfiConverterRustBuffer {
+ typealias SwiftType = [String]
+
+ public static func write(_ value: [String], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterString.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [String]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterString.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypePreservedJson: FfiConverterRustBuffer {
+ typealias SwiftType = [PreservedJson]
+
+ public static func write(_ value: [PreservedJson], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypePreservedJson.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [PreservedJson] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [PreservedJson]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypePreservedJson.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeOSGymSandboxClaimCondition: FfiConverterRustBuffer {
+ typealias SwiftType = [OsGymSandboxClaimCondition]
+
+ public static func write(_ value: [OsGymSandboxClaimCondition], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeOSGymSandboxClaimCondition.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [OsGymSandboxClaimCondition] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [OsGymSandboxClaimCondition]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeOSGymSandboxClaimCondition.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeSandboxService: FfiConverterRustBuffer {
+ typealias SwiftType = [SandboxService]
+
+ public static func write(_ value: [SandboxService], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeSandboxService.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [SandboxService] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [SandboxService]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeSandboxService.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDictionaryStringString: FfiConverterRustBuffer {
+ public static func write(_ value: [String: String], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for (key, value) in value {
+ FfiConverterString.write(key, into: &buf)
+ FfiConverterString.write(value, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: String] {
+ let len: Int32 = try readInt(&buf)
+ var dict = [String: String]()
+ dict.reserveCapacity(Int(len))
+ for _ in 0..<len {
+ let key = try FfiConverterString.read(from: &buf)
+ let value = try FfiConverterString.read(from: &buf)
+ dict[key] = value
+ }
+ return dict
+ }
+}
+
+private enum InitializationResult {
+ case ok
+ case contractVersionMismatch
+ case apiChecksumMismatch
+}
+// Use a global variable to perform the versioning checks. Swift ensures that
+// the code inside is only computed once.
+private let initializationResult: InitializationResult = {
+ // Get the bindings contract version from our ComponentInterface
+ let bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ let scaffolding_contract_version = ffi_cyclops_sdk_schema_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version {
+ return InitializationResult.contractVersionMismatch
+ }
+ if (uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json() != 675) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json() != 56364) {
+ return InitializationResult.apiChecksumMismatch
+ }
+
+ return InitializationResult.ok
+}()
+
+// Make the ensure init function public so that other modules which have external type references to
+// our types can call it.
+public func uniffiEnsureCyclopsSdkSchemaInitialized() {
+ switch initializationResult {
+ case .ok:
+ break
+ case .contractVersionMismatch:
+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ case .apiChecksumMismatch:
+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+// swiftlint:enable all
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.h
new file mode 100644
index 0000000000..b86c185c46
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.h
@@ -0,0 +1,558 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+// The following structs are used to implement the lowest level
+// of the FFI, and thus useful to multiple uniffied crates.
+// We ensure they are declared exactly once, with a header guard, UNIFFI_SHARED_H.
+#ifdef UNIFFI_SHARED_H
+ // We also try to prevent mixing versions of shared uniffi header structs.
+ // If you add anything to the #else block, you must increment the version suffix in UNIFFI_SHARED_HEADER_V4
+ #ifndef UNIFFI_SHARED_HEADER_V4
+ #error Combining helper code from multiple versions of uniffi is not supported
+ #endif // ndef UNIFFI_SHARED_HEADER_V4
+#else
+#define UNIFFI_SHARED_H
+#define UNIFFI_SHARED_HEADER_V4
+// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️
+// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️
+
+typedef struct RustBuffer
+{
+ uint64_t capacity;
+ uint64_t len;
+ uint8_t *_Nullable data;
+} RustBuffer;
+
+typedef struct ForeignBytes
+{
+ int32_t len;
+ const uint8_t *_Nullable data;
+} ForeignBytes;
+
+// Error definitions
+typedef struct RustCallStatus {
+ int8_t code;
+ RustBuffer errorBuf;
+} RustCallStatus;
+
+// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️
+// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️
+#endif // def UNIFFI_SHARED_H
+#ifndef UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK
+#define UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK
+typedef void (*UniffiRustFutureContinuationCallback)(uint64_t, int8_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK
+typedef void (*UniffiForeignFutureDroppedCallback)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE
+#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE
+typedef void (*UniffiCallbackInterfaceFree)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_CLONE
+#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_CLONE
+typedef uint64_t (*UniffiCallbackInterfaceClone)(uint64_t
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK_STRUCT
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_DROPPED_CALLBACK_STRUCT
+typedef struct UniffiForeignFutureDroppedCallbackStruct {
+ uint64_t handle;
+ UniffiForeignFutureDroppedCallback _Nonnull free;
+} UniffiForeignFutureDroppedCallbackStruct;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U8
+typedef struct UniffiForeignFutureResultU8 {
+ uint8_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU8;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8
+typedef void (*UniffiForeignFutureCompleteU8)(uint64_t, UniffiForeignFutureResultU8
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I8
+typedef struct UniffiForeignFutureResultI8 {
+ int8_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI8;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8
+typedef void (*UniffiForeignFutureCompleteI8)(uint64_t, UniffiForeignFutureResultI8
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U16
+typedef struct UniffiForeignFutureResultU16 {
+ uint16_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU16;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16
+typedef void (*UniffiForeignFutureCompleteU16)(uint64_t, UniffiForeignFutureResultU16
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I16
+typedef struct UniffiForeignFutureResultI16 {
+ int16_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI16;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16
+typedef void (*UniffiForeignFutureCompleteI16)(uint64_t, UniffiForeignFutureResultI16
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U32
+typedef struct UniffiForeignFutureResultU32 {
+ uint32_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32
+typedef void (*UniffiForeignFutureCompleteU32)(uint64_t, UniffiForeignFutureResultU32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I32
+typedef struct UniffiForeignFutureResultI32 {
+ int32_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32
+typedef void (*UniffiForeignFutureCompleteI32)(uint64_t, UniffiForeignFutureResultI32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_U64
+typedef struct UniffiForeignFutureResultU64 {
+ uint64_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultU64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64
+typedef void (*UniffiForeignFutureCompleteU64)(uint64_t, UniffiForeignFutureResultU64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_I64
+typedef struct UniffiForeignFutureResultI64 {
+ int64_t returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultI64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64
+typedef void (*UniffiForeignFutureCompleteI64)(uint64_t, UniffiForeignFutureResultI64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F32
+typedef struct UniffiForeignFutureResultF32 {
+ float returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultF32;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32
+typedef void (*UniffiForeignFutureCompleteF32)(uint64_t, UniffiForeignFutureResultF32
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_F64
+typedef struct UniffiForeignFutureResultF64 {
+ double returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultF64;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64
+typedef void (*UniffiForeignFutureCompleteF64)(uint64_t, UniffiForeignFutureResultF64
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_RUST_BUFFER
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_RUST_BUFFER
+typedef struct UniffiForeignFutureResultRustBuffer {
+ RustBuffer returnValue;
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultRustBuffer;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER
+typedef void (*UniffiForeignFutureCompleteRustBuffer)(uint64_t, UniffiForeignFutureResultRustBuffer
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_VOID
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_RESULT_VOID
+typedef struct UniffiForeignFutureResultVoid {
+ RustCallStatus callStatus;
+} UniffiForeignFutureResultVoid;
+
+#endif
+#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID
+#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID
+typedef void (*UniffiForeignFutureCompleteVoid)(uint64_t, UniffiForeignFutureResultVoid
+ );
+
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_CLONE_PRESERVEDJSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_CLONE_PRESERVEDJSON
+uint64_t uniffi_cyclops_sdk_schema_fn_clone_preservedjson(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_FREE_PRESERVEDJSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_FREE_PRESERVEDJSON
+void uniffi_cyclops_sdk_schema_fn_free_preservedjson(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_CONSTRUCTOR_PRESERVEDJSON_FROM_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_CONSTRUCTOR_PRESERVEDJSON_FROM_JSON
+uint64_t uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json(RustBuffer value, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_PRESERVEDJSON_TO_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_PRESERVEDJSON_TO_JSON
+RustBuffer uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json(uint64_t ptr, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_EQ
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_EQ
+int8_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq(RustBuffer ptr, RustBuffer other, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_NE
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_NE
+int8_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne(RustBuffer ptr, RustBuffer other, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_HASH
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_HASH
+uint64_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash(RustBuffer ptr, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_ALLOC
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_ALLOC
+RustBuffer ffi_cyclops_sdk_schema_rustbuffer_alloc(uint64_t size, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_FROM_BYTES
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_FROM_BYTES
+RustBuffer ffi_cyclops_sdk_schema_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_FREE
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_FREE
+void ffi_cyclops_sdk_schema_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_RESERVE
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_RESERVE
+RustBuffer ffi_cyclops_sdk_schema_rustbuffer_reserve(RustBuffer buf, uint64_t additional, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U8
+void ffi_cyclops_sdk_schema_rust_future_poll_u8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U8
+void ffi_cyclops_sdk_schema_rust_future_cancel_u8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U8
+void ffi_cyclops_sdk_schema_rust_future_free_u8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U8
+uint8_t ffi_cyclops_sdk_schema_rust_future_complete_u8(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I8
+void ffi_cyclops_sdk_schema_rust_future_poll_i8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I8
+void ffi_cyclops_sdk_schema_rust_future_cancel_i8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I8
+void ffi_cyclops_sdk_schema_rust_future_free_i8(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I8
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I8
+int8_t ffi_cyclops_sdk_schema_rust_future_complete_i8(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U16
+void ffi_cyclops_sdk_schema_rust_future_poll_u16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U16
+void ffi_cyclops_sdk_schema_rust_future_cancel_u16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U16
+void ffi_cyclops_sdk_schema_rust_future_free_u16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U16
+uint16_t ffi_cyclops_sdk_schema_rust_future_complete_u16(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I16
+void ffi_cyclops_sdk_schema_rust_future_poll_i16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I16
+void ffi_cyclops_sdk_schema_rust_future_cancel_i16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I16
+void ffi_cyclops_sdk_schema_rust_future_free_i16(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I16
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I16
+int16_t ffi_cyclops_sdk_schema_rust_future_complete_i16(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U32
+void ffi_cyclops_sdk_schema_rust_future_poll_u32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U32
+void ffi_cyclops_sdk_schema_rust_future_cancel_u32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U32
+void ffi_cyclops_sdk_schema_rust_future_free_u32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U32
+uint32_t ffi_cyclops_sdk_schema_rust_future_complete_u32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I32
+void ffi_cyclops_sdk_schema_rust_future_poll_i32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I32
+void ffi_cyclops_sdk_schema_rust_future_cancel_i32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I32
+void ffi_cyclops_sdk_schema_rust_future_free_i32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I32
+int32_t ffi_cyclops_sdk_schema_rust_future_complete_i32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_U64
+void ffi_cyclops_sdk_schema_rust_future_poll_u64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_U64
+void ffi_cyclops_sdk_schema_rust_future_cancel_u64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_U64
+void ffi_cyclops_sdk_schema_rust_future_free_u64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_U64
+uint64_t ffi_cyclops_sdk_schema_rust_future_complete_u64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_I64
+void ffi_cyclops_sdk_schema_rust_future_poll_i64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_I64
+void ffi_cyclops_sdk_schema_rust_future_cancel_i64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_I64
+void ffi_cyclops_sdk_schema_rust_future_free_i64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_I64
+int64_t ffi_cyclops_sdk_schema_rust_future_complete_i64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_F32
+void ffi_cyclops_sdk_schema_rust_future_poll_f32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_F32
+void ffi_cyclops_sdk_schema_rust_future_cancel_f32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_F32
+void ffi_cyclops_sdk_schema_rust_future_free_f32(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_F32
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_F32
+float ffi_cyclops_sdk_schema_rust_future_complete_f32(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_F64
+void ffi_cyclops_sdk_schema_rust_future_poll_f64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_F64
+void ffi_cyclops_sdk_schema_rust_future_cancel_f64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_F64
+void ffi_cyclops_sdk_schema_rust_future_free_f64(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_F64
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_F64
+double ffi_cyclops_sdk_schema_rust_future_complete_f64(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_RUST_BUFFER
+void ffi_cyclops_sdk_schema_rust_future_poll_rust_buffer(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_RUST_BUFFER
+void ffi_cyclops_sdk_schema_rust_future_cancel_rust_buffer(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_RUST_BUFFER
+void ffi_cyclops_sdk_schema_rust_future_free_rust_buffer(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_RUST_BUFFER
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_RUST_BUFFER
+RustBuffer ffi_cyclops_sdk_schema_rust_future_complete_rust_buffer(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_POLL_VOID
+void ffi_cyclops_sdk_schema_rust_future_poll_void(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_CANCEL_VOID
+void ffi_cyclops_sdk_schema_rust_future_cancel_void(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_FREE_VOID
+void ffi_cyclops_sdk_schema_rust_future_free_void(uint64_t handle
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_VOID
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUST_FUTURE_COMPLETE_VOID
+void ffi_cyclops_sdk_schema_rust_future_complete_void(uint64_t handle, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_CHECKSUM_METHOD_PRESERVEDJSON_TO_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_CHECKSUM_METHOD_PRESERVEDJSON_TO_JSON
+uint16_t uniffi_cyclops_sdk_schema_checksum_method_preservedjson_to_json(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_CHECKSUM_CONSTRUCTOR_PRESERVEDJSON_FROM_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_CHECKSUM_CONSTRUCTOR_PRESERVEDJSON_FROM_JSON
+uint16_t uniffi_cyclops_sdk_schema_checksum_constructor_preservedjson_from_json(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_UNIFFI_CONTRACT_VERSION
+#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_UNIFFI_CONTRACT_VERSION
+uint32_t ffi_cyclops_sdk_schema_uniffi_contract_version(void
+
+);
+#endif
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.modulemap b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.modulemap
new file mode 100644
index 0000000000..d01faa266c
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkSchemaFFI.modulemap
@@ -0,0 +1,7 @@
+module CyclopsSdkSchemaFFI {
+ header "CyclopsSdkSchemaFFI.h"
+ export *
+ use "Darwin"
+ use "_Builtin_stdbool"
+ use "_Builtin_stdint"
+}
diff --git a/libs/fleet/sdk-bindings/swift/README.md b/libs/fleet/sdk-bindings/swift/README.md
new file mode 100644
index 0000000000..0206d37b80
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/README.md
@@ -0,0 +1,13 @@
+# Swift Contract Binding
+
+On macOS with Xcode Swift installed, set `REPO_ROOT` to the absolute path of this
+clone (for example, `REPO_ROOT=/path/to/clone`), then compile generated schema
+and SDK sources into one `CyclopsSdk` module and execute the contract test:
+
+```bash
+REPO_ROOT=/path/to/clone
+$REPO_ROOT/cyclops-cs/scripts/run-swift-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/swift/tests/TestAsyncClient.swift"
+$REPO_ROOT/cyclops-cs/scripts/run-swift-sdk-binding.sh "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/swift/AppControlled.swift"
+```
+
+The launcher passes both generated Swift source files to one `swiftc` invocation and uses the checked-in FFI module maps plus an rpath to the freshly-built cdylib.
diff --git a/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
new file mode 100644
index 0000000000..2670964716
--- /dev/null
+++ b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
@@ -0,0 +1,147 @@
+import Foundation
+
+private struct Expected: @unchecked Sendable {
+ let method: String
+ let url: String
+ let headers: [HttpHeader]
+ let body: Data?
+ let status: UInt16
+ let response: Data
+}
+
+private let jsonHeaders = [
+ HttpHeader(name: "accept", value: "application/json"),
+ HttpHeader(name: "content-type", value: "application/json"),
+ HttpHeader(name: "authorization", value: "Bearer offline-token"),
+]
+
+private func tokenExpected() -> Expected {
+ Expected(
+ method: "POST",
+ url: "https://keycloak.invalid/token",
+ headers: [
+ HttpHeader(name: "accept", value: "application/json"),
+ HttpHeader(name: "content-type", value: "application/x-www-form-urlencoded"),
+ ],
+ body: Data("grant_type=client_credentials&client_id=client-id&client_secret=client-secret".utf8),
+ status: 200,
+ response: Data(#"{"access_token":"offline-token","expires_in":3600}"#.utf8)
+ )
+}
+
+private func serviceExpected(body: Data?, response: Data) -> Expected {
+ Expected(
+ method: "POST",
+ url: "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp",
+ headers: [HttpHeader(name: "authorization", value: "Bearer offline-token")],
+ body: body,
+ status: 202,
+ response: response
+ )
+}
+
+private func lifecycleQueue() -> [Expected] {
+ [
+ tokenExpected(),
+ Expected(method: "POST", url: "https://cyclops.invalid/api/namespaces", headers: jsonHeaders, body: Data(#"{"name":"default"}"#.utf8), status: 201, response: Data("{}".utf8)),
+ Expected(method: "POST", url: "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools", headers: jsonHeaders, body: Data(#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"replicas":1,"template":{"containerDiskImage":"registry.example/desktop:offline"},"services":[{"name":"mcp","targetPort":8080}]},"status":null}"#.utf8), status: 201, response: Data(#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"replicas":1,"template":{"containerDiskImage":"registry.example/desktop:offline"},"services":[{"name":"mcp","targetPort":8080}]},"status":null}"#.utf8)),
+ Expected(method: "POST", url: "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims", headers: jsonHeaders, body: Data(#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"claim-1","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":null}"#.utf8), status: 201, response: Data(#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":{"phase":"Bound","sandbox":{"name":"offline-sandbox"}}}"#.utf8)),
+ Expected(method: "GET", url: "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", headers: jsonHeaders, body: nil, status: 200, response: Data(#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"}},"status":{"phase":"Bound","sandbox":{"name":"offline-sandbox"}}}"#.utf8)),
+ Expected(method: "GET", url: "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", headers: jsonHeaders, body: nil, status: 200, response: Data(#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"default","name":"default","labels":null},"spec":{"replicas":1,"template":{"containerDiskImage":"registry.example/desktop:offline"},"services":[{"name":"mcp","targetPort":8080}]},"status":null}"#.utf8)),
+ serviceExpected(body: Data(#"{"offline":true}"#.utf8), response: Data("offline service accepted".utf8)),
+ Expected(method: "DELETE", url: "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", headers: jsonHeaders, body: nil, status: 204, response: Data()),
+ Expected(method: "DELETE", url: "https://cyclops.invalid/api/k8s/apis/cua.ai/v1/namespaces/default/osgymworkspacepools/default", headers: jsonHeaders, body: nil, status: 204, response: Data()),
+ Expected(method: "DELETE", url: "https://cyclops.invalid/api/namespaces/default", headers: jsonHeaders, body: nil, status: 204, response: Data()),
+ ]
+}
+
+actor ScriptedHttpClient: HttpClient {
+ private var expected: [Expected]
+ private var requests: [HttpRequest] = []
+
+ fileprivate init(expected: [Expected]) {
+ self.expected = expected
+ }
+
+ func execute(request: HttpRequest) async throws -> HttpResponse {
+ guard !expected.isEmpty else { preconditionFailure("unexpected request") }
+ let item = expected.removeFirst()
+ precondition(request.method == item.method && request.url == item.url)
+ precondition(request.headers == item.headers)
+ precondition(request.body == item.body)
+ requests.append(request)
+ return HttpResponse(status: item.status, headers: [], body: item.response)
+ }
+
+ func assertExhausted() { precondition(expected.isEmpty) }
+ func recordedRequestCount() -> Int { requests.count }
+}
+
+final class FailingHttpClient: HttpClient, @unchecked Sendable {
+ func execute(request: HttpRequest) async throws -> HttpResponse {
+ throw HttpError.Transport(reason: "scripted callback failure")
+ }
+}
+
+private func configuration() -> CyclopsConfiguration {
+ CyclopsConfiguration(baseUrl: "https://cyclops.invalid", tokenUrl: "https://keycloak.invalid/token", credentials: CyclopsCredentials(clientId: "client-id", clientSecret: "client-secret"), poolPollIntervalMs: 1, poolPollLimit: 1, claimPollIntervalMs: 1, claimPollLimit: 2)
+}
+
+private let sandbox = Sandbox(namespace: "default", claim: "default", name: "offline-sandbox", services: ["mcp"])
+private func serviceRequest(_ body: Data?) -> HttpRequest {
+ HttpRequest(method: "POST", url: "https://ignored.invalid/mcp", headers: [], body: body)
+}
+
+@main struct AppControlled {
+ static func main() async throws {
+ let vmTemplate = VmTemplate(containerDiskImage: "registry.example/desktop:offline", command: nil, runtime: nil, runtimeClassName: nil, nodeSelector: nil, tolerations: nil, imagePullPolicy: nil, imagePullSecret: nil, cpuCores: nil, memory: nil, firmware: nil, probes: nil, services: nil, oidc: nil)
+ let spec = PoolSpec(replicas: 1, template: PoolTemplate(runtime: nil, runtimeClassName: nil, nodeSelector: nil, tolerations: nil, command: nil, containerDiskImage: vmTemplate.containerDiskImage, imagePullSecret: nil, cpuCores: nil, memory: nil, firmware: nil, probes: nil, oidc: nil), autoscaling: nil, services: [SandboxService(name: "mcp", targetPort: 8080, protocol: nil)])
+ let transport = ScriptedHttpClient(expected: lifecycleQueue())
+ let client = try CyclopsClient.connect(configuration: configuration(), httpClient: transport)
+ let pool = try await client.createPool(request: CreatePoolRequest(namespace: "default", spec: spec))
+ let claim = try await client.createClaim(request: CreateClaimRequest(pool: pool, spec: ClaimSpec(sandboxTemplateRef: SandboxTemplateRef(name: pool.metadata.name), warmpool: nil, bindDeadline: nil, lifecycle: nil)))
+ let createdSandbox = try await client.waitClaim(claim: claim)
+ let service = try await client.serviceRequest(sandbox: createdSandbox, service: "mcp", path: "/mcp", request: serviceRequest(Data(#"{"offline":true}"#.utf8)))
+ try await client.deleteClaim(claim: claim)
+ try await client.deletePool(pool: pool)
+ await transport.assertExhausted()
+ precondition(service.status == 202)
+
+ let failingClient = try CyclopsClient.connect(configuration: configuration(), httpClient: FailingHttpClient())
+ do {
+ _ = try await failingClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(nil))
+ preconditionFailure("expected generated SdkError.Transport")
+ } catch SdkError.Transport(let reason) {
+ precondition(reason == "scripted callback failure")
+ }
+
+ let bodyTransport = ScriptedHttpClient(expected: [
+ tokenExpected(),
+ serviceExpected(body: nil, response: Data()),
+ serviceExpected(body: Data(), response: Data([0, 0x7f, 0xff])),
+ ])
+ let bodyClient = try CyclopsClient.connect(configuration: configuration(), httpClient: bodyTransport)
+ let emptyBodyResponse = try await bodyClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(nil))
+ precondition(emptyBodyResponse.body.isEmpty)
+ let binaryBodyResponse = try await bodyClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(Data()))
+ precondition(binaryBodyResponse.body == Data([0, 0x7f, 0xff]))
+ await bodyTransport.assertExhausted()
+
+ let concurrentTransport = ScriptedHttpClient(expected: [
+ tokenExpected(),
+ serviceExpected(body: nil, response: Data("warm".utf8)),
+ serviceExpected(body: Data("parallel".utf8), response: Data("first".utf8)),
+ serviceExpected(body: Data("parallel".utf8), response: Data("second".utf8)),
+ ])
+ let concurrentClient = try CyclopsClient.connect(configuration: configuration(), httpClient: concurrentTransport)
+ _ = try await concurrentClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(nil))
+ async let first = concurrentClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(Data("parallel".utf8)))
+ async let second = concurrentClient.serviceRequest(sandbox: sandbox, service: "mcp", path: "/mcp", request: serviceRequest(Data("parallel".utf8)))
+ let concurrentResponses = try await (first, second)
+ precondition(Set([concurrentResponses.0.body, concurrentResponses.1.body]) == Set([Data("first".utf8), Data("second".utf8)]))
+ await concurrentTransport.assertExhausted()
+ let recordedRequestCount = await concurrentTransport.recordedRequestCount()
+ precondition(recordedRequestCount == 4)
+ print("pool=\(pool.metadata.name) claim=\(claim.metadata.name) sandbox=\(createdSandbox.name) service_status=\(service.status)")
+ }
+}
diff --git a/libs/fleet/sdk-bindings/typescript/.gitignore b/libs/fleet/sdk-bindings/typescript/.gitignore
deleted file mode 100644
index afef9bc672..0000000000
--- a/libs/fleet/sdk-bindings/typescript/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-dist-examples/
-node_modules/
diff --git a/libs/fleet/sdk-bindings/typescript/package-lock.json b/libs/fleet/sdk-bindings/typescript/package-lock.json
deleted file mode 100644
index c404f0bf03..0000000000
--- a/libs/fleet/sdk-bindings/typescript/package-lock.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "name": "@trycua/cyclops-sdk",
- "version": "0.1.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "@trycua/cyclops-sdk",
- "version": "0.1.0",
- "devDependencies": {
- "@types/node": "22.10.5",
- "typescript": "5.7.2"
- }
- },
- "node_modules/@types/node": {
- "version": "22.10.5",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.5.tgz",
- "integrity": "sha512-F8Q+SeGimwOo86fiovQh8qiXfFEh2/ocYv7tU5pJ3EXMSSxk1Joj5wefpFK2fHTf/N6HKGSxIDBT9f3gCxXPkQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "undici-types": "~6.20.0"
- }
- },
- "node_modules/typescript": {
- "version": "5.7.2",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz",
- "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
- },
- "engines": {
- "node": ">=14.17"
- }
- },
- "node_modules/undici-types": {
- "version": "6.20.0",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
- "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",
- "dev": true,
- "license": "MIT"
- }
- }
-}
diff --git a/libs/fleet/sdk-bindings/typescript/package.json b/libs/fleet/sdk-bindings/typescript/package.json
deleted file mode 100644
index 066ffb3c8c..0000000000
--- a/libs/fleet/sdk-bindings/typescript/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "name": "@trycua/cyclops-sdk",
- "version": "0.1.0",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "tsc -p tsconfig.json && tsc -p tsconfig.examples.json",
- "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.contract.json && tsc -p tsconfig.examples.json --noEmit",
- "test": "npm run build && node --test test/*.test.js"
- },
- "devDependencies": {
- "typescript": "5.7.2",
- "@types/node": "22.10.5"
- },
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
- }
- }
-}
diff --git a/libs/fleet/sdk-bindings/typescript/src/generated-crd.ts b/libs/fleet/sdk-bindings/typescript/src/generated-crd.ts
deleted file mode 100644
index cbb61850af..0000000000
--- a/libs/fleet/sdk-bindings/typescript/src/generated-crd.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-export type ClaimSpec = {
- bindDeadline?: number
- lifecycle?: ClaimSpecLifecycle
- sandboxTemplateRef: SandboxTemplateRef
- warmpool?: string
-}
-export type ClaimSpecLifecycle = {
- autoRenew?: boolean
- shutdownPolicy?: string
- shutdownTime?: string
-}
-export type PoolSpec = {
- autoscaling?: PoolSpecAutoscaling
- replicas: number
- services?: PoolSpecService[]
- template: PoolTemplate
-}
-export type PoolSpecAutoscaling = {
- initialPoolSize?: number
- maxPoolSize?: number
- minPoolSize?: number
-}
-export type PoolSpecService = {
- name: string
- protocol?: PoolSpecServiceProtocol
- targetPort: number
-}
-export type PoolSpecServiceProtocol = "TCP" | "UDP"
-export type PoolTemplate = {
- command?: string[]
- containerDiskImage: string
- cpuCores?: number
- firmware?: PoolTemplateFirmware
- imagePullSecret?: string
- memory?: string
- nodeSelector?: Record<string, string>
- oidc?: PoolTemplateOidc
- probes?: unknown
- runtime?: PoolTemplateRuntime
- runtimeClassName?: string
- tolerations?: unknown[]
-}
-export type PoolTemplateFirmware = "bios" | "efi"
-export type PoolTemplateOidc = {
- awsRegion?: string
- awsRoleArn?: string
- credentialsSecret: string
- refreshIntervalSeconds?: number
- tokenUrl: string
-}
-export type PoolTemplateRuntime = "kubevirt" | "macos" | "gvisor"
-export type SandboxTemplateRef = {
- name: string
-}
diff --git a/libs/fleet/sdk-bindings/typescript/src/index.ts b/libs/fleet/sdk-bindings/typescript/src/index.ts
deleted file mode 100644
index bcd71dead0..0000000000
--- a/libs/fleet/sdk-bindings/typescript/src/index.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
-import type { ClaimSpec, PoolSpec } from "./generated-crd.js"
-
-export * from "./generated-crd.js"
-
-export type OAuthConfiguration = { tokenUrl: string; clientId: string; clientSecret: string }
-export type Configuration = { baseUrl: string; oauth: OAuthConfiguration }
-export type ResourceMetadata = { namespace: string; name: string; labels?: Record<string, string> }
-export type Pool = { apiVersion: "cua.ai/v1"; kind: "OSGymWorkspacePool"; metadata: ResourceMetadata; spec: Record<string, unknown>; status?: Record<string, unknown> }
-export type Claim = { apiVersion: "osgym.cua.ai/v1alpha1"; kind: "OSGymSandboxClaim"; metadata: ResourceMetadata; spec: Record<string, unknown>; status?: Record<string, unknown> }
-export type Sandbox = { namespace: string; claim: string; sandbox: string; services: string[] }
-export type CreatePoolRequest = { namespace: string; spec: PoolSpec }
-export type CreateClaimRequest = { pool: Pool; spec?: ClaimSpec }
-type ServiceHttpResponse = { status: number; body: string }
-export type ServiceFetch = (path: string, init?: RequestInit) => Promise<Response>
-
-export class UnknownServiceError extends Error {
- readonly requested: string
- readonly available: readonly string[]
-
- constructor(requested: string, available: readonly string[]) {
- super(`unknown sandbox service ${JSON.stringify(requested)}; available services: ${JSON.stringify(available)}`)
- this.name = "UnknownServiceError"
- this.requested = requested
- this.available = [...available]
- }
-}
-
-type HostCall =
- | { kind: "http"; request: { method: string; url: string; headers: [string, string][]; body?: string } }
- | { kind: "sleep"; milliseconds: number }
- | { kind: "now_ms" }
- | { kind: "acquire_oauth_credentials" }
- | { kind: "load_access_token" }
- | { kind: "store_access_token"; token: { value: string; expires_at_ms: number } }
-
-type Reply<T> = { ok: boolean; value?: T; error?: string }
-
-export class SDK {
- readonly #configuration: Configuration
- readonly #process: ChildProcessWithoutNullStreams
- #buffer = ""
- #token?: { value: string; expires_at_ms: number }
- #pending: { resolve: (value: unknown) => void; reject: (error: Error) => void }[] = []
-
- private constructor(configuration: Configuration) {
- this.#configuration = configuration
- this.#process = spawn(process.env.CYCLOPS_CORE_RUNNER ?? "cyclops-core-runner", [], { stdio: "pipe" })
- this.#process.stdout.setEncoding("utf8")
- this.#process.stdout.on("data", chunk => this.#read(String(chunk)))
- this.#process.on("error", error => this.#fail(error))
- this.#process.on("exit", code => this.#fail(new Error(`core runner exited with ${code ?? "unknown"}`)))
- }
-
- static async connect(configuration: Configuration): Promise<SDK> {
- const sdk = new SDK(configuration)
- try {
- await sdk.#call({ op: "configure", configuration: { protocol_version: 7, base_url: configuration.baseUrl } })
- return sdk
- } catch (error) {
- sdk.close()
- throw error
- }
- }
-
- createPool(request: CreatePoolRequest): Promise<Pool> { return this.#call({ op: "create_pool", request }) }
- listPools(namespace: string): Promise<Pool[]> { return this.#call({ op: "list_pools", namespace }) }
- getPool(pool: Pool): Promise<Pool> { return this.#call({ op: "get_pool", pool }) }
- updatePool(pool: Pool): Promise<Pool> { return this.#call({ op: "update_pool", pool }) }
- deletePool(pool: Pool): Promise<void> { return this.#call({ op: "delete_pool", pool }) }
- createClaim(request: CreateClaimRequest): Promise<Claim> { return this.#call({ op: "create_claim", request }) }
- listClaims(namespace: string): Promise<Claim[]> { return this.#call({ op: "list_claims", namespace }) }
- getClaim(claim: Claim): Promise<Claim> { return this.#call({ op: "get_claim", claim }) }
- updateClaim(claim: Claim): Promise<Claim> { return this.#call({ op: "update_claim", claim }) }
- deleteClaim(claim: Claim): Promise<void> { return this.#call({ op: "delete_claim", claim }) }
- waitClaim(claim: Claim): Promise<Sandbox> { return this.#call({ op: "wait_claim", claim }) }
- serviceFetch(sandbox: Sandbox, service: string): ServiceFetch {
- const available = [...new Set(sandbox.services)].sort()
- if (!available.includes(service)) throw new UnknownServiceError(service, available)
- return async (path, init = {}) => {
- if (!path.startsWith("/") || path.startsWith("//") || path.includes("#")) {
- throw new TypeError(`service request path must be relative and start with '/': ${path}`)
- }
- const request = new Request(`https://cyclops.invalid${path}`, init)
- const body = init.body === undefined || init.body === null ? undefined : await request.text()
- const response = await this.#call<ServiceHttpResponse>({
- op: "service_request",
- sandbox,
- service,
- request: {
- method: request.method,
- path,
- headers: Array.from(request.headers.entries()),
- body,
- },
- })
- const responseBody = [204, 205, 304].includes(response.status) ? null : response.body
- return new Response(responseBody, { status: response.status })
- }
- }
- close(): void { this.#process.stdin.end(); this.#process.kill("SIGTERM") }
-
- #call<T>(request: unknown): Promise<T> {
- return new Promise<T>((resolve, reject) => {
- this.#pending.push({ resolve: value => resolve(value as T), reject })
- this.#process.stdin.write(`${JSON.stringify(request)}\n`)
- })
- }
-
- async #read(chunk: string): Promise<void> {
- this.#buffer += chunk
- while (this.#buffer.includes("\n")) {
- const newline = this.#buffer.indexOf("\n")
- const line = this.#buffer.slice(0, newline)
- this.#buffer = this.#buffer.slice(newline + 1)
- if (!line) continue
- const message = JSON.parse(line) as Reply<unknown> | HostCall
- if ("kind" in message) {
- try { this.#process.stdin.write(`${JSON.stringify({ ok: true, value: await this.#dispatch(message) })}\n`) }
- catch (error) { this.#process.stdin.write(`${JSON.stringify({ ok: false, error: { transport: String(error) } })}\n`) }
- continue
- }
- const pending = this.#pending.shift()
- if (!pending) continue
- if (message.ok) pending.resolve(message.value)
- else pending.reject(new Error(message.error ?? "core operation failed"))
- }
- }
-
- async #dispatch(message: HostCall): Promise<unknown> {
- if (message.kind === "http") {
- const response = await fetch(message.request.url, { method: message.request.method, headers: Object.fromEntries(message.request.headers), body: message.request.body, redirect: "manual" })
- return { status: response.status, body: await response.text() }
- }
- if (message.kind === "sleep") { await new Promise(resolve => setTimeout(resolve, message.milliseconds)); return null }
- if (message.kind === "now_ms") return Date.now()
- if (message.kind === "acquire_oauth_credentials") return { token_url: this.#configuration.oauth.tokenUrl, client_id: this.#configuration.oauth.clientId, client_secret: this.#configuration.oauth.clientSecret }
- if (message.kind === "load_access_token") return this.#token ?? null
- this.#token = message.token
- return null
- }
-
- #fail(error: Error): void {
- for (const pending of this.#pending.splice(0)) pending.reject(error)
- }
-}
-
-export function connect(configuration: Configuration): Promise<SDK> { return SDK.connect(configuration) }
diff --git a/libs/fleet/sdk-bindings/typescript/test/connect-failure.test.js b/libs/fleet/sdk-bindings/typescript/test/connect-failure.test.js
deleted file mode 100644
index 169ffa2dc5..0000000000
--- a/libs/fleet/sdk-bindings/typescript/test/connect-failure.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import assert from "node:assert/strict"
-import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises"
-import { tmpdir } from "node:os"
-import { join } from "node:path"
-import { test } from "node:test"
-import { setTimeout as delay } from "node:timers/promises"
-
-import { connect } from "../dist/index.js"
-
-test("connect terminates the core runner when configuration fails", async () => {
- const directory = await mkdtemp(join(tmpdir(), "cyclops-sdk-connect-"))
- const runner = join(directory, "runner.mjs")
- const pidFile = join(directory, "pid")
- const terminatedFile = join(directory, "terminated")
- await writeFile(runner, `#!/usr/bin/env node
-import { writeFileSync } from "node:fs"
-import { createInterface } from "node:readline"
-writeFileSync(${JSON.stringify(pidFile)}, String(process.pid))
-process.on("SIGTERM", () => { writeFileSync(${JSON.stringify(terminatedFile)}, "yes"); process.exit(0) })
-createInterface({ input: process.stdin }).once("line", () => process.stdout.write('{"ok":false,"error":"invalid configuration"}\\n'))
-`)
- await chmod(runner, 0o755)
- const previousRunner = process.env.CYCLOPS_CORE_RUNNER
- process.env.CYCLOPS_CORE_RUNNER = runner
- let pid
- try {
- await assert.rejects(
- connect({
- baseUrl: "invalid",
- oauth: { tokenUrl: "https://auth.example/token", clientId: "id", clientSecret: "secret" },
- }),
- /invalid configuration/,
- )
- pid = Number(await readFile(pidFile, "utf8"))
- for (let attempt = 0; attempt < 20; attempt++) {
- try {
- assert.equal(await readFile(terminatedFile, "utf8"), "yes")
- return
- } catch {
- await delay(25)
- }
- }
- assert.fail("core runner was not terminated")
- } finally {
- if (previousRunner === undefined) delete process.env.CYCLOPS_CORE_RUNNER
- else process.env.CYCLOPS_CORE_RUNNER = previousRunner
- if (pid) {
- try { process.kill(pid, "SIGKILL") } catch {}
- }
- }
-})
diff --git a/libs/fleet/sdk-bindings/typescript/test/public-api.ts b/libs/fleet/sdk-bindings/typescript/test/public-api.ts
deleted file mode 100644
index e7dc4db27b..0000000000
--- a/libs/fleet/sdk-bindings/typescript/test/public-api.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import {
- connect,
- type Claim,
- type CreateClaimRequest,
- type CreatePoolRequest,
- type Configuration,
- type Pool,
- type PoolSpec,
- type Sandbox,
- type ServiceFetch,
-} from "../src/index.js"
-
-const configuration: Configuration = {
- baseUrl: "https://run.example",
- oauth: { tokenUrl: "https://auth.example/token", clientId: "id", clientSecret: "secret" },
-}
-const poolSpec: PoolSpec = {
- replicas: 1,
- template: { containerDiskImage: "example/workspace:latest", cpuCores: 4, memory: "4Gi" },
-}
-const pool: Pool = {
- apiVersion: "cua.ai/v1",
- kind: "OSGymWorkspacePool",
- metadata: { namespace: "pool-one", name: "pool-one" },
- spec: { replicas: 1, template: { containerDiskImage: "example/workspace:latest", cpuCores: 4, memory: "4Gi" } },
-}
-const claim: Claim = {
- apiVersion: "osgym.cua.ai/v1alpha1",
- kind: "OSGymSandboxClaim",
- metadata: { namespace: "pool-one", name: "claim-one" },
- spec: { sandboxTemplateRef: { name: "pool-one-template" } },
-}
-
-async function contract(): Promise<Sandbox> {
- const sdk = await connect(configuration)
- const poolRequest: CreatePoolRequest = { namespace: "pool-one", spec: poolSpec }
- const createdPool = await sdk.createPool(poolRequest)
- await sdk.listPools(createdPool.metadata.namespace)
- await sdk.getPool(pool)
- await sdk.updatePool(pool)
- const claimRequest: CreateClaimRequest = { pool: createdPool }
- const createdClaim = await sdk.createClaim(claimRequest)
- await sdk.listClaims(createdClaim.metadata.namespace)
- await sdk.getClaim(claim)
- await sdk.updateClaim(claim)
- const sandbox = await sdk.waitClaim(claim)
- const service: ServiceFetch = sdk.serviceFetch(sandbox, "mcp")
- const response: Response = await service("/mcp", { method: "POST", body: "{}" })
- void response
- // @ts-expect-error URL-based authenticated clients are intentionally not public.
- void sdk.rawClient
- await sdk.deleteClaim(claim)
- await sdk.deletePool(pool)
- sdk.close()
- return sandbox
-}
-void contract
diff --git a/libs/fleet/sdk-bindings/typescript/test/service-client.test.js b/libs/fleet/sdk-bindings/typescript/test/service-client.test.js
deleted file mode 100644
index 53da8ad862..0000000000
--- a/libs/fleet/sdk-bindings/typescript/test/service-client.test.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import { SDK, UnknownServiceError } from "../dist/index.js"
-
-test("serviceFetch rejects unknown services with sorted available names", () => {
- const sdk = Object.create(SDK.prototype)
- assert.throws(
- () => sdk.serviceFetch({ namespace: "pool-one", claim: "claim-one", sandbox: "sandbox-one", services: ["novnc", "mcp", "mcp"] }, "metrics"),
- error => {
- assert.ok(error instanceof UnknownServiceError)
- assert.equal(error.requested, "metrics")
- assert.deepEqual(error.available, ["mcp", "novnc"])
- return true
- },
- )
-})
diff --git a/libs/fleet/sdk-bindings/typescript/tsconfig.contract.json b/libs/fleet/sdk-bindings/typescript/tsconfig.contract.json
deleted file mode 100644
index 8e3c56a096..0000000000
--- a/libs/fleet/sdk-bindings/typescript/tsconfig.contract.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "rootDir": ".",
- "outDir": "/tmp/cyclops-sdk-typescript-contract",
- "declaration": false,
- "noEmit": true
- },
- "include": ["src/**/*.ts", "test/**/*.ts"]
-}
diff --git a/libs/fleet/sdk-bindings/typescript/tsconfig.examples.json b/libs/fleet/sdk-bindings/typescript/tsconfig.examples.json
deleted file mode 100644
index 3910c6ab42..0000000000
--- a/libs/fleet/sdk-bindings/typescript/tsconfig.examples.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "rootDir": "../examples/typescript",
- "outDir": "dist-examples",
- "declaration": false
- },
- "include": [
- "../examples/typescript/**/*.ts"
- ]
-}
diff --git a/libs/fleet/sdk-bindings/typescript/tsconfig.json b/libs/fleet/sdk-bindings/typescript/tsconfig.json
deleted file mode 100644
index 4d96503645..0000000000
--- a/libs/fleet/sdk-bindings/typescript/tsconfig.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "NodeNext",
- "moduleResolution": "NodeNext",
- "outDir": "dist",
- "rootDir": "src",
- "strict": true,
- "declaration": true,
- "skipLibCheck": true,
- "types": ["node"]
- },
- "include": ["src/**/*.ts"]
-}
diff --git a/libs/fleet/sdk-bindings/uniffi.toml b/libs/fleet/sdk-bindings/uniffi.toml
new file mode 100644
index 0000000000..a6d3b08201
--- /dev/null
+++ b/libs/fleet/sdk-bindings/uniffi.toml
@@ -0,0 +1,39 @@
+[crate-roots]
+cyclops_sdk = "../sdk"
+cyclops_sdk_schema = "../sdk-schema"
+
+[crates.cyclops_sdk.bindings.python]
+cdylib_name = "cyclops_sdk"
+
+[crates.cyclops_sdk.bindings.python.external_packages]
+cyclops_sdk_schema = "cyclops_sdk"
+
+[crates.cyclops_sdk_schema.bindings.python]
+cdylib_name = "cyclops_sdk"
+
+[crates.cyclops_sdk.bindings.kotlin]
+package_name = "ai.cua.cyclops.sdk"
+cdylib_name = "cyclops_sdk"
+
+[crates.cyclops_sdk.bindings.kotlin.external_packages]
+cyclops_sdk_schema = "ai.cua.cyclops.sdk.schema"
+
+[crates.cyclops_sdk_schema.bindings.kotlin]
+package_name = "ai.cua.cyclops.sdk.schema"
+cdylib_name = "cyclops_sdk"
+
+[crates.cyclops_sdk.bindings.swift]
+module_name = "CyclopsSdk"
+ffi_module_name = "CyclopsSdkFFI"
+ffi_module_filename = "CyclopsSdkFFI"
+
+[crates.cyclops_sdk_schema.bindings.swift]
+module_name = "CyclopsSdkSchema"
+ffi_module_name = "CyclopsSdkSchemaFFI"
+ffi_module_filename = "CyclopsSdkSchemaFFI"
+
+[crates.cyclops_sdk.bindings.ruby]
+cdylib_name = "cyclops_sdk"
+
+[crates.cyclops_sdk_schema.bindings.ruby]
+cdylib_name = "cyclops_sdk"
diff --git a/libs/fleet/sdk-core/Cargo.lock b/libs/fleet/sdk-core/Cargo.lock
deleted file mode 100644
index a07a870163..0000000000
--- a/libs/fleet/sdk-core/Cargo.lock
+++ /dev/null
@@ -1,759 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-version = 4
-
-[[package]]
-name = "anyhow"
-version = "1.0.103"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
-
-[[package]]
-name = "bitflags"
-version = "2.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
-
-[[package]]
-name = "cyclops-sdk-core"
-version = "0.1.0"
-dependencies = [
- "serde",
- "serde_json",
- "thiserror",
- "url",
- "wit-bindgen",
-]
-
-[[package]]
-name = "displaydoc"
-version = "0.2.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "equivalent"
-version = "1.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
-
-[[package]]
-name = "foldhash"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
-
-[[package]]
-name = "form_urlencoded"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
-dependencies = [
- "percent-encoding",
-]
-
-[[package]]
-name = "futures"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
-dependencies = [
- "futures-channel",
- "futures-core",
- "futures-executor",
- "futures-io",
- "futures-sink",
- "futures-task",
- "futures-util",
-]
-
-[[package]]
-name = "futures-channel"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
-dependencies = [
- "futures-core",
- "futures-sink",
-]
-
-[[package]]
-name = "futures-core"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
-
-[[package]]
-name = "futures-executor"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
-dependencies = [
- "futures-core",
- "futures-task",
- "futures-util",
-]
-
-[[package]]
-name = "futures-io"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
-
-[[package]]
-name = "futures-macro"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "futures-sink"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
-
-[[package]]
-name = "futures-task"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
-
-[[package]]
-name = "futures-util"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
-dependencies = [
- "futures-channel",
- "futures-core",
- "futures-io",
- "futures-macro",
- "futures-sink",
- "futures-task",
- "memchr",
- "pin-project-lite",
- "slab",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.15.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
-dependencies = [
- "foldhash",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.17.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
-
-[[package]]
-name = "heck"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
-
-[[package]]
-name = "icu_collections"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
-dependencies = [
- "displaydoc",
- "potential_utf",
- "utf8_iter",
- "yoke",
- "zerofrom",
- "zerovec",
-]
-
-[[package]]
-name = "icu_locale_core"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
-dependencies = [
- "displaydoc",
- "litemap",
- "tinystr",
- "writeable",
- "zerovec",
-]
-
-[[package]]
-name = "icu_normalizer"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
-dependencies = [
- "icu_collections",
- "icu_normalizer_data",
- "icu_properties",
- "icu_provider",
- "smallvec",
- "zerovec",
-]
-
-[[package]]
-name = "icu_normalizer_data"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
-
-[[package]]
-name = "icu_properties"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
-dependencies = [
- "icu_collections",
- "icu_locale_core",
- "icu_properties_data",
- "icu_provider",
- "zerotrie",
- "zerovec",
-]
-
-[[package]]
-name = "icu_properties_data"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
-
-[[package]]
-name = "icu_provider"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
-dependencies = [
- "displaydoc",
- "icu_locale_core",
- "writeable",
- "yoke",
- "zerofrom",
- "zerotrie",
- "zerovec",
-]
-
-[[package]]
-name = "id-arena"
-version = "2.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
-
-[[package]]
-name = "idna"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
-dependencies = [
- "idna_adapter",
- "smallvec",
- "utf8_iter",
-]
-
-[[package]]
-name = "idna_adapter"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
-dependencies = [
- "icu_normalizer",
- "icu_properties",
-]
-
-[[package]]
-name = "indexmap"
-version = "2.14.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
-dependencies = [
- "equivalent",
- "hashbrown 0.17.1",
- "serde",
- "serde_core",
-]
-
-[[package]]
-name = "itoa"
-version = "1.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
-
-[[package]]
-name = "leb128fmt"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
-
-[[package]]
-name = "litemap"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
-
-[[package]]
-name = "log"
-version = "0.4.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
-
-[[package]]
-name = "memchr"
-version = "2.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
-
-[[package]]
-name = "once_cell"
-version = "1.21.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
-
-[[package]]
-name = "percent-encoding"
-version = "2.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
-
-[[package]]
-name = "pin-project-lite"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
-
-[[package]]
-name = "potential_utf"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
-dependencies = [
- "zerovec",
-]
-
-[[package]]
-name = "prettyplease"
-version = "0.2.37"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
-dependencies = [
- "proc-macro2",
- "syn",
-]
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.106"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
-dependencies = [
- "unicode-ident",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.46"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "semver"
-version = "1.0.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
-
-[[package]]
-name = "serde"
-version = "1.0.228"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
-dependencies = [
- "serde_core",
- "serde_derive",
-]
-
-[[package]]
-name = "serde_core"
-version = "1.0.228"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.228"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde_json"
-version = "1.0.150"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
-dependencies = [
- "itoa",
- "memchr",
- "serde",
- "serde_core",
- "zmij",
-]
-
-[[package]]
-name = "slab"
-version = "0.4.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
-
-[[package]]
-name = "smallvec"
-version = "1.15.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
-
-[[package]]
-name = "spdx"
-version = "0.10.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3"
-dependencies = [
- "smallvec",
-]
-
-[[package]]
-name = "stable_deref_trait"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
-
-[[package]]
-name = "syn"
-version = "2.0.119"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
-
-[[package]]
-name = "synstructure"
-version = "0.13.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "thiserror"
-version = "2.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
-dependencies = [
- "thiserror-impl",
-]
-
-[[package]]
-name = "thiserror-impl"
-version = "2.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "tinystr"
-version = "0.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
-dependencies = [
- "displaydoc",
- "zerovec",
-]
-
-[[package]]
-name = "unicode-ident"
-version = "1.0.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
-
-[[package]]
-name = "url"
-version = "2.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
-dependencies = [
- "form_urlencoded",
- "idna",
- "percent-encoding",
- "serde",
-]
-
-[[package]]
-name = "utf8_iter"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
-
-[[package]]
-name = "wasm-encoder"
-version = "0.225.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f7eac0445cac73bcf09e6a97f83248d64356dccf9f2b100199769b6b42464e5"
-dependencies = [
- "leb128fmt",
- "wasmparser",
-]
-
-[[package]]
-name = "wasm-metadata"
-version = "0.225.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1d20d0bf2c73c32a5114cf35a5c10ccf9f9aa37a3a2c0114b3e11cbf6faac12"
-dependencies = [
- "anyhow",
- "indexmap",
- "serde",
- "serde_derive",
- "serde_json",
- "spdx",
- "url",
- "wasm-encoder",
- "wasmparser",
-]
-
-[[package]]
-name = "wasmparser"
-version = "0.225.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36e5456165f81e64cb9908a0fe9b9d852c2c74582aa3fe2be3c2da57f937d3ae"
-dependencies = [
- "bitflags",
- "hashbrown 0.15.5",
- "indexmap",
- "semver",
-]
-
-[[package]]
-name = "wit-bindgen"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e4dd9a372b25d6f35456b0a730d2adabeb0c4878066ba8f8089800349be6ecb5"
-dependencies = [
- "wit-bindgen-rt",
- "wit-bindgen-rust-macro",
-]
-
-[[package]]
-name = "wit-bindgen-core"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f108fa9b77a346372858b30c11ea903680e7e2b9d820b1a5883e9d530bf51c7e"
-dependencies = [
- "anyhow",
- "heck",
- "wit-parser",
-]
-
-[[package]]
-name = "wit-bindgen-rt"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
-dependencies = [
- "bitflags",
- "futures",
- "once_cell",
-]
-
-[[package]]
-name = "wit-bindgen-rust"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5ba5b852e976d35dbf6cb745746bf1bd4fc26782bab1e0c615fc71a7d8aac05"
-dependencies = [
- "anyhow",
- "heck",
- "indexmap",
- "prettyplease",
- "syn",
- "wasm-metadata",
- "wit-bindgen-core",
- "wit-component",
-]
-
-[[package]]
-name = "wit-bindgen-rust-macro"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "401529c9af9304a20ed99fa01799e467b7d37727126f0c9a958895471268ad7a"
-dependencies = [
- "anyhow",
- "prettyplease",
- "proc-macro2",
- "quote",
- "syn",
- "wit-bindgen-core",
- "wit-bindgen-rust",
-]
-
-[[package]]
-name = "wit-component"
-version = "0.225.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2505c917564c1d74774563bbcd3e4f8c216a6508050862fd5f449ee56e3c5125"
-dependencies = [
- "anyhow",
- "bitflags",
- "indexmap",
- "log",
- "serde",
- "serde_derive",
- "serde_json",
- "wasm-encoder",
- "wasm-metadata",
- "wasmparser",
- "wit-parser",
-]
-
-[[package]]
-name = "wit-parser"
-version = "0.225.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebefaa234e47224f10ce60480c5bfdece7497d0f3b87a12b41ff39e5c8377a78"
-dependencies = [
- "anyhow",
- "id-arena",
- "indexmap",
- "log",
- "semver",
- "serde",
- "serde_derive",
- "serde_json",
- "unicode-xid",
- "wasmparser",
-]
-
-[[package]]
-name = "writeable"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
-
-[[package]]
-name = "yoke"
-version = "0.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
-dependencies = [
- "stable_deref_trait",
- "yoke-derive",
- "zerofrom",
-]
-
-[[package]]
-name = "yoke-derive"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
- "synstructure",
-]
-
-[[package]]
-name = "zerofrom"
-version = "0.1.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
-dependencies = [
- "zerofrom-derive",
-]
-
-[[package]]
-name = "zerofrom-derive"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
- "synstructure",
-]
-
-[[package]]
-name = "zerotrie"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
-dependencies = [
- "displaydoc",
- "yoke",
- "zerofrom",
-]
-
-[[package]]
-name = "zerovec"
-version = "0.11.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
-dependencies = [
- "yoke",
- "zerofrom",
- "zerovec-derive",
-]
-
-[[package]]
-name = "zerovec-derive"
-version = "0.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "zmij"
-version = "1.0.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/libs/fleet/sdk-core/Cargo.toml b/libs/fleet/sdk-core/Cargo.toml
deleted file mode 100644
index 4ab17c1e69..0000000000
--- a/libs/fleet/sdk-core/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-[package]
-name = "cyclops-sdk-core"
-version = "0.1.0"
-edition = "2021"
-license = "MIT"
-
-[lib]
-crate-type = ["cdylib", "rlib"]
-
-[[bin]]
-name = "cyclops-core-runner"
-path = "src/core_runner.rs"
-
-[dependencies]
-serde = { version = "1.0.217", features = ["derive"] }
-serde_json = "1.0.138"
-thiserror = "2.0.11"
-url = "2.5.8"
-wit-bindgen = "0.39.0"
diff --git a/libs/fleet/sdk-core/README.md b/libs/fleet/sdk-core/README.md
deleted file mode 100644
index c033b23a88..0000000000
--- a/libs/fleet/sdk-core/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Cyclops SDK core
-
-The Rust core owns typed pool and claim CRUD, porcelain defaults, claim polling, service endpoint resolution, OAuth token caching and refresh, authenticated HTTP execution, and one retry after `401`. Bindings never receive bearer tokens or service endpoint URLs.
-
-Pool creation accepts `namespace + PoolSpec`, ensures the caller-owned namespace, and rolls the namespace back if pool creation fails. Pool deletion removes the pool before deleting its namespace. For nonzero replica pools, claim creation waits for an available sandbox before creating the claim. Zero-replica pools remain demand-driven. Claim creation accepts an optional generated `ClaimSpec`; otherwise, the core derives `<pool-name>-template`.
-
-`wait_claim` returns sandbox identity and the service names declared by its pool. `service_request` accepts that sandbox, one declared service name, and an HTTP request with a relative path. The core validates every route component, resolves the private control-plane route, applies managed authorization, performs the request, and refreshes the token once after `401`. Unknown-service errors include the requested name and sorted available names. No exported operation accepts an application-constructed URL.
-
-The native JSON-lines runner and WASM component expose the same typed resource and service HTTP operations. Language bindings provide transport adapters and idiomatic request surfaces only.
diff --git a/libs/fleet/sdk-core/src/client.rs b/libs/fleet/sdk-core/src/client.rs
deleted file mode 100644
index a08af33b14..0000000000
--- a/libs/fleet/sdk-core/src/client.rs
+++ /dev/null
@@ -1,752 +0,0 @@
-use crate::{
- validate_configuration, validate_name, Claim, ClaimSpec, Configuration, CreateClaimRequest,
- CreatePoolRequest, Pool, ResourceList, ResourceMetadata, Sandbox, SandboxTemplateRef,
-};
-use serde::{de::DeserializeOwned, Deserialize, Serialize};
-use serde_json::Value;
-use std::collections::BTreeMap;
-use thiserror::Error;
-use url::{form_urlencoded, Url as ParsedUrl};
-
-const TOKEN_EXPIRY_SKEW_MS: u64 = 30_000;
-const POOL_POLL_INTERVAL_MS: u64 = 5_000;
-const POOL_MAX_POLL_ATTEMPTS: u32 = 180;
-const CLAIM_POLL_INTERVAL_MS: u64 = 5_000;
-const CLAIM_MAX_POLL_ATTEMPTS: u32 = 180;
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct HttpRequest {
- pub method: String,
- pub url: String,
- pub headers: Vec<(String, String)>,
- pub body: Option<String>,
-}
-
-impl HttpRequest {
- pub fn get(url: impl Into<String>) -> Self {
- Self::new("GET", url, None)
- }
- pub fn post(url: impl Into<String>, body: impl Into<String>) -> Self {
- Self::new("POST", url, Some(body.into()))
- }
- pub fn put(url: impl Into<String>, body: impl Into<String>) -> Self {
- Self::new("PUT", url, Some(body.into()))
- }
- pub fn delete(url: impl Into<String>) -> Self {
- Self::new("DELETE", url, None)
- }
- pub fn new(method: impl Into<String>, url: impl Into<String>, body: Option<String>) -> Self {
- Self {
- method: method.into(),
- url: url.into(),
- headers: vec![
- ("accept".into(), "application/json".into()),
- ("content-type".into(), "application/json".into()),
- ],
- body,
- }
- }
- fn with_bearer(mut self, token: &str) -> Self {
- self.headers
- .retain(|(name, _)| !name.eq_ignore_ascii_case("authorization"));
- self.headers
- .push(("authorization".into(), format!("Bearer {token}")));
- self
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct HttpResponse {
- pub status: u16,
- pub body: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct ServiceHttpRequest {
- pub method: String,
- pub path: String,
- pub headers: Vec<(String, String)>,
- pub body: Option<String>,
-}
-
-impl ServiceHttpRequest {
- pub fn get(path: impl Into<String>) -> Self {
- Self::new("GET", path, None)
- }
- pub fn post(path: impl Into<String>, body: impl Into<String>) -> Self {
- Self::new("POST", path, Some(body.into()))
- }
- pub fn new(method: impl Into<String>, path: impl Into<String>, body: Option<String>) -> Self {
- Self {
- method: method.into(),
- path: path.into(),
- headers: Vec::new(),
- body,
- }
- }
-}
-
-pub type ServiceHttpResponse = HttpResponse;
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct OAuthCredentials {
- pub token_url: String,
- pub client_id: String,
- pub client_secret: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct AccessToken {
- pub value: String,
- pub expires_at_ms: u64,
-}
-
-#[derive(Debug, Clone, Error, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum PlatformError {
- #[error("transport error: {0}")]
- Transport(String),
- #[error("clock error: {0}")]
- Clock(String),
- #[error("credential error: {0}")]
- Credentials(String),
- #[error("token storage error: {0}")]
- TokenStorage(String),
-}
-
-pub trait Platform {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError>;
- fn sleep(&mut self, milliseconds: u64) -> Result<(), PlatformError>;
- fn now_ms(&mut self) -> u64;
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError>;
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError>;
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError>;
-}
-
-#[derive(Debug, Error, PartialEq, Eq)]
-pub enum SdkError {
- #[error("invalid configuration: {0}")]
- Configuration(String),
- #[error("transport error: {0}")]
- Transport(String),
- #[error("token error: {0}")]
- Token(String),
- #[error("response body error: {0}")]
- Body(String),
- #[error("{operation} returned HTTP {status}: {body}")]
- Status {
- operation: String,
- status: u16,
- body: String,
- },
- #[error("pool entered terminal phase {phase}: {status}")]
- PoolFailed { phase: String, status: String },
- #[error("pool did not become available before the polling limit")]
- PoolTimeout,
- #[error("claim entered terminal phase {phase}: {status}")]
- ClaimFailed { phase: String, status: String },
- #[error("claim did not bind before the polling limit")]
- ClaimTimeout,
- #[error("unknown sandbox service {requested:?}; available services: {available:?}")]
- UnknownService {
- requested: String,
- available: Vec<String>,
- },
- #[error("service request path must be relative and start with '/': {0}")]
- InvalidServicePath(String),
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Url(String);
-impl Url {
- pub fn as_str(&self) -> &str {
- &self.0
- }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct PoolUrl {
- collection: Url,
- item: Url,
-}
-impl PoolUrl {
- pub fn new(base: &str, namespace: &str, name: &str) -> Result<Self, SdkError> {
- validate_url_parts(base, namespace, name)?;
- let collection = format!(
- "{}/api/k8s/apis/cua.ai/v1/namespaces/{namespace}/osgymworkspacepools",
- base.trim_end_matches('/')
- );
- Ok(Self {
- item: Url(format!("{collection}/{name}")),
- collection: Url(collection),
- })
- }
- pub fn collection(&self) -> &Url {
- &self.collection
- }
- pub fn item(&self) -> &Url {
- &self.item
- }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ClaimUrl {
- collection: Url,
- item: Url,
-}
-impl ClaimUrl {
- pub fn new(base: &str, namespace: &str, name: &str) -> Result<Self, SdkError> {
- validate_url_parts(base, namespace, name)?;
- let collection = format!(
- "{}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/{namespace}/osgymsandboxclaims",
- base.trim_end_matches('/')
- );
- Ok(Self {
- item: Url(format!("{collection}/{name}")),
- collection: Url(collection),
- })
- }
- pub fn collection(&self) -> &Url {
- &self.collection
- }
- pub fn item(&self) -> &Url {
- &self.item
- }
-}
-
-pub struct Sdk<P> {
- platform: P,
- configuration: Configuration,
- next_claim_id: u64,
- claim_services: BTreeMap<String, Vec<String>>,
-}
-
-impl<P: Platform> Sdk<P> {
- pub fn connect(platform: P, configuration: Configuration) -> Result<Self, SdkError> {
- validate_configuration(&configuration)
- .map_err(|error| SdkError::Configuration(error.to_string()))?;
- Ok(Self {
- platform,
- configuration,
- next_claim_id: 0,
- claim_services: BTreeMap::new(),
- })
- }
- pub fn platform(&self) -> &P {
- &self.platform
- }
- pub fn platform_mut(&mut self) -> &mut P {
- &mut self.platform
- }
- pub fn into_platform(self) -> P {
- self.platform
- }
- pub fn service_request(
- &mut self,
- sandbox: &Sandbox,
- service: &str,
- request: ServiceHttpRequest,
- ) -> Result<ServiceHttpResponse, SdkError> {
- validate_service(sandbox, service)?;
- let url = service_url(
- &self.configuration.base_url,
- sandbox,
- service,
- &request.path,
- )?;
- let mut headers = request.headers;
- headers.retain(|(name, _)| !is_transport_owned_header(name));
- self.send_raw(HttpRequest {
- method: request.method,
- url,
- headers,
- body: request.body,
- })
- }
-
- pub fn create_pool(&mut self, request: CreatePoolRequest) -> Result<Pool, SdkError> {
- validate_name(&request.namespace)
- .map_err(|error| SdkError::Configuration(error.to_string()))?;
- let namespace = request.namespace.clone();
- let namespace_created = self.ensure_namespace(&namespace)?;
- let pool = Pool {
- api_version: "cua.ai/v1".into(),
- kind: "OSGymWorkspacePool".into(),
- metadata: ResourceMetadata {
- namespace: namespace.clone(),
- name: request.namespace,
- labels: None,
- },
- spec: serde_json::to_value(request.spec)
- .map_err(|error| SdkError::Body(error.to_string()))?,
- status: None,
- };
- let url = self.pool_url(&pool)?;
- let result = self.send_json(
- "create pool",
- HttpRequest::post(url.collection().as_str(), to_json(&pool)?),
- &[200, 201, 202],
- );
- if result.is_err() && namespace_created {
- let _ = self.delete_namespace(&namespace);
- }
- result
- }
- pub fn list_pools(&mut self, namespace: &str) -> Result<Vec<Pool>, SdkError> {
- let url = PoolUrl::new(&self.configuration.base_url, namespace, "list")?;
- let list: ResourceList<Pool> = self.send_json(
- "list pools",
- HttpRequest::get(url.collection().as_str()),
- &[200],
- )?;
- Ok(list.items)
- }
- pub fn get_pool(&mut self, pool: Pool) -> Result<Pool, SdkError> {
- let url = self.pool_url(&pool)?;
- self.send_json("get pool", HttpRequest::get(url.item().as_str()), &[200])
- }
- pub fn update_pool(&mut self, pool: Pool) -> Result<Pool, SdkError> {
- let url = self.pool_url(&pool)?;
- self.send_json(
- "update pool",
- HttpRequest::put(url.item().as_str(), to_json(&pool)?),
- &[200],
- )
- }
- pub fn delete_pool(&mut self, pool: Pool) -> Result<(), SdkError> {
- let namespace = pool.metadata.namespace.clone();
- let url = self.pool_url(&pool)?;
- self.send_unit(
- "delete pool",
- HttpRequest::delete(url.item().as_str()),
- &[200, 202, 204, 404],
- )?;
- self.delete_namespace(&namespace)
- }
- pub fn create_claim(&mut self, request: CreateClaimRequest) -> Result<Claim, SdkError> {
- let CreateClaimRequest { pool, spec } = request;
- let requested_replicas = pool
- .spec
- .get("replicas")
- .and_then(Value::as_u64)
- .unwrap_or(0);
- let pool = if requested_replicas > 0 {
- self.wait_pool_ready(pool)?
- } else {
- pool
- };
- let services = service_names(&pool);
- let namespace = pool.metadata.namespace;
- let pool_name = pool.metadata.name;
- validate_name(&namespace).map_err(|error| SdkError::Configuration(error.to_string()))?;
- validate_name(&pool_name).map_err(|error| SdkError::Configuration(error.to_string()))?;
- let spec = match spec {
- Some(spec) => spec,
- None => ClaimSpec::builder()
- .sandbox_template_ref(
- SandboxTemplateRef::builder()
- .name(format!("{pool_name}-template"))
- .build()
- .map_err(SdkError::Configuration)?,
- )
- .build()
- .map_err(SdkError::Configuration)?,
- };
- validate_name(&spec.sandbox_template_ref.name)
- .map_err(|error| SdkError::Configuration(error.to_string()))?;
- let claim_id = self.next_claim_id;
- self.next_claim_id = self.next_claim_id.wrapping_add(1);
- let claim = Claim {
- api_version: "osgym.cua.ai/v1alpha1".into(),
- kind: "OSGymSandboxClaim".into(),
- metadata: ResourceMetadata {
- namespace,
- name: format!("claim-{:x}-{claim_id:x}", self.platform.now_ms()),
- labels: None,
- },
- spec: serde_json::to_value(spec).map_err(|error| SdkError::Body(error.to_string()))?,
- status: None,
- };
- let url = self.claim_url(&claim)?;
- let created = self.send_json(
- "create claim",
- HttpRequest::post(url.collection().as_str(), to_json(&claim)?),
- &[200, 201, 202],
- )?;
- self.claim_services.insert(claim_key(&created), services);
- Ok(created)
- }
- pub fn list_claims(&mut self, namespace: &str) -> Result<Vec<Claim>, SdkError> {
- let url = ClaimUrl::new(&self.configuration.base_url, namespace, "list")?;
- let list: ResourceList<Claim> = self.send_json(
- "list claims",
- HttpRequest::get(url.collection().as_str()),
- &[200],
- )?;
- Ok(list.items)
- }
- pub fn get_claim(&mut self, claim: Claim) -> Result<Claim, SdkError> {
- let url = self.claim_url(&claim)?;
- self.send_json("get claim", HttpRequest::get(url.item().as_str()), &[200])
- }
- pub fn update_claim(&mut self, claim: Claim) -> Result<Claim, SdkError> {
- let url = self.claim_url(&claim)?;
- self.send_json(
- "update claim",
- HttpRequest::put(url.item().as_str(), to_json(&claim)?),
- &[200],
- )
- }
- pub fn delete_claim(&mut self, claim: Claim) -> Result<(), SdkError> {
- let key = claim_key(&claim);
- let url = self.claim_url(&claim)?;
- self.send_unit(
- "delete claim",
- HttpRequest::delete(url.item().as_str()),
- &[200, 202, 204, 404],
- )?;
- self.claim_services.remove(&key);
- Ok(())
- }
- pub fn wait_claim(&mut self, claim: Claim) -> Result<Sandbox, SdkError> {
- let services = self.services_for_claim(&claim)?;
- for _ in 0..CLAIM_MAX_POLL_ATTEMPTS {
- let current = self.get_claim(claim.clone())?;
- let phase = current
- .status
- .as_ref()
- .and_then(|status| status.get("phase"))
- .and_then(Value::as_str)
- .unwrap_or("Pending");
- if phase == "Bound" {
- return sandbox_from_claim(&current, services.clone());
- }
- if matches!(phase, "Failed" | "Error" | "Expired") {
- return Err(SdkError::ClaimFailed {
- phase: phase.into(),
- status: current
- .status
- .as_ref()
- .map(Value::to_string)
- .unwrap_or_else(|| "null".into()),
- });
- }
- self.platform
- .sleep(CLAIM_POLL_INTERVAL_MS)
- .map_err(map_platform_error)?;
- }
- Err(SdkError::ClaimTimeout)
- }
-
- fn services_for_claim(&mut self, claim: &Claim) -> Result<Vec<String>, SdkError> {
- if let Some(services) = self.claim_services.get(&claim_key(claim)) {
- return Ok(services.clone());
- }
- let template = claim
- .spec
- .get("sandboxTemplateRef")
- .and_then(|value| value.get("name"))
- .and_then(Value::as_str)
- .ok_or_else(|| SdkError::Body("claim omitted spec.sandboxTemplateRef.name".into()))?;
- let pool_name = template.strip_suffix("-template").ok_or_else(|| {
- SdkError::Body(format!("cannot resolve pool from template {template:?}"))
- })?;
- let url = PoolUrl::new(
- &self.configuration.base_url,
- &claim.metadata.namespace,
- pool_name,
- )?;
- let pool: Pool = self.send_json(
- "get pool services",
- HttpRequest::get(url.item().as_str()),
- &[200],
- )?;
- Ok(service_names(&pool))
- }
-
- fn wait_pool_ready(&mut self, pool: Pool) -> Result<Pool, SdkError> {
- for _ in 0..POOL_MAX_POLL_ATTEMPTS {
- let current = self.get_pool(pool.clone())?;
- let status = current.status.as_ref();
- let available = status
- .and_then(|value| value.get("availableCount"))
- .and_then(Value::as_u64)
- .unwrap_or(0);
- if available > 0 {
- return Ok(current);
- }
- let phase = status
- .and_then(|value| value.get("phase"))
- .and_then(Value::as_str)
- .unwrap_or("Provisioning");
- if matches!(phase, "Failed" | "Error") {
- return Err(SdkError::PoolFailed {
- phase: phase.into(),
- status: status
- .map(Value::to_string)
- .unwrap_or_else(|| "null".into()),
- });
- }
- self.platform
- .sleep(POOL_POLL_INTERVAL_MS)
- .map_err(map_platform_error)?;
- }
- Err(SdkError::PoolTimeout)
- }
-
- fn ensure_namespace(&mut self, name: &str) -> Result<bool, SdkError> {
- validate_name(name).map_err(|error| SdkError::Configuration(error.to_string()))?;
- let url = format!(
- "{}/api/namespaces",
- self.configuration.base_url.trim_end_matches('/')
- );
- let response = self.send_allowed(
- "create namespace",
- HttpRequest::post(url, to_json(&serde_json::json!({ "name": name }))?),
- &[200, 201, 202, 409],
- )?;
- Ok(response.status != 409)
- }
- fn delete_namespace(&mut self, name: &str) -> Result<(), SdkError> {
- validate_name(name).map_err(|error| SdkError::Configuration(error.to_string()))?;
- let url = format!(
- "{}/api/namespaces/{name}",
- self.configuration.base_url.trim_end_matches('/')
- );
- self.send_unit(
- "delete namespace",
- HttpRequest::delete(url),
- &[200, 202, 204, 404],
- )
- }
-
- fn pool_url(&self, pool: &Pool) -> Result<PoolUrl, SdkError> {
- PoolUrl::new(
- &self.configuration.base_url,
- &pool.metadata.namespace,
- &pool.metadata.name,
- )
- }
- fn claim_url(&self, claim: &Claim) -> Result<ClaimUrl, SdkError> {
- ClaimUrl::new(
- &self.configuration.base_url,
- &claim.metadata.namespace,
- &claim.metadata.name,
- )
- }
- fn send_json<T: DeserializeOwned>(
- &mut self,
- operation: &str,
- request: HttpRequest,
- allowed: &[u16],
- ) -> Result<T, SdkError> {
- let response = self.send_allowed(operation, request, allowed)?;
- serde_json::from_str(&response.body).map_err(|error| SdkError::Body(error.to_string()))
- }
- fn send_unit(
- &mut self,
- operation: &str,
- request: HttpRequest,
- allowed: &[u16],
- ) -> Result<(), SdkError> {
- self.send_allowed(operation, request, allowed).map(|_| ())
- }
- fn send_allowed(
- &mut self,
- operation: &str,
- request: HttpRequest,
- allowed: &[u16],
- ) -> Result<HttpResponse, SdkError> {
- let response = self.send_raw(request)?;
- if allowed.contains(&response.status) {
- Ok(response)
- } else {
- Err(status_error(operation, response))
- }
- }
- fn send_raw(&mut self, request: HttpRequest) -> Result<HttpResponse, SdkError> {
- if !same_origin(&self.configuration.base_url, &request.url) {
- return self.platform.http(request).map_err(map_platform_error);
- }
- let token = self.access_token(false)?;
- let response = self
- .platform
- .http(request.clone().with_bearer(&token.value))
- .map_err(map_platform_error)?;
- if response.status != 401 {
- return Ok(response);
- }
- let refreshed = self.access_token(true)?;
- self.platform
- .http(request.with_bearer(&refreshed.value))
- .map_err(map_platform_error)
- }
- fn access_token(&mut self, force_refresh: bool) -> Result<AccessToken, SdkError> {
- let now = self.platform.now_ms();
- if !force_refresh {
- if let Some(token) = self
- .platform
- .load_access_token()
- .map_err(map_platform_error)?
- {
- if token.expires_at_ms > now.saturating_add(TOKEN_EXPIRY_SKEW_MS) {
- return Ok(token);
- }
- }
- }
- let credentials = self
- .platform
- .acquire_oauth_credentials()
- .map_err(map_platform_error)?;
- let body = form_urlencoded::Serializer::new(String::new())
- .append_pair("grant_type", "client_credentials")
- .append_pair("client_id", &credentials.client_id)
- .append_pair("client_secret", &credentials.client_secret)
- .finish();
- let mut request = HttpRequest::post(credentials.token_url, body);
- request.headers = vec![
- ("accept".into(), "application/json".into()),
- (
- "content-type".into(),
- "application/x-www-form-urlencoded".into(),
- ),
- ];
- let response = self.platform.http(request).map_err(map_platform_error)?;
- if !(200..300).contains(&response.status) {
- return Err(status_error("acquire OAuth token", response));
- }
- #[derive(Deserialize)]
- struct TokenResponse {
- access_token: String,
- expires_in: u64,
- }
- let body: TokenResponse = serde_json::from_str(&response.body)
- .map_err(|error| SdkError::Token(error.to_string()))?;
- let token = AccessToken {
- value: body.access_token,
- expires_at_ms: now.saturating_add(body.expires_in.saturating_mul(1_000)),
- };
- self.platform
- .store_access_token(&token)
- .map_err(map_platform_error)?;
- Ok(token)
- }
-}
-
-fn same_origin(base: &str, request: &str) -> bool {
- match (ParsedUrl::parse(base), ParsedUrl::parse(request)) {
- (Ok(base), Ok(request)) => base.origin() == request.origin(),
- _ => false,
- }
-}
-fn validate_url_parts(base: &str, namespace: &str, name: &str) -> Result<(), SdkError> {
- if !(base.starts_with("http://") || base.starts_with("https://")) {
- return Err(SdkError::Configuration(
- "base_url must use http or https".into(),
- ));
- }
- validate_name(namespace).map_err(|error| SdkError::Configuration(error.to_string()))?;
- validate_name(name).map_err(|error| SdkError::Configuration(error.to_string()))
-}
-fn to_json<T: Serialize>(value: &T) -> Result<String, SdkError> {
- serde_json::to_string(value).map_err(|error| SdkError::Body(error.to_string()))
-}
-fn status_error(operation: &str, response: HttpResponse) -> SdkError {
- SdkError::Status {
- operation: operation.into(),
- status: response.status,
- body: response.body,
- }
-}
-fn map_platform_error(error: PlatformError) -> SdkError {
- SdkError::Transport(error.to_string())
-}
-fn claim_key(claim: &Claim) -> String {
- format!("{}/{}", claim.metadata.namespace, claim.metadata.name)
-}
-
-fn service_names(pool: &Pool) -> Vec<String> {
- let mut services = pool
- .spec
- .get("services")
- .and_then(Value::as_array)
- .into_iter()
- .flatten()
- .filter_map(|service| service.get("name").and_then(Value::as_str))
- .map(str::to_owned)
- .collect::<Vec<_>>();
- services.sort();
- services.dedup();
- services
-}
-
-fn validate_service(sandbox: &Sandbox, service: &str) -> Result<(), SdkError> {
- if sandbox
- .services
- .iter()
- .any(|available| available == service)
- {
- return Ok(());
- }
- let mut available = sandbox.services.clone();
- available.sort();
- available.dedup();
- Err(SdkError::UnknownService {
- requested: service.into(),
- available,
- })
-}
-
-fn is_transport_owned_header(name: &str) -> bool {
- matches!(
- name.to_ascii_lowercase().as_str(),
- "host"
- | "connection"
- | "proxy-authorization"
- | "proxy-connection"
- | "te"
- | "trailer"
- | "transfer-encoding"
- | "upgrade"
- )
-}
-
-fn service_url(
- base_url: &str,
- sandbox: &Sandbox,
- service: &str,
- path: &str,
-) -> Result<String, SdkError> {
- validate_url_parts(base_url, &sandbox.namespace, &sandbox.sandbox)?;
- validate_name(service).map_err(|error| SdkError::Configuration(error.to_string()))?;
- if !path.starts_with('/') || path.starts_with("//") || path.contains('#') {
- return Err(SdkError::InvalidServicePath(path.into()));
- }
- Ok(format!(
- "{}/api/svc/{}/{}-{}{}",
- base_url.trim_end_matches('/'),
- sandbox.namespace,
- sandbox.sandbox,
- service,
- path
- ))
-}
-
-fn sandbox_from_claim(claim: &Claim, services: Vec<String>) -> Result<Sandbox, SdkError> {
- let status = claim
- .status
- .as_ref()
- .ok_or_else(|| SdkError::Body("bound claim omitted status".into()))?;
- let sandbox = status
- .get("sandbox")
- .and_then(|value| value.get("name"))
- .and_then(Value::as_str)
- .ok_or_else(|| SdkError::Body("bound claim omitted status.sandbox.name".into()))?
- .to_string();
- Ok(Sandbox {
- namespace: claim.metadata.namespace.clone(),
- claim: claim.metadata.name.clone(),
- sandbox,
- services,
- })
-}
diff --git a/libs/fleet/sdk-core/src/core_runner.rs b/libs/fleet/sdk-core/src/core_runner.rs
deleted file mode 100644
index ce5ad10ccb..0000000000
--- a/libs/fleet/sdk-core/src/core_runner.rs
+++ /dev/null
@@ -1,232 +0,0 @@
-use cyclops_sdk_core::{
- AccessToken, Claim, Configuration, CreateClaimRequest, CreatePoolRequest, HttpRequest,
- HttpResponse, OAuthCredentials, Platform, PlatformError, Pool, Sandbox, Sdk,
- ServiceHttpRequest,
-};
-use serde::{de::DeserializeOwned, Deserialize, Serialize};
-use std::io::{self, BufRead, Write};
-
-#[derive(Deserialize)]
-#[serde(tag = "op", rename_all = "snake_case")]
-enum Request {
- Configure {
- configuration: Configuration,
- },
- CreatePool {
- request: Box<CreatePoolRequest>,
- },
- ListPools {
- namespace: String,
- },
- GetPool {
- pool: Pool,
- },
- UpdatePool {
- pool: Pool,
- },
- DeletePool {
- pool: Pool,
- },
- CreateClaim {
- request: Box<CreateClaimRequest>,
- },
- ListClaims {
- namespace: String,
- },
- GetClaim {
- claim: Claim,
- },
- UpdateClaim {
- claim: Claim,
- },
- DeleteClaim {
- claim: Claim,
- },
- WaitClaim {
- claim: Claim,
- },
- #[serde(rename = "service_request")]
- ServiceHttp {
- sandbox: Sandbox,
- service: String,
- request: ServiceHttpRequest,
- },
-}
-
-#[derive(Serialize)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-enum HostCall<'a> {
- Http { request: HttpRequest },
- Sleep { milliseconds: u64 },
- NowMs,
- AcquireOauthCredentials,
- LoadAccessToken,
- StoreAccessToken { token: &'a AccessToken },
-}
-
-#[derive(Deserialize)]
-struct HostReply {
- ok: bool,
- value: serde_json::Value,
- error: Option<PlatformError>,
-}
-#[derive(Serialize)]
-struct Reply<T> {
- ok: bool,
- value: Option<T>,
- error: Option<String>,
-}
-struct RpcPlatform<R, W> {
- input: R,
- output: W,
-}
-
-impl<R: BufRead, W: Write> RpcPlatform<R, W> {
- fn read_request(&mut self) -> Result<Option<Request>, String> {
- let mut line = String::new();
- if self
- .input
- .read_line(&mut line)
- .map_err(|error| error.to_string())?
- == 0
- {
- return Ok(None);
- }
- serde_json::from_str(&line)
- .map(Some)
- .map_err(|error| error.to_string())
- }
- fn write_reply<T: Serialize>(&mut self, reply: &Reply<T>) -> Result<(), String> {
- serde_json::to_writer(&mut self.output, reply).map_err(|error| error.to_string())?;
- writeln!(self.output).map_err(|error| error.to_string())?;
- self.output.flush().map_err(|error| error.to_string())
- }
- fn call<T: DeserializeOwned>(&mut self, call: HostCall<'_>) -> Result<T, PlatformError> {
- serde_json::to_writer(&mut self.output, &call)
- .map_err(|error| PlatformError::Transport(error.to_string()))?;
- writeln!(self.output).map_err(|error| PlatformError::Transport(error.to_string()))?;
- self.output
- .flush()
- .map_err(|error| PlatformError::Transport(error.to_string()))?;
- let mut line = String::new();
- self.input
- .read_line(&mut line)
- .map_err(|error| PlatformError::Transport(error.to_string()))?;
- if line.is_empty() {
- return Err(PlatformError::Transport("host adapter exited".into()));
- }
- let reply: HostReply = serde_json::from_str(&line)
- .map_err(|error| PlatformError::Transport(format!("invalid host reply: {error}")))?;
- if reply.ok {
- serde_json::from_value(reply.value).map_err(|error| {
- PlatformError::Transport(format!("invalid host reply value: {error}"))
- })
- } else {
- Err(reply
- .error
- .unwrap_or_else(|| PlatformError::Transport("host reply omitted error".into())))
- }
- }
- fn call_unit(&mut self, call: HostCall<'_>) -> Result<(), PlatformError> {
- let _: serde_json::Value = self.call(call)?;
- Ok(())
- }
-}
-
-impl<R: BufRead, W: Write> Platform for RpcPlatform<R, W> {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError> {
- self.call(HostCall::Http { request })
- }
- fn sleep(&mut self, milliseconds: u64) -> Result<(), PlatformError> {
- self.call_unit(HostCall::Sleep { milliseconds })
- }
- fn now_ms(&mut self) -> u64 {
- self.call(HostCall::NowMs).unwrap_or(0)
- }
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError> {
- self.call(HostCall::AcquireOauthCredentials)
- }
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError> {
- self.call(HostCall::LoadAccessToken)
- }
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError> {
- self.call_unit(HostCall::StoreAccessToken { token })
- }
-}
-
-fn reply<T: Serialize>(result: Result<T, cyclops_sdk_core::SdkError>) -> Reply<T> {
- match result {
- Ok(value) => Reply {
- ok: true,
- value: Some(value),
- error: None,
- },
- Err(error) => Reply {
- ok: false,
- value: None,
- error: Some(error.to_string()),
- },
- }
-}
-
-fn main() -> Result<(), String> {
- let stdin = io::stdin();
- let stdout = io::stdout();
- let mut platform = RpcPlatform {
- input: stdin.lock(),
- output: stdout.lock(),
- };
- let configuration = match platform.read_request()? {
- Some(Request::Configure { configuration }) => configuration,
- Some(_) => return Err("first request must configure the SDK".into()),
- None => return Ok(()),
- };
- let mut sdk = Sdk::connect(platform, configuration).map_err(|error| error.to_string())?;
- sdk.platform_mut().write_reply(&Reply {
- ok: true,
- value: Some(()),
- error: None,
- })?;
- while let Some(request) = sdk.platform_mut().read_request()? {
- let response = match request {
- Request::Configure { .. } => serde_json::to_value(Reply::<()> {
- ok: false,
- value: None,
- error: Some("SDK is already configured".into()),
- }),
- Request::CreatePool { request } => {
- serde_json::to_value(reply(sdk.create_pool(*request)))
- }
- Request::ListPools { namespace } => {
- serde_json::to_value(reply(sdk.list_pools(&namespace)))
- }
- Request::GetPool { pool } => serde_json::to_value(reply(sdk.get_pool(pool))),
- Request::UpdatePool { pool } => serde_json::to_value(reply(sdk.update_pool(pool))),
- Request::DeletePool { pool } => serde_json::to_value(reply(sdk.delete_pool(pool))),
- Request::CreateClaim { request } => {
- serde_json::to_value(reply(sdk.create_claim(*request)))
- }
- Request::ListClaims { namespace } => {
- serde_json::to_value(reply(sdk.list_claims(&namespace)))
- }
- Request::GetClaim { claim } => serde_json::to_value(reply(sdk.get_claim(claim))),
- Request::UpdateClaim { claim } => serde_json::to_value(reply(sdk.update_claim(claim))),
- Request::DeleteClaim { claim } => serde_json::to_value(reply(sdk.delete_claim(claim))),
- Request::WaitClaim { claim } => serde_json::to_value(reply(sdk.wait_claim(claim))),
- Request::ServiceHttp {
- sandbox,
- service,
- request,
- } => serde_json::to_value(reply(sdk.service_request(&sandbox, &service, request))),
- }
- .map_err(|error| error.to_string())?;
- serde_json::to_writer(&mut sdk.platform_mut().output, &response)
- .map_err(|error| error.to_string())?;
- writeln!(sdk.platform_mut().output).map_err(|error| error.to_string())?;
- sdk.platform_mut()
- .output
- .flush()
- .map_err(|error| error.to_string())?;
- }
- Ok(())
-}
diff --git a/libs/fleet/sdk-core/src/generated_crd.rs b/libs/fleet/sdk-core/src/generated_crd.rs
deleted file mode 100644
index 7f56e45f2c..0000000000
--- a/libs/fleet/sdk-core/src/generated_crd.rs
+++ /dev/null
@@ -1,516 +0,0 @@
-// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct ClaimSpec {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "bindDeadline")]
- pub bind_deadline: Option<u32>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "lifecycle")]
- pub lifecycle: Option<ClaimSpecLifecycle>,
- #[serde(rename = "sandboxTemplateRef")]
- pub sandbox_template_ref: SandboxTemplateRef,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "warmpool")]
- pub warmpool: Option<String>,
-}
-
-impl ClaimSpec {
- pub fn builder() -> ClaimSpecBuilder {
- ClaimSpecBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct ClaimSpecBuilder {
- bind_deadline: Option<u32>,
- lifecycle: Option<ClaimSpecLifecycle>,
- sandbox_template_ref: Option<SandboxTemplateRef>,
- warmpool: Option<String>,
-}
-
-impl ClaimSpecBuilder {
- pub fn bind_deadline(mut self, value: u32) -> Self {
- self.bind_deadline = Some(value);
- self
- }
- pub fn lifecycle(mut self, value: ClaimSpecLifecycle) -> Self {
- self.lifecycle = Some(value);
- self
- }
- pub fn sandbox_template_ref(mut self, value: SandboxTemplateRef) -> Self {
- self.sandbox_template_ref = Some(value);
- self
- }
- pub fn warmpool(mut self, value: String) -> Self {
- self.warmpool = Some(value);
- self
- }
- pub fn build(self) -> Result<ClaimSpec, String> {
- Ok(ClaimSpec {
- bind_deadline: self.bind_deadline,
- lifecycle: self.lifecycle,
- sandbox_template_ref: self
- .sandbox_template_ref
- .ok_or_else(|| "sandboxTemplateRef is required".to_string())?,
- warmpool: self.warmpool,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct ClaimSpecLifecycle {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "autoRenew")]
- pub auto_renew: Option<bool>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "shutdownPolicy")]
- pub shutdown_policy: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "shutdownTime")]
- pub shutdown_time: Option<String>,
-}
-
-impl ClaimSpecLifecycle {
- pub fn builder() -> ClaimSpecLifecycleBuilder {
- ClaimSpecLifecycleBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct ClaimSpecLifecycleBuilder {
- auto_renew: Option<bool>,
- shutdown_policy: Option<String>,
- shutdown_time: Option<String>,
-}
-
-impl ClaimSpecLifecycleBuilder {
- pub fn auto_renew(mut self, value: bool) -> Self {
- self.auto_renew = Some(value);
- self
- }
- pub fn shutdown_policy(mut self, value: String) -> Self {
- self.shutdown_policy = Some(value);
- self
- }
- pub fn shutdown_time(mut self, value: String) -> Self {
- self.shutdown_time = Some(value);
- self
- }
- pub fn build(self) -> Result<ClaimSpecLifecycle, String> {
- Ok(ClaimSpecLifecycle {
- auto_renew: self.auto_renew,
- shutdown_policy: self.shutdown_policy,
- shutdown_time: self.shutdown_time,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PoolSpec {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "autoscaling")]
- pub autoscaling: Option<PoolSpecAutoscaling>,
- #[serde(rename = "replicas")]
- pub replicas: u32,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "services")]
- pub services: Option<Vec<PoolSpecService>>,
- #[serde(rename = "template")]
- pub template: PoolTemplate,
-}
-
-impl PoolSpec {
- pub fn builder() -> PoolSpecBuilder {
- PoolSpecBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct PoolSpecBuilder {
- autoscaling: Option<PoolSpecAutoscaling>,
- replicas: Option<u32>,
- services: Option<Vec<PoolSpecService>>,
- template: Option<PoolTemplate>,
-}
-
-impl PoolSpecBuilder {
- pub fn autoscaling(mut self, value: PoolSpecAutoscaling) -> Self {
- self.autoscaling = Some(value);
- self
- }
- pub fn replicas(mut self, value: u32) -> Self {
- self.replicas = Some(value);
- self
- }
- pub fn services(mut self, value: Vec<PoolSpecService>) -> Self {
- self.services = Some(value);
- self
- }
- pub fn template(mut self, value: PoolTemplate) -> Self {
- self.template = Some(value);
- self
- }
- pub fn build(self) -> Result<PoolSpec, String> {
- Ok(PoolSpec {
- autoscaling: self.autoscaling,
- replicas: self
- .replicas
- .ok_or_else(|| "replicas is required".to_string())?,
- services: self.services,
- template: self
- .template
- .ok_or_else(|| "template is required".to_string())?,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PoolSpecAutoscaling {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "initialPoolSize")]
- pub initial_pool_size: Option<u32>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "maxPoolSize")]
- pub max_pool_size: Option<u32>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "minPoolSize")]
- pub min_pool_size: Option<u32>,
-}
-
-impl PoolSpecAutoscaling {
- pub fn builder() -> PoolSpecAutoscalingBuilder {
- PoolSpecAutoscalingBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct PoolSpecAutoscalingBuilder {
- initial_pool_size: Option<u32>,
- max_pool_size: Option<u32>,
- min_pool_size: Option<u32>,
-}
-
-impl PoolSpecAutoscalingBuilder {
- pub fn initial_pool_size(mut self, value: u32) -> Self {
- self.initial_pool_size = Some(value);
- self
- }
- pub fn max_pool_size(mut self, value: u32) -> Self {
- self.max_pool_size = Some(value);
- self
- }
- pub fn min_pool_size(mut self, value: u32) -> Self {
- self.min_pool_size = Some(value);
- self
- }
- pub fn build(self) -> Result<PoolSpecAutoscaling, String> {
- Ok(PoolSpecAutoscaling {
- initial_pool_size: self.initial_pool_size,
- max_pool_size: self.max_pool_size,
- min_pool_size: self.min_pool_size,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PoolSpecService {
- #[serde(rename = "name")]
- pub name: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "protocol")]
- pub protocol: Option<PoolSpecServiceProtocol>,
- #[serde(rename = "targetPort")]
- pub target_port: u32,
-}
-
-impl PoolSpecService {
- pub fn builder() -> PoolSpecServiceBuilder {
- PoolSpecServiceBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct PoolSpecServiceBuilder {
- name: Option<String>,
- protocol: Option<PoolSpecServiceProtocol>,
- target_port: Option<u32>,
-}
-
-impl PoolSpecServiceBuilder {
- pub fn name(mut self, value: String) -> Self {
- self.name = Some(value);
- self
- }
- pub fn protocol(mut self, value: PoolSpecServiceProtocol) -> Self {
- self.protocol = Some(value);
- self
- }
- pub fn target_port(mut self, value: u32) -> Self {
- self.target_port = Some(value);
- self
- }
- pub fn build(self) -> Result<PoolSpecService, String> {
- Ok(PoolSpecService {
- name: self.name.ok_or_else(|| "name is required".to_string())?,
- protocol: self.protocol,
- target_port: self
- .target_port
- .ok_or_else(|| "targetPort is required".to_string())?,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub enum PoolSpecServiceProtocol {
- #[serde(rename = "TCP")]
- TCP,
- #[serde(rename = "UDP")]
- UDP,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PoolTemplate {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "command")]
- pub command: Option<Vec<String>>,
- #[serde(rename = "containerDiskImage")]
- pub container_disk_image: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "cpuCores")]
- pub cpu_cores: Option<u32>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "firmware")]
- pub firmware: Option<PoolTemplateFirmware>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "imagePullSecret")]
- pub image_pull_secret: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "memory")]
- pub memory: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "nodeSelector")]
- pub node_selector: Option<std::collections::BTreeMap<String, String>>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "oidc")]
- pub oidc: Option<PoolTemplateOidc>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "probes")]
- pub probes: Option<serde_json::Value>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "runtime")]
- pub runtime: Option<PoolTemplateRuntime>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "runtimeClassName")]
- pub runtime_class_name: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "tolerations")]
- pub tolerations: Option<Vec<serde_json::Value>>,
-}
-
-impl PoolTemplate {
- pub fn builder() -> PoolTemplateBuilder {
- PoolTemplateBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct PoolTemplateBuilder {
- command: Option<Vec<String>>,
- container_disk_image: Option<String>,
- cpu_cores: Option<u32>,
- firmware: Option<PoolTemplateFirmware>,
- image_pull_secret: Option<String>,
- memory: Option<String>,
- node_selector: Option<std::collections::BTreeMap<String, String>>,
- oidc: Option<PoolTemplateOidc>,
- probes: Option<serde_json::Value>,
- runtime: Option<PoolTemplateRuntime>,
- runtime_class_name: Option<String>,
- tolerations: Option<Vec<serde_json::Value>>,
-}
-
-impl PoolTemplateBuilder {
- pub fn command(mut self, value: Vec<String>) -> Self {
- self.command = Some(value);
- self
- }
- pub fn container_disk_image(mut self, value: String) -> Self {
- self.container_disk_image = Some(value);
- self
- }
- pub fn cpu_cores(mut self, value: u32) -> Self {
- self.cpu_cores = Some(value);
- self
- }
- pub fn firmware(mut self, value: PoolTemplateFirmware) -> Self {
- self.firmware = Some(value);
- self
- }
- pub fn image_pull_secret(mut self, value: String) -> Self {
- self.image_pull_secret = Some(value);
- self
- }
- pub fn memory(mut self, value: String) -> Self {
- self.memory = Some(value);
- self
- }
- pub fn node_selector(mut self, value: std::collections::BTreeMap<String, String>) -> Self {
- self.node_selector = Some(value);
- self
- }
- pub fn oidc(mut self, value: PoolTemplateOidc) -> Self {
- self.oidc = Some(value);
- self
- }
- pub fn probes(mut self, value: serde_json::Value) -> Self {
- self.probes = Some(value);
- self
- }
- pub fn runtime(mut self, value: PoolTemplateRuntime) -> Self {
- self.runtime = Some(value);
- self
- }
- pub fn runtime_class_name(mut self, value: String) -> Self {
- self.runtime_class_name = Some(value);
- self
- }
- pub fn tolerations(mut self, value: Vec<serde_json::Value>) -> Self {
- self.tolerations = Some(value);
- self
- }
- pub fn build(self) -> Result<PoolTemplate, String> {
- Ok(PoolTemplate {
- command: self.command,
- container_disk_image: self
- .container_disk_image
- .ok_or_else(|| "containerDiskImage is required".to_string())?,
- cpu_cores: self.cpu_cores,
- firmware: self.firmware,
- image_pull_secret: self.image_pull_secret,
- memory: self.memory,
- node_selector: self.node_selector,
- oidc: self.oidc,
- probes: self.probes,
- runtime: self.runtime,
- runtime_class_name: self.runtime_class_name,
- tolerations: self.tolerations,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub enum PoolTemplateFirmware {
- #[serde(rename = "bios")]
- Bios,
- #[serde(rename = "efi")]
- Efi,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct PoolTemplateOidc {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "awsRegion")]
- pub aws_region: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "awsRoleArn")]
- pub aws_role_arn: Option<String>,
- #[serde(rename = "credentialsSecret")]
- pub credentials_secret: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[serde(rename = "refreshIntervalSeconds")]
- pub refresh_interval_seconds: Option<u32>,
- #[serde(rename = "tokenUrl")]
- pub token_url: String,
-}
-
-impl PoolTemplateOidc {
- pub fn builder() -> PoolTemplateOidcBuilder {
- PoolTemplateOidcBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct PoolTemplateOidcBuilder {
- aws_region: Option<String>,
- aws_role_arn: Option<String>,
- credentials_secret: Option<String>,
- refresh_interval_seconds: Option<u32>,
- token_url: Option<String>,
-}
-
-impl PoolTemplateOidcBuilder {
- pub fn aws_region(mut self, value: String) -> Self {
- self.aws_region = Some(value);
- self
- }
- pub fn aws_role_arn(mut self, value: String) -> Self {
- self.aws_role_arn = Some(value);
- self
- }
- pub fn credentials_secret(mut self, value: String) -> Self {
- self.credentials_secret = Some(value);
- self
- }
- pub fn refresh_interval_seconds(mut self, value: u32) -> Self {
- self.refresh_interval_seconds = Some(value);
- self
- }
- pub fn token_url(mut self, value: String) -> Self {
- self.token_url = Some(value);
- self
- }
- pub fn build(self) -> Result<PoolTemplateOidc, String> {
- Ok(PoolTemplateOidc {
- aws_region: self.aws_region,
- aws_role_arn: self.aws_role_arn,
- credentials_secret: self
- .credentials_secret
- .ok_or_else(|| "credentialsSecret is required".to_string())?,
- refresh_interval_seconds: self.refresh_interval_seconds,
- token_url: self
- .token_url
- .ok_or_else(|| "tokenUrl is required".to_string())?,
- })
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub enum PoolTemplateRuntime {
- #[serde(rename = "kubevirt")]
- Kubevirt,
- #[serde(rename = "macos")]
- Macos,
- #[serde(rename = "gvisor")]
- Gvisor,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct SandboxTemplateRef {
- #[serde(rename = "name")]
- pub name: String,
-}
-
-impl SandboxTemplateRef {
- pub fn builder() -> SandboxTemplateRefBuilder {
- SandboxTemplateRefBuilder::default()
- }
-}
-
-#[derive(Debug, Clone, Default)]
-pub struct SandboxTemplateRefBuilder {
- name: Option<String>,
-}
-
-impl SandboxTemplateRefBuilder {
- pub fn name(mut self, value: String) -> Self {
- self.name = Some(value);
- self
- }
- pub fn build(self) -> Result<SandboxTemplateRef, String> {
- Ok(SandboxTemplateRef {
- name: self.name.ok_or_else(|| "name is required".to_string())?,
- })
- }
-}
diff --git a/libs/fleet/sdk-core/src/generated_crd_component.rs b/libs/fleet/sdk-core/src/generated_crd_component.rs
deleted file mode 100644
index 60de4de551..0000000000
--- a/libs/fleet/sdk-core/src/generated_crd_component.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-fn claim_spec_json(value: crd_types::ClaimSpec) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.bind_deadline {
- object.insert("bindDeadline".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.lifecycle {
- object.insert("lifecycle".into(), claim_spec_lifecycle_json(value)?);
- }
- object.insert(
- "sandboxTemplateRef".into(),
- sandbox_template_ref_json(value.sandbox_template_ref)?,
- );
- if let Some(value) = value.warmpool {
- object.insert("warmpool".into(), serde_json::Value::from(value));
- }
- Ok(serde_json::Value::Object(object))
-}
-
-fn claim_spec_lifecycle_json(
- value: crd_types::ClaimSpecLifecycle,
-) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.auto_renew {
- object.insert("autoRenew".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.shutdown_policy {
- object.insert("shutdownPolicy".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.shutdown_time {
- object.insert("shutdownTime".into(), serde_json::Value::from(value));
- }
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_spec_json(value: crd_types::PoolSpec) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.autoscaling {
- object.insert("autoscaling".into(), pool_spec_autoscaling_json(value)?);
- }
- object.insert("replicas".into(), serde_json::Value::from(value.replicas));
- if let Some(value) = value.services {
- object.insert(
- "services".into(),
- serde_json::Value::Array(
- value
- .into_iter()
- .map(|item| Ok(pool_spec_service_json(item)?))
- .collect::<Result<Vec<_>, String>>()?,
- ),
- );
- }
- object.insert("template".into(), pool_template_json(value.template)?);
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_spec_autoscaling_json(
- value: crd_types::PoolSpecAutoscaling,
-) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.initial_pool_size {
- object.insert("initialPoolSize".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.max_pool_size {
- object.insert("maxPoolSize".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.min_pool_size {
- object.insert("minPoolSize".into(), serde_json::Value::from(value));
- }
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_spec_service_json(value: crd_types::PoolSpecService) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- object.insert("name".into(), serde_json::Value::from(value.name));
- if let Some(value) = value.protocol {
- object.insert("protocol".into(), pool_spec_service_protocol_json(value));
- }
- object.insert(
- "targetPort".into(),
- serde_json::Value::from(value.target_port),
- );
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_spec_service_protocol_json(value: crd_types::PoolSpecServiceProtocol) -> serde_json::Value {
- serde_json::Value::String(
- match value {
- crd_types::PoolSpecServiceProtocol::Tcp => "TCP",
- crd_types::PoolSpecServiceProtocol::Udp => "UDP",
- }
- .into(),
- )
-}
-
-fn pool_template_json(value: crd_types::PoolTemplate) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.command {
- object.insert(
- "command".into(),
- serde_json::Value::Array(
- value
- .into_iter()
- .map(|item| serde_json::Value::from(item))
- .collect(),
- ),
- );
- }
- object.insert(
- "containerDiskImage".into(),
- serde_json::Value::from(value.container_disk_image),
- );
- if let Some(value) = value.cpu_cores {
- object.insert("cpuCores".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.firmware {
- object.insert("firmware".into(), pool_template_firmware_json(value));
- }
- if let Some(value) = value.image_pull_secret {
- object.insert("imagePullSecret".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.memory {
- object.insert("memory".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.node_selector {
- object.insert(
- "nodeSelector".into(),
- serde_json::Value::Object(
- value
- .into_iter()
- .map(|entry| (entry.key, serde_json::Value::from(entry.value)))
- .collect(),
- ),
- );
- }
- if let Some(value) = value.oidc {
- object.insert("oidc".into(), pool_template_oidc_json(value)?);
- }
- if let Some(value) = value.probes {
- object.insert(
- "probes".into(),
- serde_json::from_str(&value).map_err(|error| error.to_string())?,
- );
- }
- if let Some(value) = value.runtime {
- object.insert("runtime".into(), pool_template_runtime_json(value));
- }
- if let Some(value) = value.runtime_class_name {
- object.insert("runtimeClassName".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.tolerations {
- object.insert(
- "tolerations".into(),
- serde_json::Value::Array(
- value
- .into_iter()
- .map(|item| Ok(serde_json::from_str(&item).map_err(|error| error.to_string())?))
- .collect::<Result<Vec<_>, String>>()?,
- ),
- );
- }
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_template_firmware_json(value: crd_types::PoolTemplateFirmware) -> serde_json::Value {
- serde_json::Value::String(
- match value {
- crd_types::PoolTemplateFirmware::Bios => "bios",
- crd_types::PoolTemplateFirmware::Efi => "efi",
- }
- .into(),
- )
-}
-
-fn pool_template_oidc_json(
- value: crd_types::PoolTemplateOidc,
-) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- if let Some(value) = value.aws_region {
- object.insert("awsRegion".into(), serde_json::Value::from(value));
- }
- if let Some(value) = value.aws_role_arn {
- object.insert("awsRoleArn".into(), serde_json::Value::from(value));
- }
- object.insert(
- "credentialsSecret".into(),
- serde_json::Value::from(value.credentials_secret),
- );
- if let Some(value) = value.refresh_interval_seconds {
- object.insert(
- "refreshIntervalSeconds".into(),
- serde_json::Value::from(value),
- );
- }
- object.insert("tokenUrl".into(), serde_json::Value::from(value.token_url));
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_template_runtime_json(value: crd_types::PoolTemplateRuntime) -> serde_json::Value {
- serde_json::Value::String(
- match value {
- crd_types::PoolTemplateRuntime::Kubevirt => "kubevirt",
- crd_types::PoolTemplateRuntime::Macos => "macos",
- crd_types::PoolTemplateRuntime::Gvisor => "gvisor",
- }
- .into(),
- )
-}
-
-fn sandbox_template_ref_json(
- value: crd_types::SandboxTemplateRef,
-) -> Result<serde_json::Value, String> {
- let mut object = serde_json::Map::new();
- object.insert("name".into(), serde_json::Value::from(value.name));
- Ok(serde_json::Value::Object(object))
-}
-
-fn pool_spec_from_wit(value: crd_types::PoolSpec) -> Result<super::PoolSpec, String> {
- serde_json::from_value(pool_spec_json(value)?).map_err(|error| error.to_string())
-}
-
-fn claim_spec_from_wit(value: crd_types::ClaimSpec) -> Result<super::ClaimSpec, String> {
- serde_json::from_value(claim_spec_json(value)?).map_err(|error| error.to_string())
-}
diff --git a/libs/fleet/sdk-core/src/lib.rs b/libs/fleet/sdk-core/src/lib.rs
deleted file mode 100644
index 53d9ef6a0a..0000000000
--- a/libs/fleet/sdk-core/src/lib.rs
+++ /dev/null
@@ -1,423 +0,0 @@
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-use thiserror::Error;
-
-mod client;
-pub mod generated_crd;
-pub use client::{
- AccessToken, ClaimUrl, HttpRequest, HttpResponse, OAuthCredentials, Platform, PlatformError,
- PoolUrl, Sdk, SdkError, ServiceHttpRequest, ServiceHttpResponse,
-};
-pub use generated_crd::*;
-
-pub const PROTOCOL_VERSION: u32 = 7;
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct Configuration {
- pub protocol_version: u32,
- pub base_url: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct ResourceMetadata {
- pub namespace: String,
- pub name: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub labels: Option<std::collections::BTreeMap<String, String>>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct Pool {
- pub api_version: String,
- pub kind: String,
- pub metadata: ResourceMetadata,
- pub spec: Value,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub status: Option<Value>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct Claim {
- pub api_version: String,
- pub kind: String,
- pub metadata: ResourceMetadata,
- pub spec: Value,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub status: Option<Value>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-#[serde(bound(deserialize = "T: Deserialize<'de>"))]
-pub struct ResourceList<T> {
- #[serde(default)]
- pub items: Vec<T>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct Sandbox {
- pub namespace: String,
- pub claim: String,
- pub sandbox: String,
- pub services: Vec<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct CreatePoolRequest {
- pub namespace: String,
- pub spec: PoolSpec,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct CreateClaimRequest {
- pub pool: Pool,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub spec: Option<ClaimSpec>,
-}
-
-#[derive(Debug, Error)]
-pub enum CoreError {
- #[error("protocol version {0} is unsupported; expected {PROTOCOL_VERSION}")]
- Protocol(u32),
- #[error("resource names must be DNS-1123 labels")]
- InvalidName,
- #[error("base_url must use http or https")]
- InvalidBaseUrl,
-}
-
-pub(crate) fn validate_configuration(configuration: &Configuration) -> Result<(), CoreError> {
- if configuration.protocol_version != PROTOCOL_VERSION {
- return Err(CoreError::Protocol(configuration.protocol_version));
- }
- if !(configuration.base_url.starts_with("http://")
- || configuration.base_url.starts_with("https://"))
- {
- return Err(CoreError::InvalidBaseUrl);
- }
- Ok(())
-}
-pub(crate) fn validate_name(value: &str) -> Result<(), CoreError> {
- if is_dns_label(value) {
- Ok(())
- } else {
- Err(CoreError::InvalidName)
- }
-}
-fn is_dns_label(value: &str) -> bool {
- !value.is_empty()
- && value.len() <= 63
- && value
- .bytes()
- .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
- && !value.starts_with('-')
- && !value.ends_with('-')
-}
-
-#[cfg(target_arch = "wasm32")]
-mod component {
- wit_bindgen::generate!({ path: "wit", world: "cyclops-sdk" });
- use super::{
- AccessToken, HttpRequest, HttpResponse, OAuthCredentials, Platform, PlatformError, Sdk,
- ServiceHttpRequest as CoreServiceHttpRequest,
- };
- use std::cell::RefCell;
- use trycua::cyclops_sdk::{crd_types, platform, requests, resources, service_http};
- include!("generated_crd_component.rs");
-
- struct ComponentPlatform;
- impl Platform for ComponentPlatform {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError> {
- platform::http(&platform::HttpRequest {
- method: request.method,
- url: request.url,
- headers: request
- .headers
- .into_iter()
- .map(|(name, value)| platform::Header { name, value })
- .collect(),
- body: request.body,
- })
- .map(|response| HttpResponse {
- status: response.status,
- body: response.body,
- })
- .map_err(PlatformError::Transport)
- }
- fn sleep(&mut self, milliseconds: u64) -> Result<(), PlatformError> {
- platform::sleep(milliseconds).map_err(PlatformError::Clock)
- }
- fn now_ms(&mut self) -> u64 {
- platform::now_ms()
- }
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError> {
- platform::acquire_oauth_credentials()
- .map(|value| OAuthCredentials {
- token_url: value.token_url,
- client_id: value.client_id,
- client_secret: value.client_secret,
- })
- .map_err(PlatformError::Credentials)
- }
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError> {
- platform::load_access_token()
- .map(|value| {
- value.map(|token| AccessToken {
- value: token.value,
- expires_at_ms: token.expires_at_ms,
- })
- })
- .map_err(PlatformError::TokenStorage)
- }
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError> {
- platform::store_access_token(&platform::AccessToken {
- value: token.value.clone(),
- expires_at_ms: token.expires_at_ms,
- })
- .map_err(PlatformError::TokenStorage)
- }
- }
- thread_local! { static SDK: RefCell<Option<Sdk<ComponentPlatform>>> = const { RefCell::new(None) }; }
- fn with_sdk<T>(
- operation: impl FnOnce(&mut Sdk<ComponentPlatform>) -> Result<T, String>,
- ) -> Result<T, String> {
- SDK.with(|slot| {
- operation(
- slot.borrow_mut()
- .as_mut()
- .ok_or_else(|| "SDK is not configured".to_string())?,
- )
- })
- }
- fn pool_from_wit(value: resources::Pool) -> Result<super::Pool, String> {
- Ok(super::Pool {
- api_version: value.api_version,
- kind: value.kind,
- metadata: super::ResourceMetadata {
- namespace: value.metadata.namespace,
- name: value.metadata.name,
- labels: value
- .metadata
- .labels_json
- .map(|labels| serde_json::from_str(&labels).map_err(|error| error.to_string()))
- .transpose()?,
- },
- spec: serde_json::from_str(&value.spec_json).map_err(|error| error.to_string())?,
- status: value
- .status_json
- .map(|status| serde_json::from_str(&status).map_err(|error| error.to_string()))
- .transpose()?,
- })
- }
- fn pool_to_wit(value: super::Pool) -> Result<resources::Pool, String> {
- Ok(resources::Pool {
- api_version: value.api_version,
- kind: value.kind,
- metadata: resources::ResourceMetadata {
- namespace: value.metadata.namespace,
- name: value.metadata.name,
- labels_json: value
- .metadata
- .labels
- .map(|labels| serde_json::to_string(&labels).map_err(|error| error.to_string()))
- .transpose()?,
- },
- spec_json: serde_json::to_string(&value.spec).map_err(|error| error.to_string())?,
- status_json: value
- .status
- .map(|status| serde_json::to_string(&status).map_err(|error| error.to_string()))
- .transpose()?,
- })
- }
- fn claim_from_wit(value: resources::Claim) -> Result<super::Claim, String> {
- Ok(super::Claim {
- api_version: value.api_version,
- kind: value.kind,
- metadata: super::ResourceMetadata {
- namespace: value.metadata.namespace,
- name: value.metadata.name,
- labels: value
- .metadata
- .labels_json
- .map(|labels| serde_json::from_str(&labels).map_err(|error| error.to_string()))
- .transpose()?,
- },
- spec: serde_json::from_str(&value.spec_json).map_err(|error| error.to_string())?,
- status: value
- .status_json
- .map(|status| serde_json::from_str(&status).map_err(|error| error.to_string()))
- .transpose()?,
- })
- }
- fn claim_to_wit(value: super::Claim) -> Result<resources::Claim, String> {
- Ok(resources::Claim {
- api_version: value.api_version,
- kind: value.kind,
- metadata: resources::ResourceMetadata {
- namespace: value.metadata.namespace,
- name: value.metadata.name,
- labels_json: value
- .metadata
- .labels
- .map(|labels| serde_json::to_string(&labels).map_err(|error| error.to_string()))
- .transpose()?,
- },
- spec_json: serde_json::to_string(&value.spec).map_err(|error| error.to_string())?,
- status_json: value
- .status
- .map(|status| serde_json::to_string(&status).map_err(|error| error.to_string()))
- .transpose()?,
- })
- }
- fn sandbox_to_wit(value: super::Sandbox) -> resources::Sandbox {
- resources::Sandbox {
- namespace: value.namespace,
- claim: value.claim,
- sandbox: value.sandbox,
- services: value.services,
- }
- }
- fn sandbox_from_wit(value: resources::Sandbox) -> super::Sandbox {
- super::Sandbox {
- namespace: value.namespace,
- claim: value.claim,
- sandbox: value.sandbox,
- services: value.services,
- }
- }
-
- struct CyclopsComponent;
- impl Guest for CyclopsComponent {
- fn protocol_version() -> u32 {
- super::PROTOCOL_VERSION
- }
- fn configure(configuration_json: String) -> Result<(), String> {
- let configuration =
- serde_json::from_str(&configuration_json).map_err(|error| error.to_string())?;
- let sdk = Sdk::connect(ComponentPlatform, configuration)
- .map_err(|error| error.to_string())?;
- SDK.with(|slot| *slot.borrow_mut() = Some(sdk));
- Ok(())
- }
- fn create_pool(request: requests::CreatePoolRequest) -> Result<resources::Pool, String> {
- with_sdk(|sdk| {
- pool_to_wit(
- sdk.create_pool(super::CreatePoolRequest {
- namespace: request.namespace,
- spec: pool_spec_from_wit(request.spec)?,
- })
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn list_pools(namespace: String) -> Result<Vec<resources::Pool>, String> {
- with_sdk(|sdk| {
- sdk.list_pools(&namespace)
- .map_err(|error| error.to_string())?
- .into_iter()
- .map(pool_to_wit)
- .collect()
- })
- }
- fn get_pool(value: resources::Pool) -> Result<resources::Pool, String> {
- with_sdk(|sdk| {
- pool_to_wit(
- sdk.get_pool(pool_from_wit(value)?)
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn update_pool(value: resources::Pool) -> Result<resources::Pool, String> {
- with_sdk(|sdk| {
- pool_to_wit(
- sdk.update_pool(pool_from_wit(value)?)
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn delete_pool(value: resources::Pool) -> Result<(), String> {
- with_sdk(|sdk| {
- sdk.delete_pool(pool_from_wit(value)?)
- .map_err(|error| error.to_string())
- })
- }
- fn create_claim(request: requests::CreateClaimRequest) -> Result<resources::Claim, String> {
- with_sdk(|sdk| {
- claim_to_wit(
- sdk.create_claim(super::CreateClaimRequest {
- pool: pool_from_wit(request.pool)?,
- spec: request.spec.map(claim_spec_from_wit).transpose()?,
- })
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn list_claims(namespace: String) -> Result<Vec<resources::Claim>, String> {
- with_sdk(|sdk| {
- sdk.list_claims(&namespace)
- .map_err(|error| error.to_string())?
- .into_iter()
- .map(claim_to_wit)
- .collect()
- })
- }
- fn get_claim(value: resources::Claim) -> Result<resources::Claim, String> {
- with_sdk(|sdk| {
- claim_to_wit(
- sdk.get_claim(claim_from_wit(value)?)
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn update_claim(value: resources::Claim) -> Result<resources::Claim, String> {
- with_sdk(|sdk| {
- claim_to_wit(
- sdk.update_claim(claim_from_wit(value)?)
- .map_err(|error| error.to_string())?,
- )
- })
- }
- fn delete_claim(value: resources::Claim) -> Result<(), String> {
- with_sdk(|sdk| {
- sdk.delete_claim(claim_from_wit(value)?)
- .map_err(|error| error.to_string())
- })
- }
- fn wait_claim(value: resources::Claim) -> Result<resources::Sandbox, String> {
- with_sdk(|sdk| {
- Ok(sandbox_to_wit(
- sdk.wait_claim(claim_from_wit(value)?)
- .map_err(|error| error.to_string())?,
- ))
- })
- }
- fn service_request(
- value: resources::Sandbox,
- service: String,
- request: service_http::ServiceHttpRequest,
- ) -> Result<service_http::ServiceHttpResponse, String> {
- with_sdk(|sdk| {
- sdk.service_request(
- &sandbox_from_wit(value),
- &service,
- CoreServiceHttpRequest {
- method: request.method,
- path: request.path,
- headers: request
- .headers
- .into_iter()
- .map(|header| (header.name, header.value))
- .collect(),
- body: request.body,
- },
- )
- .map(|response| service_http::ServiceHttpResponse {
- status: response.status,
- body: response.body,
- })
- .map_err(|error| error.to_string())
- })
- }
- }
- export!(CyclopsComponent);
-}
diff --git a/libs/fleet/sdk-core/tests/client_flow.rs b/libs/fleet/sdk-core/tests/client_flow.rs
deleted file mode 100644
index a01cd2895e..0000000000
--- a/libs/fleet/sdk-core/tests/client_flow.rs
+++ /dev/null
@@ -1,502 +0,0 @@
-use cyclops_sdk_core::{
- AccessToken, Claim, ClaimUrl, Configuration, CreateClaimRequest, CreatePoolRequest,
- HttpRequest, HttpResponse, OAuthCredentials, Platform, PlatformError, PoolSpec, PoolTemplate,
- PoolUrl, Sandbox, Sdk, SdkError, ServiceHttpRequest,
-};
-use serde_json::json;
-use std::collections::VecDeque;
-
-#[derive(Default)]
-struct FakePlatform {
- responses: VecDeque<HttpResponse>,
- requests: Vec<HttpRequest>,
- sleeps: Vec<u64>,
- token: Option<AccessToken>,
- oauth: Option<OAuthCredentials>,
- credential_requests: usize,
-}
-
-impl Platform for FakePlatform {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError> {
- self.requests.push(request);
- self.responses
- .pop_front()
- .ok_or_else(|| PlatformError::Transport("missing response".into()))
- }
- fn sleep(&mut self, milliseconds: u64) -> Result<(), PlatformError> {
- self.sleeps.push(milliseconds);
- Ok(())
- }
- fn now_ms(&mut self) -> u64 {
- 1_000
- }
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError> {
- self.credential_requests += 1;
- Ok(self.oauth.clone().unwrap_or_else(|| OAuthCredentials {
- token_url: "https://auth.example/token".into(),
- client_id: "id".into(),
- client_secret: "secret".into(),
- }))
- }
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError> {
- Ok(self.token.clone())
- }
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError> {
- self.token = Some(token.clone());
- Ok(())
- }
-}
-
-fn claim() -> Claim {
- serde_json::from_value(json!({
- "apiVersion":"osgym.cua.ai/v1alpha1", "kind":"OSGymSandboxClaim",
- "metadata":{"namespace":"pool-a","name":"claim-a"},
- "spec":{"sandboxTemplateRef":{"name":"pool-a-template"}}
- }))
- .unwrap()
-}
-
-fn connected(responses: Vec<HttpResponse>) -> Sdk<FakePlatform> {
- let platform = FakePlatform {
- responses: responses.into(),
- token: Some(AccessToken {
- value: "cached".into(),
- expires_at_ms: 301_001,
- }),
- ..FakePlatform::default()
- };
- Sdk::connect(
- platform,
- Configuration {
- protocol_version: cyclops_sdk_core::PROTOCOL_VERSION,
- base_url: "https://run.example".into(),
- },
- )
- .unwrap()
-}
-
-#[test]
-fn canonical_resource_urls_are_namespaced() {
- let pool = PoolUrl::new("https://run.example/", "pool-a", "pool-a").unwrap();
- assert_eq!(
- pool.collection().as_str(),
- "https://run.example/api/k8s/apis/cua.ai/v1/namespaces/pool-a/osgymworkspacepools"
- );
- assert_eq!(
- pool.item().as_str(),
- "https://run.example/api/k8s/apis/cua.ai/v1/namespaces/pool-a/osgymworkspacepools/pool-a"
- );
- let claim = ClaimUrl::new("https://run.example", "pool-a", "claim-a").unwrap();
- assert_eq!(claim.collection().as_str(), "https://run.example/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/pool-a/osgymsandboxclaims");
- assert_eq!(claim.item().as_str(), "https://run.example/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/pool-a/osgymsandboxclaims/claim-a");
-}
-
-fn sandbox_with_services() -> Sandbox {
- Sandbox {
- namespace: "pool-a".into(),
- claim: "claim-a".into(),
- sandbox: "sandbox-a".into(),
- services: vec!["mcp".into(), "novnc".into()],
- }
-}
-
-#[test]
-fn service_request_resolves_relative_path_and_reuses_auth_retry() {
- let mut sdk = connected(vec![
- HttpResponse {
- status: 401,
- body: "expired".into(),
- },
- HttpResponse {
- status: 200,
- body: r#"{"access_token":"fresh","expires_in":300}"#.into(),
- },
- HttpResponse {
- status: 200,
- body: "initialized".into(),
- },
- ]);
- let response = sdk
- .service_request(
- &sandbox_with_services(),
- "mcp",
- ServiceHttpRequest {
- method: "POST".into(),
- path: "/mcp?session=one".into(),
- headers: vec![
- ("content-type".into(), "application/json".into()),
- ("authorization".into(), "Caller token".into()),
- ("host".into(), "cyclops.invalid".into()),
- ("connection".into(), "keep-alive".into()),
- ],
- body: Some("{}".into()),
- },
- )
- .unwrap();
- assert_eq!(response.status, 200);
- assert_eq!(response.body, "initialized");
- assert_eq!(sdk.platform().requests.len(), 3);
- assert_eq!(
- sdk.platform().requests[0].url,
- "https://run.example/api/svc/pool-a/sandbox-a-mcp/mcp?session=one"
- );
- assert_eq!(
- sdk.platform().requests[2].url,
- sdk.platform().requests[0].url
- );
- assert!(sdk.platform().requests[0]
- .headers
- .contains(&("authorization".into(), "Bearer cached".into())));
- assert!(!sdk.platform().requests[0]
- .headers
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("host")
- || name.eq_ignore_ascii_case("connection")));
- assert!(sdk.platform().requests[2]
- .headers
- .contains(&("authorization".into(), "Bearer fresh".into())));
-}
-
-#[test]
-fn service_request_rejects_unknown_service_with_available_names() {
- let mut sdk = connected(vec![]);
- let error = sdk
- .service_request(
- &sandbox_with_services(),
- "metrics",
- ServiceHttpRequest::get("/health"),
- )
- .unwrap_err();
- assert_eq!(
- error,
- SdkError::UnknownService {
- requested: "metrics".into(),
- available: vec!["mcp".into(), "novnc".into()],
- }
- );
- assert!(sdk.platform().requests.is_empty());
-}
-
-#[test]
-fn service_request_rejects_absolute_urls() {
- let mut sdk = connected(vec![]);
- let error = sdk
- .service_request(
- &sandbox_with_services(),
- "mcp",
- ServiceHttpRequest::get("https://attacker.example/mcp"),
- )
- .unwrap_err();
- assert_eq!(
- error,
- SdkError::InvalidServicePath("https://attacker.example/mcp".into())
- );
- assert!(sdk.platform().requests.is_empty());
-}
-
-#[test]
-fn service_request_rejects_forged_route_parts() {
- let mut sdk = connected(vec![]);
- let mut sandbox = sandbox_with_services();
- sandbox.sandbox = "../other".into();
- let error = sdk
- .service_request(&sandbox, "mcp", ServiceHttpRequest::get("/mcp"))
- .unwrap_err();
- assert!(matches!(error, SdkError::Configuration(_)));
- assert!(sdk.platform().requests.is_empty());
-}
-
-#[test]
-fn wait_claim_reuses_get_claim_until_bound() {
- let pending = json!({
- "apiVersion":"osgym.cua.ai/v1alpha1", "kind":"OSGymSandboxClaim",
- "metadata":{"namespace":"pool-a","name":"claim-a"},
- "spec":{"sandboxTemplateRef":{"name":"pool-a-template"}},
- "status":{"phase":"Pending"}
- })
- .to_string();
- let bound = json!({
- "apiVersion":"osgym.cua.ai/v1alpha1", "kind":"OSGymSandboxClaim",
- "metadata":{"namespace":"pool-a","name":"claim-a"},
- "spec":{"sandboxTemplateRef":{"name":"pool-a-template"}},
- "status":{"phase":"Bound","sandbox":{"name":"sandbox-a"}}
- })
- .to_string();
- let pool = json!({
- "apiVersion":"cua.ai/v1", "kind":"OSGymWorkspacePool",
- "metadata":{"namespace":"pool-a","name":"pool-a"},
- "spec":{"replicas":1,"services":[{"name":"mcp","targetPort":3000}],"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}}
- })
- .to_string();
- let mut sdk = connected(vec![
- HttpResponse {
- status: 200,
- body: pool,
- },
- HttpResponse {
- status: 200,
- body: pending,
- },
- HttpResponse {
- status: 200,
- body: bound,
- },
- ]);
- let sandbox = sdk.wait_claim(claim()).unwrap();
- assert_eq!(sandbox.sandbox, "sandbox-a");
- assert_eq!(sdk.platform().requests.len(), 3);
- assert_eq!(sandbox.services, ["mcp"]);
- assert!(sdk
- .platform()
- .requests
- .iter()
- .all(|request| request.method == "GET"));
- assert_eq!(sdk.platform().sleeps, [5_000]);
-}
-
-#[test]
-fn oauth_credentials_are_form_encoded() {
- let platform = FakePlatform {
- responses: vec![
- HttpResponse {
- status: 200,
- body: r#"{"access_token":"fresh","expires_in":300}"#.into(),
- },
- HttpResponse {
- status: 200,
- body: "ok".into(),
- },
- ]
- .into(),
- oauth: Some(OAuthCredentials {
- token_url: "https://auth.example/token".into(),
- client_id: "id&+= %".into(),
- client_secret: "s/e?c#r&et=+ %".into(),
- }),
- ..FakePlatform::default()
- };
- let mut sdk = Sdk::connect(
- platform,
- Configuration {
- protocol_version: cyclops_sdk_core::PROTOCOL_VERSION,
- base_url: "https://run.example".into(),
- },
- )
- .unwrap();
- sdk.service_request(
- &sandbox_with_services(),
- "mcp",
- ServiceHttpRequest::get("/mcp"),
- )
- .unwrap();
- assert_eq!(
- sdk.platform().requests[0].body.as_deref(),
- Some("grant_type=client_credentials&client_id=id%26%2B%3D+%25&client_secret=s%2Fe%3Fc%23r%26et%3D%2B+%25")
- );
-}
-
-#[test]
-fn compact_specs_are_expanded_into_canonical_resources() {
- let pool_body = r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}}}"#;
- let pool_response = pool_body.to_string();
- let claim_response = serde_json::to_string(&claim()).unwrap();
- let claim_body = r#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"pool-one","name":"claim-3e8-0"},"spec":{"sandboxTemplateRef":{"name":"pool-one-template"}}}"#;
- let mut sdk = connected(vec![
- HttpResponse {
- status: 201,
- body: r#"{"name":"pool-one","status":"Active"}"#.into(),
- },
- HttpResponse {
- status: 201,
- body: pool_response.clone(),
- },
- HttpResponse {
- status: 200,
- body: ready_pool_body(),
- },
- HttpResponse {
- status: 201,
- body: claim_response,
- },
- ]);
- let created_pool = sdk
- .create_pool(CreatePoolRequest {
- namespace: "pool-one".into(),
- spec: PoolSpec::builder()
- .replicas(1)
- .template(
- PoolTemplate::builder()
- .container_disk_image("example/workspace:latest".into())
- .cpu_cores(4)
- .memory("4Gi".into())
- .build()
- .unwrap(),
- )
- .build()
- .unwrap(),
- })
- .unwrap();
- sdk.create_claim(CreateClaimRequest {
- pool: created_pool,
- spec: None,
- })
- .unwrap();
- assert_eq!(sdk.platform().requests.len(), 4);
- assert_eq!(
- sdk.platform().requests[0].url,
- "https://run.example/api/namespaces"
- );
- assert_eq!(
- sdk.platform().requests[0].body.as_deref(),
- Some(r#"{"name":"pool-one"}"#)
- );
- assert_eq!(sdk.platform().requests[1].body.as_deref(), Some(pool_body));
- assert_eq!(sdk.platform().requests[2].method, "GET");
- assert_eq!(sdk.platform().requests[3].body.as_deref(), Some(claim_body));
-}
-
-#[test]
-fn create_claim_waits_for_a_requested_pool_replica_to_become_available() {
- let pending = serde_json::from_str::<cyclops_sdk_core::Pool>(
- r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}},"status":{"phase":"Provisioning","availableCount":0,"totalCount":1}}"#,
- )
- .unwrap();
- let pool = pool_resource();
- let claim_response = serde_json::to_string(&claim()).unwrap();
- let mut sdk = connected(vec![
- HttpResponse {
- status: 200,
- body: serde_json::to_string(&pending).unwrap(),
- },
- HttpResponse {
- status: 200,
- body: ready_pool_body(),
- },
- HttpResponse {
- status: 201,
- body: claim_response,
- },
- ]);
- sdk.create_claim(CreateClaimRequest { pool, spec: None })
- .unwrap();
- assert_eq!(sdk.platform().requests.len(), 3);
- assert_eq!(
- sdk.platform()
- .requests
- .iter()
- .map(|request| request.method.as_str())
- .collect::<Vec<_>>(),
- ["GET", "GET", "POST"]
- );
- assert_eq!(sdk.platform().sleeps, [5_000]);
-}
-
-#[test]
-fn create_claim_does_not_wait_for_a_zero_replica_pool() {
- let mut pool = pool_resource();
- pool.spec["replicas"] = serde_json::Value::from(0);
- let mut sdk = connected(vec![HttpResponse {
- status: 201,
- body: serde_json::to_string(&claim()).unwrap(),
- }]);
- sdk.create_claim(CreateClaimRequest { pool, spec: None })
- .unwrap();
- assert_eq!(sdk.platform().requests.len(), 1);
- assert_eq!(sdk.platform().requests[0].method, "POST");
-}
-
-#[test]
-fn create_pool_reuses_an_existing_namespace() {
- let pool_body = r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}}}"#;
- let mut sdk = connected(vec![
- HttpResponse {
- status: 409,
- body: "namespace already exists".into(),
- },
- HttpResponse {
- status: 201,
- body: pool_body.into(),
- },
- ]);
- sdk.create_pool(pool_request()).unwrap();
- assert_eq!(sdk.platform().requests.len(), 2);
-}
-
-#[test]
-fn create_pool_rolls_back_a_new_namespace_when_pool_creation_fails() {
- let mut sdk = connected(vec![
- HttpResponse {
- status: 201,
- body: r#"{"name":"pool-one","status":"Active"}"#.into(),
- },
- HttpResponse {
- status: 403,
- body: "forbidden".into(),
- },
- HttpResponse {
- status: 202,
- body: String::new(),
- },
- ]);
- let error = sdk.create_pool(pool_request()).unwrap_err();
- assert!(error.to_string().contains("create pool returned HTTP 403"));
- assert_eq!(sdk.platform().requests.len(), 3);
- assert_eq!(sdk.platform().requests[2].method, "DELETE");
- assert_eq!(
- sdk.platform().requests[2].url,
- "https://run.example/api/namespaces/pool-one"
- );
-}
-
-#[test]
-fn delete_pool_deletes_the_pool_before_its_namespace() {
- let mut sdk = connected(vec![
- HttpResponse {
- status: 202,
- body: String::new(),
- },
- HttpResponse {
- status: 202,
- body: String::new(),
- },
- ]);
- let pool = pool_resource();
- sdk.delete_pool(pool).unwrap();
- assert_eq!(sdk.platform().requests.len(), 2);
- assert!(sdk.platform().requests[0]
- .url
- .ends_with("/osgymworkspacepools/pool-one"));
- assert_eq!(
- sdk.platform().requests[1].url,
- "https://run.example/api/namespaces/pool-one"
- );
-}
-
-fn pool_resource() -> cyclops_sdk_core::Pool {
- serde_json::from_str(
- r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}}}"#,
- )
- .unwrap()
-}
-
-fn ready_pool_body() -> String {
- r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}},"status":{"phase":"Ready","availableCount":1,"totalCount":1}}"#.into()
-}
-
-fn pool_request() -> CreatePoolRequest {
- CreatePoolRequest {
- namespace: "pool-one".into(),
- spec: PoolSpec::builder()
- .replicas(1)
- .template(
- PoolTemplate::builder()
- .container_disk_image("example/workspace:latest".into())
- .cpu_cores(4)
- .memory("4Gi".into())
- .build()
- .unwrap(),
- )
- .build()
- .unwrap(),
- }
-}
diff --git a/libs/fleet/sdk-core/tests/public_api.rs b/libs/fleet/sdk-core/tests/public_api.rs
deleted file mode 100644
index 32037acd18..0000000000
--- a/libs/fleet/sdk-core/tests/public_api.rs
+++ /dev/null
@@ -1,195 +0,0 @@
-use cyclops_sdk_core::{
- AccessToken, Claim, Configuration, CreateClaimRequest, CreatePoolRequest, HttpRequest,
- HttpResponse, OAuthCredentials, Platform, PlatformError, Pool, PoolSpec, PoolTemplate, Sandbox,
- Sdk,
-};
-use std::collections::VecDeque;
-
-#[derive(Default)]
-struct FakePlatform {
- responses: VecDeque<HttpResponse>,
- requests: Vec<HttpRequest>,
- token: Option<AccessToken>,
-}
-
-impl Platform for FakePlatform {
- fn http(&mut self, request: HttpRequest) -> Result<HttpResponse, PlatformError> {
- self.requests.push(request);
- self.responses
- .pop_front()
- .ok_or_else(|| PlatformError::Transport("missing response".into()))
- }
- fn sleep(&mut self, _milliseconds: u64) -> Result<(), PlatformError> {
- Ok(())
- }
- fn now_ms(&mut self) -> u64 {
- 1_000
- }
- fn acquire_oauth_credentials(&mut self) -> Result<OAuthCredentials, PlatformError> {
- unreachable!()
- }
- fn load_access_token(&mut self) -> Result<Option<AccessToken>, PlatformError> {
- Ok(self.token.clone())
- }
- fn store_access_token(&mut self, token: &AccessToken) -> Result<(), PlatformError> {
- self.token = Some(token.clone());
- Ok(())
- }
-}
-
-fn connected(responses: impl IntoIterator<Item = (u16, String)>) -> Sdk<FakePlatform> {
- Sdk::connect(
- FakePlatform {
- responses: responses
- .into_iter()
- .map(|(status, body)| HttpResponse { status, body })
- .collect(),
- token: Some(AccessToken {
- value: "cached".into(),
- expires_at_ms: 301_001,
- }),
- ..FakePlatform::default()
- },
- Configuration {
- protocol_version: cyclops_sdk_core::PROTOCOL_VERSION,
- base_url: "https://run.example".into(),
- },
- )
- .unwrap()
-}
-
-fn pool() -> Pool {
- serde_json::from_str(r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}}}"#).unwrap()
-}
-
-fn claim() -> Claim {
- serde_json::from_str(r#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"pool-one","name":"claim-one"},"spec":{"sandboxTemplateRef":{"name":"pool-one-template"}}}"#).unwrap()
-}
-
-#[test]
-fn canonical_pool_and_claim_crud_uses_typed_resources() {
- let pool_json = serde_json::to_string(&pool()).unwrap();
- let claim_json = serde_json::to_string(&claim()).unwrap();
- let list_pools = format!(r#"{{"items":[{pool_json}]}}"#);
- let list_claims = format!(r#"{{"items":[{claim_json}]}}"#);
- let bound_claim = r#"{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"pool-one","name":"claim-one"},"spec":{"sandboxTemplateRef":{"name":"pool-one-template"}},"status":{"phase":"Bound","sandbox":{"name":"sandbox-one"}}}"#;
- let mut sdk = connected([
- (201, r#"{"name":"pool-one","status":"Active"}"#.into()),
- (201, pool_json.clone()),
- (200, list_pools),
- (200, pool_json.clone()),
- (200, pool_json),
- (
- 200,
- r#"{"apiVersion":"cua.ai/v1","kind":"OSGymWorkspacePool","metadata":{"namespace":"pool-one","name":"pool-one"},"spec":{"replicas":1,"template":{"containerDiskImage":"example/workspace:latest","cpuCores":4,"memory":"4Gi"}},"status":{"phase":"Ready","availableCount":1,"totalCount":1}}"#.into(),
- ),
- (201, claim_json.clone()),
- (200, list_claims),
- (200, claim_json.clone()),
- (200, claim_json),
- (200, bound_claim.into()),
- (204, String::new()),
- (204, String::new()),
- (204, String::new()),
- ]);
-
- let pool = sdk
- .create_pool(CreatePoolRequest {
- namespace: "pool-one".into(),
- spec: PoolSpec::builder()
- .replicas(1)
- .template(
- PoolTemplate::builder()
- .container_disk_image("example/workspace:latest".into())
- .cpu_cores(4)
- .memory("4Gi".into())
- .build()
- .unwrap(),
- )
- .build()
- .unwrap(),
- })
- .unwrap();
- sdk.list_pools("pool-one").unwrap();
- sdk.get_pool(pool.clone()).unwrap();
- sdk.update_pool(pool.clone()).unwrap();
- let claim = sdk
- .create_claim(CreateClaimRequest {
- pool: pool.clone(),
- spec: None,
- })
- .unwrap();
- sdk.list_claims("pool-one").unwrap();
- sdk.get_claim(claim.clone()).unwrap();
- sdk.update_claim(claim.clone()).unwrap();
- let Sandbox { sandbox, .. } = sdk.wait_claim(claim.clone()).unwrap();
- sdk.delete_claim(claim).unwrap();
- sdk.delete_pool(pool).unwrap();
- assert_eq!(sandbox, "sandbox-one");
-
- let methods = sdk
- .platform()
- .requests
- .iter()
- .map(|request| request.method.as_str())
- .collect::<Vec<_>>();
- assert_eq!(
- methods,
- [
- "POST", "POST", "GET", "GET", "PUT", "GET", "POST", "GET", "GET", "PUT", "GET",
- "DELETE", "DELETE", "DELETE"
- ]
- );
-}
-
-#[test]
-fn wit_exports_typed_resources_and_service_http() {
- let wit = format!(
- "{}\n{}",
- include_str!("../wit/cyclops-sdk.wit"),
- include_str!("../wit/generated-crd.wit")
- );
- for resource in [
- "record pool",
- "record pool-spec",
- "record claim",
- "record claim-spec",
- "record sandbox",
- ] {
- assert!(wit.contains(resource), "missing typed {resource}");
- }
- assert!(!wit.contains("pool-json"));
- assert!(!wit.contains("claim-json"));
- for operation in [
- "create-pool",
- "list-pools",
- "get-pool",
- "update-pool",
- "delete-pool",
- "create-claim",
- "list-claims",
- "get-claim",
- "update-claim",
- "delete-claim",
- "wait-claim",
- "service-request",
- ] {
- assert!(wit.contains(operation), "missing {operation}");
- }
- assert!(!wit.contains("raw-request"));
- assert!(wit.contains("record service-http-request"));
- assert!(wit.contains("record service-http-response"));
- for leaked_url in ["server-url", "mcp-url", "novnc-url"] {
- assert!(!wit.contains(leaked_url), "leaked {leaked_url}");
- }
- for prohibited in [
- concat!("create", "-namespace"),
- concat!("release", "-claim"),
- concat!("claim", "-status"),
- concat!("claimed", "-sandbox"),
- concat!("run", "-task"),
- concat!("run", "-call", "back"),
- ] {
- assert!(!wit.contains(prohibited), "prohibited {prohibited}");
- }
-}
diff --git a/libs/fleet/sdk-core/wit/cyclops-sdk.wit b/libs/fleet/sdk-core/wit/cyclops-sdk.wit
deleted file mode 100644
index 9d3f67c1a0..0000000000
--- a/libs/fleet/sdk-core/wit/cyclops-sdk.wit
+++ /dev/null
@@ -1,56 +0,0 @@
-package trycua:[email protected];
-
-interface platform {
- record header { name: string, value: string }
- record http-request { method: string, url: string, headers: list<header>, body: option<string> }
- record http-response { status: u16, body: string }
- record oauth-credentials { token-url: string, client-id: string, client-secret: string }
- record access-token { value: string, expires-at-ms: u64 }
- http: func(request: http-request) -> result<http-response, string>;
- sleep: func(milliseconds: u64) -> result<_, string>;
- now-ms: func() -> u64;
- acquire-oauth-credentials: func() -> result<oauth-credentials, string>;
- load-access-token: func() -> result<option<access-token>, string>;
- store-access-token: func(token: access-token) -> result<_, string>;
-}
-
-interface resources {
- record resource-metadata { namespace: string, name: string, labels-json: option<string> }
- record pool { api-version: string, kind: string, metadata: resource-metadata, spec-json: string, status-json: option<string> }
- record claim { api-version: string, kind: string, metadata: resource-metadata, spec-json: string, status-json: option<string> }
- record sandbox { namespace: string, claim: string, sandbox: string, services: list<string> }
-}
-
-interface requests {
- use resources.{pool};
- use crd-types.{pool-spec, claim-spec};
- record create-pool-request { namespace: string, spec: pool-spec }
- record create-claim-request { pool: pool, spec: option<claim-spec> }
-}
-
-interface service-http {
- record header { name: string, value: string }
- record service-http-request { method: string, path: string, headers: list<header>, body: option<string> }
- record service-http-response { status: u16, body: string }
-}
-
-world cyclops-sdk {
- import platform;
- use resources.{pool, claim, sandbox};
- use requests.{create-pool-request, create-claim-request};
- use service-http.{service-http-request, service-http-response};
- export protocol-version: func() -> u32;
- export configure: func(configuration-json: string) -> result<_, string>;
- export create-pool: func(request: create-pool-request) -> result<pool, string>;
- export list-pools: func(namespace: string) -> result<list<pool>, string>;
- export get-pool: func(value: pool) -> result<pool, string>;
- export update-pool: func(value: pool) -> result<pool, string>;
- export delete-pool: func(value: pool) -> result<_, string>;
- export create-claim: func(request: create-claim-request) -> result<claim, string>;
- export list-claims: func(namespace: string) -> result<list<claim>, string>;
- export get-claim: func(value: claim) -> result<claim, string>;
- export update-claim: func(value: claim) -> result<claim, string>;
- export delete-claim: func(value: claim) -> result<_, string>;
- export wait-claim: func(value: claim) -> result<sandbox, string>;
- export service-request: func(value: sandbox, service: string, request: service-http-request) -> result<service-http-response, string>;
-}
diff --git a/libs/fleet/sdk-core/wit/generated-crd.wit b/libs/fleet/sdk-core/wit/generated-crd.wit
deleted file mode 100644
index 0a7816fc41..0000000000
--- a/libs/fleet/sdk-core/wit/generated-crd.wit
+++ /dev/null
@@ -1,60 +0,0 @@
-// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.
-package trycua:[email protected];
-
-interface crd-types {
- record string-map-entry { key: string, value: string }
- record claim-spec {
- bind-deadline: option<u32>,
- lifecycle: option<claim-spec-lifecycle>,
- sandbox-template-ref: sandbox-template-ref,
- warmpool: option<string>,
- }
- record claim-spec-lifecycle {
- auto-renew: option<bool>,
- shutdown-policy: option<string>,
- shutdown-time: option<string>,
- }
- record pool-spec {
- autoscaling: option<pool-spec-autoscaling>,
- replicas: u32,
- services: option<list<pool-spec-service>>,
- template: pool-template,
- }
- record pool-spec-autoscaling {
- initial-pool-size: option<u32>,
- max-pool-size: option<u32>,
- min-pool-size: option<u32>,
- }
- record pool-spec-service {
- name: string,
- protocol: option<pool-spec-service-protocol>,
- target-port: u32,
- }
- enum pool-spec-service-protocol { tcp, udp }
- record pool-template {
- command: option<list<string>>,
- container-disk-image: string,
- cpu-cores: option<u32>,
- firmware: option<pool-template-firmware>,
- image-pull-secret: option<string>,
- memory: option<string>,
- node-selector: option<list<string-map-entry>>,
- oidc: option<pool-template-oidc>,
- probes: option<string>,
- runtime: option<pool-template-runtime>,
- runtime-class-name: option<string>,
- tolerations: option<list<string>>,
- }
- enum pool-template-firmware { bios, efi }
- record pool-template-oidc {
- aws-region: option<string>,
- aws-role-arn: option<string>,
- credentials-secret: string,
- refresh-interval-seconds: option<u32>,
- token-url: string,
- }
- enum pool-template-runtime { kubevirt, macos, gvisor }
- record sandbox-template-ref {
- name: string,
- }
-}
diff --git a/libs/fleet/sdk-schema-generator/go.mod b/libs/fleet/sdk-schema-generator/go.mod
deleted file mode 100644
index 7eeec79710..0000000000
--- a/libs/fleet/sdk-schema-generator/go.mod
+++ /dev/null
@@ -1,5 +0,0 @@
-module github.com/trycua/cloud/cyclops-cs/sdk-schema-generator
-
-go 1.23.0
-
-require gopkg.in/yaml.v3 v3.0.1
diff --git a/libs/fleet/sdk-schema-generator/go.sum b/libs/fleet/sdk-schema-generator/go.sum
deleted file mode 100644
index a62c313c5b..0000000000
--- a/libs/fleet/sdk-schema-generator/go.sum
+++ /dev/null
@@ -1,4 +0,0 @@
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/libs/fleet/sdk-schema-generator/main.go b/libs/fleet/sdk-schema-generator/main.go
deleted file mode 100644
index faf44e5aba..0000000000
--- a/libs/fleet/sdk-schema-generator/main.go
+++ /dev/null
@@ -1,686 +0,0 @@
-package main
-
-import (
- "bytes"
- "flag"
- "fmt"
- goformat "go/format"
- "io"
- "os"
- "os/exec"
- "path/filepath"
- "sort"
- "strings"
- "unicode"
-
- yamlv3 "gopkg.in/yaml.v3"
-)
-
-type node struct {
- Name string
- JSONName string
- Type string
- Required bool
- Enum []string
- Properties []*node
- Items *node
- MapValues *node
- Opaque bool
-}
-
-type rootType struct {
- CRDName string
- Version string
- Name string
- Node *node
-}
-
-type output struct {
- Path string
- Data []byte
-}
-
-func main() {
- root := flag.String("root", ".", "repository root")
- check := flag.Bool("check", false, "fail if generated files differ")
- flag.Parse()
-
- crdPath := filepath.Join(*root, "clusters/base/osgym/crd.yaml")
- roots := []*rootType{
- {CRDName: "osgymworkspacepools.cua.ai", Version: "v1", Name: "PoolSpec"},
- {CRDName: "osgymsandboxclaims.osgym.cua.ai", Version: "v1alpha1", Name: "ClaimSpec"},
- }
- loadRoots(crdPath, roots)
-
- outputs := []output{
- {filepath.Join(*root, "cyclops-cs/sdk-core/wit/generated-crd.wit"), renderWIT(roots)},
- {filepath.Join(*root, "cyclops-cs/sdk-core/src/generated_crd.rs"), formatRust(renderRust(roots))},
- {filepath.Join(*root, "cyclops-cs/sdk-core/src/generated_crd_component.rs"), formatRust(renderComponent(roots))},
- {filepath.Join(*root, "cyclops-cs/sdk-bindings/typescript/src/generated-crd.ts"), renderTypeScript(roots)},
- {filepath.Join(*root, "cyclops-cs/sdk-bindings/python/cyclops_sdk/generated_crd.py"), renderPython(roots)},
- {filepath.Join(*root, "cyclops-cs/sdk-bindings/go/generated_crd.go"), formatGo(renderGo(roots))},
- }
-
- failed := false
- for _, item := range outputs {
- current, err := os.ReadFile(item.Path)
- if *check {
- if err != nil || !bytes.Equal(current, item.Data) {
- fmt.Fprintf(os.Stderr, "generated file is stale: %s\n", item.Path)
- failed = true
- }
- continue
- }
- if err := os.MkdirAll(filepath.Dir(item.Path), 0o755); err != nil {
- fatalf("create output directory: %v", err)
- }
- if err := os.WriteFile(item.Path, item.Data, 0o644); err != nil {
- fatalf("write %s: %v", item.Path, err)
- }
- }
- if failed {
- os.Exit(1)
- }
-}
-
-func formatRust(source []byte) []byte {
- command := exec.Command("rustfmt", "--emit", "stdout")
- command.Stdin = bytes.NewReader(source)
- formatted, err := command.Output()
- if err != nil {
- fatalf("rustfmt generated source: %v", err)
- }
- return formatted
-}
-
-func formatGo(source []byte) []byte {
- formatted, err := goformat.Source(source)
- if err != nil {
- fatalf("gofmt generated source: %v", err)
- }
- return formatted
-}
-
-func loadRoots(path string, roots []*rootType) {
- data, err := os.ReadFile(path)
- if err != nil {
- fatalf("read CRDs: %v", err)
- }
- wanted := map[string]*rootType{}
- for _, root := range roots {
- wanted[root.CRDName] = root
- }
- decoder := yamlv3.NewDecoder(bytes.NewReader(data))
- for {
- var document map[string]any
- if err := decoder.Decode(&document); err != nil {
- if err == io.EOF {
- break
- }
- fatalf("decode CRDs: %v", err)
- }
- metadata, _ := document["metadata"].(map[string]any)
- root := wanted[fmt.Sprint(metadata["name"])]
- if root == nil {
- continue
- }
- versions := mustSlice(mustMap(document["spec"], "spec")["versions"], "spec.versions")
- for _, raw := range versions {
- version := mustMap(raw, "version")
- if fmt.Sprint(version["name"]) != root.Version {
- continue
- }
- schema := mustMap(mustMap(version["schema"], "schema")["openAPIV3Schema"], "openAPIV3Schema")
- spec := property(schema, "spec")
- root.Node = parseNode(root.Name, "spec", spec, true)
- }
- }
- for _, root := range roots {
- if root.Node == nil {
- fatalf("missing %s %s schema", root.CRDName, root.Version)
- }
- }
-}
-
-func parseNode(name, jsonName string, schema map[string]any, required bool) *node {
- result := &node{Name: name, JSONName: jsonName, Type: fmt.Sprint(schema["type"]), Required: required}
- if values, ok := schema["enum"].([]any); ok {
- for _, value := range values {
- result.Enum = append(result.Enum, fmt.Sprint(value))
- }
- }
- if schema["x-kubernetes-preserve-unknown-fields"] == true {
- result.Opaque = true
- return result
- }
- switch result.Type {
- case "object":
- if additional, ok := schema["additionalProperties"].(map[string]any); ok {
- result.MapValues = parseNode(name+"Value", "value", additional, true)
- return result
- }
- properties, _ := schema["properties"].(map[string]any)
- requiredSet := stringSet(schema["required"])
- keys := sortedKeys(properties)
- for _, key := range keys {
- childName := name + exportedName(key)
- if key == "template" && strings.HasSuffix(name, "Spec") {
- childName = strings.TrimSuffix(name, "Spec") + "Template"
- }
- if key == "sandboxTemplateRef" {
- childName = "SandboxTemplateRef"
- }
- result.Properties = append(result.Properties, parseNode(childName, key, mustMap(properties[key], key), requiredSet[key]))
- }
- case "array":
- result.Items = parseNode(strings.TrimSuffix(name, "s"), "item", mustMap(schema["items"], name+".items"), true)
- }
- return result
-}
-
-func renderWIT(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- out.WriteString("package trycua:[email protected];\n\ninterface crd-types {\n")
- nodes := collectNamed(roots)
- if hasMap(nodes) {
- out.WriteString(" record string-map-entry { key: string, value: string }\n")
- }
- for _, item := range nodes {
- if len(item.Enum) > 0 {
- fmt.Fprintf(&out, " enum %s { %s }\n", witName(item.Name), strings.Join(enumWIT(item.Enum), ", "))
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- fmt.Fprintf(&out, " record %s {\n", witName(item.Name))
- for _, field := range item.Properties {
- fieldType := witType(field)
- if !field.Required {
- fieldType = "option<" + fieldType + ">"
- }
- fmt.Fprintf(&out, " %s: %s,\n", witName(field.JSONName), fieldType)
- }
- out.WriteString(" }\n")
- }
- out.WriteString("}\n")
- return out.Bytes()
-}
-
-func renderRust(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- out.WriteString("use serde::{Deserialize, Serialize};\n\n")
- for _, item := range collectNamed(roots) {
- if len(item.Enum) > 0 {
- out.WriteString("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n")
- fmt.Fprintf(&out, "pub enum %s {\n", item.Name)
- for _, value := range item.Enum {
- fmt.Fprintf(&out, " #[serde(rename = %q)]\n %s,\n", value, exportedName(value))
- }
- out.WriteString("}\n\n")
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- out.WriteString("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n")
- fmt.Fprintf(&out, "pub struct %s {\n", item.Name)
- for _, field := range item.Properties {
- fieldType := rustType(field)
- if !field.Required {
- fieldType = "Option<" + fieldType + ">"
- out.WriteString(" #[serde(default, skip_serializing_if = \"Option::is_none\")]\n")
- }
- fmt.Fprintf(&out, " #[serde(rename = %q)]\n pub %s: %s,\n", field.JSONName, rustField(field.JSONName), fieldType)
- }
- out.WriteString("}\n\n")
- renderRustBuilder(&out, item)
- }
- return out.Bytes()
-}
-
-func renderRustBuilder(out *bytes.Buffer, item *node) {
- fmt.Fprintf(out, "impl %s {\n", item.Name)
- fmt.Fprintf(out, " pub fn builder() -> %sBuilder { %sBuilder::default() }\n", item.Name, item.Name)
- out.WriteString("}\n\n")
- fmt.Fprintf(out, "#[derive(Debug, Clone, Default)]\npub struct %sBuilder {\n", item.Name)
- for _, field := range item.Properties {
- fmt.Fprintf(out, " %s: Option<%s>,\n", rustField(field.JSONName), rustType(field))
- }
- out.WriteString("}\n\n")
- fmt.Fprintf(out, "impl %sBuilder {\n", item.Name)
- for _, field := range item.Properties {
- fieldName := rustField(field.JSONName)
- fieldType := rustType(field)
- fmt.Fprintf(out, " pub fn %s(mut self, value: %s) -> Self {\n", fieldName, fieldType)
- fmt.Fprintf(out, " self.%s = Some(value);\n self\n }\n", fieldName)
- }
- fmt.Fprintf(out, " pub fn build(self) -> Result<%s, String> {\n", item.Name)
- fmt.Fprintf(out, " Ok(%s {\n", item.Name)
- for _, field := range item.Properties {
- fieldName := rustField(field.JSONName)
- if field.Required {
- fmt.Fprintf(out, " %s: self.%s.ok_or_else(|| %q.to_string())?,\n", fieldName, fieldName, field.JSONName+" is required")
- } else {
- fmt.Fprintf(out, " %s: self.%s,\n", fieldName, fieldName)
- }
- }
- out.WriteString(" })\n }\n}\n\n")
-}
-
-func renderComponent(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- for _, item := range collectNamed(roots) {
- if len(item.Enum) > 0 {
- fmt.Fprintf(&out, "fn %s_json(value: crd_types::%s) -> serde_json::Value {\n", snake(item.Name), item.Name)
- out.WriteString(" serde_json::Value::String(match value {\n")
- for _, value := range item.Enum {
- fmt.Fprintf(&out, " crd_types::%s::%s => %q,\n", item.Name, exportedName(strings.ToLower(value)), value)
- }
- out.WriteString(" }.into())\n}\n\n")
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- fmt.Fprintf(&out, "fn %s_json(value: crd_types::%s) -> Result<serde_json::Value, String> {\n", snake(item.Name), item.Name)
- out.WriteString(" let mut object = serde_json::Map::new();\n")
- for _, field := range item.Properties {
- fieldAccess := "value." + rustField(field.JSONName)
- if field.Required {
- fmt.Fprintf(&out, " object.insert(%q.into(), %s);\n", field.JSONName, componentValue(field, fieldAccess))
- } else {
- fmt.Fprintf(&out, " if let Some(value) = %s { object.insert(%q.into(), %s); }\n", fieldAccess, field.JSONName, componentValue(field, "value"))
- }
- }
- out.WriteString(" Ok(serde_json::Value::Object(object))\n}\n\n")
- }
- for _, root := range roots {
- fmt.Fprintf(&out, "fn %s_from_wit(value: crd_types::%s) -> Result<super::%s, String> {\n", snake(root.Name), root.Name, root.Name)
- fmt.Fprintf(&out, " serde_json::from_value(%s_json(value)?).map_err(|error| error.to_string())\n}\n\n", snake(root.Name))
- }
- return out.Bytes()
-}
-
-func renderTypeScript(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- for _, item := range collectNamed(roots) {
- if len(item.Enum) > 0 {
- fmt.Fprintf(&out, "export type %s = %s\n", item.Name, quoteUnion(item.Enum))
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- fmt.Fprintf(&out, "export type %s = {\n", item.Name)
- for _, field := range item.Properties {
- optional := ""
- if !field.Required {
- optional = "?"
- }
- fmt.Fprintf(&out, " %s%s: %s\n", field.JSONName, optional, tsType(field))
- }
- out.WriteString("}\n")
- }
- return out.Bytes()
-}
-
-func renderPython(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("# Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- out.WriteString("from __future__ import annotations\n\n")
- out.WriteString("from typing import Any, Literal, NotRequired, TypedDict\n\n")
- for _, item := range collectNamed(roots) {
- if len(item.Enum) > 0 {
- fmt.Fprintf(&out, "%s = Literal[%s]\n\n", item.Name, quotedCSV(item.Enum))
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- fmt.Fprintf(&out, "class %s(TypedDict):\n", item.Name)
- if len(item.Properties) == 0 {
- out.WriteString(" pass\n")
- }
- for _, field := range item.Properties {
- fieldType := pyType(field)
- if !field.Required {
- fieldType = "NotRequired[" + fieldType + "]"
- }
- fmt.Fprintf(&out, " %s: %s\n", field.JSONName, fieldType)
- }
- out.WriteString("\n")
- }
- return out.Bytes()
-}
-
-func renderGo(roots []*rootType) []byte {
- var out bytes.Buffer
- out.WriteString("// Code generated from clusters/base/osgym/crd.yaml; DO NOT EDIT.\n")
- out.WriteString("package cyclopssdk\n\n")
- for _, item := range collectNamed(roots) {
- if len(item.Enum) > 0 {
- fmt.Fprintf(&out, "type %s string\n\nconst (\n", item.Name)
- for _, value := range item.Enum {
- fmt.Fprintf(&out, "\t%s%s %s = %q\n", item.Name, exportedName(value), item.Name, value)
- }
- out.WriteString(")\n\n")
- continue
- }
- if item.Type != "object" || item.MapValues != nil || item.Opaque {
- continue
- }
- fmt.Fprintf(&out, "type %s struct {\n", item.Name)
- for _, field := range item.Properties {
- fieldType := goType(field)
- tag := field.JSONName
- if !field.Required {
- if goNeedsPointer(field) {
- fieldType = "*" + fieldType
- }
- tag += ",omitempty"
- }
- fmt.Fprintf(&out, "\t%s %s `json:%q`\n", exportedName(field.JSONName), fieldType, tag)
- }
- out.WriteString("}\n\n")
- }
- return out.Bytes()
-}
-
-func collectNamed(roots []*rootType) []*node {
- seen := map[string]*node{}
- var visit func(*node)
- visit = func(item *node) {
- if item == nil {
- return
- }
- if (item.Type == "object" && item.MapValues == nil && !item.Opaque) || len(item.Enum) > 0 {
- seen[item.Name] = item
- }
- for _, child := range item.Properties {
- visit(child)
- }
- visit(item.Items)
- visit(item.MapValues)
- }
- for _, root := range roots {
- visit(root.Node)
- }
- keys := make([]string, 0, len(seen))
- for key := range seen {
- keys = append(keys, key)
- }
- sort.Strings(keys)
- result := make([]*node, 0, len(keys))
- for _, key := range keys {
- result = append(result, seen[key])
- }
- return result
-}
-
-func witType(item *node) string {
- if len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque) {
- return witName(item.Name)
- }
- if item.Opaque {
- return "string"
- }
- switch item.Type {
- case "string":
- return "string"
- case "integer":
- return "u32"
- case "boolean":
- return "bool"
- case "array":
- return "list<" + witType(item.Items) + ">"
- case "object":
- return "list<string-map-entry>"
- default:
- fatalf("unsupported WIT schema type %q for %s", item.Type, item.Name)
- return ""
- }
-}
-
-func rustType(item *node) string {
- if len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque) {
- return item.Name
- }
- if item.Opaque {
- return "serde_json::Value"
- }
- switch item.Type {
- case "string":
- return "String"
- case "integer":
- return "u32"
- case "boolean":
- return "bool"
- case "array":
- return "Vec<" + rustType(item.Items) + ">"
- case "object":
- return "std::collections::BTreeMap<String, " + rustType(item.MapValues) + ">"
- default:
- fatalf("unsupported Rust schema type %q for %s", item.Type, item.Name)
- return ""
- }
-}
-
-func tsType(item *node) string {
- if len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque) {
- return item.Name
- }
- if item.Opaque {
- return "unknown"
- }
- switch item.Type {
- case "string":
- return "string"
- case "integer":
- return "number"
- case "boolean":
- return "boolean"
- case "array":
- return tsType(item.Items) + "[]"
- case "object":
- return "Record<string, " + tsType(item.MapValues) + ">"
- default:
- fatalf("unsupported TypeScript schema type %q", item.Type)
- return "never"
- }
-}
-
-func pyType(item *node) string {
- if len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque) {
- return item.Name
- }
- if item.Opaque {
- return "Any"
- }
- switch item.Type {
- case "string":
- return "str"
- case "integer":
- return "int"
- case "boolean":
- return "bool"
- case "array":
- return "list[" + pyType(item.Items) + "]"
- case "object":
- return "dict[str, " + pyType(item.MapValues) + "]"
- default:
- fatalf("unsupported Python schema type %q", item.Type)
- return "Any"
- }
-}
-
-func goType(item *node) string {
- if len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque) {
- return item.Name
- }
- if item.Opaque {
- return "any"
- }
- switch item.Type {
- case "string":
- return "string"
- case "integer":
- return "uint32"
- case "boolean":
- return "bool"
- case "array":
- return "[]" + goType(item.Items)
- case "object":
- return "map[string]" + goType(item.MapValues)
- default:
- fatalf("unsupported Go schema type %q", item.Type)
- return "any"
- }
-}
-
-func componentValue(item *node, expression string) string {
- if len(item.Enum) > 0 {
- return snake(item.Name) + "_json(" + expression + ")"
- }
- if item.Opaque {
- return "serde_json::from_str(&" + expression + ").map_err(|error| error.to_string())?"
- }
- if item.Type == "object" && item.MapValues == nil {
- return snake(item.Name) + "_json(" + expression + ")?"
- }
- switch item.Type {
- case "string", "integer", "boolean":
- return "serde_json::Value::from(" + expression + ")"
- case "array":
- inner := componentValue(item.Items, "item")
- if strings.Contains(inner, "?") {
- return "serde_json::Value::Array(" + expression + ".into_iter().map(|item| Ok(" + inner + ")).collect::<Result<Vec<_>, String>>()?)"
- }
- return "serde_json::Value::Array(" + expression + ".into_iter().map(|item| " + inner + ").collect())"
- case "object":
- return "serde_json::Value::Object(" + expression + ".into_iter().map(|entry| (entry.key, serde_json::Value::from(entry.value))).collect())"
- default:
- fatalf("unsupported component type %q", item.Type)
- return ""
- }
-}
-
-func property(schema map[string]any, name string) map[string]any {
- return mustMap(mustMap(schema["properties"], "properties")[name], name)
-}
-func stringSet(value any) map[string]bool {
- result := map[string]bool{}
- for _, item := range mustSliceDefault(value) {
- result[fmt.Sprint(item)] = true
- }
- return result
-}
-func mustSliceDefault(value any) []any {
- if value == nil {
- return nil
- }
- return mustSlice(value, "array")
-}
-func sortedKeys(values map[string]any) []string {
- keys := make([]string, 0, len(values))
- for key := range values {
- keys = append(keys, key)
- }
- sort.Strings(keys)
- return keys
-}
-func hasMap(nodes []*node) bool {
- for _, item := range nodes {
- for _, field := range item.Properties {
- if field.Type == "object" && field.MapValues != nil {
- return true
- }
- }
- }
- return false
-}
-func goNeedsPointer(item *node) bool {
- return item.Type == "string" || item.Type == "integer" || item.Type == "boolean" || len(item.Enum) > 0 || (item.Type == "object" && item.MapValues == nil && !item.Opaque)
-}
-func exportedName(value string) string {
- parts := splitWords(value)
- var out strings.Builder
- for _, part := range parts {
- if part == "" {
- continue
- }
- runes := []rune(part)
- runes[0] = unicode.ToUpper(runes[0])
- out.WriteString(string(runes))
- }
- return out.String()
-}
-func splitWords(value string) []string {
- value = strings.ReplaceAll(value, "-", "_")
- var out []string
- start := 0
- runes := []rune(value)
- for i := 1; i < len(runes); i++ {
- if unicode.IsUpper(runes[i]) && (unicode.IsLower(runes[i-1]) || unicode.IsDigit(runes[i-1])) {
- out = append(out, string(runes[start:i]))
- start = i
- }
- }
- out = append(out, string(runes[start:]))
- return strings.FieldsFunc(strings.Join(out, "_"), func(r rune) bool { return r == '_' })
-}
-func snake(value string) string {
- parts := splitWords(value)
- for i := range parts {
- parts[i] = strings.ToLower(parts[i])
- }
- return strings.Join(parts, "_")
-}
-func witName(value string) string { return strings.ReplaceAll(snake(value), "_", "-") }
-func rustField(value string) string {
- result := snake(value)
- if result == "type" {
- return "type_"
- }
- return result
-}
-func enumWIT(values []string) []string {
- result := make([]string, len(values))
- for i, value := range values {
- result[i] = witName(value)
- }
- return result
-}
-func quoteUnion(values []string) string {
- quoted := make([]string, len(values))
- for i, value := range values {
- quoted[i] = fmt.Sprintf("%q", value)
- }
- return strings.Join(quoted, " | ")
-}
-func quotedCSV(values []string) string {
- quoted := make([]string, len(values))
- for i, value := range values {
- quoted[i] = fmt.Sprintf("%q", value)
- }
- return strings.Join(quoted, ", ")
-}
-func mustMap(value any, name string) map[string]any {
- result, ok := value.(map[string]any)
- if !ok {
- fatalf("%s is not an object", name)
- }
- return result
-}
-func mustSlice(value any, name string) []any {
- result, ok := value.([]any)
- if !ok {
- fatalf("%s is not an array", name)
- }
- return result
-}
-func fatalf(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...); os.Exit(1) }
diff --git a/libs/fleet/sdk-schema-generator/main_test.go b/libs/fleet/sdk-schema-generator/main_test.go
deleted file mode 100644
index 47f68c063f..0000000000
--- a/libs/fleet/sdk-schema-generator/main_test.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package main
-
-import (
- "strings"
- "testing"
-)
-
-func TestRenderRustGeneratesBuilders(t *testing.T) {
- roots := []*rootType{{
- Name: "ExampleSpec",
- Node: &node{
- Name: "ExampleSpec",
- Type: "object",
- Properties: []*node{
- {Name: "ExampleSpecName", JSONName: "name", Type: "string", Required: true},
- {Name: "ExampleSpecCount", JSONName: "count", Type: "integer", Required: false},
- },
- },
- }}
-
- source := string(renderRust(roots))
- for _, expected := range []string{
- "pub fn builder() -> ExampleSpecBuilder",
- "pub struct ExampleSpecBuilder",
- "name: Option<String>",
- "count: Option<u32>",
- "pub fn name(mut self, value: String) -> Self",
- "pub fn count(mut self, value: u32) -> Self",
- `ok_or_else(|| "name is required".to_string())?`,
- "count: self.count",
- } {
- if !strings.Contains(source, expected) {
- t.Fatalf("generated Rust missing %q:\n%s", expected, source)
- }
- }
-}
diff --git a/libs/fleet/sdk-schema/Cargo.toml b/libs/fleet/sdk-schema/Cargo.toml
new file mode 100644
index 0000000000..d46b3e0a29
--- /dev/null
+++ b/libs/fleet/sdk-schema/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "cyclops-sdk-schema"
+version = "0.1.0"
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lib]
+crate-type = ["rlib"]
+
+[[bin]]
+name = "generate-crds"
+path = "src/generate_crds.rs"
+
+[dependencies]
+anyhow.workspace = true
+k8s-openapi.workspace = true
+kube.workspace = true
+schemars.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+serde_yaml.workspace = true
+thiserror.workspace = true
+uniffi.workspace = true
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/libs/fleet/sdk-schema/src/claim.rs b/libs/fleet/sdk-schema/src/claim.rs
new file mode 100644
index 0000000000..47fb0c9fdd
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/claim.rs
@@ -0,0 +1,184 @@
+use crate::{
+ SandboxTemplateRef,
+ common::{bool_schema, date_time_schema, integer_schema, string_schema},
+};
+use kube::CustomResource;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+fn default_warmpool() -> Option<String> {
+ Some("default".into())
+}
+
+fn default_shutdown_policy() -> Option<String> {
+ Some("Retain".into())
+}
+
+fn default_auto_renew() -> Option<bool> {
+ Some(false)
+}
+
+fn sandbox_template_ref_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ schemars::json_schema!({
+ "type": "object",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "OSGymSandboxTemplate the warm pool's OSGymSandboxes\nuse.\n"
+ }
+ }
+ })
+}
+
+fn claim_lifecycle_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ ClaimLifecycle::json_schema(generator)
+}
+
+fn claim_conditions_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Vec::<OSGymSandboxClaimCondition>::json_schema(generator)
+}
+
+fn claim_sandbox_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ OSGymSandboxClaimSandbox::json_schema(generator)
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct ClaimLifecycle {
+ #[schemars(
+ default,
+ schema_with = "date_time_schema",
+ description = "Absolute UTC expiry. The claim reaper deletes the\nclaim (GC-cascading the bound OSGymSandbox) once\nnow > shutdownTime. /step PATCHes this forward.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub shutdown_time: Option<String>,
+ #[schemars(
+ default = "default_shutdown_policy",
+ schema_with = "string_schema",
+ description = "Retain (default) — on claim deletion the bound\nOSGymSandbox is RETURNED to the warm pool and\nrestarted in place (VMI deleted -> KubeVirt\nrecreates it from spec.running:true with a fresh\ncontainerDisk overlay = clean desktop). Delete —\nthe escape hatch: destroy the OSGymSandbox CR\n(its finalizer tears down VM+Service,\nreconcile_pool respawns). The orchestrator never\nsets this field, so it picks up the new Retain\ndefault.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub shutdown_policy: Option<String>,
+ #[schemars(
+ default = "default_auto_renew",
+ schema_with = "bool_schema",
+ description = "When true, the lane auto-renew timer in\npool-operator extends shutdownTime forward on\nevery renew tick. Set on lane-backed claims\n(managed by /api/runs/{name}/lanes) so a lane's\nVM is not reaped while the customer is between\n/step calls; left false for batch claims, which\nrenew through /step as before. The orchestrator\nnever touches this -- only the cyclops-cs runs\nmanager sets it on lane create.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub auto_renew: Option<bool>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxClaimCondition {
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub type_: Option<String>,
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub status: Option<String>,
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reason: Option<String>,
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_transition_time: Option<String>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxClaimSandbox {
+ #[schemars(
+ default,
+ schema_with = "string_schema",
+ description = "Adopted OSGymSandbox name (== vmName)."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ #[schemars(
+ default,
+ schema_with = "string_schema",
+ description = "In-cluster DNS of the bound OSGymSandbox's Service.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub service: Option<String>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxClaimStatus {
+ #[schemars(
+ default,
+ schema_with = "string_schema",
+ description = "Pending | Bound | Failed — a derived field written by\nthe claim controller alongside conditions, kept for\npool.py byte-compatibility.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub phase: Option<String>,
+ #[schemars(
+ default,
+ schema_with = "claim_conditions_schema",
+ description = "Standard metav1.Condition list."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub conditions: Option<Vec<OSGymSandboxClaimCondition>>,
+ #[schemars(default, schema_with = "claim_sandbox_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sandbox: Option<OSGymSandboxClaimSandbox>,
+}
+
+#[allow(clippy::duplicated_attributes)]
+#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[kube(
+ group = "osgym.cua.ai",
+ version = "v1alpha1",
+ kind = "OSGymSandboxClaim",
+ plural = "osgymsandboxclaims",
+ namespaced,
+ shortname = "osbc",
+ status = "OSGymSandboxClaimStatus",
+ printcolumn(
+ name = "Template",
+ type_ = "string",
+ json_path = ".spec.sandboxTemplateRef.name"
+ ),
+ printcolumn(name = "Phase", type_ = "string", json_path = ".status.phase"),
+ printcolumn(name = "Sandbox", type_ = "string", json_path = ".status.sandbox.name"),
+ printcolumn(
+ name = "ShutdownTime",
+ type_ = "string",
+ json_path = ".spec.lifecycle.shutdownTime"
+ ),
+ printcolumn(
+ name = "Age",
+ type_ = "date",
+ json_path = ".metadata.creationTimestamp"
+ ),
+ doc = ""
+)]
+#[serde(rename_all = "camelCase")]
+pub struct ClaimSpec {
+ #[schemars(schema_with = "sandbox_template_ref_schema")]
+ pub sandbox_template_ref: SandboxTemplateRef,
+ #[schemars(
+ default = "default_warmpool",
+ schema_with = "string_schema",
+ description = "\"none\" | \"default\" | <name> — which OSGymSandboxWarmPool\nto adopt an OSGymSandbox from.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub warmpool: Option<String>,
+ #[schemars(
+ default,
+ schema_with = "integer_schema",
+ range(min = 0),
+ description = "Seconds the claim stays Pending waiting for a Sandbox to\nbind before it is marked Failed (default 300, set by the\noperator's OSGYM_CLAIM_BIND_DEADLINE). A Pending claim is\nthe autoscaler's demand signal, so the claim is kept\nPending across a cold VM boot + KEDA scale-up rather than\nfailing fast. Raise it for pools with slow cold starts.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bind_deadline: Option<u32>,
+ #[schemars(default, schema_with = "claim_lifecycle_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lifecycle: Option<ClaimLifecycle>,
+}
diff --git a/libs/fleet/sdk-schema/src/common.rs b/libs/fleet/sdk-schema/src/common.rs
new file mode 100644
index 0000000000..2aee8e75ba
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/common.rs
@@ -0,0 +1,261 @@
+use crate::PreservedJson;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::{collections::HashMap, sync::Arc};
+
+pub(crate) fn string_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ String::json_schema(generator)
+}
+
+pub(crate) fn bool_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ bool::json_schema(generator)
+}
+
+pub(crate) fn integer_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ schemars::json_schema!({"type": "integer"})
+}
+
+pub(crate) fn string_list_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Vec::<String>::json_schema(generator)
+}
+
+pub(crate) fn runtime_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ RuntimeKind::json_schema(generator)
+}
+
+pub(crate) fn firmware_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Firmware::json_schema(generator)
+}
+
+fn image_pull_policy_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ ImagePullPolicy::json_schema(generator)
+}
+
+fn service_protocol_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ ServiceProtocol::json_schema(generator)
+}
+
+pub(crate) fn node_selector_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ HashMap::<String, String>::json_schema(generator)
+}
+
+pub(crate) fn tolerations_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Vec::<Arc<PreservedJson>>::json_schema(generator)
+}
+
+pub(crate) fn preserved_json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ PreservedJson::json_schema(generator)
+}
+
+fn services_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Vec::<SandboxService>::json_schema(generator)
+}
+
+pub(crate) fn oidc_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ OidcConfig::json_schema(generator)
+}
+
+pub(crate) fn default_runtime() -> Option<RuntimeKind> {
+ Some(RuntimeKind::Kubevirt)
+}
+
+pub(crate) fn default_cpu_cores() -> Option<u32> {
+ Some(4)
+}
+
+pub(crate) fn default_memory() -> Option<String> {
+ Some("4Gi".into())
+}
+
+pub(crate) fn default_firmware() -> Option<Firmware> {
+ Some(Firmware::Bios)
+}
+
+fn default_protocol() -> Option<ServiceProtocol> {
+ Some(ServiceProtocol::TCP)
+}
+
+fn default_aws_region() -> Option<String> {
+ Some("us-west-2".into())
+}
+
+fn default_refresh_interval_seconds() -> Option<u32> {
+ Some(1800)
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Enum)]
+#[serde(rename_all = "lowercase")]
+pub enum RuntimeKind {
+ Kubevirt,
+ Macos,
+ Gvisor,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Enum)]
+#[serde(rename_all = "lowercase")]
+pub enum Firmware {
+ Bios,
+ Efi,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Enum)]
+pub enum ImagePullPolicy {
+ Always,
+ IfNotPresent,
+ Never,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Enum)]
+pub enum ServiceProtocol {
+ TCP,
+ UDP,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct SandboxService {
+ #[schemars(description = "Service name suffix (sandbox name is prepended).")]
+ pub name: String,
+ #[schemars(
+ description = "Port on the VM pod to forward to.",
+ range(min = 1, max = 65535)
+ )]
+ #[schemars(schema_with = "integer_schema")]
+ pub target_port: u16,
+ #[schemars(default = "default_protocol", schema_with = "service_protocol_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub protocol: Option<ServiceProtocol>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OidcConfig {
+ #[schemars(
+ description = "Name of a Secret in the pool namespace holding the tenant's Keycloak client credentials under keys client_id and client_secret."
+ )]
+ pub credentials_secret: String,
+ #[schemars(
+ description = "Keycloak token endpoint for the workloads realm, e.g. https://auth.cua.ai/realms/workloads/protocol/openid-connect/token"
+ )]
+ pub token_url: String,
+ #[schemars(
+ description = "Optional. When set, the guest is configured (env + ~/.aws/config) so the AWS SDK assumes this role via the injected web-identity token with no extra setup.",
+ schema_with = "string_schema"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub aws_role_arn: Option<String>,
+ #[schemars(
+ default = "default_aws_region",
+ schema_with = "string_schema",
+ description = "AWS region for in-guest AWS SDK calls."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub aws_region: Option<String>,
+ #[schemars(
+ default = "default_refresh_interval_seconds",
+ schema_with = "integer_schema",
+ description = "How often the in-guest refresher re-mints the token (half the 1h token TTL by default).",
+ range(min = 60)
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub refresh_interval_seconds: Option<u32>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct VmTemplate {
+ #[schemars(
+ description = "KubeVirt containerDisk OCI image (runtime=kubevirt) or the sandbox pod image ref (runtime=macos/gvisor)."
+ )]
+ pub container_disk_image: String,
+ #[schemars(
+ description = "Pod runtimes (macos/gvisor) only. Entrypoint command for the sandbox container (overrides the image default)."
+ )]
+ #[schemars(schema_with = "string_list_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub command: Option<Vec<String>>,
+ #[schemars(
+ default = "default_runtime",
+ description = "Pool backend runtime. \"kubevirt\" (default) reconciles each sandbox into a KubeVirt VM. \"macos\" reconciles it into a macOS sandbox (an agent-sandbox Sandbox on a macOS node); \"gvisor\" into a gVisor (runsc) pod on the gVisor K3s workers (also an agent-sandbox Sandbox). For the pod runtimes containerDiskImage is the pod image ref and firmware/cpuCores/memory are advisory."
+ )]
+ #[schemars(schema_with = "runtime_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub runtime: Option<RuntimeKind>,
+ #[schemars(
+ description = "Pod runtimes (macos/gvisor) only. RuntimeClass for the sandbox pod (defaults: \"cua-macos-native\" for macos, \"gvisor\" for gvisor). Ignored for kubevirt."
+ )]
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub runtime_class_name: Option<String>,
+ #[schemars(
+ description = "Pod runtimes (macos/gvisor) only. nodeSelector for the sandbox pod (defaults: cua.ai/macos=true for macos, cua.ai/gvisor=enabled for gvisor)."
+ )]
+ #[schemars(schema_with = "node_selector_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub node_selector: Option<HashMap<String, String>>,
+ #[schemars(
+ description = "Pod runtimes (macos/gvisor) only. Tolerations for the sandbox pod so it schedules onto tainted nodes (macos defaults tolerate the cua.ai/macos taint; the gVisor workers are untainted, so gvisor defaults to none)."
+ )]
+ #[schemars(schema_with = "tolerations_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub tolerations: Option<Vec<Arc<PreservedJson>>>,
+ #[schemars(
+ description = "Pod runtimes (macos/gvisor) only. Image pull policy (default IfNotPresent)."
+ )]
+ #[schemars(schema_with = "image_pull_policy_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub image_pull_policy: Option<ImagePullPolicy>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub image_pull_secret: Option<String>,
+ #[schemars(default = "default_cpu_cores", range(min = 1))]
+ #[schemars(schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu_cores: Option<u32>,
+ #[schemars(default = "default_memory")]
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub memory: Option<String>,
+ #[schemars(
+ default = "default_firmware",
+ description = "VM firmware. Use \"efi\" for GPT/UEFI-only guest images (e.g. the dockur-built Windows desktop-workspace); \"bios\" is KubeVirt's default and what the Linux workspace images boot with."
+ )]
+ #[schemars(schema_with = "firmware_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub firmware: Option<Firmware>,
+ #[schemars(
+ description = "Optional KubeVirt readinessProbe/livenessProbe for the VMI, gating ready on the guest actually serving."
+ )]
+ #[schemars(schema_with = "preserved_json_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub probes: Option<Arc<PreservedJson>>,
+ #[schemars(description = "Extra K8s Services created per-sandbox.")]
+ #[schemars(schema_with = "services_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub services: Option<Vec<SandboxService>>,
+ #[schemars(
+ description = "Optional Keycloak workload-OIDC token injection. When set, the pool-operator renders a cloud-init disk that drops the tenant-scoped Keycloak client credentials into the guest and runs an in-guest systemd refresher that mints + rotates an OIDC access token at /var/run/cua/oidc/token. Lets the workload federate into AWS (sts:AssumeRoleWithWebIdentity) and other OIDC-trust providers, scoped to the tenant that owns the pool. See docs/decisions/2026-06-25-osgym-pool-workload-oidc.md."
+ )]
+ #[schemars(schema_with = "oidc_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default)]
+ pub oidc: Option<OidcConfig>,
+}
+
+pub(crate) fn date_time_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ schemars::json_schema!({"type": "string", "format": "date-time"})
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+pub struct SandboxTemplateRef {
+ pub name: String,
+}
diff --git a/libs/fleet/sdk-schema/src/generate.rs b/libs/fleet/sdk-schema/src/generate.rs
new file mode 100644
index 0000000000..209406db92
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/generate.rs
@@ -0,0 +1,99 @@
+use crate::{
+ OSGymSandbox, OSGymSandboxClaim, OSGymSandboxTemplate, OSGymSandboxWarmPool, OSGymWorkspacePool,
+};
+use anyhow::{Context, Result, bail};
+use kube::CustomResourceExt;
+use serde::Deserialize;
+use serde_json::Value;
+use std::{fs, path::Path};
+
+pub fn render_crds() -> Result<String> {
+ let resources = [
+ serde_yaml::to_string(&OSGymSandbox::crd())?,
+ serde_yaml::to_string(&OSGymSandboxTemplate::crd())?,
+ serde_yaml::to_string(&OSGymSandboxWarmPool::crd())?,
+ serde_yaml::to_string(&OSGymSandboxClaim::crd())?,
+ serde_yaml::to_string(&OSGymWorkspacePool::crd())?,
+ ];
+
+ Ok(resources.join("---\n"))
+}
+
+pub fn write_crds(path: impl AsRef<Path>) -> Result<()> {
+ let path = path.as_ref();
+ let output = render_crds()?;
+
+ if let Some(parent) = path
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ {
+ fs::create_dir_all(parent).with_context(|| {
+ format!("failed to create CRD output directory {}", parent.display())
+ })?;
+ }
+
+ fs::write(path, output)
+ .with_context(|| format!("failed to write CRD bundle to {}", path.display()))?;
+ Ok(())
+}
+
+pub fn semantic_yaml_documents(input: &str) -> Result<Vec<Value>> {
+ serde_yaml::Deserializer::from_str(input)
+ .map(|document| {
+ let yaml = serde_yaml::Value::deserialize(document)?;
+ Ok(serde_json::to_value(yaml)?)
+ })
+ .collect()
+}
+
+pub fn check_crds(path: impl AsRef<Path>) -> Result<()> {
+ let path = path.as_ref();
+ let generated = semantic_yaml_documents(&render_crds()?)?;
+ let checked_in =
+ semantic_yaml_documents(&fs::read_to_string(path).with_context(|| {
+ format!("failed to read checked-in CRD bundle at {}", path.display())
+ })?)?;
+
+ let changed_resources = changed_resource_names(&generated, &checked_in);
+ if changed_resources.is_empty() {
+ return Ok(());
+ }
+
+ bail!(
+ "CRD bundle drift detected in {}:\n{}\nRun `cargo run --manifest-path cyclops-cs/Cargo.toml -p cyclops-sdk-schema --bin generate-crds -- --output {}` to regenerate it.",
+ path.display(),
+ changed_resources
+ .iter()
+ .map(|name| format!("- {name}"))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ path.display(),
+ );
+}
+
+fn changed_resource_names(generated: &[Value], checked_in: &[Value]) -> Vec<String> {
+ let expected_names = generated.iter().map(resource_name).collect::<Vec<_>>();
+ let actual_names = checked_in.iter().map(resource_name).collect::<Vec<_>>();
+ let mut names = Vec::new();
+
+ for (index, name) in expected_names.iter().enumerate() {
+ if generated.get(index) != checked_in.get(index) {
+ names.push((*name).to_owned());
+ }
+ }
+ for (index, name) in actual_names.iter().enumerate() {
+ if checked_in.get(index) != generated.get(index) && !names.iter().any(|entry| entry == name)
+ {
+ names.push((*name).to_owned());
+ }
+ }
+
+ names
+}
+
+fn resource_name(value: &Value) -> &str {
+ value
+ .pointer("/metadata/name")
+ .and_then(Value::as_str)
+ .unwrap_or("<unnamed document>")
+}
diff --git a/libs/fleet/sdk-schema/src/generate_crds.rs b/libs/fleet/sdk-schema/src/generate_crds.rs
new file mode 100644
index 0000000000..76ee42f666
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/generate_crds.rs
@@ -0,0 +1,40 @@
+use cyclops_sdk_schema::generate::{check_crds, write_crds};
+use std::{env, path::PathBuf, process};
+
+fn main() {
+ if let Err(error) = run() {
+ eprintln!("{error:#}");
+ process::exit(1);
+ }
+}
+
+fn run() -> anyhow::Result<()> {
+ let mut check = false;
+ let mut output = PathBuf::from("clusters/base/osgym/crd.yaml");
+ let mut arguments = env::args_os().skip(1);
+
+ while let Some(argument) = arguments.next() {
+ match argument.to_str() {
+ Some("--check") => check = true,
+ Some("--output") => {
+ output = arguments
+ .next()
+ .map(PathBuf::from)
+ .ok_or_else(|| anyhow::anyhow!("--output requires a path"))?;
+ }
+ Some("--help") | Some("-h") => {
+ println!("Usage: generate-crds [--check] [--output <path>]");
+ return Ok(());
+ }
+ _ => anyhow::bail!("unknown argument: {}", argument.to_string_lossy()),
+ }
+ }
+
+ if check {
+ return check_crds(output);
+ }
+
+ write_crds(&output)?;
+ println!("wrote {}", output.display());
+ Ok(())
+}
diff --git a/libs/fleet/sdk-schema/src/json.rs b/libs/fleet/sdk-schema/src/json.rs
new file mode 100644
index 0000000000..92de89c1b5
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/json.rs
@@ -0,0 +1,90 @@
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use serde_json::Value;
+use std::{fmt, str::FromStr, sync::Arc};
+use thiserror::Error;
+
+#[derive(Clone, Debug, PartialEq, uniffi::Object)]
+pub struct PreservedJson(Value);
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum JsonValueError {
+ #[error("value must be valid JSON: {reason}")]
+ Invalid { reason: String },
+}
+
+impl PreservedJson {
+ pub fn parse(value: String) -> Result<Self, JsonValueError> {
+ serde_json::from_str::<Value>(&value)
+ .map_err(|error| JsonValueError::Invalid {
+ reason: error.to_string(),
+ })
+ .and_then(Self::from_value)
+ }
+
+ fn from_value(value: Value) -> Result<Self, JsonValueError> {
+ if value.is_object() {
+ Ok(Self(value))
+ } else {
+ Err(JsonValueError::Invalid {
+ reason: "value must be a JSON object".into(),
+ })
+ }
+ }
+
+ pub fn as_value(&self) -> &Value {
+ &self.0
+ }
+}
+
+#[uniffi::export]
+impl PreservedJson {
+ #[uniffi::constructor]
+ pub fn from_json(value: String) -> Result<Arc<Self>, JsonValueError> {
+ Self::parse(value).map(Arc::new)
+ }
+
+ pub fn to_json(&self) -> String {
+ self.to_string()
+ }
+}
+
+impl fmt::Display for PreservedJson {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(formatter)
+ }
+}
+
+impl FromStr for PreservedJson {
+ type Err = JsonValueError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ Self::parse(value.to_owned())
+ }
+}
+
+impl Serialize for PreservedJson {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ self.0.serialize(serializer)
+ }
+}
+
+impl<'de> Deserialize<'de> for PreservedJson {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ Value::deserialize(deserializer)
+ .and_then(|value| Self::from_value(value).map_err(serde::de::Error::custom))
+ }
+}
+
+impl JsonSchema for PreservedJson {
+ fn schema_name() -> std::borrow::Cow<'static, str> {
+ "PreservedJson".into()
+ }
+
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "type": "object",
+ "x-kubernetes-preserve-unknown-fields": true,
+ })
+ }
+}
diff --git a/libs/fleet/sdk-schema/src/lib.rs b/libs/fleet/sdk-schema/src/lib.rs
new file mode 100644
index 0000000000..5fa158be26
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/lib.rs
@@ -0,0 +1,29 @@
+mod claim;
+mod common;
+pub mod generate;
+mod json;
+mod sandbox;
+mod warmpool;
+mod workspace_pool;
+
+pub use claim::{
+ ClaimLifecycle, ClaimSpec, OSGymSandboxClaim, OSGymSandboxClaimCondition,
+ OSGymSandboxClaimSandbox, OSGymSandboxClaimStatus,
+};
+pub use common::SandboxTemplateRef;
+pub use common::{
+ Firmware, ImagePullPolicy, OidcConfig, RuntimeKind, SandboxService, ServiceProtocol, VmTemplate,
+};
+pub use json::{JsonValueError, PreservedJson};
+pub use sandbox::{
+ OSGymSandbox, OSGymSandboxSpec, OSGymSandboxStatus, OSGymSandboxTemplate,
+ OSGymSandboxTemplateSpec,
+};
+pub use warmpool::{
+ OSGymSandboxWarmPool, OSGymSandboxWarmPoolSpec, OSGymSandboxWarmPoolStatus, WarmPoolAutoscaling,
+};
+pub use workspace_pool::{
+ OSGymWorkspacePool, OSGymWorkspacePoolStatus, PoolSpec, PoolTemplate, WorkspacePoolAutoscaling,
+};
+
+uniffi::setup_scaffolding!("cyclops_sdk_schema");
diff --git a/libs/fleet/sdk-schema/src/sandbox.rs b/libs/fleet/sdk-schema/src/sandbox.rs
new file mode 100644
index 0000000000..0ea65f8118
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/sandbox.rs
@@ -0,0 +1,106 @@
+use crate::{
+ VmTemplate,
+ common::{bool_schema, date_time_schema, string_schema},
+};
+use kube::CustomResource;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[allow(clippy::duplicated_attributes)]
+#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[kube(
+ group = "osgym.cua.ai",
+ version = "v1alpha1",
+ kind = "OSGymSandbox",
+ plural = "osgymsandboxes",
+ namespaced,
+ shortname = "osbx",
+ status = "OSGymSandboxStatus",
+ printcolumn(name = "Phase", type_ = "string", json_path = ".status.phase"),
+ printcolumn(name = "Ready", type_ = "boolean", json_path = ".status.ready"),
+ printcolumn(name = "VM", type_ = "string", json_path = ".status.vmName"),
+ printcolumn(
+ name = "Age",
+ type_ = "date",
+ json_path = ".metadata.creationTimestamp"
+ ),
+ doc = ""
+)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxSpec {
+ pub vm_template: VmTemplate,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxStatus {
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default, description = "Pending | Ready | Terminating.")]
+ pub phase: Option<String>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(
+ default,
+ description = "Backend that provisioned this sandbox (\"macos\" for a native macOS Sandbox, \"gvisor\" for a gVisor pod, unset/kubevirt otherwise). Set by the operator."
+ )]
+ pub runtime: Option<String>,
+ #[schemars(schema_with = "bool_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default, description = "Mirrored from the KubeVirt VM status.ready.")]
+ pub ready: Option<bool>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default, description = "Name of the owned KubeVirt VirtualMachine.")]
+ pub vm_name: Option<String>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(default, description = "In-cluster DNS of the VM's Service.")]
+ pub service: Option<String>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(
+ default,
+ description = "Human-readable detail, set when the OSGymSandbox is\nstuck (e.g. spec.vmTemplate.containerDiskImage missing).\n"
+ )]
+ pub message: Option<String>,
+ #[schemars(schema_with = "date_time_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(
+ default,
+ description = "When the in-place restart (return-to-pool) was\nissued. Used only by the reset-timeout backstop in\nsandbox_mirror_vm_status \u{2014} if the Sandbox is still\nnot Ready RESET_TIMEOUT_SECS after this, the operator\ngives up the restart and deletes the OSGymSandbox CR\n(its finalizer tears down VM+Service, reconcile_pool\nrespawns). Cleared on the Resetting->Ready transition.\n"
+ )]
+ pub reset_issued_at: Option<String>,
+ #[schemars(schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(
+ default,
+ description = "metadata.uid of the VirtualMachineInstance present\nwhen the in-place restart was issued. The mirror\ngates the Resetting->Ready transition on observing a\nVMI with a *different* uid \u{2014} i.e. KubeVirt actually\nrecreated the VMI rather than the old one lingering.\nCleared on the Resetting->Ready transition.\n"
+ )]
+ pub reset_vmi_uid: Option<String>,
+}
+
+#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[kube(
+ group = "osgym.cua.ai",
+ version = "v1alpha1",
+ kind = "OSGymSandboxTemplate",
+ plural = "osgymsandboxtemplates",
+ namespaced,
+ shortname = "osbt",
+ printcolumn(
+ name = "Image",
+ type_ = "string",
+ json_path = ".spec.vmTemplate.containerDiskImage"
+ ),
+ printcolumn(
+ name = "Age",
+ type_ = "date",
+ json_path = ".metadata.creationTimestamp"
+ ),
+ doc = ""
+)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxTemplateSpec {
+ pub vm_template: VmTemplate,
+}
diff --git a/libs/fleet/sdk-schema/src/warmpool.rs b/libs/fleet/sdk-schema/src/warmpool.rs
new file mode 100644
index 0000000000..e86bd9e78f
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/warmpool.rs
@@ -0,0 +1,116 @@
+use crate::{
+ SandboxTemplateRef,
+ common::{integer_schema, string_schema},
+};
+use kube::CustomResource;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+fn default_zero() -> Option<u32> {
+ Some(0)
+}
+
+fn default_max_pool_size() -> Option<u32> {
+ Some(50)
+}
+
+fn sandbox_template_ref_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ schemars::json_schema!({
+ "type": "object",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Name of the OSGymSandboxTemplate to use."
+ }
+ }
+ })
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct WarmPoolAutoscaling {
+ #[schemars(
+ default = "default_zero",
+ schema_with = "integer_schema",
+ range(min = 0),
+ description = "ScaledObject minReplicaCount — the durable warm\nfloor kept while the extension is enabled. 0 lets\nthe pool scale to zero when there are no claims.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub min_pool_size: Option<u32>,
+ #[schemars(
+ default = "default_zero",
+ schema_with = "integer_schema",
+ range(min = 0),
+ description = "One-time warm head-start: the pool-operator seeds\nspec.replicas to this when the pool is created so\nthe first claims bind without a cold start. KEDA\nthen owns spec.replicas; the value decays toward\nthe live claim demand (floored at minPoolSize)\nonce KEDA begins polling.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub initial_pool_size: Option<u32>,
+ #[schemars(
+ default = "default_max_pool_size",
+ schema_with = "integer_schema",
+ range(min = 1),
+ description = "ScaledObject maxReplicaCount — hard ceiling."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_pool_size: Option<u32>,
+}
+
+#[allow(clippy::duplicated_attributes)]
+#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[kube(
+ group = "osgym.cua.ai",
+ version = "v1alpha1",
+ kind = "OSGymSandboxWarmPool",
+ plural = "osgymsandboxwarmpools",
+ namespaced,
+ shortname = "oswp",
+ status = "OSGymSandboxWarmPoolStatus",
+ scale(
+ spec_replicas_path = ".spec.replicas",
+ status_replicas_path = ".status.replicas",
+ label_selector_path = ".status.selector"
+ ),
+ printcolumn(name = "Replicas", type_ = "integer", json_path = ".spec.replicas"),
+ printcolumn(name = "Ready", type_ = "integer", json_path = ".status.readyReplicas"),
+ printcolumn(
+ name = "Age",
+ type_ = "date",
+ json_path = ".metadata.creationTimestamp"
+ ),
+ doc = ""
+)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxWarmPoolSpec {
+ #[schemars(
+ schema_with = "integer_schema",
+ range(min = 0),
+ description = "Desired number of pre-warmed OSGymSandboxes."
+ )]
+ pub replicas: u32,
+ #[schemars(schema_with = "sandbox_template_ref_schema")]
+ pub sandbox_template_ref: SandboxTemplateRef,
+ #[schemars(
+ description = "OPTIONAL autoscaling extension. When present, the\npool-operator manages a KEDA ScaledObject that drives\nspec.replicas (via the /scale subresource) from the\npool's claim demand — the count of live\nOSGymSandboxClaims (Pending + Bound), published as\nosgym_pool_claim_demand. A Pending claim is unmet\ndemand so the pool grows; deleting claims shrinks it\n(drain-safe). Absent = a plain warm pool whose\nspec.replicas is set statically, with no autoscaling.\nSee docs/decisions/2026-06-15-pool-claim-autoscaling.md.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub autoscaling: Option<WarmPoolAutoscaling>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymSandboxWarmPoolStatus {
+ #[schemars(default, schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub replicas: Option<u32>,
+ #[schemars(default, schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ready_replicas: Option<u32>,
+ #[schemars(
+ default,
+ schema_with = "string_schema",
+ description = "Label selector for the pool's OSGymSandboxes."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub selector: Option<String>,
+}
diff --git a/libs/fleet/sdk-schema/src/workspace_pool.rs b/libs/fleet/sdk-schema/src/workspace_pool.rs
new file mode 100644
index 0000000000..1a73d4e180
--- /dev/null
+++ b/libs/fleet/sdk-schema/src/workspace_pool.rs
@@ -0,0 +1,250 @@
+use crate::{
+ Firmware, OidcConfig, PreservedJson, RuntimeKind, SandboxService, WarmPoolAutoscaling,
+ common::{
+ default_cpu_cores, default_firmware, default_memory, default_runtime, firmware_schema,
+ integer_schema, node_selector_schema, oidc_schema, preserved_json_schema, runtime_schema,
+ string_list_schema, string_schema, tolerations_schema,
+ },
+};
+use kube::CustomResource;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::{
+ collections::HashMap,
+ hash::{Hash, Hasher},
+ sync::Arc,
+};
+
+pub type WorkspacePoolAutoscaling = WarmPoolAutoscaling;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct PoolTemplate {
+ #[schemars(
+ default = "default_runtime",
+ schema_with = "runtime_schema",
+ description = "Pool backend. \"kubevirt\" (default) provisions a KubeVirt\nVM. \"macos\" provisions a macOS sandbox (ADMIN-ONLY\n\u{2014} the cyclops-cs backend rejects macos pool writes from\nnon-admins; the SPA hides the option). Flows verbatim\nthrough the compat shim into the OSGymSandboxTemplate\nvmTemplate, where macos_backend dispatches on it.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub runtime: Option<RuntimeKind>,
+ #[schemars(
+ default,
+ schema_with = "string_schema",
+ description = "runtime=macos only. Sandbox pod RuntimeClass (default cua-macos-native)."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub runtime_class_name: Option<String>,
+ #[schemars(
+ default,
+ schema_with = "node_selector_schema",
+ description = "runtime=macos only. nodeSelector to pin onto macOS nodes."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_selector: Option<HashMap<String, String>>,
+ #[schemars(
+ default,
+ schema_with = "tolerations_schema",
+ description = "runtime=macos only. Tolerations for tainted macOS nodes."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tolerations: Option<Vec<Arc<PreservedJson>>>,
+ #[schemars(
+ default,
+ schema_with = "string_list_schema",
+ description = "runtime=macos only. Sandbox container entrypoint."
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub command: Option<Vec<String>>,
+ pub container_disk_image: String,
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub image_pull_secret: Option<String>,
+ #[schemars(
+ default = "default_cpu_cores",
+ schema_with = "integer_schema",
+ range(min = 1)
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu_cores: Option<u32>,
+ #[schemars(default = "default_memory", schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub memory: Option<String>,
+ #[schemars(
+ default = "default_firmware",
+ schema_with = "firmware_schema",
+ description = "VM firmware. Use \"efi\" for GPT/UEFI-only guest images\n(e.g. the dockur-built Windows desktop-workspace);\n\"bios\" is KubeVirt's default and what the Linux\nworkspace images boot with.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub firmware: Option<Firmware>,
+ #[schemars(
+ default,
+ schema_with = "preserved_json_schema",
+ description = "Optional KubeVirt readinessProbe/livenessProbe for the\nVMI, gating ready on the guest actually serving. (Was\npreviously sent by the dashboard but pruned by this\nschema \u{2014} adding it makes the field actually persist.)\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub probes: Option<Arc<PreservedJson>>,
+ #[schemars(
+ default,
+ schema_with = "oidc_schema",
+ description = "Optional Keycloak workload-OIDC token injection,\npropagated verbatim by the compat shim onto the generated\nOSGymSandboxTemplate.spec.vmTemplate.oidc. When set, the\npool-operator renders a cloud-init disk that drops the\ntenant-scoped Keycloak client credentials into the guest\nand runs an in-guest refresher that mints + rotates an\nOIDC access token at /var/run/cua/oidc/token. See\ndocs/decisions/2026-06-25-osgym-pool-workload-oidc.md.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub oidc: Option<OidcConfig>,
+}
+
+#[allow(clippy::duplicated_attributes)]
+#[uniffi::export(Eq, Hash)]
+#[derive(
+ CustomResource, Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record,
+)]
+#[kube(
+ group = "cua.ai",
+ version = "v1",
+ kind = "OSGymWorkspacePool",
+ plural = "osgymworkspacepools",
+ namespaced,
+ shortname = "owsp",
+ status = "OSGymWorkspacePoolStatus",
+ printcolumn(name = "Replicas", type_ = "integer", json_path = ".spec.replicas"),
+ printcolumn(
+ name = "Available",
+ type_ = "integer",
+ json_path = ".status.availableCount"
+ ),
+ printcolumn(name = "Phase", type_ = "string", json_path = ".status.phase"),
+ printcolumn(
+ name = "Age",
+ type_ = "date",
+ json_path = ".metadata.creationTimestamp"
+ ),
+ doc = ""
+)]
+#[serde(rename_all = "camelCase")]
+pub struct PoolSpec {
+ #[schemars(schema_with = "integer_schema", range(min = 0))]
+ pub replicas: u32,
+ pub template: PoolTemplate,
+ #[schemars(
+ description = "OPTIONAL autoscaling extension. Propagated verbatim by\nthe compat shim onto the generated\nOSGymSandboxWarmPool.spec.autoscaling, which opts the\npool into KEDA autoscaling on claim demand. Absent = a\nplain pool. See\ndocs/decisions/2026-06-15-pool-claim-autoscaling.md.\n"
+ )]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub autoscaling: Option<WorkspacePoolAutoscaling>,
+ #[schemars(description = "Extra K8s Services created per-sandbox.")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub services: Option<Vec<SandboxService>>,
+}
+
+impl Hash for PoolSpec {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ let value =
+ serde_json::to_value(self).expect("PoolSpec serialization should be infallible");
+ hash_json_value(&value, state);
+ }
+}
+
+fn hash_json_value<H: Hasher>(value: &serde_json::Value, state: &mut H) {
+ match value {
+ serde_json::Value::Null => 0_u8.hash(state),
+ serde_json::Value::Bool(value) => {
+ 1_u8.hash(state);
+ value.hash(state);
+ }
+ serde_json::Value::Number(value) => {
+ 2_u8.hash(state);
+ value.hash(state);
+ }
+ serde_json::Value::String(value) => {
+ 3_u8.hash(state);
+ value.hash(state);
+ }
+ serde_json::Value::Array(values) => {
+ 4_u8.hash(state);
+ values.len().hash(state);
+ for value in values {
+ hash_json_value(value, state);
+ }
+ }
+ serde_json::Value::Object(values) => {
+ 5_u8.hash(state);
+ values.len().hash(state);
+ let mut keys: Vec<_> = values.keys().collect();
+ keys.sort_unstable();
+ for key in keys {
+ key.hash(state);
+ hash_json_value(&values[key], state);
+ }
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct OSGymWorkspacePoolStatus {
+ #[schemars(default, schema_with = "string_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub phase: Option<String>,
+ #[schemars(default, schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub total_count: Option<u32>,
+ #[schemars(default, schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub available_count: Option<u32>,
+ #[schemars(default, schema_with = "integer_schema")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub claimed_count: Option<u32>,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::{
+ collections::{HashMap, hash_map::DefaultHasher},
+ hash::{Hash, Hasher},
+ };
+
+ #[test]
+ fn canonical_json_hash_matches_equal_zero_representations() {
+ let positive = serde_json::json!(0.0);
+ let negative = serde_json::json!(-0.0);
+ assert_eq!(positive, negative);
+
+ let mut positive_hasher = DefaultHasher::new();
+ hash_json_value(&positive, &mut positive_hasher);
+ let mut negative_hasher = DefaultHasher::new();
+ hash_json_value(&negative, &mut negative_hasher);
+ assert_eq!(positive_hasher.finish(), negative_hasher.finish());
+ }
+
+ #[test]
+ fn pool_spec_hash_is_stable_across_node_selector_insertion_order() {
+ let mut left: PoolSpec = serde_json::from_value(serde_json::json!({
+ "replicas": 1,
+ "template": { "containerDiskImage": "example.invalid/workspace:latest" }
+ }))
+ .expect("pool spec fixture should deserialize");
+ let mut right = left.clone();
+
+ left.template.node_selector = Some(HashMap::from([
+ ("kubernetes.io/arch".to_string(), "amd64".to_string()),
+ (
+ "topology.kubernetes.io/zone".to_string(),
+ "us-east-1a".to_string(),
+ ),
+ ]));
+ right.template.node_selector = Some(HashMap::from([
+ (
+ "topology.kubernetes.io/zone".to_string(),
+ "us-east-1a".to_string(),
+ ),
+ ("kubernetes.io/arch".to_string(), "amd64".to_string()),
+ ]));
+
+ assert_eq!(left, right);
+
+ let mut left_hasher = DefaultHasher::new();
+ left.hash(&mut left_hasher);
+ let mut right_hasher = DefaultHasher::new();
+ right.hash(&mut right_hasher);
+ assert_eq!(left_hasher.finish(), right_hasher.finish());
+ }
+}
diff --git a/libs/fleet/sdk-schema/tests/claim_crds.rs b/libs/fleet/sdk-schema/tests/claim_crds.rs
new file mode 100644
index 0000000000..703967c892
--- /dev/null
+++ b/libs/fleet/sdk-schema/tests/claim_crds.rs
@@ -0,0 +1,119 @@
+use cyclops_sdk_schema::{OSGymSandboxClaim, OSGymSandboxWarmPool};
+use kube::CustomResourceExt;
+use serde::Deserialize;
+use serde_json::{Value, json};
+
+const AUTHORITATIVE_CRDS: &str = include_str!("../../../clusters/base/osgym/crd.yaml");
+
+fn authoritative_crd(name: &str) -> Value {
+ serde_yaml::Deserializer::from_str(AUTHORITATIVE_CRDS)
+ .map(|document| Value::deserialize(document).unwrap())
+ .find(|document| document.pointer("/metadata/name") == Some(&json!(name)))
+ .unwrap()
+}
+
+fn normalize_numbers(value: &mut Value) {
+ match value {
+ Value::Array(values) => values.iter_mut().for_each(normalize_numbers),
+ Value::Object(values) => values.values_mut().for_each(normalize_numbers),
+ Value::Number(number) => {
+ if let Some(number) = number.as_f64().filter(|number| number.fract() == 0.0) {
+ *value = json!(number as i64);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn normalize_known_kube_derive_artifacts(mut value: Value) -> Value {
+ let names = value
+ .pointer_mut("/spec/names")
+ .unwrap()
+ .as_object_mut()
+ .unwrap();
+ if names.get("categories") == Some(&json!([])) {
+ names.remove("categories");
+ }
+
+ let schema = value
+ .pointer_mut("/spec/versions/0/schema/openAPIV3Schema")
+ .unwrap()
+ .as_object_mut()
+ .unwrap();
+ schema.remove("title");
+ if schema.get("required") == Some(&json!(["spec"])) {
+ schema.remove("required");
+ }
+ let properties = schema
+ .get_mut("properties")
+ .and_then(Value::as_object_mut)
+ .unwrap();
+ if let Some(status) = properties.get_mut("status").and_then(Value::as_object_mut) {
+ status.remove("nullable");
+ }
+ if let Some(autoscaling) = properties
+ .get_mut("spec")
+ .and_then(Value::as_object_mut)
+ .and_then(|spec| spec.get_mut("properties"))
+ .and_then(Value::as_object_mut)
+ .and_then(|spec| spec.get_mut("autoscaling"))
+ .and_then(Value::as_object_mut)
+ {
+ autoscaling.remove("nullable");
+ }
+
+ normalize_numbers(&mut value);
+ value
+}
+
+#[test]
+fn raw_kube_derive_output_has_intentional_warm_pool_and_claim_shape_differences() {
+ let warm_pool = serde_json::to_value(OSGymSandboxWarmPool::crd()).unwrap();
+ let claim = serde_json::to_value(OSGymSandboxClaim::crd()).unwrap();
+
+ for value in [&warm_pool, &claim] {
+ assert_eq!(
+ value.pointer("/spec/versions/0/schema/openAPIV3Schema/required"),
+ Some(&json!(["spec"]))
+ );
+ assert!(
+ value
+ .pointer("/spec/versions/0/schema/openAPIV3Schema/title")
+ .is_some()
+ );
+ assert_eq!(value.pointer("/spec/names/categories"), Some(&json!([])));
+ assert_eq!(
+ value.pointer("/spec/versions/0/schema/openAPIV3Schema/properties/status/nullable"),
+ Some(&json!(true))
+ );
+ }
+ assert_eq!(
+ warm_pool.pointer(
+ "/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/autoscaling/nullable"
+ ),
+ Some(&json!(true))
+ );
+}
+
+#[test]
+fn warm_pool_raw_crd_matches_the_authoritative_field_contract() {
+ let generated = normalize_known_kube_derive_artifacts(
+ serde_json::to_value(OSGymSandboxWarmPool::crd()).unwrap(),
+ );
+ let authoritative = normalize_known_kube_derive_artifacts(authoritative_crd(
+ "osgymsandboxwarmpools.osgym.cua.ai",
+ ));
+
+ assert_eq!(generated, authoritative);
+}
+
+#[test]
+fn claim_raw_crd_matches_the_authoritative_field_contract() {
+ let generated = normalize_known_kube_derive_artifacts(
+ serde_json::to_value(OSGymSandboxClaim::crd()).unwrap(),
+ );
+ let authoritative =
+ normalize_known_kube_derive_artifacts(authoritative_crd("osgymsandboxclaims.osgym.cua.ai"));
+
+ assert_eq!(generated, authoritative);
+}
diff --git a/libs/fleet/sdk-schema/tests/crd_contract.rs b/libs/fleet/sdk-schema/tests/crd_contract.rs
new file mode 100644
index 0000000000..31aa427cf9
--- /dev/null
+++ b/libs/fleet/sdk-schema/tests/crd_contract.rs
@@ -0,0 +1,258 @@
+use cyclops_sdk_schema::generate::{render_crds, semantic_yaml_documents};
+use serde_json::json;
+
+const AUTHORITATIVE_CRDS: &str = include_str!("../../../clusters/base/osgym/crd.yaml");
+
+#[test]
+fn generated_bundle_matches_checked_in_contract() {
+ let generated = semantic_yaml_documents(&render_crds().unwrap()).unwrap();
+ let checked_in = semantic_yaml_documents(AUTHORITATIVE_CRDS).unwrap();
+
+ assert_eq!(generated, checked_in);
+}
+
+#[test]
+fn generated_bundle_has_stable_resource_order() {
+ let documents = semantic_yaml_documents(&render_crds().unwrap()).unwrap();
+ let names = documents
+ .iter()
+ .map(|value| value.pointer("/metadata/name").unwrap().as_str().unwrap())
+ .collect::<Vec<_>>();
+
+ assert_eq!(
+ names,
+ vec![
+ "osgymsandboxes.osgym.cua.ai",
+ "osgymsandboxtemplates.osgym.cua.ai",
+ "osgymsandboxwarmpools.osgym.cua.ai",
+ "osgymsandboxclaims.osgym.cua.ai",
+ "osgymworkspacepools.cua.ai",
+ ]
+ );
+}
+
+#[test]
+fn workspace_pool_preserves_fields_constraints_and_kubernetes_extensions() {
+ let workspace_pool = semantic_yaml_documents(&render_crds().unwrap())
+ .unwrap()
+ .into_iter()
+ .find(|document| {
+ document.pointer("/metadata/name") == Some(&json!("osgymworkspacepools.cua.ai"))
+ })
+ .unwrap();
+ let schema = "/spec/versions/0/schema/openAPIV3Schema";
+
+ assert_eq!(
+ workspace_pool.pointer(&format!("{schema}/properties/spec/required")),
+ Some(&json!(["replicas", "template"]))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/properties/spec/properties/replicas/minimum"
+ )),
+ Some(&json!(0.0))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/properties/spec/properties/template/required"
+ )),
+ Some(&json!(["containerDiskImage"]))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!("{schema}/properties/spec/properties/template/properties/tolerations/items/x-kubernetes-preserve-unknown-fields")),
+ Some(&json!(true))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!("{schema}/properties/spec/properties/template/properties/probes/x-kubernetes-preserve-unknown-fields")),
+ Some(&json!(true))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/properties/spec/properties/autoscaling/properties/minPoolSize/default"
+ )),
+ Some(&json!(0))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/properties/spec/properties/autoscaling/properties/maxPoolSize/minimum"
+ )),
+ Some(&json!(1.0))
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/properties/spec/properties/services/items/properties/targetPort/maximum"
+ )),
+ Some(&json!(65535.0))
+ );
+ assert_eq!(
+ workspace_pool.pointer("/spec/versions/0/subresources/status"),
+ Some(&json!({}))
+ );
+ assert_eq!(
+ workspace_pool.pointer("/spec/versions/0/additionalPrinterColumns"),
+ Some(&json!([
+ {"name": "Replicas", "type": "integer", "jsonPath": ".spec.replicas"},
+ {"name": "Available", "type": "integer", "jsonPath": ".status.availableCount"},
+ {"name": "Phase", "type": "string", "jsonPath": ".status.phase"},
+ {"name": "Age", "type": "date", "jsonPath": ".metadata.creationTimestamp"},
+ ]))
+ );
+}
+
+fn generated_documents() -> Vec<serde_json::Value> {
+ semantic_yaml_documents(&render_crds().unwrap()).unwrap()
+}
+
+fn write_documents(path: &std::path::Path, documents: &[serde_json::Value]) {
+ let yaml = documents
+ .iter()
+ .map(serde_yaml::to_string)
+ .collect::<Result<Vec<_>, _>>()
+ .unwrap()
+ .join("---\n");
+ std::fs::write(path, yaml).unwrap();
+}
+
+fn assert_drift_reports(documents: &[serde_json::Value], expected_names: &[&str]) {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("crd.yaml");
+ write_documents(&path, documents);
+
+ let error = cyclops_sdk_schema::generate::check_crds(&path)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("CRD bundle drift detected"));
+ for name in expected_names {
+ assert!(error.contains(name), "missing {name} from {error}");
+ }
+}
+
+#[test]
+fn workspace_pool_schema_allows_only_historical_template_paths() {
+ let documents = generated_documents();
+ let workspace_pool = documents
+ .iter()
+ .find(|document| {
+ document.pointer("/metadata/name") == Some(&json!("osgymworkspacepools.cua.ai"))
+ })
+ .unwrap();
+ let schema = "/spec/versions/0/schema/openAPIV3Schema/properties";
+ let spec = workspace_pool
+ .pointer(&format!("{schema}/spec"))
+ .and_then(serde_json::Value::as_object)
+ .unwrap();
+ let template = workspace_pool
+ .pointer(&format!("{schema}/spec/properties/template"))
+ .and_then(serde_json::Value::as_object)
+ .unwrap();
+
+ assert_eq!(spec.get("required"), Some(&json!(["replicas", "template"])));
+ assert_eq!(
+ spec.get("properties")
+ .and_then(serde_json::Value::as_object)
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect::<std::collections::BTreeSet<_>>(),
+ std::collections::BTreeSet::from(["autoscaling", "replicas", "services", "template",])
+ );
+ assert_eq!(
+ template.get("required"),
+ Some(&json!(["containerDiskImage"]))
+ );
+ assert_eq!(
+ template
+ .get("properties")
+ .and_then(serde_json::Value::as_object)
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect::<std::collections::BTreeSet<_>>(),
+ std::collections::BTreeSet::from([
+ "command",
+ "containerDiskImage",
+ "cpuCores",
+ "firmware",
+ "imagePullSecret",
+ "memory",
+ "nodeSelector",
+ "oidc",
+ "probes",
+ "runtime",
+ "runtimeClassName",
+ "tolerations",
+ ])
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/spec/properties/template/properties/imagePullPolicy"
+ )),
+ None
+ );
+ assert_eq!(
+ workspace_pool.pointer(&format!(
+ "{schema}/spec/properties/template/properties/services"
+ )),
+ None
+ );
+}
+
+#[test]
+fn check_crds_reports_modified_removed_added_reordered_and_duplicate_documents() {
+ let documents = generated_documents();
+
+ let mut modified = documents.clone();
+ *modified[0].pointer_mut("/spec/group").unwrap() = json!("changed.example");
+ assert_drift_reports(&modified, &["osgymsandboxes.osgym.cua.ai"]);
+
+ let mut removed = documents.clone();
+ removed.pop();
+ assert_drift_reports(&removed, &["osgymworkspacepools.cua.ai"]);
+
+ let mut added = documents.clone();
+ let mut additional = documents[0].clone();
+ *additional.pointer_mut("/metadata/name").unwrap() = json!("additional.cua.ai");
+ added.push(additional);
+ assert_drift_reports(&added, &["additional.cua.ai"]);
+
+ let mut reordered = documents.clone();
+ reordered.swap(0, 1);
+ assert_drift_reports(
+ &reordered,
+ &[
+ "osgymsandboxes.osgym.cua.ai",
+ "osgymsandboxtemplates.osgym.cua.ai",
+ ],
+ );
+
+ let mut duplicated = documents;
+ duplicated.push(duplicated[0].clone());
+ assert_drift_reports(&duplicated, &["osgymsandboxes.osgym.cua.ai"]);
+}
+
+#[test]
+fn write_crds_creates_parent_directories_and_contextualizes_failures() {
+ let directory = tempfile::tempdir().unwrap();
+ let output = directory.path().join("nested/generated/crd.yaml");
+ cyclops_sdk_schema::generate::write_crds(&output).unwrap();
+ assert_eq!(
+ semantic_yaml_documents(&std::fs::read_to_string(&output).unwrap()).unwrap(),
+ generated_documents()
+ );
+
+ let blocked_parent = directory.path().join("not-a-directory");
+ std::fs::write(&blocked_parent, "blocked").unwrap();
+ let error = cyclops_sdk_schema::generate::write_crds(blocked_parent.join("crd.yaml"))
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("failed to create CRD output directory"));
+ assert!(error.contains(&blocked_parent.display().to_string()));
+
+ let directory_target = directory.path().join("directory-target");
+ std::fs::create_dir(&directory_target).unwrap();
+ let error = cyclops_sdk_schema::generate::write_crds(&directory_target)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("failed to write CRD bundle"));
+ assert!(error.contains(&directory_target.display().to_string()));
+}
diff --git a/libs/fleet/sdk-schema/tests/ffi_models.rs b/libs/fleet/sdk-schema/tests/ffi_models.rs
new file mode 100644
index 0000000000..10ed7a9613
--- /dev/null
+++ b/libs/fleet/sdk-schema/tests/ffi_models.rs
@@ -0,0 +1,216 @@
+use cyclops_sdk_schema::{
+ Firmware, ImagePullPolicy, JsonValueError, OSGymSandboxClaimCondition,
+ OSGymSandboxClaimSandbox, OSGymSandboxClaimStatus, OSGymSandboxStatus,
+ OSGymSandboxWarmPoolStatus, OidcConfig, PreservedJson, RuntimeKind, SandboxService,
+ ServiceProtocol, VmTemplate,
+};
+use schemars::schema_for;
+use serde_json::json;
+use std::{collections::HashMap, sync::Arc};
+
+#[test]
+fn preserved_json_accepts_valid_json() {
+ let value = PreservedJson::parse(r#"{"exec":{"command":["true"]}}"#.into()).unwrap();
+ assert_eq!(value.to_string(), r#"{"exec":{"command":["true"]}}"#);
+}
+
+#[test]
+fn preserved_json_rejects_invalid_json() {
+ let error = PreservedJson::parse("{not-json}".into()).unwrap_err();
+ assert!(error.to_string().contains("valid JSON"));
+}
+
+#[test]
+fn preserved_json_schema_keeps_the_crd_object_contract() {
+ let schema = schema_for!(PreservedJson);
+ let value = schema.as_value();
+
+ assert_eq!(value.get("type"), Some(&json!("object")));
+ assert_eq!(
+ value.get("x-kubernetes-preserve-unknown-fields"),
+ Some(&json!(true))
+ );
+}
+
+#[test]
+fn preserved_json_from_json_returns_a_foreign_object() {
+ let value = PreservedJson::from_json(r#"{"exec":{"command":["true"]}}"#.into()).unwrap();
+
+ assert_eq!(value.to_json(), r#"{"exec":{"command":["true"]}}"#);
+}
+
+#[test]
+fn preserved_json_from_json_returns_a_structured_error() {
+ let error = PreservedJson::from_json("{not-json}".into()).unwrap_err();
+
+ assert!(matches!(error, JsonValueError::Invalid { .. }));
+}
+
+fn assert_non_object_json_is_rejected(value: &str) {
+ let parse_error = PreservedJson::parse(value.into()).unwrap_err();
+ assert!(matches!(parse_error, JsonValueError::Invalid { .. }));
+
+ let constructor_error = PreservedJson::from_json(value.into()).unwrap_err();
+ assert!(matches!(constructor_error, JsonValueError::Invalid { .. }));
+
+ let deserialize_error = serde_json::from_str::<PreservedJson>(value).unwrap_err();
+ assert!(deserialize_error.to_string().contains("JSON object"));
+}
+
+#[test]
+fn preserved_json_rejects_arrays() {
+ assert_non_object_json_is_rejected("[]");
+}
+
+#[test]
+fn preserved_json_rejects_scalars() {
+ assert_non_object_json_is_rejected("true");
+}
+
+#[test]
+fn preserved_json_rejects_null() {
+ assert_non_object_json_is_rejected("null");
+}
+
+#[test]
+fn vm_template_round_trips_every_known_field() {
+ let template = VmTemplate {
+ container_disk_image: "registry.example/vm:latest".into(),
+ command: Some(vec!["/bin/sh".into(), "-c".into(), "echo ready".into()]),
+ runtime: Some(RuntimeKind::Gvisor),
+ runtime_class_name: Some("gvisor".into()),
+ node_selector: Some(HashMap::from([("cua.ai/gvisor".into(), "enabled".into())])),
+ tolerations: Some(vec![Arc::new(
+ PreservedJson::parse(r#"{"key":"cua.ai/macos","effect":"NoSchedule"}"#.into()).unwrap(),
+ )]),
+ image_pull_policy: Some(ImagePullPolicy::IfNotPresent),
+ image_pull_secret: Some("registry-creds".into()),
+ cpu_cores: Some(8),
+ memory: Some("8Gi".into()),
+ firmware: Some(Firmware::Efi),
+ probes: Some(Arc::new(
+ PreservedJson::parse(r#"{"readinessProbe":{"tcpSocket":{"port":22}}}"#.into()).unwrap(),
+ )),
+ services: Some(vec![SandboxService {
+ name: "ssh".into(),
+ target_port: 22,
+ protocol: Some(ServiceProtocol::TCP),
+ }]),
+ oidc: Some(OidcConfig {
+ credentials_secret: "workload-oidc".into(),
+ token_url: "https://auth.example/token".into(),
+ aws_region: Some("us-west-2".into()),
+ aws_role_arn: Some("arn:aws:iam::123456789012:role/workload".into()),
+ refresh_interval_seconds: Some(900),
+ }),
+ };
+
+ let value = serde_json::to_value(&template).unwrap();
+ assert_eq!(value["imagePullPolicy"], json!("IfNotPresent"));
+ assert_eq!(value["tolerations"][0]["key"], json!("cua.ai/macos"));
+ assert_eq!(
+ value["probes"]["readinessProbe"]["tcpSocket"]["port"],
+ json!(22)
+ );
+ assert_eq!(
+ serde_json::from_value::<VmTemplate>(value).unwrap(),
+ template
+ );
+}
+
+#[test]
+fn vm_template_rejects_non_object_opaque_fields() {
+ let error = serde_json::from_value::<VmTemplate>(json!({
+ "containerDiskImage": "registry.example/vm:latest",
+ "probes": ["not", "an", "object"],
+ }))
+ .unwrap_err();
+
+ assert!(error.to_string().contains("JSON object"));
+}
+
+#[test]
+fn minimal_vm_template_omits_none_fields_and_round_trips() {
+ let template = VmTemplate {
+ container_disk_image: "registry.example/vm:latest".into(),
+ command: None,
+ runtime: None,
+ runtime_class_name: None,
+ node_selector: None,
+ tolerations: None,
+ image_pull_policy: None,
+ image_pull_secret: None,
+ cpu_cores: None,
+ memory: None,
+ firmware: None,
+ probes: None,
+ services: None,
+ oidc: None,
+ };
+
+ let value = serde_json::to_value(&template).unwrap();
+ assert_eq!(
+ value,
+ json!({"containerDiskImage": "registry.example/vm:latest"})
+ );
+ assert!(!value.to_string().contains("null"));
+ assert_eq!(
+ serde_json::from_value::<VmTemplate>(value).unwrap(),
+ template
+ );
+}
+
+#[test]
+fn exported_status_records_are_typed_and_round_trip() {
+ let sandbox_status = OSGymSandboxStatus {
+ phase: Some("Ready".into()),
+ runtime: Some("kubevirt".into()),
+ ready: Some(true),
+ vm_name: Some("sandbox-vm".into()),
+ service: Some("sandbox-service".into()),
+ message: Some("ready for claims".into()),
+ reset_issued_at: Some("2026-07-19T12:00:00Z".into()),
+ reset_vmi_uid: Some("vmi-uid".into()),
+ };
+ let warm_pool_status = OSGymSandboxWarmPoolStatus {
+ replicas: Some(3),
+ ready_replicas: Some(2),
+ selector: Some("osgym.cua.ai/pool=default".into()),
+ };
+ let claim_status = OSGymSandboxClaimStatus {
+ phase: Some("Bound".into()),
+ conditions: Some(vec![OSGymSandboxClaimCondition {
+ type_: Some("Bound".into()),
+ status: Some("True".into()),
+ reason: Some("SandboxAvailable".into()),
+ message: Some("claim bound".into()),
+ last_transition_time: Some("2026-07-19T12:00:00Z".into()),
+ }]),
+ sandbox: Some(OSGymSandboxClaimSandbox {
+ name: Some("sandbox-1".into()),
+ service: Some("sandbox-1-service".into()),
+ }),
+ };
+
+ assert_eq!(
+ serde_json::from_value::<OSGymSandboxStatus>(
+ serde_json::to_value(&sandbox_status).unwrap()
+ )
+ .unwrap(),
+ sandbox_status
+ );
+ assert_eq!(
+ serde_json::from_value::<OSGymSandboxWarmPoolStatus>(
+ serde_json::to_value(&warm_pool_status).unwrap(),
+ )
+ .unwrap(),
+ warm_pool_status
+ );
+ assert_eq!(
+ serde_json::from_value::<OSGymSandboxClaimStatus>(
+ serde_json::to_value(&claim_status).unwrap()
+ )
+ .unwrap(),
+ claim_status
+ );
+}
diff --git a/libs/fleet/sdk-schema/tests/sandbox_crds.rs b/libs/fleet/sdk-schema/tests/sandbox_crds.rs
new file mode 100644
index 0000000000..f401e55c0e
--- /dev/null
+++ b/libs/fleet/sdk-schema/tests/sandbox_crds.rs
@@ -0,0 +1,141 @@
+use cyclops_sdk_schema::{OSGymSandbox, OSGymSandboxTemplate};
+use kube::CustomResourceExt;
+use serde::Deserialize;
+use serde_json::{Value, json};
+
+const AUTHORITATIVE_CRDS: &str = include_str!("../../../clusters/base/osgym/crd.yaml");
+
+fn authoritative_crd(name: &str) -> Value {
+ serde_yaml::Deserializer::from_str(AUTHORITATIVE_CRDS)
+ .map(|document| Value::deserialize(document).unwrap())
+ .find(|document| document.pointer("/metadata/name") == Some(&json!(name)))
+ .unwrap()
+}
+
+fn normalize_numbers(value: &mut Value) {
+ match value {
+ Value::Array(values) => values.iter_mut().for_each(normalize_numbers),
+ Value::Object(values) => values.values_mut().for_each(normalize_numbers),
+ Value::Number(number) => {
+ if let Some(number) = number.as_f64().filter(|number| number.fract() == 0.0) {
+ *value = json!(number as i64);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn normalize_kube_derive_representation(mut value: Value) -> Value {
+ let names = value
+ .pointer_mut("/spec/names")
+ .unwrap()
+ .as_object_mut()
+ .unwrap();
+ if names.get("categories") == Some(&json!([])) {
+ names.remove("categories");
+ }
+
+ let schema = value
+ .pointer_mut("/spec/versions/0/schema/openAPIV3Schema")
+ .unwrap()
+ .as_object_mut()
+ .unwrap();
+ schema.remove("title");
+ if schema.get("required") == Some(&json!(["spec"])) {
+ schema.remove("required");
+ }
+ if let Some(status) = schema
+ .get_mut("properties")
+ .and_then(Value::as_object_mut)
+ .and_then(|properties| properties.get_mut("status"))
+ .and_then(Value::as_object_mut)
+ {
+ status.remove("nullable");
+ }
+
+ let version = value
+ .pointer_mut("/spec/versions/0")
+ .unwrap()
+ .as_object_mut()
+ .unwrap();
+ if version.get("subresources") == Some(&json!({})) {
+ version.remove("subresources");
+ }
+
+ normalize_numbers(&mut value);
+ value
+}
+
+#[test]
+fn raw_kube_derive_output_has_intentional_first_slice_shape_differences() {
+ let sandbox = serde_json::to_value(OSGymSandbox::crd()).unwrap();
+ let template = serde_json::to_value(OSGymSandboxTemplate::crd()).unwrap();
+
+ for value in [&sandbox, &template] {
+ assert_eq!(
+ value.pointer("/spec/versions/0/schema/openAPIV3Schema/required"),
+ Some(&json!(["spec"]))
+ );
+ assert!(
+ value
+ .pointer("/spec/versions/0/schema/openAPIV3Schema/title")
+ .is_some()
+ );
+ assert_eq!(value.pointer("/spec/names/categories"), Some(&json!([])));
+ }
+ assert_eq!(
+ sandbox.pointer("/spec/versions/0/schema/openAPIV3Schema/properties/status/nullable"),
+ Some(&json!(true))
+ );
+ assert_eq!(
+ template.pointer("/spec/versions/0/subresources"),
+ Some(&json!({}))
+ );
+}
+
+#[test]
+fn sandbox_raw_crd_matches_the_authoritative_field_contract() {
+ let generated =
+ normalize_kube_derive_representation(serde_json::to_value(OSGymSandbox::crd()).unwrap());
+ let authoritative =
+ normalize_kube_derive_representation(authoritative_crd("osgymsandboxes.osgym.cua.ai"));
+
+ assert_eq!(generated, authoritative);
+}
+
+#[test]
+fn sandbox_template_raw_crd_matches_the_authoritative_field_contract() {
+ let generated = normalize_kube_derive_representation(
+ serde_json::to_value(OSGymSandboxTemplate::crd()).unwrap(),
+ );
+ let authoritative = normalize_kube_derive_representation(authoritative_crd(
+ "osgymsandboxtemplates.osgym.cua.ai",
+ ));
+
+ assert_eq!(generated, authoritative);
+}
+
+#[test]
+fn sandbox_crd_preserves_status_and_service_constraints() {
+ let value = serde_json::to_value(OSGymSandbox::crd()).unwrap();
+
+ assert_eq!(
+ value.pointer("/spec/versions/0/subresources/status"),
+ Some(&json!({}))
+ );
+ assert_eq!(
+ value.pointer("/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/vmTemplate/properties/services/items/properties/targetPort/minimum"),
+ Some(&json!(1.0))
+ );
+ assert_eq!(
+ value.pointer("/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/vmTemplate/properties/services/items/properties/targetPort/maximum"),
+ Some(&json!(65535.0))
+ );
+}
+
+#[test]
+fn sandbox_template_has_no_status_subresource() {
+ let value = serde_json::to_value(OSGymSandboxTemplate::crd()).unwrap();
+
+ assert_eq!(value.pointer("/spec/versions/0/subresources/status"), None);
+}
diff --git a/libs/fleet/sdk/Cargo.toml b/libs/fleet/sdk/Cargo.toml
new file mode 100644
index 0000000000..433d4f81e5
--- /dev/null
+++ b/libs/fleet/sdk/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "cyclops-sdk"
+version = "0.1.0"
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lib]
+crate-type = ["lib", "cdylib"]
+
+[dependencies]
+async-trait.workspace = true
+cyclops-sdk-schema = { path = "../sdk-schema" }
+futures-timer.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
+tokio = { workspace = true, features = ["sync"] }
+uniffi.workspace = true
+url.workspace = true
+
+[dev-dependencies]
+camino = "1.0"
+tokio.workspace = true
+uniffi = { workspace = true, features = ["bindgen"] }
diff --git a/libs/fleet/sdk/src/claims.rs b/libs/fleet/sdk/src/claims.rs
new file mode 100644
index 0000000000..e97596b1bc
--- /dev/null
+++ b/libs/fleet/sdk/src/claims.rs
@@ -0,0 +1,281 @@
+use crate::{
+ Claim, CreateClaimRequest, CyclopsClient, HttpHeader, HttpRequest, HttpResponse, Pool,
+ ResourceMetadata, Sandbox, SdkError, routes,
+};
+use cyclops_sdk_schema::{ClaimSpec, SandboxTemplateRef};
+use futures_timer::Delay;
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+use std::{sync::Arc, time::Duration};
+use url::Url;
+
+const JSON_CONTENT_TYPE: &str = "application/json";
+
+#[derive(Deserialize)]
+struct ResourceList<T> {
+ items: Vec<T>,
+}
+
+#[uniffi::export]
+impl CyclopsClient {
+ pub async fn create_claim(
+ self: Arc<Self>,
+ request: CreateClaimRequest,
+ ) -> Result<Claim, SdkError> {
+ self.ensure_claim_pool_identity(&request.pool)?;
+ let pool = request.pool;
+ let spec = request.spec.unwrap_or_else(|| ClaimSpec {
+ sandbox_template_ref: SandboxTemplateRef {
+ name: format!("{}-template", pool.metadata.name),
+ },
+ warmpool: None,
+ bind_deadline: None,
+ lifecycle: None,
+ });
+ if spec.sandbox_template_ref.name.is_empty() {
+ return Err(SdkError::Configuration {
+ reason: "sandbox template name must not be empty".into(),
+ });
+ }
+
+ let claim = Claim {
+ api_version: "osgym.cua.ai/v1alpha1".into(),
+ kind: "OSGymSandboxClaim".into(),
+ metadata: ResourceMetadata {
+ namespace: pool.metadata.namespace.clone(),
+ name: claim_name(self.next_claim_sequence()?),
+ labels: None,
+ },
+ spec,
+ status: None,
+ };
+ let collection_url = routes::claim_collection(self.base_url(), &claim.metadata.namespace)?;
+ send_json(
+ self.as_ref(),
+ "create claim",
+ json_request("POST", collection_url, Some(to_json(&claim)?)),
+ &[200, 201, 202],
+ )
+ .await
+ }
+
+ pub async fn list_claims(self: Arc<Self>, namespace: String) -> Result<Vec<Claim>, SdkError> {
+ let collection_url = routes::claim_collection(self.base_url(), &namespace)?;
+ let list: ResourceList<Claim> = send_json(
+ self.as_ref(),
+ "list claims",
+ json_request("GET", collection_url, None),
+ &[200],
+ )
+ .await?;
+ Ok(list.items)
+ }
+
+ pub async fn get_claim(self: Arc<Self>, claim: Claim) -> Result<Claim, SdkError> {
+ let item_url = self.claim_item_url(&claim)?;
+ send_json(
+ self.as_ref(),
+ "get claim",
+ json_request("GET", item_url, None),
+ &[200],
+ )
+ .await
+ }
+
+ pub async fn delete_claim(self: Arc<Self>, claim: Claim) -> Result<(), SdkError> {
+ let item_url = self.claim_item_url(&claim)?;
+ send_unit(
+ self.as_ref(),
+ "delete claim",
+ json_request("DELETE", item_url, None),
+ &[200, 202, 204, 404],
+ )
+ .await
+ }
+
+ pub async fn wait_claim(self: Arc<Self>, claim: Claim) -> Result<Sandbox, SdkError> {
+ self.claim_item_url(&claim)?;
+ for attempt in 0..self.claim_poll_limit() {
+ let current = Arc::clone(&self).get_claim(claim.clone()).await?;
+ let status = current.status.as_ref();
+ let phase = status
+ .and_then(|status| status.phase.as_deref())
+ .unwrap_or("Pending");
+ if phase == "Bound" {
+ let sandbox = status
+ .and_then(|status| status.sandbox.as_ref())
+ .and_then(|sandbox| sandbox.name.as_deref())
+ .ok_or_else(|| SdkError::Body {
+ reason: "bound claim omitted status.sandbox.name".into(),
+ })?;
+ let services = service_names(&self.pool_for_claim(&current).await?);
+ return Ok(Sandbox {
+ namespace: current.metadata.namespace,
+ claim: current.metadata.name,
+ name: sandbox.into(),
+ services,
+ });
+ }
+ if is_terminal_claim_phase(phase) {
+ return Err(SdkError::ClaimFailed {
+ phase: phase.into(),
+ status: serialized_status(status)?,
+ });
+ }
+ if attempt + 1 < self.claim_poll_limit() {
+ Delay::new(Duration::from_millis(self.claim_poll_interval_ms())).await;
+ }
+ }
+ Err(SdkError::ClaimTimeout)
+ }
+}
+
+impl CyclopsClient {
+ fn ensure_claim_pool_identity(&self, pool: &Pool) -> Result<(), SdkError> {
+ routes::validate_dns_label_for("namespace", &pool.metadata.namespace)?;
+ routes::validate_dns_label_for("pool name", &pool.metadata.name)?;
+ if pool.metadata.namespace != pool.metadata.name {
+ return Err(SdkError::Configuration {
+ reason:
+ "pool metadata namespace and name must match for claim lifecycle operations"
+ .into(),
+ });
+ }
+ Ok(())
+ }
+
+ fn claim_item_url(&self, claim: &Claim) -> Result<Url, SdkError> {
+ routes::claim_item(
+ self.base_url(),
+ &claim.metadata.namespace,
+ &claim.metadata.name,
+ )
+ }
+
+ async fn pool_for_claim(&self, claim: &Claim) -> Result<Pool, SdkError> {
+ let template = &claim.spec.sandbox_template_ref.name;
+ if template.is_empty() {
+ return Err(SdkError::Body {
+ reason: "claim omitted spec.sandboxTemplateRef.name".into(),
+ });
+ }
+ let pool_name = template.strip_suffix("-template").unwrap_or(template);
+ let item_url =
+ pool_item_for_template(self.base_url(), &claim.metadata.namespace, pool_name)?;
+ send_json(
+ self,
+ "get pool services",
+ json_request("GET", item_url, None),
+ &[200],
+ )
+ .await
+ }
+}
+
+fn pool_item_for_template(base: &Url, namespace: &str, template: &str) -> Result<Url, SdkError> {
+ let mut url = routes::pool_collection(base, namespace)?;
+ url.path_segments_mut()
+ .map_err(|_| SdkError::Configuration {
+ reason: "base_url cannot accept path segments".into(),
+ })?
+ .push(template);
+ Ok(url)
+}
+
+fn claim_name(sequence: u64) -> String {
+ format!("claim-{sequence}")
+}
+
+fn service_names(pool: &Pool) -> Vec<String> {
+ let mut names: Vec<String> = pool
+ .spec
+ .services
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|service| service.name.clone())
+ .collect();
+ names.sort();
+ names.dedup();
+ names
+}
+
+fn is_terminal_claim_phase(phase: &str) -> bool {
+ matches!(phase, "Failed" | "Error" | "Expired")
+}
+
+fn serialized_status<T: Serialize>(status: Option<&T>) -> Result<String, SdkError> {
+ serde_json::to_string(&status).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })
+}
+
+fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
+ HttpRequest {
+ method: method.into(),
+ url: url.into(),
+ headers: vec![
+ HttpHeader {
+ name: "accept".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ },
+ HttpHeader {
+ name: "content-type".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ },
+ ],
+ body,
+ }
+}
+
+fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, SdkError> {
+ serde_json::to_vec(value).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })
+}
+
+async fn send_json<T: DeserializeOwned>(
+ client: &CyclopsClient,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+) -> Result<T, SdkError> {
+ let response = send_allowed(client, operation, request, allowed).await?;
+ serde_json::from_slice(&response.body).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })
+}
+
+async fn send_unit(
+ client: &CyclopsClient,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+) -> Result<(), SdkError> {
+ send_allowed(client, operation, request, allowed).await?;
+ Ok(())
+}
+
+async fn send_allowed(
+ client: &CyclopsClient,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+) -> Result<HttpResponse, SdkError> {
+ match client.execute_authenticated(request).await {
+ Ok(response) if allowed.contains(&response.status) => Ok(response),
+ Ok(response) => Err(SdkError::status(operation, response.status, &response.body)),
+ Err(SdkError::Status { status, body, .. }) if allowed.contains(&status) => {
+ Ok(HttpResponse {
+ status,
+ headers: Vec::new(),
+ body: body.into_bytes(),
+ })
+ }
+ Err(SdkError::Status { status, body, .. }) => Err(SdkError::Status {
+ operation: operation.into(),
+ status,
+ body,
+ }),
+ Err(error) => Err(error),
+ }
+}
diff --git a/libs/fleet/sdk/src/client.rs b/libs/fleet/sdk/src/client.rs
new file mode 100644
index 0000000000..5e4c6ff74c
--- /dev/null
+++ b/libs/fleet/sdk/src/client.rs
@@ -0,0 +1,197 @@
+use crate::{
+ CyclopsConfiguration, HttpClient, HttpRequest, HttpResponse, SdkError,
+ transport::{AuthenticatedRequestClass, Transport},
+};
+use std::{
+ collections::HashMap,
+ sync::{
+ Arc, Mutex, Weak,
+ atomic::{AtomicU64, Ordering},
+ },
+};
+use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
+use url::Url;
+
+#[derive(uniffi::Object)]
+pub struct CyclopsClient {
+ base_url: Url,
+ claim_sequence: AtomicU64,
+ claim_poll_interval_ms: u64,
+ claim_poll_limit: u32,
+ lifecycle_locks: Arc<NamespaceLifecycleLocks>,
+ transport: Transport,
+}
+
+struct NamespaceLifecycleLocks {
+ namespaces: Mutex<HashMap<String, Weak<AsyncMutex<()>>>>,
+}
+
+pub(crate) struct NamespaceLifecycleGuard {
+ guard: Option<OwnedMutexGuard<()>>,
+ lock: Arc<AsyncMutex<()>>,
+ locks: Arc<NamespaceLifecycleLocks>,
+ namespace: String,
+}
+
+#[uniffi::export]
+impl CyclopsClient {
+ #[uniffi::constructor]
+ pub fn connect(
+ configuration: CyclopsConfiguration,
+ http_client: Arc<dyn HttpClient>,
+ ) -> Result<Arc<Self>, SdkError> {
+ validate_configuration(&configuration)?;
+ let base_url =
+ Url::parse(&configuration.base_url).map_err(|error| SdkError::Configuration {
+ reason: format!("base_url must be a valid URL: {error}"),
+ })?;
+ let transport = Transport::new(&configuration, http_client)?;
+
+ Ok(Arc::new(Self {
+ base_url,
+ claim_sequence: AtomicU64::new(0),
+ claim_poll_interval_ms: configuration.claim_poll_interval_ms,
+ claim_poll_limit: configuration.claim_poll_limit,
+ lifecycle_locks: Arc::new(NamespaceLifecycleLocks {
+ namespaces: Mutex::new(HashMap::new()),
+ }),
+ transport,
+ }))
+ }
+}
+
+impl CyclopsClient {
+ pub(crate) fn base_url(&self) -> &Url {
+ &self.base_url
+ }
+
+ pub(crate) fn next_claim_sequence(&self) -> Result<u64, SdkError> {
+ self.claim_sequence
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
+ current.checked_add(1)
+ })
+ .map(|previous| previous + 1)
+ .map_err(|_| SdkError::Configuration {
+ reason: "claim name sequence is exhausted".into(),
+ })
+ }
+
+ pub(crate) fn claim_poll_interval_ms(&self) -> u64 {
+ self.claim_poll_interval_ms
+ }
+
+ pub(crate) fn claim_poll_limit(&self) -> u32 {
+ self.claim_poll_limit
+ }
+
+ pub(crate) async fn namespace_lifecycle_guard(
+ &self,
+ namespace: &str,
+ ) -> NamespaceLifecycleGuard {
+ let locks = Arc::clone(&self.lifecycle_locks);
+ let lock = {
+ let mut namespaces = locks
+ .namespaces
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ namespaces.retain(|_, existing| existing.strong_count() > 0);
+ match namespaces.get(namespace).and_then(Weak::upgrade) {
+ Some(existing) => existing,
+ None => {
+ let created = Arc::new(AsyncMutex::new(()));
+ namespaces.insert(namespace.into(), Arc::downgrade(&created));
+ created
+ }
+ }
+ };
+ let guard = Arc::clone(&lock).lock_owned().await;
+
+ NamespaceLifecycleGuard {
+ guard: Some(guard),
+ lock,
+ locks,
+ namespace: namespace.into(),
+ }
+ }
+
+ pub async fn execute_authenticated(
+ &self,
+ request: HttpRequest,
+ ) -> Result<HttpResponse, SdkError> {
+ self.transport
+ .execute_authenticated(request, AuthenticatedRequestClass::ControlPlane)
+ .await
+ }
+
+ pub(crate) async fn execute_authenticated_service(
+ &self,
+ request: HttpRequest,
+ ) -> Result<HttpResponse, SdkError> {
+ self.transport
+ .execute_authenticated(request, AuthenticatedRequestClass::ServiceProxy)
+ .await
+ }
+}
+
+fn validate_configuration(configuration: &CyclopsConfiguration) -> Result<(), SdkError> {
+ validate_http_url("base_url", &configuration.base_url)?;
+ validate_http_url("token_url", &configuration.token_url)?;
+
+ for (name, value) in [
+ ("pool_poll_interval_ms", configuration.pool_poll_interval_ms),
+ (
+ "claim_poll_interval_ms",
+ configuration.claim_poll_interval_ms,
+ ),
+ ] {
+ if value == 0 {
+ return Err(SdkError::Configuration {
+ reason: format!("{name} must be greater than zero"),
+ });
+ }
+ }
+
+ for (name, value) in [
+ ("pool_poll_limit", configuration.pool_poll_limit),
+ ("claim_poll_limit", configuration.claim_poll_limit),
+ ] {
+ if value == 0 {
+ return Err(SdkError::Configuration {
+ reason: format!("{name} must be greater than zero"),
+ });
+ }
+ }
+
+ Ok(())
+}
+
+fn validate_http_url(field: &str, value: &str) -> Result<(), SdkError> {
+ let url = Url::parse(value).map_err(|error| SdkError::Configuration {
+ reason: format!("{field} must be a valid URL: {error}"),
+ })?;
+
+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
+ return Err(SdkError::Configuration {
+ reason: format!("{field} must be an absolute HTTP or HTTPS URL"),
+ });
+ }
+
+ Ok(())
+}
+
+impl Drop for NamespaceLifecycleGuard {
+ fn drop(&mut self) {
+ drop(self.guard.take());
+ let mut namespaces = self
+ .locks
+ .namespaces
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let remove = namespaces.get(&self.namespace).is_some_and(|existing| {
+ Weak::ptr_eq(existing, &Arc::downgrade(&self.lock)) && existing.strong_count() == 1
+ });
+ if remove {
+ namespaces.remove(&self.namespace);
+ }
+ }
+}
diff --git a/libs/fleet/sdk/src/error.rs b/libs/fleet/sdk/src/error.rs
new file mode 100644
index 0000000000..ca365380f4
--- /dev/null
+++ b/libs/fleet/sdk/src/error.rs
@@ -0,0 +1,67 @@
+use thiserror::Error;
+
+pub const MAX_STATUS_BODY_BYTES: usize = 4_096;
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum HttpError {
+ #[error("transport error: {reason}")]
+ Transport { reason: String },
+}
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum SdkError {
+ #[error("invalid configuration: {reason}")]
+ Configuration { reason: String },
+ #[error("invalid {field} {value:?}: {reason}")]
+ InvalidResourceName {
+ field: String,
+ value: String,
+ reason: String,
+ },
+ #[error("transport error: {reason}")]
+ Transport { reason: String },
+ #[error("token error: {reason}")]
+ Token { reason: String },
+ #[error("invalid response body: {reason}")]
+ Body { reason: String },
+ #[error("{operation} returned HTTP {status}: {body}")]
+ Status {
+ operation: String,
+ status: u16,
+ body: String,
+ },
+ #[error("unknown sandbox service {requested}; available services: {available:?}")]
+ UnknownService {
+ requested: String,
+ available: Vec<String>,
+ },
+ #[error("invalid service path: {path}")]
+ InvalidServicePath { path: String },
+ #[error("claim entered terminal phase {phase}: {status}")]
+ ClaimFailed { phase: String, status: String },
+ #[error("claim did not bind before the polling limit")]
+ ClaimTimeout,
+}
+
+impl SdkError {
+ pub fn status(operation: impl Into<String>, status: u16, body: &[u8]) -> Self {
+ Self::Status {
+ operation: operation.into(),
+ status,
+ body: bounded_body(body),
+ }
+ }
+}
+
+pub fn bounded_body(body: &[u8]) -> String {
+ let rendered = String::from_utf8_lossy(body);
+ if rendered.len() <= MAX_STATUS_BODY_BYTES {
+ return rendered.into_owned();
+ }
+
+ let mut end = MAX_STATUS_BODY_BYTES;
+ while !rendered.is_char_boundary(end) {
+ end -= 1;
+ }
+ rendered[..end].into()
+}
diff --git a/libs/fleet/sdk/src/lib.rs b/libs/fleet/sdk/src/lib.rs
new file mode 100644
index 0000000000..5bc0468d7c
--- /dev/null
+++ b/libs/fleet/sdk/src/lib.rs
@@ -0,0 +1,19 @@
+mod claims;
+mod client;
+mod error;
+mod pools;
+mod routes;
+mod services;
+mod transport;
+mod types;
+
+pub use client::CyclopsClient;
+pub use error::{HttpError, MAX_STATUS_BODY_BYTES, SdkError, bounded_body};
+pub use routes::validate_dns_label;
+pub use transport::HttpClient;
+pub use types::{
+ Claim, CreateClaimRequest, CreatePoolRequest, CyclopsConfiguration, CyclopsCredentials,
+ HttpHeader, HttpRequest, HttpResponse, Pool, ResourceMetadata, Sandbox,
+};
+
+uniffi::setup_scaffolding!("cyclops_sdk");
diff --git a/libs/fleet/sdk/src/pools.rs b/libs/fleet/sdk/src/pools.rs
new file mode 100644
index 0000000000..f75e70d3f0
--- /dev/null
+++ b/libs/fleet/sdk/src/pools.rs
@@ -0,0 +1,243 @@
+use crate::{
+ CreatePoolRequest, CyclopsClient, HttpHeader, HttpRequest, HttpResponse, Pool,
+ ResourceMetadata, SdkError, routes,
+};
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+use std::sync::Arc;
+use url::Url;
+
+const JSON_CONTENT_TYPE: &str = "application/json";
+
+#[derive(Deserialize)]
+struct ResourceList<T> {
+ items: Vec<T>,
+}
+
+enum NamespaceOwnership {
+ Created,
+ Existing,
+}
+
+#[uniffi::export]
+impl CyclopsClient {
+ pub async fn create_pool(
+ self: Arc<Self>,
+ request: CreatePoolRequest,
+ ) -> Result<Pool, SdkError> {
+ let namespace_collection_url = routes::namespace_collection(self.base_url())?;
+ let namespace_item_url = routes::namespace_item(self.base_url(), &request.namespace)?;
+ let collection_url = routes::pool_collection(self.base_url(), &request.namespace)?;
+ let pool = Pool {
+ api_version: "cua.ai/v1".into(),
+ kind: "OSGymWorkspacePool".into(),
+ metadata: ResourceMetadata {
+ namespace: request.namespace.clone(),
+ name: request.namespace,
+ labels: None,
+ },
+ spec: request.spec,
+ status: None,
+ };
+ self.ensure_lifecycle_pool_identity(&pool)?;
+ routes::pool_item(
+ self.base_url(),
+ &pool.metadata.namespace,
+ &pool.metadata.name,
+ )?;
+
+ let _lifecycle_guard = self
+ .namespace_lifecycle_guard(&pool.metadata.namespace)
+ .await;
+ let namespace_created = matches!(
+ self.ensure_namespace(&namespace_collection_url, &pool.metadata.namespace)
+ .await?,
+ NamespaceOwnership::Created
+ );
+ let result = self
+ .send_json(
+ "create pool",
+ json_request("POST", collection_url, Some(to_json(&pool)?)),
+ &[200, 201, 202],
+ )
+ .await;
+
+ match result {
+ Ok(pool) => Ok(pool),
+ Err(error) => {
+ if namespace_created {
+ let _ = self.delete_namespace(&namespace_item_url).await;
+ }
+ Err(error)
+ }
+ }
+ }
+
+ pub async fn list_pools(self: Arc<Self>, namespace: String) -> Result<Vec<Pool>, SdkError> {
+ let collection_url = routes::pool_collection(self.base_url(), &namespace)?;
+ let list: ResourceList<Pool> = self
+ .send_json(
+ "list pools",
+ json_request("GET", collection_url, None),
+ &[200],
+ )
+ .await?;
+ Ok(list.items)
+ }
+
+ pub async fn get_pool(self: Arc<Self>, pool: Pool) -> Result<Pool, SdkError> {
+ let item_url = self.pool_item_url(&pool)?;
+ self.send_json("get pool", json_request("GET", item_url, None), &[200])
+ .await
+ }
+
+ pub async fn update_pool(self: Arc<Self>, pool: Pool) -> Result<Pool, SdkError> {
+ let item_url = self.pool_item_url(&pool)?;
+ let body = to_json(&pool)?;
+ self.send_json(
+ "update pool",
+ json_request("PUT", item_url, Some(body)),
+ &[200],
+ )
+ .await
+ }
+
+ pub async fn delete_pool(self: Arc<Self>, pool: Pool) -> Result<(), SdkError> {
+ self.ensure_lifecycle_pool_identity(&pool)?;
+ let item_url = self.pool_item_url(&pool)?;
+ let namespace_url = routes::namespace_item(self.base_url(), &pool.metadata.namespace)?;
+ let _lifecycle_guard = self
+ .namespace_lifecycle_guard(&pool.metadata.namespace)
+ .await;
+ self.send_unit(
+ "delete pool",
+ json_request("DELETE", item_url, None),
+ &[200, 202, 204, 404],
+ )
+ .await?;
+ self.delete_namespace(&namespace_url).await
+ }
+}
+
+impl CyclopsClient {
+ async fn ensure_namespace(
+ &self,
+ namespace_url: &Url,
+ namespace: &str,
+ ) -> Result<NamespaceOwnership, SdkError> {
+ let response = self
+ .send_allowed(
+ "create namespace",
+ json_request(
+ "POST",
+ namespace_url.clone(),
+ Some(to_json(&serde_json::json!({ "name": namespace }))?),
+ ),
+ &[201, 409],
+ )
+ .await?;
+ match response.status {
+ 201 => Ok(NamespaceOwnership::Created),
+ 409 => Ok(NamespaceOwnership::Existing),
+ status => Err(SdkError::status("create namespace", status, &response.body)),
+ }
+ }
+
+ async fn delete_namespace(&self, namespace_url: &Url) -> Result<(), SdkError> {
+ self.send_unit(
+ "delete namespace",
+ json_request("DELETE", namespace_url.clone(), None),
+ &[200, 202, 204, 404],
+ )
+ .await
+ }
+
+ fn ensure_lifecycle_pool_identity(&self, pool: &Pool) -> Result<(), SdkError> {
+ if pool.metadata.namespace != pool.metadata.name {
+ return Err(SdkError::Configuration {
+ reason:
+ "pool metadata namespace and name must match for namespace lifecycle operations"
+ .into(),
+ });
+ }
+ Ok(())
+ }
+
+ fn pool_item_url(&self, pool: &Pool) -> Result<Url, SdkError> {
+ routes::pool_item(
+ self.base_url(),
+ &pool.metadata.namespace,
+ &pool.metadata.name,
+ )
+ }
+
+ async fn send_json<T: DeserializeOwned>(
+ &self,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+ ) -> Result<T, SdkError> {
+ let response = self.send_allowed(operation, request, allowed).await?;
+ serde_json::from_slice(&response.body).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })
+ }
+
+ async fn send_unit(
+ &self,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+ ) -> Result<(), SdkError> {
+ self.send_allowed(operation, request, allowed).await?;
+ Ok(())
+ }
+
+ async fn send_allowed(
+ &self,
+ operation: &str,
+ request: HttpRequest,
+ allowed: &[u16],
+ ) -> Result<HttpResponse, SdkError> {
+ match self.execute_authenticated(request).await {
+ Ok(response) if allowed.contains(&response.status) => Ok(response),
+ Ok(response) => Err(SdkError::status(operation, response.status, &response.body)),
+ Err(SdkError::Status { status, body, .. }) if allowed.contains(&status) => {
+ Ok(HttpResponse {
+ status,
+ headers: Vec::new(),
+ body: body.into_bytes(),
+ })
+ }
+ Err(SdkError::Status { status, body, .. }) => Err(SdkError::Status {
+ operation: operation.into(),
+ status,
+ body,
+ }),
+ Err(error) => Err(error),
+ }
+ }
+}
+
+fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
+ HttpRequest {
+ method: method.into(),
+ url: url.into(),
+ headers: vec![
+ HttpHeader {
+ name: "accept".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ },
+ HttpHeader {
+ name: "content-type".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ },
+ ],
+ body,
+ }
+}
+
+fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, SdkError> {
+ serde_json::to_vec(value).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })
+}
diff --git a/libs/fleet/sdk/src/routes.rs b/libs/fleet/sdk/src/routes.rs
new file mode 100644
index 0000000000..97c7802868
--- /dev/null
+++ b/libs/fleet/sdk/src/routes.rs
@@ -0,0 +1,279 @@
+use crate::{Sandbox, SdkError};
+use url::Url;
+
+const POOL_COLLECTION_PREFIX: &str = "api/k8s/apis/cua.ai/v1/namespaces/";
+const CLAIM_COLLECTION_PREFIX: &str = "api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/";
+const CLAIM_COLLECTION_SUFFIX: &str = "/osgymsandboxclaims";
+const POOL_COLLECTION_SUFFIX: &str = "/osgymworkspacepools";
+const NAMESPACE_COLLECTION: &str = "api/namespaces";
+const NAMESPACE_PREFIX: &str = "api/namespaces/";
+const SERVICE_COLLECTION_PREFIX: &str = "api/svc/";
+
+pub fn pool_collection(base: &Url, namespace: &str) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", namespace)?;
+ route(
+ base,
+ format!("{POOL_COLLECTION_PREFIX}{namespace}{POOL_COLLECTION_SUFFIX}"),
+ )
+}
+
+pub fn pool_item(base: &Url, namespace: &str, name: &str) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", namespace)?;
+ validate_dns_label_for("name", name)?;
+ route(
+ base,
+ format!("{POOL_COLLECTION_PREFIX}{namespace}{POOL_COLLECTION_SUFFIX}/{name}"),
+ )
+}
+
+pub fn namespace_collection(base: &Url) -> Result<Url, SdkError> {
+ route(base, NAMESPACE_COLLECTION.into())
+}
+
+pub fn namespace_item(base: &Url, namespace: &str) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", namespace)?;
+ route(base, format!("{NAMESPACE_PREFIX}{namespace}"))
+}
+
+pub fn validate_dns_label(value: &str) -> Result<(), SdkError> {
+ validate_dns_label_for("resource name", value)
+}
+
+pub(crate) fn validate_dns_label_for(field: &str, value: &str) -> Result<(), SdkError> {
+ let reason = if value.is_empty() {
+ Some("must not be empty")
+ } else if value.len() > 63 {
+ Some("must be at most 63 bytes")
+ } else if value.starts_with('-') {
+ Some("must not start with a hyphen")
+ } else if value.ends_with('-') {
+ Some("must not end with a hyphen")
+ } else if !value
+ .bytes()
+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
+ {
+ Some("must contain only lowercase ASCII letters, digits, and hyphens")
+ } else {
+ None
+ };
+
+ match reason {
+ Some(reason) => Err(SdkError::InvalidResourceName {
+ field: field.into(),
+ value: value.into(),
+ reason: reason.into(),
+ }),
+ None => Ok(()),
+ }
+}
+
+fn route(base: &Url, suffix: String) -> Result<Url, SdkError> {
+ let prefix = base.path().trim_end_matches('/');
+ let path = if prefix.is_empty() {
+ format!("/{suffix}")
+ } else {
+ format!("{prefix}/{suffix}")
+ };
+ let mut url = base.clone();
+ url.set_path(&path);
+ url.set_query(None);
+ url.set_fragment(None);
+ Ok(url)
+}
+
+pub fn claim_collection(base: &Url, namespace: &str) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", namespace)?;
+ route(
+ base,
+ format!("{CLAIM_COLLECTION_PREFIX}{namespace}{CLAIM_COLLECTION_SUFFIX}"),
+ )
+}
+
+pub fn claim_item(base: &Url, namespace: &str, name: &str) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", namespace)?;
+ validate_dns_label_for("name", name)?;
+ route(
+ base,
+ format!("{CLAIM_COLLECTION_PREFIX}{namespace}{CLAIM_COLLECTION_SUFFIX}/{name}"),
+ )
+}
+
+pub fn service_url(
+ base: &Url,
+ sandbox: &Sandbox,
+ service: &str,
+ path: &str,
+) -> Result<Url, SdkError> {
+ validate_dns_label_for("namespace", &sandbox.namespace)?;
+ validate_dns_label_for("sandbox", &sandbox.name)?;
+ validate_dns_label_for("service", service)?;
+
+ let (path, query) = validate_service_path(path)?;
+ let mut url = route(
+ base,
+ format!(
+ "{SERVICE_COLLECTION_PREFIX}{}/{}-{}{}",
+ sandbox.namespace, sandbox.name, service, path
+ ),
+ )?;
+ url.set_query(query);
+ Ok(url)
+}
+
+const MAX_PERCENT_DECODE_PASSES: usize = 8;
+
+fn validate_service_path(path: &str) -> Result<(&str, Option<&str>), SdkError> {
+ if !path.starts_with('/') || path.starts_with("//") || path.contains('#') || path.contains('\\')
+ {
+ return Err(SdkError::InvalidServicePath { path: path.into() });
+ }
+
+ let (path_only, query) = path
+ .split_once('?')
+ .map_or((path, None), |(path, query)| (path, Some(query)));
+ if !is_safe_service_component(path_only, true)
+ || query.is_some_and(|query| !is_safe_service_component(query, false))
+ {
+ return Err(SdkError::InvalidServicePath { path: path.into() });
+ }
+
+ Ok((path_only, query))
+}
+
+fn is_safe_service_component(component: &str, is_path: bool) -> bool {
+ let mut bytes = component.as_bytes().to_vec();
+ for _ in 0..MAX_PERCENT_DECODE_PASSES {
+ if contains_ascii_control(&bytes) || (is_path && has_ambiguous_path_shape(&bytes)) {
+ return false;
+ }
+
+ let Some((decoded, had_percent_escape)) = decode_percent_escapes(&bytes, is_path) else {
+ return false;
+ };
+ if !had_percent_escape {
+ return true;
+ }
+ bytes = decoded;
+ }
+
+ false
+}
+
+fn contains_ascii_control(bytes: &[u8]) -> bool {
+ bytes.iter().any(|byte| *byte <= 0x1f || *byte == 0x7f)
+}
+
+fn has_ambiguous_path_shape(bytes: &[u8]) -> bool {
+ if bytes
+ .split(|byte| *byte == b'/')
+ .any(|segment| matches!(segment, b"." | b".."))
+ {
+ return true;
+ }
+
+ bytes.first() == Some(&b'/')
+ && std::str::from_utf8(&bytes[1..]).is_ok_and(|path| Url::parse(path).is_ok())
+}
+
+fn decode_percent_escapes(bytes: &[u8], is_path: bool) -> Option<(Vec<u8>, bool)> {
+ let mut decoded = Vec::with_capacity(bytes.len());
+ let mut index = 0;
+ let mut had_percent_escape = false;
+
+ while index < bytes.len() {
+ if bytes[index] != b'%' {
+ decoded.push(bytes[index]);
+ index += 1;
+ continue;
+ }
+ let value = percent_escape_value(bytes.get(index + 1)?, bytes.get(index + 2)?)?;
+ if value <= 0x1f || value == 0x7f || (is_path && matches!(value, b'/' | b'\\')) {
+ return None;
+ }
+ decoded.push(value);
+ had_percent_escape = true;
+ index += 3;
+ }
+
+ Some((decoded, had_percent_escape))
+}
+
+fn percent_escape_value(high: &u8, low: &u8) -> Option<u8> {
+ Some(hex_value(*high)? << 4 | hex_value(*low)?)
+}
+
+fn hex_value(byte: u8) -> Option<u8> {
+ match byte {
+ b'0'..=b'9' => Some(byte - b'0'),
+ b'a'..=b'f' => Some(byte - b'a' + 10),
+ b'A'..=b'F' => Some(byte - b'A' + 10),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ claim_collection, claim_item, namespace_collection, namespace_item, pool_collection,
+ pool_item,
+ };
+ use url::Url;
+
+ #[test]
+ fn routes_append_to_root_base_without_double_slashes() {
+ let base = Url::parse("https://cyclops.example:8443/").unwrap();
+
+ assert_eq!(
+ pool_collection(&base, "example-pool").unwrap().as_str(),
+ "https://cyclops.example:8443/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools"
+ );
+ assert_eq!(
+ pool_item(&base, "example-pool", "example-pool")
+ .unwrap()
+ .as_str(),
+ "https://cyclops.example:8443/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools/example-pool"
+ );
+ assert_eq!(
+ namespace_collection(&base).unwrap().as_str(),
+ "https://cyclops.example:8443/api/namespaces"
+ );
+ assert_eq!(
+ namespace_item(&base, "example-pool").unwrap().as_str(),
+ "https://cyclops.example:8443/api/namespaces/example-pool"
+ );
+ assert_eq!(
+ claim_collection(&base, "example-pool").unwrap().as_str(),
+ "https://cyclops.example:8443/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/example-pool/osgymsandboxclaims"
+ );
+ assert_eq!(
+ claim_item(&base, "example-pool", "example-claim")
+ .unwrap()
+ .as_str(),
+ "https://cyclops.example:8443/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/example-pool/osgymsandboxclaims/example-claim"
+ );
+ }
+
+ #[test]
+ fn routes_preserve_base_path_prefix_without_double_slashes() {
+ let base = Url::parse("https://gateway.example/cyclops/").unwrap();
+
+ assert_eq!(
+ pool_collection(&base, "example-pool").unwrap().as_str(),
+ "https://gateway.example/cyclops/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools"
+ );
+ assert_eq!(
+ pool_item(&base, "example-pool", "example-pool")
+ .unwrap()
+ .as_str(),
+ "https://gateway.example/cyclops/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools/example-pool"
+ );
+ assert_eq!(
+ namespace_collection(&base).unwrap().as_str(),
+ "https://gateway.example/cyclops/api/namespaces"
+ );
+ assert_eq!(
+ namespace_item(&base, "example-pool").unwrap().as_str(),
+ "https://gateway.example/cyclops/api/namespaces/example-pool"
+ );
+ }
+}
diff --git a/libs/fleet/sdk/src/services.rs b/libs/fleet/sdk/src/services.rs
new file mode 100644
index 0000000000..896624296c
--- /dev/null
+++ b/libs/fleet/sdk/src/services.rs
@@ -0,0 +1,102 @@
+use crate::{
+ HttpHeader, HttpRequest, HttpResponse, Sandbox, SdkError, client::CyclopsClient,
+ routes::service_url,
+};
+use std::{collections::HashSet, sync::Arc};
+
+#[uniffi::export]
+impl CyclopsClient {
+ pub async fn service_request(
+ self: Arc<Self>,
+ sandbox: Sandbox,
+ service: String,
+ path: String,
+ request: HttpRequest,
+ ) -> Result<HttpResponse, SdkError> {
+ if !sandbox.services.iter().any(|known| known == &service) {
+ let mut available = sandbox.services.clone();
+ available.sort_unstable();
+ available.dedup();
+ return Err(SdkError::UnknownService {
+ requested: service,
+ available,
+ });
+ }
+
+ let url = service_url(self.base_url(), &sandbox, &service, &path)?;
+ let request = HttpRequest {
+ method: request.method,
+ url: url.to_string(),
+ headers: filtered_headers(request.headers),
+ body: request.body,
+ };
+ self.execute_authenticated_service(request).await
+ }
+}
+
+fn filtered_headers(headers: Vec<HttpHeader>) -> Vec<HttpHeader> {
+ let mut blocked: HashSet<String> = [
+ "connection",
+ "host",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "proxy-connection",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ "authorization",
+ ]
+ .into_iter()
+ .map(str::to_owned)
+ .collect();
+
+ for header in &headers {
+ if header.name.eq_ignore_ascii_case("connection") {
+ for token in header.value.split(',') {
+ let token = token.trim();
+ if !token.is_empty() {
+ blocked.insert(token.to_ascii_lowercase());
+ }
+ }
+ }
+ }
+
+ headers
+ .into_iter()
+ .filter(|header| !blocked.contains(&header.name.to_ascii_lowercase()))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::filtered_headers;
+ use crate::HttpHeader;
+
+ #[test]
+ fn removes_connection_nominated_headers_case_insensitively() {
+ let headers = filtered_headers(vec![
+ HttpHeader {
+ name: "Connection".into(),
+ value: "X-Remove".into(),
+ },
+ HttpHeader {
+ name: "x-remove".into(),
+ value: "no".into(),
+ },
+ HttpHeader {
+ name: "x-keep".into(),
+ value: "yes".into(),
+ },
+ ]);
+
+ assert_eq!(
+ headers,
+ vec![HttpHeader {
+ name: "x-keep".into(),
+ value: "yes".into(),
+ }]
+ );
+ }
+}
diff --git a/libs/fleet/sdk/src/transport.rs b/libs/fleet/sdk/src/transport.rs
new file mode 100644
index 0000000000..f6b22ad300
--- /dev/null
+++ b/libs/fleet/sdk/src/transport.rs
@@ -0,0 +1,274 @@
+use crate::{CyclopsConfiguration, HttpError, HttpHeader, HttpRequest, HttpResponse, SdkError};
+use serde::Deserialize;
+use std::{
+ sync::Arc,
+ time::{Duration, Instant},
+};
+use tokio::sync::Mutex;
+use url::Url;
+
+const TOKEN_EXPIRY_SKEW: Duration = Duration::from_secs(30);
+const AUTHENTICATED_REQUEST_OPERATION: &str = "authenticated request";
+const TOKEN_OPERATION: &str = "acquire OAuth token";
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AuthenticatedRequestClass {
+ ControlPlane,
+ ServiceProxy,
+}
+
+#[uniffi::export(with_foreign)]
+#[async_trait::async_trait]
+pub trait HttpClient: Send + Sync {
+ async fn execute(&self, request: HttpRequest) -> Result<HttpResponse, HttpError>;
+}
+
+pub(crate) struct Transport {
+ base_origin: Origin,
+ token_url: String,
+ client_id: String,
+ client_secret: String,
+ http_client: Arc<dyn HttpClient>,
+ access_token: Mutex<Option<AccessToken>>,
+}
+
+#[derive(Clone)]
+struct AccessToken {
+ value: String,
+ expires_at: Instant,
+ generation: Arc<TokenGeneration>,
+}
+
+struct TokenGeneration {
+ _identity: u8,
+}
+
+#[derive(PartialEq, Eq)]
+struct Origin {
+ scheme: String,
+ host: String,
+ port: u16,
+}
+
+impl Transport {
+ pub(crate) fn new(
+ configuration: &CyclopsConfiguration,
+ http_client: Arc<dyn HttpClient>,
+ ) -> Result<Self, SdkError> {
+ Ok(Self {
+ base_origin: Origin::from_url(&configuration.base_url)?,
+ token_url: configuration.token_url.clone(),
+ client_id: configuration.client_id().to_owned(),
+ client_secret: configuration.client_secret().to_owned(),
+ http_client,
+ access_token: Mutex::new(None),
+ })
+ }
+
+ pub(crate) async fn execute_authenticated(
+ &self,
+ request: HttpRequest,
+ request_class: AuthenticatedRequestClass,
+ ) -> Result<HttpResponse, SdkError> {
+ let response = self
+ .execute_authenticated_response(request, request_class)
+ .await?;
+ match request_class {
+ AuthenticatedRequestClass::ControlPlane => self.finish_response(response),
+ AuthenticatedRequestClass::ServiceProxy => Ok(response),
+ }
+ }
+
+ async fn execute_authenticated_response(
+ &self,
+ request: HttpRequest,
+ request_class: AuthenticatedRequestClass,
+ ) -> Result<HttpResponse, SdkError> {
+ if !self.is_same_origin(&request.url) {
+ return self.execute_unchecked(request).await;
+ }
+
+ let token = self.access_token().await?;
+ let response = self
+ .execute_and_check_unauthorized(with_bearer(request.clone(), &token.value))
+ .await?;
+ if response.status != 401 || request_class == AuthenticatedRequestClass::ServiceProxy {
+ return Ok(response);
+ }
+
+ let refreshed = self.refresh_after_unauthorized(&token).await?;
+ self.execute_and_check_unauthorized(with_bearer(request, &refreshed.value))
+ .await
+ }
+
+ async fn execute_unchecked(&self, request: HttpRequest) -> Result<HttpResponse, SdkError> {
+ self.http_client
+ .execute(request)
+ .await
+ .map_err(map_http_error)
+ }
+
+ async fn execute_and_check_unauthorized(
+ &self,
+ request: HttpRequest,
+ ) -> Result<HttpResponse, SdkError> {
+ self.http_client
+ .execute(request)
+ .await
+ .map_err(map_http_error)
+ }
+
+ fn finish_response(&self, response: HttpResponse) -> Result<HttpResponse, SdkError> {
+ if (200..300).contains(&response.status) {
+ Ok(response)
+ } else {
+ Err(SdkError::status(
+ AUTHENTICATED_REQUEST_OPERATION,
+ response.status,
+ &response.body,
+ ))
+ }
+ }
+
+ async fn access_token(&self) -> Result<AccessToken, SdkError> {
+ let mut cached = self.access_token.lock().await;
+ if let Some(token) = cached.as_ref().filter(|token| token.is_valid()) {
+ return Ok(token.clone());
+ }
+
+ let token = self.acquire_token().await?;
+ *cached = Some(token.clone());
+ Ok(token)
+ }
+
+ async fn refresh_after_unauthorized(
+ &self,
+ used_token: &AccessToken,
+ ) -> Result<AccessToken, SdkError> {
+ let mut cached = self.access_token.lock().await;
+ match cached.as_ref() {
+ Some(token) if !token.is_same_generation(used_token) && token.is_valid() => {
+ return Ok(token.clone());
+ }
+ Some(token) if token.is_same_generation(used_token) => *cached = None,
+ _ => {}
+ }
+
+ let token = self.acquire_token().await?;
+ *cached = Some(token.clone());
+ Ok(token)
+ }
+
+ async fn acquire_token(&self) -> Result<AccessToken, SdkError> {
+ let body = url::form_urlencoded::Serializer::new(String::new())
+ .append_pair("grant_type", "client_credentials")
+ .append_pair("client_id", &self.client_id)
+ .append_pair("client_secret", &self.client_secret)
+ .finish();
+ let response = self
+ .http_client
+ .execute(HttpRequest {
+ method: "POST".into(),
+ url: self.token_url.clone(),
+ headers: vec![
+ HttpHeader {
+ name: "accept".into(),
+ value: "application/json".into(),
+ },
+ HttpHeader {
+ name: "content-type".into(),
+ value: "application/x-www-form-urlencoded".into(),
+ },
+ ],
+ body: Some(body.into_bytes()),
+ })
+ .await
+ .map_err(map_http_error)?;
+ if !(200..300).contains(&response.status) {
+ return Err(SdkError::status(
+ TOKEN_OPERATION,
+ response.status,
+ &response.body,
+ ));
+ }
+
+ let token: TokenResponse =
+ serde_json::from_slice(&response.body).map_err(|error| SdkError::Token {
+ reason: error.to_string(),
+ })?;
+ if token.access_token.is_empty() {
+ return Err(SdkError::Token {
+ reason: "OAuth response access_token must not be empty".into(),
+ });
+ }
+
+ let expires_at = Instant::now()
+ .checked_add(Duration::from_secs(token.expires_in))
+ .unwrap_or_else(Instant::now);
+ Ok(AccessToken {
+ value: token.access_token,
+ expires_at,
+ generation: Arc::new(TokenGeneration { _identity: 0 }),
+ })
+ }
+
+ fn is_same_origin(&self, request_url: &str) -> bool {
+ Origin::from_url(request_url).is_ok_and(|origin| origin == self.base_origin)
+ }
+}
+
+impl AccessToken {
+ fn is_same_generation(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.generation, &other.generation)
+ }
+
+ fn is_valid(&self) -> bool {
+ self.expires_at
+ .checked_sub(TOKEN_EXPIRY_SKEW)
+ .is_some_and(|refresh_at| Instant::now() < refresh_at)
+ }
+}
+
+impl Origin {
+ fn from_url(value: &str) -> Result<Self, SdkError> {
+ let url = Url::parse(value).map_err(|error| SdkError::Configuration {
+ reason: format!("URL must be valid for origin comparison: {error}"),
+ })?;
+ let host = url.host_str().ok_or_else(|| SdkError::Configuration {
+ reason: "URL must include a host for origin comparison".into(),
+ })?;
+ let port = url
+ .port_or_known_default()
+ .ok_or_else(|| SdkError::Configuration {
+ reason: "URL must have an effective port for origin comparison".into(),
+ })?;
+ Ok(Self {
+ scheme: url.scheme().to_ascii_lowercase(),
+ host: host.to_ascii_lowercase(),
+ port,
+ })
+ }
+}
+
+#[derive(Deserialize)]
+struct TokenResponse {
+ access_token: String,
+ expires_in: u64,
+}
+
+fn with_bearer(mut request: HttpRequest, token: &str) -> HttpRequest {
+ request
+ .headers
+ .retain(|header| !header.name.eq_ignore_ascii_case("authorization"));
+ request.headers.push(HttpHeader {
+ name: "authorization".into(),
+ value: format!("Bearer {token}"),
+ });
+ request
+}
+
+fn map_http_error(error: HttpError) -> SdkError {
+ match error {
+ HttpError::Transport { reason } => SdkError::Transport { reason },
+ }
+}
diff --git a/libs/fleet/sdk/src/types.rs b/libs/fleet/sdk/src/types.rs
new file mode 100644
index 0000000000..f49c76d262
--- /dev/null
+++ b/libs/fleet/sdk/src/types.rs
@@ -0,0 +1,174 @@
+use cyclops_sdk_schema::{ClaimSpec, OSGymSandboxClaimStatus, OSGymWorkspacePoolStatus, PoolSpec};
+use serde::{Deserialize, Serialize};
+use std::{collections::HashMap, fmt, sync::Arc};
+
+#[derive(uniffi::Object)]
+pub struct CyclopsCredentials {
+ client_id: String,
+ client_secret: String,
+}
+
+#[uniffi::export]
+impl CyclopsCredentials {
+ #[uniffi::constructor]
+ pub fn new(client_id: String, client_secret: String) -> Arc<Self> {
+ Arc::new(Self {
+ client_id,
+ client_secret,
+ })
+ }
+}
+
+#[allow(dead_code)]
+impl CyclopsCredentials {
+ pub(crate) fn client_id(&self) -> &str {
+ &self.client_id
+ }
+
+ pub(crate) fn client_secret(&self) -> &str {
+ &self.client_secret
+ }
+}
+
+#[derive(Clone, uniffi::Record)]
+pub struct CyclopsConfiguration {
+ pub base_url: String,
+ pub token_url: String,
+ pub credentials: Arc<CyclopsCredentials>,
+ pub pool_poll_interval_ms: u64,
+ pub pool_poll_limit: u32,
+ pub claim_poll_interval_ms: u64,
+ pub claim_poll_limit: u32,
+}
+
+impl fmt::Debug for CyclopsConfiguration {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_struct("CyclopsConfiguration")
+ .field("base_url", &self.base_url)
+ .field("token_url", &self.token_url)
+ .field("credentials", &"<redacted>")
+ .field("pool_poll_interval_ms", &self.pool_poll_interval_ms)
+ .field("pool_poll_limit", &self.pool_poll_limit)
+ .field("claim_poll_interval_ms", &self.claim_poll_interval_ms)
+ .field("claim_poll_limit", &self.claim_poll_limit)
+ .finish()
+ }
+}
+
+#[allow(dead_code)]
+impl CyclopsConfiguration {
+ pub(crate) fn client_id(&self) -> &str {
+ self.credentials.client_id()
+ }
+
+ pub(crate) fn client_secret(&self) -> &str {
+ self.credentials.client_secret()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct ResourceMetadata {
+ pub namespace: String,
+ pub name: String,
+ pub labels: Option<HashMap<String, String>>,
+}
+
+/// UniFFI cannot emit aliases for external record types. Generated bindings use
+/// `OSGymWorkspacePoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
+#[derive(Clone, Debug, Serialize, Deserialize, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct Pool {
+ pub api_version: String,
+ pub kind: String,
+ pub metadata: ResourceMetadata,
+ pub spec: PoolSpec,
+ pub status: Option<OSGymWorkspacePoolStatus>,
+}
+
+impl PartialEq for Pool {
+ fn eq(&self, other: &Self) -> bool {
+ self.api_version == other.api_version
+ && self.kind == other.kind
+ && self.metadata == other.metadata
+ && schema_values_equal(&self.spec, &other.spec)
+ && schema_values_equal(&self.status, &other.status)
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct Claim {
+ pub api_version: String,
+ pub kind: String,
+ pub metadata: ResourceMetadata,
+ pub spec: ClaimSpec,
+ pub status: Option<OSGymSandboxClaimStatus>,
+}
+
+impl PartialEq for Claim {
+ fn eq(&self, other: &Self) -> bool {
+ self.api_version == other.api_version
+ && self.kind == other.kind
+ && self.metadata == other.metadata
+ && schema_values_equal(&self.spec, &other.spec)
+ && schema_values_equal(&self.status, &other.status)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct Sandbox {
+ pub namespace: String,
+ pub claim: String,
+ pub name: String,
+ pub services: Vec<String>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, uniffi::Record)]
+pub struct CreatePoolRequest {
+ pub namespace: String,
+ pub spec: PoolSpec,
+}
+
+impl PartialEq for CreatePoolRequest {
+ fn eq(&self, other: &Self) -> bool {
+ self.namespace == other.namespace && schema_values_equal(&self.spec, &other.spec)
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, uniffi::Record)]
+pub struct CreateClaimRequest {
+ pub pool: Pool,
+ pub spec: Option<ClaimSpec>,
+}
+
+impl PartialEq for CreateClaimRequest {
+ fn eq(&self, other: &Self) -> bool {
+ self.pool == other.pool && schema_values_equal(&self.spec, &other.spec)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct HttpHeader {
+ pub name: String,
+ pub value: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct HttpRequest {
+ pub method: String,
+ pub url: String,
+ pub headers: Vec<HttpHeader>,
+ pub body: Option<Vec<u8>>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct HttpResponse {
+ pub status: u16,
+ pub headers: Vec<HttpHeader>,
+ pub body: Vec<u8>,
+}
+
+fn schema_values_equal<T: Serialize>(left: &T, right: &T) -> bool {
+ serde_json::to_value(left).ok() == serde_json::to_value(right).ok()
+}
diff --git a/libs/fleet/sdk/tests/binding_generation.rs b/libs/fleet/sdk/tests/binding_generation.rs
new file mode 100644
index 0000000000..fc462b34a8
--- /dev/null
+++ b/libs/fleet/sdk/tests/binding_generation.rs
@@ -0,0 +1,114 @@
+use camino::Utf8PathBuf;
+use std::{
+ fs,
+ path::{Path, PathBuf},
+ process::Command,
+ time::{SystemTime, UNIX_EPOCH},
+};
+use uniffi::{GenerateOptions, TargetLanguage};
+
+#[test]
+fn generated_bindings_hide_raw_credentials_and_claim_update() {
+ build_sdk_cdylib();
+
+ let output = temporary_output_directory();
+ let library = Utf8PathBuf::from_path_buf(sdk_library_path()).unwrap();
+
+ uniffi::generate(GenerateOptions {
+ languages: vec![TargetLanguage::Python, TargetLanguage::Kotlin],
+ source: library,
+ out_dir: Utf8PathBuf::from_path_buf(output.clone()).unwrap(),
+ config_override: None,
+ format: false,
+ crate_filter: Some("cyclops_sdk".into()),
+ metadata_no_deps: false,
+ })
+ .unwrap();
+
+ let python = generated_source(&output, "py");
+ let kotlin = generated_source(&output, "kt");
+ let python_configuration = record_block(
+ &python,
+ "class CyclopsConfiguration",
+ "class _UniffiFfiConverterTypeCyclopsConfiguration",
+ );
+ let kotlin_configuration = record_block(
+ &kotlin,
+ "data class CyclopsConfiguration",
+ "public object FfiConverterTypeCyclopsConfiguration",
+ );
+
+ assert!(python_configuration.contains("credentials"));
+ assert!(!python_configuration.contains("client_secret"));
+ assert!(!python_configuration.contains("clientSecret"));
+ assert!(kotlin_configuration.contains("credentials"));
+ assert!(!kotlin_configuration.contains("client_secret"));
+ assert!(!kotlin_configuration.contains("clientSecret"));
+ assert!(!python.contains("update_claim"));
+ assert!(!python.contains("updateClaim"));
+ assert!(!kotlin.contains("updateClaim"));
+ assert!(!python.contains("PoolTimeout"));
+ assert!(!python.contains("PoolFailed"));
+ assert!(!kotlin.contains("PoolTimeout"));
+ assert!(!kotlin.contains("PoolFailed"));
+
+ fs::remove_dir_all(output).unwrap();
+}
+
+fn build_sdk_cdylib() {
+ let manifest = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .join("Cargo.toml");
+ let status = Command::new(env!("CARGO"))
+ .args(["build", "--manifest-path"])
+ .arg(manifest)
+ .args(["-p", "cyclops-sdk"])
+ .status()
+ .unwrap();
+
+ assert!(status.success(), "failed to build the cyclops-sdk cdylib");
+}
+
+fn sdk_library_path() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .join("target")
+ .join("debug")
+ .join(format!("libcyclops_sdk{}", std::env::consts::DLL_SUFFIX))
+}
+
+fn temporary_output_directory() -> PathBuf {
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ std::env::temp_dir().join(format!(
+ "cyclops-sdk-bindings-{}-{timestamp}",
+ std::process::id()
+ ))
+}
+
+fn generated_source(directory: &Path, extension: &str) -> String {
+ let mut stack = vec![directory.to_path_buf()];
+ while let Some(path) = stack.pop() {
+ for entry in fs::read_dir(path).unwrap() {
+ let entry = entry.unwrap();
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if path.extension().is_some_and(|value| value == extension) {
+ return fs::read_to_string(path).unwrap();
+ }
+ }
+ }
+
+ panic!("no generated .{extension} source found");
+}
+
+fn record_block<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
+ let start = source.find(start).unwrap();
+ let source = &source[start..];
+ &source[..source.find(end).unwrap()]
+}
diff --git a/libs/fleet/sdk/tests/claim_flow.rs b/libs/fleet/sdk/tests/claim_flow.rs
new file mode 100644
index 0000000000..c83fe4b896
--- /dev/null
+++ b/libs/fleet/sdk/tests/claim_flow.rs
@@ -0,0 +1,492 @@
+mod support;
+
+use cyclops_sdk::{
+ Claim, CreateClaimRequest, CyclopsClient, CyclopsConfiguration, CyclopsCredentials, HttpHeader,
+ HttpResponse, Pool, ResourceMetadata, SdkError,
+};
+use cyclops_sdk_schema::ClaimSpec;
+use std::sync::Arc;
+use support::ScriptedHttpClient;
+
+const BASE_URL: &str = "https://cyclops.example:8443/prefix";
+const TOKEN_URL: &str = "https://identity.example/oauth/token";
+const NAMESPACE: &str = "example-pool";
+const CLAIM_COLLECTION: &str = "https://cyclops.example:8443/prefix/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/example-pool/osgymsandboxclaims";
+const POOL_ITEM: &str = "https://cyclops.example:8443/prefix/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools/example-pool";
+
+#[tokio::test]
+async fn creates_pending_demand_immediately_for_a_nonzero_unavailable_pool() {
+ let spec = claim_spec("explicit-template");
+ let created = claim("claim-1", spec.clone(), None);
+ let mut unavailable_pool = pool(1, None);
+ unavailable_pool.status = Some(
+ serde_json::from_value(serde_json::json!({ "availableCount": 0, "phase": "Pending" }))
+ .unwrap(),
+ );
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(201, &created)),
+ ]));
+
+ assert_eq!(
+ client(Arc::clone(&http), 2, 2)
+ .create_claim(CreateClaimRequest {
+ pool: unavailable_pool,
+ spec: Some(spec),
+ })
+ .await
+ .unwrap(),
+ created
+ );
+
+ let requests = http.authenticated_requests().await;
+ assert_eq!(requests.len(), 1);
+ assert_request(
+ &requests[0],
+ "POST",
+ CLAIM_COLLECTION,
+ Some(&json_bytes(&created)),
+ );
+}
+
+#[tokio::test]
+async fn zero_and_nonzero_pools_post_claims_with_identical_sequencing() {
+ for replicas in [0, 1] {
+ let expected = claim("claim-1", claim_spec("example-pool-template"), None);
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(201, &expected)),
+ ]));
+
+ client(Arc::clone(&http), 2, 2)
+ .create_claim(CreateClaimRequest {
+ pool: pool(replicas, None),
+ spec: None,
+ })
+ .await
+ .unwrap();
+
+ let requests = http.authenticated_requests().await;
+ assert_eq!(requests.len(), 1, "replicas={replicas}");
+ assert_request(
+ &requests[0],
+ "POST",
+ CLAIM_COLLECTION,
+ Some(&json_bytes(&expected)),
+ );
+ }
+}
+#[tokio::test]
+async fn claim_crud_uses_prefixed_routes_and_expected_statuses() {
+ let current = claim("named-claim", claim_spec("example-pool-template"), None);
+ let item = format!("{CLAIM_COLLECTION}/named-claim");
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(
+ 200,
+ &serde_json::json!({ "items": [current.clone()] }),
+ )),
+ Ok(json_response(200, &current)),
+ Ok(response(204, b"")),
+ ]));
+ let client = client(Arc::clone(&http), 1, 1);
+
+ assert_eq!(
+ client.clone().list_claims(NAMESPACE.into()).await.unwrap(),
+ vec![current.clone()]
+ );
+ assert_eq!(
+ client.clone().get_claim(current.clone()).await.unwrap(),
+ current
+ );
+ client.clone().delete_claim(current.clone()).await.unwrap();
+
+ let requests = http.authenticated_requests().await;
+ assert_request(&requests[0], "GET", CLAIM_COLLECTION, None);
+ assert_request(&requests[1], "GET", &item, None);
+ assert_request(&requests[2], "DELETE", &item, None);
+}
+
+#[tokio::test]
+async fn wait_claim_returns_bound_sandbox_with_sorted_deduplicated_pool_services() {
+ let current = claim(
+ "named-claim",
+ claim_spec("example-pool-template"),
+ Some(serde_json::json!({
+ "phase": "Bound",
+ "sandbox": { "name": "sandbox-42", "service": "internal-only" },
+ })),
+ );
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &current)),
+ Ok(json_response(200, &pool(1, Some(vec!["z", "a", "z"])))),
+ ]));
+ let client = client(Arc::clone(&http), 1, 2);
+
+ assert_eq!(
+ client.wait_claim(current.clone()).await.unwrap(),
+ cyclops_sdk::Sandbox {
+ namespace: NAMESPACE.into(),
+ claim: "named-claim".into(),
+ name: "sandbox-42".into(),
+ services: vec!["a".into(), "z".into()],
+ }
+ );
+
+ let requests = http.authenticated_requests().await;
+ assert_request(
+ &requests[0],
+ "GET",
+ &format!("{CLAIM_COLLECTION}/named-claim"),
+ None,
+ );
+ assert_request(&requests[1], "GET", POOL_ITEM, None);
+}
+
+#[tokio::test]
+async fn wait_claim_reports_terminal_and_timeout_statuses() {
+ let failed = claim(
+ "named-claim",
+ claim_spec("example-pool-template"),
+ Some(serde_json::json!({ "phase": "Failed", "conditions": [] })),
+ );
+ let failed_http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &failed)),
+ ]));
+ assert!(matches!(
+ client(Arc::clone(&failed_http), 1, 2).wait_claim(failed).await,
+ Err(SdkError::ClaimFailed { ref phase, ref status })
+ if phase == "Failed" && status.contains("conditions")
+ ));
+
+ let pending = claim("named-claim", claim_spec("example-pool-template"), None);
+ let timeout_http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &pending)),
+ Ok(json_response(200, &pending)),
+ ]));
+ assert!(matches!(
+ client(Arc::clone(&timeout_http), 1, 2)
+ .wait_claim(pending)
+ .await,
+ Err(SdkError::ClaimTimeout)
+ ));
+ assert_eq!(timeout_http.authenticated_requests().await.len(), 2);
+}
+
+#[tokio::test]
+async fn generated_claim_names_are_unique_under_concurrency_and_fit_dns_labels() {
+ let pool_name = "a".repeat(63);
+ let pool = pool_named(&pool_name, 0, None);
+ let first = claim("placeholder", claim_spec("short-template"), None);
+ let second = first.clone();
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(201, &first)),
+ Ok(json_response(201, &second)),
+ ]));
+ let client = client(Arc::clone(&http), 1, 1);
+
+ let (first, second) = tokio::join!(
+ client.clone().create_claim(CreateClaimRequest {
+ pool: pool.clone(),
+ spec: Some(claim_spec("short-template"))
+ }),
+ client.create_claim(CreateClaimRequest {
+ pool,
+ spec: Some(claim_spec("short-template"))
+ }),
+ );
+ assert!(first.is_ok());
+ assert!(second.is_ok());
+
+ let requests = http.authenticated_requests().await;
+ let names: Vec<String> = requests
+ .iter()
+ .map(|request| {
+ let body: serde_json::Value =
+ serde_json::from_slice(request.body.as_deref().unwrap()).unwrap();
+ body["metadata"]["name"].as_str().unwrap().to_owned()
+ })
+ .collect();
+ assert_eq!(names.len(), 2);
+ assert_ne!(names[0], names[1]);
+ assert!(names.iter().all(|name| name.len() <= 63));
+ assert!(names.iter().all(|name| {
+ name.bytes()
+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
+ }));
+}
+
+#[tokio::test]
+async fn validation_and_malformed_responses_fail_without_unexpected_http() {
+ let invalid_http = Arc::new(ScriptedHttpClient::new([]));
+ let invalid_pool = Pool {
+ metadata: ResourceMetadata {
+ namespace: "Uppercase".into(),
+ ..pool(0, None).metadata
+ },
+ ..pool(0, None)
+ };
+ assert!(matches!(
+ client(Arc::clone(&invalid_http), 1, 1)
+ .create_claim(CreateClaimRequest {
+ pool: invalid_pool,
+ spec: None
+ })
+ .await,
+ Err(SdkError::InvalidResourceName { .. })
+ ));
+ assert_eq!(invalid_http.request_count().await, 0);
+
+ let invalid_name_http = Arc::new(ScriptedHttpClient::new([]));
+ let invalid_claim = Claim {
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: "Uppercase".into(),
+ labels: None,
+ },
+ ..claim("valid-claim", claim_spec("example-pool-template"), None)
+ };
+ assert!(matches!(
+ client(Arc::clone(&invalid_name_http), 1, 1)
+ .get_claim(invalid_claim)
+ .await,
+ Err(SdkError::InvalidResourceName { .. })
+ ));
+ assert_eq!(invalid_name_http.request_count().await, 0);
+
+ let malformed_http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, b"not json")),
+ ]));
+ assert!(matches!(
+ client(Arc::clone(&malformed_http), 1, 1)
+ .list_claims(NAMESPACE.into())
+ .await,
+ Err(SdkError::Body { .. })
+ ));
+}
+
+fn client(http: Arc<ScriptedHttpClient>, pool_limit: u32, claim_limit: u32) -> Arc<CyclopsClient> {
+ CyclopsClient::connect(
+ CyclopsConfiguration {
+ base_url: BASE_URL.into(),
+ token_url: TOKEN_URL.into(),
+ credentials: CyclopsCredentials::new("client".into(), "secret".into()),
+ pool_poll_interval_ms: 1,
+ pool_poll_limit: pool_limit,
+ claim_poll_interval_ms: 1,
+ claim_poll_limit: claim_limit,
+ },
+ http,
+ )
+ .unwrap()
+}
+
+fn pool(replicas: u32, services: Option<Vec<&str>>) -> Pool {
+ pool_named(NAMESPACE, replicas, services)
+}
+
+fn pool_named(name: &str, replicas: u32, services: Option<Vec<&str>>) -> Pool {
+ let services = services.map(|services| {
+ services
+ .into_iter()
+ .map(|name| serde_json::json!({ "name": name, "targetPort": 8080 }))
+ .collect::<Vec<_>>()
+ });
+ Pool {
+ api_version: "cua.ai/v1".into(),
+ kind: "OSGymWorkspacePool".into(),
+ metadata: ResourceMetadata {
+ namespace: name.into(),
+ name: name.into(),
+ labels: None,
+ },
+ spec: serde_json::from_value(serde_json::json!({
+ "replicas": replicas,
+ "template": { "containerDiskImage": "registry.example/image:latest" },
+ "services": services,
+ }))
+ .unwrap(),
+ status: None,
+ }
+}
+
+fn claim(name: &str, spec: ClaimSpec, status: Option<serde_json::Value>) -> Claim {
+ Claim {
+ api_version: "osgym.cua.ai/v1alpha1".into(),
+ kind: "OSGymSandboxClaim".into(),
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: name.into(),
+ labels: None,
+ },
+ spec,
+ status: status.map(|status| serde_json::from_value(status).unwrap()),
+ }
+}
+
+fn claim_spec(template: &str) -> ClaimSpec {
+ serde_json::from_value(serde_json::json!({ "sandboxTemplateRef": { "name": template } }))
+ .unwrap()
+}
+
+fn token() -> HttpResponse {
+ response(200, br#"{"access_token":"token-a","expires_in":3600}"#)
+}
+fn json_response(status: u16, value: &impl serde::Serialize) -> HttpResponse {
+ response(status, &json_bytes(value))
+}
+fn json_bytes(value: &impl serde::Serialize) -> Vec<u8> {
+ serde_json::to_vec(value).unwrap()
+}
+fn response(status: u16, body: &[u8]) -> HttpResponse {
+ HttpResponse {
+ status,
+ headers: Vec::new(),
+ body: body.to_vec(),
+ }
+}
+fn assert_request(
+ request: &cyclops_sdk::HttpRequest,
+ method: &str,
+ url: &str,
+ body: Option<&[u8]>,
+) {
+ assert_eq!(request.method, method);
+ assert_eq!(request.url, url);
+ assert_eq!(request.body.as_deref(), body);
+ assert_eq!(
+ request.headers,
+ vec![
+ HttpHeader {
+ name: "accept".into(),
+ value: "application/json".into()
+ },
+ HttpHeader {
+ name: "content-type".into(),
+ value: "application/json".into()
+ },
+ HttpHeader {
+ name: "authorization".into(),
+ value: "Bearer token-a".into()
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn default_template_ref_for_a_63_byte_pool_passes_through_without_dns_validation() {
+ let pool_name = "a".repeat(63);
+ let template_name = format!("{pool_name}-template");
+ let pool = pool_named(&pool_name, 0, None);
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(
+ 201,
+ &claim("claim-1", claim_spec(&template_name), None),
+ )),
+ ]));
+
+ client(Arc::clone(&http), 1, 1)
+ .create_claim(CreateClaimRequest { pool, spec: None })
+ .await
+ .unwrap();
+
+ let requests = http.authenticated_requests().await;
+ assert_eq!(requests.len(), 1);
+ let body: serde_json::Value =
+ serde_json::from_slice(requests[0].body.as_deref().unwrap()).unwrap();
+ assert_eq!(body["spec"]["sandboxTemplateRef"]["name"], template_name);
+}
+
+#[tokio::test]
+async fn explicit_non_dns_template_ref_passes_through_but_empty_ref_is_rejected_before_http() {
+ let template_name = "Team_Name/Template:with spaces";
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(
+ 201,
+ &claim("claim-1", claim_spec(template_name), None),
+ )),
+ ]));
+ client(Arc::clone(&http), 1, 1)
+ .create_claim(CreateClaimRequest {
+ pool: pool(0, None),
+ spec: Some(claim_spec(template_name)),
+ })
+ .await
+ .unwrap();
+ let requests = http.authenticated_requests().await;
+ let body: serde_json::Value =
+ serde_json::from_slice(requests[0].body.as_deref().unwrap()).unwrap();
+ assert_eq!(body["spec"]["sandboxTemplateRef"]["name"], template_name);
+
+ let empty_http = Arc::new(ScriptedHttpClient::new([]));
+ assert!(matches!(
+ client(Arc::clone(&empty_http), 1, 1)
+ .create_claim(CreateClaimRequest {
+ pool: pool(0, None),
+ spec: Some(claim_spec("")),
+ })
+ .await,
+ Err(SdkError::Configuration { .. })
+ ));
+ assert_eq!(empty_http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn wait_claim_uses_controller_removesuffix_behavior_for_template_refs_without_suffixes() {
+ let current = claim(
+ "named-claim",
+ claim_spec("example-pool"),
+ Some(serde_json::json!({
+ "phase": "Bound",
+ "sandbox": { "name": "sandbox-42" },
+ })),
+ );
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &current)),
+ Ok(json_response(200, &pool(1, Some(vec!["shell"])))),
+ ]));
+
+ assert_eq!(
+ client(Arc::clone(&http), 1, 1)
+ .wait_claim(current)
+ .await
+ .unwrap()
+ .name,
+ "sandbox-42"
+ );
+ let requests = http.authenticated_requests().await;
+ assert_request(
+ &requests[0],
+ "GET",
+ &format!("{CLAIM_COLLECTION}/named-claim"),
+ None,
+ );
+ assert_request(&requests[1], "GET", POOL_ITEM, None);
+}
+
+#[tokio::test]
+async fn wait_claim_rejects_invalid_claim_identity_before_token_or_pool_lookup() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let invalid = Claim {
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: "Uppercase".into(),
+ labels: None,
+ },
+ ..claim("named-claim", claim_spec("example-pool-template"), None)
+ };
+
+ assert!(matches!(
+ client(Arc::clone(&http), 1, 1).wait_claim(invalid).await,
+ Err(SdkError::InvalidResourceName { .. })
+ ));
+ assert_eq!(http.request_count().await, 0);
+}
diff --git a/libs/fleet/sdk/tests/oauth.rs b/libs/fleet/sdk/tests/oauth.rs
new file mode 100644
index 0000000000..9d0b5df539
--- /dev/null
+++ b/libs/fleet/sdk/tests/oauth.rs
@@ -0,0 +1,348 @@
+mod support;
+
+use cyclops_sdk::{
+ CyclopsClient, CyclopsConfiguration, CyclopsCredentials, HttpError, HttpHeader, HttpRequest,
+ HttpResponse, SdkError,
+};
+use std::sync::Arc;
+use support::ScriptedHttpClient;
+
+const BASE_URL: &str = "https://cyclops.example:8443/api";
+const TOKEN_URL: &str = "https://identity.example/oauth/token";
+
+#[tokio::test]
+async fn caches_token_until_expiry_and_encodes_credentials() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token("token-a", 3600)),
+ Ok(response(200, b"first")),
+ Ok(response(200, b"second")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap()
+ .body,
+ b"first"
+ );
+ assert_eq!(
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/claims"))
+ .await
+ .unwrap()
+ .body,
+ b"second"
+ );
+
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 3);
+ assert_eq!(requests[0].url, TOKEN_URL);
+ assert_eq!(requests[0].method, "POST");
+ assert_eq!(
+ requests[0].body,
+ Some(b"grant_type=client_credentials&client_id=client+id%2B%2F%25&client_secret=secret+%26%3D%2B%2F%25".to_vec())
+ );
+ assert_eq!(
+ requests[0].headers,
+ vec![
+ header("accept", "application/json"),
+ header("content-type", "application/x-www-form-urlencoded"),
+ ]
+ );
+ assert_bearer(&requests[1], "token-a");
+ assert_bearer(&requests[2], "token-a");
+ assert_eq!(
+ requests[1].headers,
+ vec![
+ header("x-intent", "preserve-order"),
+ header("x-trace", "keep"),
+ header("authorization", "Bearer token-a"),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn refreshes_a_token_at_the_expiry_skew() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token("token-a", 30)),
+ Ok(response(200, b"first")),
+ Ok(token("token-b", 3600)),
+ Ok(response(200, b"second")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap();
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/claims"))
+ .await
+ .unwrap();
+
+ let requests = http.requests().await;
+ assert_eq!(
+ requests
+ .iter()
+ .filter(|request| request.url == TOKEN_URL)
+ .count(),
+ 2
+ );
+ assert_bearer(&requests[1], "token-a");
+ assert_bearer(&requests[3], "token-b");
+}
+
+#[tokio::test]
+async fn concurrent_cache_misses_fetch_one_token() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let blocked_token = http.enqueue_blocking(Ok(token("token-a", 3600))).await;
+ http.enqueue(Ok(response(200, b"first"))).await;
+ http.enqueue(Ok(response(200, b"second"))).await;
+ let client = client(Arc::clone(&http));
+
+ let first = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ }
+ });
+ blocked_token.wait_until_started().await;
+ let second = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/claims"))
+ .await
+ }
+ });
+
+ tokio::task::yield_now().await;
+ assert_eq!(
+ http.requests().await.len(),
+ 1,
+ "only one token request is in flight"
+ );
+ blocked_token.release();
+ assert_eq!(first.await.unwrap().unwrap().body, b"first");
+ assert_eq!(second.await.unwrap().unwrap().body, b"second");
+
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 3);
+ assert_eq!(
+ requests
+ .iter()
+ .filter(|request| request.url == TOKEN_URL)
+ .count(),
+ 1
+ );
+}
+
+#[tokio::test]
+async fn delayed_unauthorized_does_not_invalidate_same_value_newer_generation() {
+ let http = Arc::new(ScriptedHttpClient::new([Ok(token("shared-token", 3600))]));
+ let delayed_unauthorized = http.enqueue_blocking(Ok(response(401, b"expired-a"))).await;
+ http.enqueue(Ok(response(401, b"expired-b"))).await;
+ http.enqueue(Ok(token("shared-token", 3600))).await;
+ http.enqueue(Ok(response(200, b"retried-b"))).await;
+ http.enqueue(Ok(response(200, b"retried-a"))).await;
+ let client = client(Arc::clone(&http));
+
+ let request_a = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools/a"))
+ .await
+ }
+ });
+ delayed_unauthorized.wait_until_started().await;
+
+ let response_b = client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools/b"))
+ .await
+ .unwrap();
+ assert_eq!(response_b.body, b"retried-b");
+
+ delayed_unauthorized.release();
+ let response_a = request_a.await.unwrap().unwrap();
+ assert_eq!(response_a.body, b"retried-a");
+
+ let requests = http.requests().await;
+ assert_eq!(
+ requests
+ .iter()
+ .filter(|request| request.url == TOKEN_URL)
+ .count(),
+ 2,
+ "a delayed 401 must not clear a newer same-value token generation"
+ );
+ assert_eq!(requests.len(), 6);
+}
+
+#[tokio::test]
+async fn refreshes_once_after_unauthorized() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token("token-a", 3600)),
+ Ok(response(401, b"expired")),
+ Ok(token("token-b", 3600)),
+ Ok(response(200, b"ok")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap()
+ .body,
+ b"ok"
+ );
+
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 4);
+ assert_bearer(&requests[1], "token-a");
+ assert_bearer(&requests[3], "token-b");
+}
+
+#[tokio::test]
+async fn does_not_retry_a_second_unauthorized() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token("token-a", 3600)),
+ Ok(response(401, b"expired")),
+ Ok(token("token-b", 3600)),
+ Ok(response(401, b"still expired")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ let error = client
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::Status { status: 401, .. }));
+ assert_eq!(http.requests().await.len(), 4);
+}
+
+#[tokio::test]
+async fn maps_oauth_errors_and_invalid_json() {
+ let status_http = Arc::new(ScriptedHttpClient::new([Ok(response(503, b"unavailable"))]));
+ let error = client(status_http)
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, SdkError::Status { operation, status: 503, .. } if operation == "acquire OAuth token")
+ );
+
+ let invalid_json_http = Arc::new(ScriptedHttpClient::new([Ok(response(200, b"not json"))]));
+ let error = client(invalid_json_http)
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::Token { .. }));
+
+ let callback_http = Arc::new(ScriptedHttpClient::new([Err(HttpError::Transport {
+ reason: "offline".into(),
+ })]));
+ let error = client(callback_http)
+ .execute_authenticated(request("https://cyclops.example:8443/api/pools"))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::Transport { reason } if reason == "offline"));
+}
+
+#[tokio::test]
+async fn does_not_attach_bearer_to_cross_origin_requests() {
+ let http = Arc::new(ScriptedHttpClient::new([Ok(response(200, b"external"))]));
+ let client = client(Arc::clone(&http));
+ let external = HttpRequest {
+ method: "GET".into(),
+ url: "https://cyclops.example/api/pools".into(),
+ headers: vec![header("Authorization", "Basic external")],
+ body: Some(vec![0, 1, 2]),
+ };
+
+ let response = client.execute_authenticated(external).await.unwrap();
+ assert_eq!(response.body, b"external");
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 1);
+ assert_eq!(
+ requests[0].headers,
+ vec![header("Authorization", "Basic external")]
+ );
+ assert_eq!(requests[0].body, Some(vec![0, 1, 2]));
+}
+
+fn client(http: Arc<ScriptedHttpClient>) -> Arc<CyclopsClient> {
+ CyclopsClient::connect(
+ CyclopsConfiguration {
+ base_url: BASE_URL.into(),
+ token_url: TOKEN_URL.into(),
+ credentials: CyclopsCredentials::new("client id+/%".into(), "secret &=+/%".into()),
+ pool_poll_interval_ms: 1,
+ pool_poll_limit: 1,
+ claim_poll_interval_ms: 1,
+ claim_poll_limit: 1,
+ },
+ http,
+ )
+ .unwrap()
+}
+
+fn request(url: &str) -> HttpRequest {
+ HttpRequest {
+ method: "GET".into(),
+ url: url.into(),
+ headers: vec![
+ header("x-intent", "preserve-order"),
+ header("Authorization", "Bearer caller-token"),
+ header("x-trace", "keep"),
+ ],
+ body: None,
+ }
+}
+
+fn token(value: &str, expires_in: u64) -> HttpResponse {
+ response(
+ 200,
+ format!(r#"{{"access_token":"{value}","expires_in":{expires_in}}}"#).as_bytes(),
+ )
+}
+
+fn response(status: u16, body: &[u8]) -> HttpResponse {
+ HttpResponse {
+ status,
+ headers: vec![],
+ body: body.to_vec(),
+ }
+}
+
+fn header(name: &str, value: &str) -> HttpHeader {
+ HttpHeader {
+ name: name.into(),
+ value: value.into(),
+ }
+}
+
+fn assert_bearer(request: &HttpRequest, token: &str) {
+ assert_eq!(
+ request
+ .headers
+ .iter()
+ .filter(|header| header.name.eq_ignore_ascii_case("authorization"))
+ .count(),
+ 1
+ );
+ assert_eq!(
+ request
+ .headers
+ .iter()
+ .find(|header| header.name.eq_ignore_ascii_case("authorization"))
+ .unwrap()
+ .value,
+ format!("Bearer {token}")
+ );
+}
diff --git a/libs/fleet/sdk/tests/pool_flow.rs b/libs/fleet/sdk/tests/pool_flow.rs
new file mode 100644
index 0000000000..06b971e768
--- /dev/null
+++ b/libs/fleet/sdk/tests/pool_flow.rs
@@ -0,0 +1,684 @@
+mod support;
+
+use cyclops_sdk::{
+ CreatePoolRequest, CyclopsClient, CyclopsConfiguration, CyclopsCredentials, HttpHeader,
+ HttpResponse, Pool, ResourceMetadata, SdkError,
+};
+use cyclops_sdk_schema::PoolSpec;
+use futures_timer::Delay;
+use std::{sync::Arc, time::Duration};
+use support::ScriptedHttpClient;
+
+const BASE_URL: &str = "https://cyclops.example:8443";
+const TOKEN_URL: &str = "https://identity.example/oauth/token";
+const NAMESPACE: &str = "example-pool";
+const COLLECTION: &str = "https://cyclops.example:8443/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools";
+const ITEM: &str = "https://cyclops.example:8443/api/k8s/apis/cua.ai/v1/namespaces/example-pool/osgymworkspacepools/example-pool";
+const NAMESPACE_COLLECTION: &str = "https://cyclops.example:8443/api/namespaces";
+const NAMESPACE_ITEM: &str = "https://cyclops.example:8443/api/namespaces/example-pool";
+
+#[tokio::test]
+async fn creates_namespace_via_backend_collection_contract_then_pool_with_typed_json() {
+ let created = pool();
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(201, br#"{}"#)),
+ Ok(json_response(201, &created)),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ .unwrap(),
+ created
+ );
+
+ let requests = resource_requests(&http).await;
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[1], "POST", COLLECTION, Some(&json_bytes(&pool())));
+}
+
+#[tokio::test]
+async fn rolls_back_only_a_namespace_created_by_this_call_and_preserves_pool_error() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(201, br#"{}"#)),
+ Ok(response(422, b"pool rejected")),
+ Ok(response(500, b"rollback failed")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ let error = client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ SdkError::Status {
+ ref operation,
+ status: 422,
+ ref body,
+ } if operation == "create pool" && body == "pool rejected"
+ ));
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 3);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[1], "POST", COLLECTION, Some(&json_bytes(&pool())));
+ assert_request(&requests[2], "DELETE", NAMESPACE_ITEM, None);
+}
+
+#[tokio::test]
+async fn does_not_roll_back_namespace_reported_existing_by_409() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(409, b"already exists")),
+ Ok(response(422, b"pool rejected")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert!(
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ .is_err()
+ );
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 2);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[1], "POST", COLLECTION, Some(&json_bytes(&pool())));
+}
+
+#[tokio::test]
+async fn rejects_namespace_200_without_creating_a_pool_or_rolling_back() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, b"unexpected success")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert!(matches!(
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await,
+ Err(SdkError::Status {
+ ref operation,
+ status: 200,
+ ref body,
+ }) if operation == "create namespace" && body == "unexpected success"
+ ));
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 1);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+}
+
+#[tokio::test]
+async fn rejects_unexpected_namespace_status_without_creating_a_pool() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(202, b"pending")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert!(matches!(
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await,
+ Err(SdkError::Status {
+ ref operation,
+ status: 202,
+ ref body,
+ }) if operation == "create namespace" && body == "pending"
+ ));
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 1);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+}
+
+#[tokio::test]
+async fn serializes_same_namespace_create_lifecycle_before_rollback() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ http.enqueue(Ok(token())).await;
+ http.enqueue(Ok(response(201, b"{}"))).await;
+ let blocked_pool = http
+ .enqueue_blocking(Ok(response(422, b"first pool rejected")))
+ .await;
+ let client = client(Arc::clone(&http));
+
+ let first = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ }
+ });
+ blocked_pool.wait_until_started().await;
+
+ let second = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ }
+ });
+ tokio::task::yield_now().await;
+ assert_eq!(resource_requests(&http).await.len(), 2);
+
+ http.enqueue(Ok(response(204, b""))).await;
+ http.enqueue(Ok(response(409, b"already exists"))).await;
+ http.enqueue(Ok(json_response(201, &pool()))).await;
+ blocked_pool.release();
+
+ assert!(matches!(
+ first.await.unwrap(),
+ Err(SdkError::Status {
+ ref operation,
+ status: 422,
+ ref body,
+ }) if operation == "create pool" && body == "first pool rejected"
+ ));
+ assert_eq!(second.await.unwrap().unwrap(), pool());
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 5);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[1], "POST", COLLECTION, Some(&json_bytes(&pool())));
+ assert_request(&requests[2], "DELETE", NAMESPACE_ITEM, None);
+ assert_request(
+ &requests[3],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[4], "POST", COLLECTION, Some(&json_bytes(&pool())));
+}
+
+#[tokio::test]
+async fn creates_for_different_namespaces_proceed_concurrently() {
+ const OTHER_NAMESPACE: &str = "other-pool";
+
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ http.enqueue(Ok(token())).await;
+ let blocked_namespace = http.enqueue_blocking(Ok(response(201, b"{}"))).await;
+ http.enqueue(Ok(response(201, b"{}"))).await;
+ http.enqueue(Ok(json_response(201, &pool_named(OTHER_NAMESPACE))))
+ .await;
+ http.enqueue(Ok(json_response(201, &pool()))).await;
+ let client = client(Arc::clone(&http));
+
+ let first = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ }
+ });
+ blocked_namespace.wait_until_started().await;
+
+ let mut second = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: OTHER_NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ }
+ });
+ let second_pool = tokio::select! {
+ result = &mut second => result.unwrap().unwrap(),
+ _ = Delay::new(Duration::from_millis(200)) => panic!("different namespaces were serialized"),
+ };
+ assert_eq!(second_pool, pool_named(OTHER_NAMESPACE));
+
+ let other_collection = format!(
+ "https://cyclops.example:8443/api/k8s/apis/cua.ai/v1/namespaces/{OTHER_NAMESPACE}/osgymworkspacepools"
+ );
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 3);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(
+ &requests[1],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"other-pool"}"#),
+ );
+ assert_request(
+ &requests[2],
+ "POST",
+ &other_collection,
+ Some(&json_bytes(&pool_named(OTHER_NAMESPACE))),
+ );
+
+ blocked_namespace.release();
+ assert_eq!(first.await.unwrap().unwrap(), pool());
+}
+
+#[tokio::test]
+async fn create_and_delete_for_the_same_namespace_do_not_interleave() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ http.enqueue(Ok(token())).await;
+ http.enqueue(Ok(response(201, b"{}"))).await;
+ let blocked_create = http.enqueue_blocking(Ok(json_response(201, &pool()))).await;
+ let client = client(Arc::clone(&http));
+
+ let create = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .create_pool(CreatePoolRequest {
+ namespace: NAMESPACE.into(),
+ spec: pool_spec(),
+ })
+ .await
+ }
+ });
+ blocked_create.wait_until_started().await;
+
+ let delete = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move { client.delete_pool(pool()).await }
+ });
+ tokio::task::yield_now().await;
+ assert_eq!(resource_requests(&http).await.len(), 2);
+
+ http.enqueue(Ok(response(204, b""))).await;
+ http.enqueue(Ok(response(204, b""))).await;
+ blocked_create.release();
+
+ assert_eq!(create.await.unwrap().unwrap(), pool());
+ delete.await.unwrap().unwrap();
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 4);
+ assert_request(
+ &requests[0],
+ "POST",
+ NAMESPACE_COLLECTION,
+ Some(br#"{"name":"example-pool"}"#),
+ );
+ assert_request(&requests[1], "POST", COLLECTION, Some(&json_bytes(&pool())));
+ assert_request(&requests[2], "DELETE", ITEM, None);
+ assert_request(&requests[3], "DELETE", NAMESPACE_ITEM, None);
+}
+
+#[tokio::test]
+async fn lists_gets_and_updates_typed_pools() {
+ let current = pool();
+ let updated = Pool {
+ spec: serde_json::from_value(serde_json::json!({
+ "replicas": 2,
+ "template": { "containerDiskImage": "registry.example/updated:latest" },
+ }))
+ .unwrap(),
+ ..pool()
+ };
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(
+ 200,
+ &json_bytes(&serde_json::json!({ "items": [current.clone()] })),
+ )),
+ Ok(json_response(200, &current)),
+ Ok(json_response(200, &updated)),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ client.clone().list_pools(NAMESPACE.into()).await.unwrap(),
+ vec![current.clone()]
+ );
+ assert_eq!(
+ client.clone().get_pool(current.clone()).await.unwrap(),
+ current
+ );
+ assert_eq!(
+ client.update_pool(updated.clone()).await.unwrap(),
+ updated.clone()
+ );
+
+ let requests = resource_requests(&http).await;
+ assert_request(&requests[0], "GET", COLLECTION, None);
+ assert_request(&requests[1], "GET", ITEM, None);
+ assert_request(&requests[2], "PUT", ITEM, Some(&json_bytes(&updated)));
+}
+
+#[tokio::test]
+async fn deletes_pool_before_namespace_and_accepts_empty_delete_bodies() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(204, b"")),
+ Ok(response(204, b"")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ client.delete_pool(pool()).await.unwrap();
+
+ let requests = resource_requests(&http).await;
+ assert_request(&requests[0], "DELETE", ITEM, None);
+ assert_request(&requests[1], "DELETE", NAMESPACE_ITEM, None);
+}
+
+#[tokio::test]
+async fn rejects_deleting_a_pool_outside_the_namespace_owned_lifecycle() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+ let pool = Pool {
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: "other-pool".into(),
+ labels: None,
+ },
+ ..pool()
+ };
+
+ assert!(matches!(
+ client.delete_pool(pool).await,
+ Err(SdkError::Configuration { ref reason })
+ if reason == "pool metadata namespace and name must match for namespace lifecycle operations"
+ ));
+ assert_eq!(http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn gets_and_updates_non_lifecycle_pool_resources_without_namespace_cleanup() {
+ let other = Pool {
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: "other-pool".into(),
+ labels: None,
+ },
+ ..pool()
+ };
+ let other_item = format!("{COLLECTION}/other-pool");
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &other)),
+ Ok(json_response(200, &other)),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(client.clone().get_pool(other.clone()).await.unwrap(), other);
+ assert_eq!(
+ client.update_pool(other.clone()).await.unwrap(),
+ other.clone()
+ );
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 2);
+ assert_request(&requests[0], "GET", &other_item, None);
+ assert_request(&requests[1], "PUT", &other_item, Some(&json_bytes(&other)));
+}
+
+#[tokio::test]
+async fn does_not_delete_namespace_when_pool_deletion_fails() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(500, b"pool delete failed")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert!(matches!(
+ client.delete_pool(pool()).await,
+ Err(SdkError::Status {
+ ref operation,
+ status: 500,
+ ref body,
+ }) if operation == "delete pool" && body == "pool delete failed"
+ ));
+
+ let requests = resource_requests(&http).await;
+ assert_eq!(requests.len(), 1);
+ assert_request(&requests[0], "DELETE", ITEM, None);
+}
+
+#[tokio::test]
+async fn maps_invalid_json_and_non_success_responses() {
+ let invalid_json_http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, b"not json")),
+ ]));
+ let invalid_json_client = client(Arc::clone(&invalid_json_http));
+ assert!(matches!(
+ invalid_json_client.get_pool(pool()).await,
+ Err(SdkError::Body { .. })
+ ));
+
+ let status_http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(503, b"unavailable")),
+ ]));
+ let status_client = client(Arc::clone(&status_http));
+ assert!(matches!(
+ status_client.list_pools(NAMESPACE.into()).await,
+ Err(SdkError::Status { status: 503, .. })
+ ));
+}
+
+#[tokio::test]
+async fn rejects_invalid_dns_labels_without_http_requests() {
+ for value in [
+ "",
+ "Uppercase",
+ "-leading",
+ "trailing-",
+ "has/slash",
+ &"a".repeat(64),
+ ] {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+
+ let error = client.list_pools(value.into()).await.unwrap_err();
+ assert!(matches!(
+ error,
+ SdkError::InvalidResourceName {
+ ref field,
+ value: ref invalid_value,
+ ref reason,
+ } if field == "namespace" && invalid_value == value && !reason.is_empty()
+ ));
+ assert_eq!(
+ http.request_count().await,
+ 0,
+ "{value:?} must not reach HTTP"
+ );
+ }
+
+ for value in [
+ "",
+ "Uppercase",
+ "-leading",
+ "trailing-",
+ "has/slash",
+ &"a".repeat(64),
+ ] {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+ let error = client
+ .get_pool(Pool {
+ metadata: ResourceMetadata {
+ namespace: NAMESPACE.into(),
+ name: value.into(),
+ labels: None,
+ },
+ ..pool()
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ SdkError::InvalidResourceName {
+ ref field,
+ value: ref invalid_value,
+ ref reason,
+ } if field == "name" && invalid_value == value && !reason.is_empty()
+ ));
+ assert_eq!(
+ http.request_count().await,
+ 0,
+ "{value:?} must not reach HTTP"
+ );
+ }
+}
+
+fn client(http: Arc<ScriptedHttpClient>) -> Arc<CyclopsClient> {
+ CyclopsClient::connect(
+ CyclopsConfiguration {
+ base_url: BASE_URL.into(),
+ token_url: TOKEN_URL.into(),
+ credentials: CyclopsCredentials::new("client".into(), "secret".into()),
+ pool_poll_interval_ms: 1,
+ pool_poll_limit: 1,
+ claim_poll_interval_ms: 1,
+ claim_poll_limit: 1,
+ },
+ http,
+ )
+ .unwrap()
+}
+
+fn pool() -> Pool {
+ pool_named(NAMESPACE)
+}
+
+fn pool_named(namespace: &str) -> Pool {
+ Pool {
+ api_version: "cua.ai/v1".into(),
+ kind: "OSGymWorkspacePool".into(),
+ metadata: ResourceMetadata {
+ namespace: namespace.into(),
+ name: namespace.into(),
+ labels: None,
+ },
+ spec: pool_spec(),
+ status: None,
+ }
+}
+
+fn pool_spec() -> PoolSpec {
+ serde_json::from_value(serde_json::json!({
+ "replicas": 1,
+ "template": { "containerDiskImage": "registry.example/image:latest" },
+ }))
+ .unwrap()
+}
+
+fn token() -> HttpResponse {
+ response(200, br#"{"access_token":"token-a","expires_in":3600}"#)
+}
+
+fn json_response(status: u16, value: &impl serde::Serialize) -> HttpResponse {
+ response(status, &json_bytes(value))
+}
+
+fn json_bytes(value: &impl serde::Serialize) -> Vec<u8> {
+ serde_json::to_vec(value).unwrap()
+}
+
+fn response(status: u16, body: &[u8]) -> HttpResponse {
+ HttpResponse {
+ status,
+ headers: Vec::new(),
+ body: body.to_vec(),
+ }
+}
+
+async fn resource_requests(http: &ScriptedHttpClient) -> Vec<cyclops_sdk::HttpRequest> {
+ http.requests().await.into_iter().skip(1).collect()
+}
+
+fn assert_request(
+ request: &cyclops_sdk::HttpRequest,
+ method: &str,
+ url: &str,
+ body: Option<&[u8]>,
+) {
+ assert_eq!(request.method, method);
+ assert_eq!(request.url, url);
+ assert_eq!(request.body.as_deref(), body);
+ assert_eq!(
+ request.headers,
+ vec![
+ HttpHeader {
+ name: "accept".into(),
+ value: "application/json".into(),
+ },
+ HttpHeader {
+ name: "content-type".into(),
+ value: "application/json".into(),
+ },
+ HttpHeader {
+ name: "authorization".into(),
+ value: "Bearer token-a".into(),
+ },
+ ]
+ );
+}
diff --git a/libs/fleet/sdk/tests/public_api.rs b/libs/fleet/sdk/tests/public_api.rs
new file mode 100644
index 0000000000..cb3dbaa450
--- /dev/null
+++ b/libs/fleet/sdk/tests/public_api.rs
@@ -0,0 +1,308 @@
+use std::sync::Arc;
+
+use cyclops_sdk::{
+ Claim, CreateClaimRequest, CreatePoolRequest, CyclopsClient, CyclopsConfiguration,
+ CyclopsCredentials, HttpClient, HttpError, HttpHeader, HttpRequest, HttpResponse, Pool,
+ ResourceMetadata, Sandbox, SdkError,
+};
+use cyclops_sdk_schema::{ClaimSpec, OSGymSandboxClaimStatus, OSGymWorkspacePoolStatus, PoolSpec};
+
+struct RecordingHttpClient;
+
+#[async_trait::async_trait]
+impl HttpClient for RecordingHttpClient {
+ async fn execute(&self, request: HttpRequest) -> Result<HttpResponse, HttpError> {
+ assert_eq!(request.headers[0].name, "x-first");
+ assert_eq!(request.headers[1].name, "x-second");
+ assert_eq!(request.body, Some(vec![0, 255]));
+
+ Ok(HttpResponse {
+ status: 200,
+ headers: vec![
+ HttpHeader {
+ name: "x-first".into(),
+ value: "one".into(),
+ },
+ HttpHeader {
+ name: "x-second".into(),
+ value: "two".into(),
+ },
+ ],
+ body: vec![255, 0],
+ })
+ }
+}
+
+fn configuration() -> CyclopsConfiguration {
+ CyclopsConfiguration {
+ base_url: "https://run.cua.ai".into(),
+ token_url: "https://auth.cua.ai/token".into(),
+ credentials: CyclopsCredentials::new("client".into(), "super-secret-value".into()),
+ pool_poll_interval_ms: 1_000,
+ pool_poll_limit: 300,
+ claim_poll_interval_ms: 1_000,
+ claim_poll_limit: 300,
+ }
+}
+
+fn pool_spec() -> PoolSpec {
+ serde_json::from_value(serde_json::json!({
+ "replicas": 1,
+ "template": { "containerDiskImage": "registry.example/image:latest" },
+ }))
+ .unwrap()
+}
+
+fn claim_spec() -> ClaimSpec {
+ serde_json::from_value(serde_json::json!({
+ "sandboxTemplateRef": { "name": "pool-template" },
+ }))
+ .unwrap()
+}
+
+fn pool() -> Pool {
+ Pool {
+ api_version: "cua.ai/v1".into(),
+ kind: "OSGymWorkspacePool".into(),
+ metadata: ResourceMetadata {
+ namespace: "default".into(),
+ name: "pool".into(),
+ labels: None,
+ },
+ spec: pool_spec(),
+ status: None,
+ }
+}
+
+fn claim() -> Claim {
+ Claim {
+ api_version: "osgym.cua.ai/v1alpha1".into(),
+ kind: "OSGymSandboxClaim".into(),
+ metadata: ResourceMetadata {
+ namespace: "default".into(),
+ name: "claim".into(),
+ labels: None,
+ },
+ spec: claim_spec(),
+ status: None,
+ }
+}
+
+#[test]
+fn public_configuration_and_transport_are_constructible() {
+ let configuration = configuration();
+ assert_eq!(configuration.pool_poll_limit, 300);
+
+ let client = CyclopsClient::connect(configuration, Arc::new(RecordingHttpClient));
+ assert!(client.is_ok());
+}
+
+#[test]
+fn configuration_rejects_invalid_urls_and_polling_values() {
+ let mut invalid_url = configuration();
+ invalid_url.base_url = "not a URL".into();
+ assert!(matches!(
+ CyclopsClient::connect(invalid_url, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+
+ let mut invalid_token_url = configuration();
+ invalid_token_url.token_url = "not a URL".into();
+ assert!(matches!(
+ CyclopsClient::connect(invalid_token_url, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+
+ let mut zero_pool_interval = configuration();
+ zero_pool_interval.pool_poll_interval_ms = 0;
+ assert!(matches!(
+ CyclopsClient::connect(zero_pool_interval, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+
+ let mut zero_interval = configuration();
+ zero_interval.claim_poll_interval_ms = 0;
+ assert!(matches!(
+ CyclopsClient::connect(zero_interval, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+
+ let mut zero_limit = configuration();
+ zero_limit.pool_poll_limit = 0;
+ assert!(matches!(
+ CyclopsClient::connect(zero_limit, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+
+ let mut zero_claim_limit = configuration();
+ zero_claim_limit.claim_poll_limit = 0;
+ assert!(matches!(
+ CyclopsClient::connect(zero_claim_limit, Arc::new(RecordingHttpClient)),
+ Err(SdkError::Configuration { .. })
+ ));
+}
+
+#[test]
+fn configuration_debug_redacts_client_secret() {
+ let rendered = format!("{:?}", configuration());
+
+ assert!(rendered.contains("<redacted>"));
+ assert!(!rendered.contains("super-secret-value"));
+}
+
+#[tokio::test]
+async fn foreign_http_client_preserves_ordered_headers_and_byte_bodies() {
+ let response = RecordingHttpClient
+ .execute(HttpRequest {
+ method: "POST".into(),
+ url: "https://run.cua.ai/v1/pools".into(),
+ headers: vec![
+ HttpHeader {
+ name: "x-first".into(),
+ value: "one".into(),
+ },
+ HttpHeader {
+ name: "x-second".into(),
+ value: "two".into(),
+ },
+ ],
+ body: Some(vec![0, 255]),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(response.body, vec![255, 0]);
+}
+
+#[test]
+fn http_request_distinguishes_absent_and_empty_bodies() {
+ let absent = HttpRequest {
+ method: "GET".into(),
+ url: "https://run.cua.ai/v1/pools".into(),
+ headers: vec![],
+ body: None,
+ };
+ let empty = HttpRequest {
+ body: Some(vec![]),
+ ..absent.clone()
+ };
+
+ assert_ne!(absent, empty);
+ assert_eq!(empty.body, Some(vec![]));
+}
+
+#[test]
+fn resources_use_canonical_schema_specs_and_statuses() {
+ let metadata = ResourceMetadata {
+ namespace: "default".into(),
+ name: "example".into(),
+ labels: None,
+ };
+ assert_eq!(metadata.namespace, "default");
+
+ fn pool_status(_: Option<OSGymWorkspacePoolStatus>) {}
+ fn claim_status(_: Option<OSGymSandboxClaimStatus>) {}
+
+ fn assert_pool_types(pool: Pool) {
+ let Pool { spec, status, .. } = pool;
+ let _: PoolSpec = spec;
+ pool_status(status);
+ }
+
+ fn assert_claim_types(claim: Claim) {
+ let Claim { spec, status, .. } = claim;
+ let _: ClaimSpec = spec;
+ claim_status(status);
+ }
+
+ fn assert_create_pool_request(request: CreatePoolRequest) {
+ let CreatePoolRequest { namespace, spec } = request;
+ let _: String = namespace;
+ let _: PoolSpec = spec;
+ }
+
+ fn assert_create_claim_request(request: CreateClaimRequest) {
+ let CreateClaimRequest { pool, spec } = request;
+ assert_pool_types(pool);
+ let _: Option<ClaimSpec> = spec;
+ }
+
+ let _: fn(Claim) = assert_claim_types;
+ let _: fn(CreatePoolRequest) = assert_create_pool_request;
+ let _: fn(CreateClaimRequest) = assert_create_claim_request;
+}
+
+#[test]
+fn resources_support_equality_and_kubernetes_camel_case_json() {
+ let pool = pool();
+ let claim = claim();
+ let sandbox = Sandbox {
+ namespace: "default".into(),
+ claim: "claim".into(),
+ name: "bound-sandbox".into(),
+ services: vec!["mcp".into(), "vnc".into()],
+ };
+ let create_pool = CreatePoolRequest {
+ namespace: "default".into(),
+ spec: pool.spec.clone(),
+ };
+ let create_claim = CreateClaimRequest {
+ pool: pool.clone(),
+ spec: Some(claim.spec.clone()),
+ };
+
+ assert_eq!(pool, pool.clone());
+ assert_eq!(claim, claim.clone());
+ assert_eq!(sandbox, sandbox.clone());
+ assert_eq!(create_pool, create_pool.clone());
+ assert_eq!(create_claim, create_claim.clone());
+
+ let pool_json = serde_json::to_value(pool).unwrap();
+ assert_eq!(pool_json["apiVersion"], "cua.ai/v1");
+ assert!(pool_json.get("api_version").is_none());
+ let claim_json = serde_json::to_value(claim).unwrap();
+ assert_eq!(claim_json["apiVersion"], "osgym.cua.ai/v1alpha1");
+ assert!(claim_json.get("api_version").is_none());
+}
+
+#[test]
+fn sandbox_is_a_claim_bound_identity() {
+ let sandbox = Sandbox {
+ namespace: "default".into(),
+ claim: "claim-a".into(),
+ name: "sandbox-a".into(),
+ services: vec!["mcp".into(), "vnc".into()],
+ };
+
+ assert_eq!(sandbox.namespace, "default");
+ assert_eq!(sandbox.claim, "claim-a");
+ assert_eq!(sandbox.name, "sandbox-a");
+ assert_eq!(sandbox.services, vec!["mcp", "vnc"]);
+}
+
+#[test]
+fn invalid_resource_names_have_a_distinct_error() {
+ let error = SdkError::InvalidResourceName {
+ field: "name".into(),
+ value: "Invalid_Name".into(),
+ reason: "must contain only lowercase ASCII letters, digits, and hyphens".into(),
+ };
+
+ assert!(matches!(error, SdkError::InvalidResourceName { .. }));
+}
+
+#[test]
+fn status_error_body_is_lossy_and_bounded_to_4096_bytes() {
+ let mut body = vec![b'a'; 4_093];
+ body.extend("😀".as_bytes());
+ let error = SdkError::status("list pools", 500, &body);
+
+ match error {
+ SdkError::Status { body, .. } => {
+ assert_eq!(body, "a".repeat(4_093));
+ assert!(body.len() <= 4_096);
+ assert!(!body.contains('\u{fffd}'));
+ }
+ _ => panic!("expected a status error"),
+ }
+}
diff --git a/libs/fleet/sdk/tests/service_flow.rs b/libs/fleet/sdk/tests/service_flow.rs
new file mode 100644
index 0000000000..7e8c18b6d8
--- /dev/null
+++ b/libs/fleet/sdk/tests/service_flow.rs
@@ -0,0 +1,433 @@
+mod support;
+
+use cyclops_sdk::{
+ CyclopsClient, CyclopsConfiguration, CyclopsCredentials, HttpError, HttpHeader, HttpRequest,
+ HttpResponse, Sandbox, SdkError,
+};
+use std::sync::Arc;
+use support::ScriptedHttpClient;
+
+const BASE_URL: &str = "https://cyclops.example:8443/control/";
+const TOKEN_URL: &str = "https://auth.example/token";
+
+#[tokio::test]
+async fn routes_known_service_under_base_prefix_and_forwards_query() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, vec![0, 255, 1])),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ let result = client
+ .service_request(
+ sandbox(),
+ "mcp".into(),
+ "/tools?cursor=next".into(),
+ request(None),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result.status, 200);
+ assert_eq!(result.body, vec![0, 255, 1]);
+ let requests = http.requests().await;
+ assert_eq!(
+ requests[1].url,
+ "https://cyclops.example:8443/control/api/svc/pool-test/sandbox-1-mcp/tools?cursor=next"
+ );
+ assert_eq!(requests[1].method, "PATCH");
+}
+
+#[tokio::test]
+async fn rejects_unknown_service_with_sorted_unique_available_names() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+ let mut sandbox = sandbox();
+ sandbox.services = vec!["zeta".into(), "mcp".into(), "api".into(), "mcp".into()];
+
+ let error = client
+ .service_request(sandbox, "missing".into(), "/".into(), request(None))
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ error,
+ SdkError::UnknownService { requested, available }
+ if requested == "missing" && available == ["api", "mcp", "zeta"]
+ ));
+ assert_eq!(http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn rejects_ambiguous_or_normalizing_service_paths_before_http() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+
+ for path in [
+ "tools",
+ "//other.example/tools",
+ "https://other.example/tools",
+ "/https://other.example/tools",
+ "/tools#fragment",
+ "/tools?cursor=next#fragment",
+ "/../admin",
+ "/safe/../admin",
+ "/%2e%2e/admin",
+ "/safe/%2E%2e/admin",
+ "/safe%2fadmin",
+ "/safe%5cadmin",
+ ] {
+ let error = Arc::clone(&client)
+ .service_request(sandbox(), "mcp".into(), path.into(), request(None))
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, SdkError::InvalidServicePath { path: rejected } if rejected == path)
+ );
+ }
+
+ assert_eq!(http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn rejects_literal_and_encoded_controls_before_service_http() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+ let mut cases = Vec::new();
+
+ for control in (0_u8..=0x1f).chain([0x7f]) {
+ let control = char::from(control);
+ cases.push(format!("/ready{control}tail"));
+ cases.push(format!("/ready?note=before{control}after"));
+ }
+ for encoded in [
+ "%00", "%09", "%0A", "%0a", "%0D", "%0d", "%1F", "%1f", "%7F", "%7f",
+ ] {
+ cases.push(format!("/ready{encoded}"));
+ cases.push(format!("/ready?note={encoded}"));
+ cases.push(format!("/ready%25{}", &encoded[1..]));
+ cases.push(format!("/ready?note=%25{}", &encoded[1..]));
+ }
+ cases.extend([
+ "/safe%252fadmin".into(),
+ "/safe%255cadmin".into(),
+ "/safe/%252e%252e/admin".into(),
+ ]);
+
+ for path in cases {
+ let error = Arc::clone(&client)
+ .service_request(sandbox(), "mcp".into(), path.clone(), request(None))
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, SdkError::InvalidServicePath { path: rejected } if rejected == path)
+ );
+ }
+ assert_eq!(http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn validates_sandbox_identity_and_known_service_dns_labels_before_http() {
+ let http = Arc::new(ScriptedHttpClient::new([]));
+ let client = client(Arc::clone(&http));
+
+ let mut invalid_namespace = sandbox();
+ invalid_namespace.namespace = "Bad".into();
+ let error = Arc::clone(&client)
+ .service_request(invalid_namespace, "mcp".into(), "/".into(), request(None))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::InvalidResourceName { field, .. } if field == "namespace"));
+
+ let mut invalid_sandbox = sandbox();
+ invalid_sandbox.name = "bad_name".into();
+ let error = Arc::clone(&client)
+ .service_request(invalid_sandbox, "mcp".into(), "/".into(), request(None))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::InvalidResourceName { field, .. } if field == "sandbox"));
+
+ let mut invalid_service = sandbox();
+ invalid_service.services = vec!["Bad".into()];
+ let error = client
+ .service_request(invalid_service, "Bad".into(), "/".into(), request(None))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, SdkError::InvalidResourceName { field, .. } if field == "service"));
+ assert_eq!(http.request_count().await, 0);
+}
+
+#[tokio::test]
+async fn filters_hop_by_hop_and_connection_nominated_headers_without_reordering_others() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, vec![])),
+ ]));
+ let client = client(Arc::clone(&http));
+ let request = HttpRequest {
+ method: "POST".into(),
+ url: "https://attacker.example/ignored".into(),
+ headers: vec![
+ header("Connection", "Keep-Alive, X-Remove"),
+ header("keep-alive", "timeout=5"),
+ header("X-Remove", "smuggled"),
+ header("HOST", "attacker.example"),
+ header("Authorization", "Bearer attacker"),
+ header("Proxy-Authorization", "Basic attacker"),
+ header("Proxy-Connection", "keep-alive"),
+ header("Transfer-Encoding", "chunked"),
+ header("TE", "trailers"),
+ header("Trailer", "x-trailer"),
+ header("Upgrade", "websocket"),
+ header("X-Keep", "first"),
+ header("x-keep", "second"),
+ header("Cookie", "session=kept"),
+ ],
+ body: Some(vec![0, 255, 1]),
+ };
+
+ client
+ .service_request(sandbox(), "mcp".into(), "/upload".into(), request)
+ .await
+ .unwrap();
+
+ let request = &http.requests().await[1];
+ assert_eq!(
+ request.url,
+ "https://cyclops.example:8443/control/api/svc/pool-test/sandbox-1-mcp/upload"
+ );
+ assert_eq!(
+ request.headers,
+ vec![
+ header("X-Keep", "first"),
+ header("x-keep", "second"),
+ header("Cookie", "session=kept"),
+ header("authorization", "Bearer service-token"),
+ ]
+ );
+ assert_eq!(request.body, Some(vec![0, 255, 1]));
+}
+
+#[tokio::test]
+async fn preserves_absent_empty_and_nonempty_request_bodies() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, vec![])),
+ Ok(response(200, vec![])),
+ Ok(response(200, vec![])),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ for body in [None, Some(vec![]), Some(vec![0, 255, 1])] {
+ Arc::clone(&client)
+ .service_request(sandbox(), "mcp".into(), "/body".into(), request(body))
+ .await
+ .unwrap();
+ }
+
+ let requests = http.requests().await;
+ assert_eq!(requests[1].body, None);
+ assert_eq!(requests[2].body, Some(vec![]));
+ assert_eq!(requests[3].body, Some(vec![0, 255, 1]));
+}
+
+#[tokio::test]
+async fn preserves_valid_utf8_and_percent_encoded_query_data() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(response(200, vec![])),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ client
+ .service_request(
+ sandbox(),
+ "mcp".into(),
+ "/search?label=naïve&check=%E2%9C%93&space=%20".into(),
+ request(None),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ http.requests().await[1].url,
+ "https://cyclops.example:8443/control/api/svc/pool-test/sandbox-1-mcp/search?label=na%C3%AFve&check=%E2%9C%93&space=%20"
+ );
+}
+
+#[tokio::test]
+async fn returns_non_success_service_responses_and_binary_headers_unchanged() {
+ let expected = HttpResponse {
+ status: 418,
+ headers: vec![header("x-first", "one"), header("x-first", "two")],
+ body: vec![0, 255, 1],
+ };
+ let http = Arc::new(ScriptedHttpClient::new([Ok(token()), Ok(expected.clone())]));
+ let client = client(http);
+
+ let response = client
+ .service_request(sandbox(), "mcp".into(), "/teapot".into(), request(None))
+ .await
+ .unwrap();
+
+ assert_eq!(response, expected);
+}
+
+#[tokio::test]
+async fn returns_service_unauthorized_once_without_refreshing_or_replaying() {
+ let expected = HttpResponse {
+ status: 401,
+ headers: vec![
+ header("x-upstream", "first"),
+ header("x-upstream", "second"),
+ ],
+ body: b"service denied".to_vec(),
+ };
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(expected.clone()),
+ Ok(token()),
+ Ok(response(201, b"replayed".to_vec())),
+ ]));
+ let client = client(Arc::clone(&http));
+ let request = HttpRequest {
+ method: "POST".into(),
+ url: "https://attacker.example/ignored".into(),
+ headers: vec![header("content-type", "application/octet-stream")],
+ body: Some(vec![0, 255, 1]),
+ };
+
+ let response = client
+ .service_request(sandbox(), "mcp".into(), "/mutate".into(), request)
+ .await
+ .unwrap();
+
+ assert_eq!(response, expected);
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 2);
+ assert_eq!(
+ requests
+ .iter()
+ .filter(|request| request.url == TOKEN_URL)
+ .count(),
+ 1
+ );
+ assert_eq!(requests[1].method, "POST");
+ assert_eq!(requests[1].body, Some(vec![0, 255, 1]));
+}
+
+#[tokio::test]
+async fn maps_foreign_service_transport_errors() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Err(HttpError::Transport {
+ reason: "offline".into(),
+ }),
+ ]));
+ let client = client(http);
+
+ let error = client
+ .service_request(sandbox(), "mcp".into(), "/health".into(), request(None))
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, SdkError::Transport { reason } if reason == "offline"));
+}
+
+#[tokio::test]
+async fn concurrent_service_calls_do_not_serialize_on_one_client() {
+ let http = Arc::new(ScriptedHttpClient::new([Ok(token())]));
+ let first_response = http
+ .enqueue_blocking(Ok(response(200, b"first".to_vec())))
+ .await;
+ let second_response = http
+ .enqueue_blocking(Ok(response(200, b"second".to_vec())))
+ .await;
+ let client = client(Arc::clone(&http));
+
+ let first = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .service_request(sandbox(), "mcp".into(), "/first".into(), request(None))
+ .await
+ }
+ });
+ first_response.wait_until_started().await;
+
+ let second = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move {
+ client
+ .service_request(sandbox(), "mcp".into(), "/second".into(), request(None))
+ .await
+ }
+ });
+ second_response.wait_until_started().await;
+ assert_eq!(
+ http.request_count().await,
+ 3,
+ "second service request must reach the transport while the first is blocked"
+ );
+
+ first_response.release();
+ second_response.release();
+ assert_eq!(first.await.unwrap().unwrap().body, b"first");
+ assert_eq!(second.await.unwrap().unwrap().body, b"second");
+}
+
+fn client(http: Arc<ScriptedHttpClient>) -> Arc<CyclopsClient> {
+ CyclopsClient::connect(
+ CyclopsConfiguration {
+ base_url: BASE_URL.into(),
+ token_url: TOKEN_URL.into(),
+ credentials: CyclopsCredentials::new("client-id".into(), "client-secret".into()),
+ pool_poll_interval_ms: 1,
+ pool_poll_limit: 3,
+ claim_poll_interval_ms: 1,
+ claim_poll_limit: 3,
+ },
+ http,
+ )
+ .unwrap()
+}
+
+fn sandbox() -> Sandbox {
+ Sandbox {
+ namespace: "pool-test".into(),
+ claim: "claim-1".into(),
+ name: "sandbox-1".into(),
+ services: vec!["mcp".into(), "api".into()],
+ }
+}
+
+fn request(body: Option<Vec<u8>>) -> HttpRequest {
+ HttpRequest {
+ method: "PATCH".into(),
+ url: "https://attacker.example/ignored".into(),
+ headers: vec![],
+ body,
+ }
+}
+
+fn token() -> HttpResponse {
+ response(
+ 200,
+ br#"{"access_token":"service-token","expires_in":3600}"#.to_vec(),
+ )
+}
+
+fn response(status: u16, body: Vec<u8>) -> HttpResponse {
+ HttpResponse {
+ status,
+ headers: vec![],
+ body,
+ }
+}
+
+fn header(name: &str, value: &str) -> HttpHeader {
+ HttpHeader {
+ name: name.into(),
+ value: value.into(),
+ }
+}
diff --git a/libs/fleet/sdk/tests/support/mod.rs b/libs/fleet/sdk/tests/support/mod.rs
new file mode 100644
index 0000000000..d8da321e05
--- /dev/null
+++ b/libs/fleet/sdk/tests/support/mod.rs
@@ -0,0 +1,111 @@
+#![allow(dead_code)]
+
+use async_trait::async_trait;
+use cyclops_sdk::{HttpClient, HttpError, HttpRequest, HttpResponse};
+use std::{collections::VecDeque, sync::Arc};
+use tokio::sync::{Mutex, Notify};
+
+pub struct ScriptedHttpClient {
+ requests: Mutex<Vec<HttpRequest>>,
+ responses: Mutex<VecDeque<QueuedResponse>>,
+}
+
+enum QueuedResponse {
+ Immediate(Result<HttpResponse, HttpError>),
+ Blocking {
+ response: Result<HttpResponse, HttpError>,
+ started: Arc<Notify>,
+ release: Arc<Notify>,
+ },
+}
+
+pub struct BlockedResponse {
+ started: Arc<Notify>,
+ release: Arc<Notify>,
+}
+
+impl ScriptedHttpClient {
+ pub fn new(responses: impl IntoIterator<Item = Result<HttpResponse, HttpError>>) -> Self {
+ Self {
+ requests: Mutex::new(Vec::new()),
+ responses: Mutex::new(
+ responses
+ .into_iter()
+ .map(QueuedResponse::Immediate)
+ .collect(),
+ ),
+ }
+ }
+
+ pub async fn enqueue(&self, response: Result<HttpResponse, HttpError>) {
+ self.responses
+ .lock()
+ .await
+ .push_back(QueuedResponse::Immediate(response));
+ }
+
+ pub async fn enqueue_blocking(
+ &self,
+ response: Result<HttpResponse, HttpError>,
+ ) -> BlockedResponse {
+ let started = Arc::new(Notify::new());
+ let release = Arc::new(Notify::new());
+ self.responses
+ .lock()
+ .await
+ .push_back(QueuedResponse::Blocking {
+ response,
+ started: Arc::clone(&started),
+ release: Arc::clone(&release),
+ });
+ BlockedResponse { started, release }
+ }
+
+ pub async fn requests(&self) -> Vec<HttpRequest> {
+ self.requests.lock().await.clone()
+ }
+
+ pub async fn request_count(&self) -> usize {
+ self.requests.lock().await.len()
+ }
+
+ pub async fn authenticated_requests(&self) -> Vec<HttpRequest> {
+ self.requests().await.into_iter().skip(1).collect()
+ }
+}
+
+impl BlockedResponse {
+ pub async fn wait_until_started(&self) {
+ self.started.notified().await;
+ }
+
+ pub fn release(&self) {
+ self.release.notify_one();
+ }
+}
+
+#[async_trait]
+impl HttpClient for ScriptedHttpClient {
+ async fn execute(&self, request: HttpRequest) -> Result<HttpResponse, HttpError> {
+ self.requests.lock().await.push(request);
+ let response = {
+ self.responses
+ .lock()
+ .await
+ .pop_front()
+ .expect("scripted HTTP client received an unexpected request")
+ };
+ match response {
+ QueuedResponse::Immediate(response) => response,
+ QueuedResponse::Blocking {
+ response,
+ started,
+ release,
+ } => {
+ started.notify_one();
+ release.notified().await;
+ response
+ }
+ }
+ }
+}
diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go
index 56819105f2..573c9d2a79 100644
--- a/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go
+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go
@@ -60,8 +60,8 @@ func poolResourceSchema() schema.Schema {
"memory": schema.StringAttribute{Required: true},
"container_disk_image": schema.StringAttribute{Required: true},
"image_pull_secret": schema.StringAttribute{Optional: true, Computed: true, Description: "Kubernetes image pull secret. Defaults to ecr-credentials."},
- "runtime": schema.StringAttribute{Optional: true, Computed: true, Description: "Pool backend. \"kubevirt\" (default) provisions a KubeVirt VM. \"macos\" provisions a macOS sandbox (ADMIN-ONLY — the cyclops-cs backend rejects macos pool writes from non-admins; the SPA hides the option). Flows verbatim through the compat shim into the OSGymSandboxTemplate vmTemplate, where macos_backend dispatches on it.", Validators: []validator.String{stringvalidator.OneOf("gvisor", "kubevirt", "macos")}},
- "firmware": schema.StringAttribute{Optional: true, Computed: true, Description: "VM firmware. Use \"efi\" for GPT/UEFI-only guest images (e.g. the dockur-built Windows desktop-workspace); \"bios\" is KubeVirt's default and what the Linux workspace images boot with.", Validators: []validator.String{stringvalidator.OneOf("bios", "efi")}},
+ "runtime": schema.StringAttribute{Optional: true, Computed: true, Description: "Pool backend. \"kubevirt\" (default) provisions a KubeVirt\nVM. \"macos\" provisions a macOS sandbox (ADMIN-ONLY\n— the cyclops-cs backend rejects macos pool writes from\nnon-admins; the SPA hides the option). Flows verbatim\nthrough the compat shim into the OSGymSandboxTemplate\nvmTemplate, where macos_backend dispatches on it.", Validators: []validator.String{stringvalidator.OneOf("gvisor", "kubevirt", "macos")}},
+ "firmware": schema.StringAttribute{Optional: true, Computed: true, Description: "VM firmware. Use \"efi\" for GPT/UEFI-only guest images\n(e.g. the dockur-built Windows desktop-workspace);\n\"bios\" is KubeVirt's default and what the Linux\nworkspace images boot with.", Validators: []validator.String{stringvalidator.OneOf("bios", "efi")}},
"readiness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI readinessProbe."},
"liveness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI livenessProbe."},
"phase": schema.StringAttribute{Computed: true},
@@ -76,9 +76,9 @@ func poolResourceSchema() schema.Schema {
"protocol": schema.StringAttribute{Optional: true, Computed: true, Validators: []validator.String{stringvalidator.OneOf("TCP", "UDP")}},
}}},
"autoscaling": schema.SingleNestedBlock{Attributes: map[string]schema.Attribute{
- "min_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "Durable warm floor (KEDA minReplicaCount).", Validators: []validator.Int64{int64validator.AtLeast(0)}},
- "initial_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "One-time warm head-start seeded on create.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
- "max_pool_size": schema.Int64Attribute{Required: true, Description: "Hard ceiling (KEDA maxReplicaCount).", Validators: []validator.Int64{int64validator.AtLeast(1)}},
+ "min_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "ScaledObject minReplicaCount — the durable warm\nfloor kept while the extension is enabled. 0 lets\nthe pool scale to zero when there are no claims.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
+ "initial_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "One-time warm head-start: the pool-operator seeds\nspec.replicas to this when the pool is created so\nthe first claims bind without a cold start. KEDA\nthen owns spec.replicas; the value decays toward\nthe live claim demand (floored at minPoolSize)\nonce KEDA begins polling.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
+ "max_pool_size": schema.Int64Attribute{Required: true, Description: "ScaledObject maxReplicaCount — hard ceiling.", Validators: []validator.Int64{int64validator.AtLeast(1)}},
}},
},
}